Spaces:
Sleeping
Sleeping
File size: 12,929 Bytes
0998987 83daf1c 0ef208e 0998987 07221e5 0998987 e285d1f 0998987 896329b 0ef208e 0998987 0ef208e bbcf9c6 896329b bbcf9c6 83daf1c 0998987 896329b 0998987 896329b 0ef208e 0998987 c6d4440 0ef208e c6d4440 896329b 0ef208e 896329b 0ef208e c6d4440 bbcf9c6 0ef208e c6d4440 0ef208e c6d4440 0ef208e 896329b c6d4440 0ef208e 896329b 0ef208e 381e7fa 0ef208e 0998987 c6d4440 0ef208e c6d4440 896329b 0998987 0ef208e 896329b 83daf1c 896329b 83daf1c 896329b 83daf1c 896329b 83daf1c 896329b bbcf9c6 0998987 0ef208e 19cbf37 0ef208e 0998987 896329b bbcf9c6 83daf1c bbcf9c6 83daf1c bbcf9c6 896329b 83daf1c 896329b 83daf1c 896329b 83daf1c 896329b e285d1f 896329b 83daf1c 896329b 83daf1c 896329b 0998987 896329b 83daf1c 896329b 83daf1c 896329b 0998987 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# pip install flask google-genai
import os, time, base64, struct
from flask import Flask, request, render_template_string, jsonify, Response, stream_with_context
from google import genai
from google.genai import types
app = Flask(__name__)
HTML = """
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Gemini Multi (Text → Streaming TTS)</title></head>
<body style="font-family:sans-serif;padding:2rem;">
<h1>Gemini Multi (Text + Image → Streaming TTS)</h1>
<form id="genai-form" enctype="multipart/form-data">
<textarea id="prompt" name="text" rows="6" cols="60" placeholder="Enter prompt"></textarea><br/><br/>
<input type="file" id="image" name="image" accept="image/*" /><br/><br/>
<label>Voice: <input id="voice" name="voice" value="Sadachbia" /></label><br/>
<label>Accent: <input id="accent" name="accent" value="British" /></label><br/>
<label>Tone: <input id="tone" name="tone" value="casual and friendly" /></label><br/><br/>
<button type="submit">Generate</button>
</form>
<pre id="output" style="background:#f4f4f4;padding:1rem;margin-top:1rem;"></pre>
<div id="audio-out" style="margin-top:1rem;"></div>
<div id="status" style="margin-top:1rem;color:#666;"></div>
<script>
const form = document.getElementById('genai-form');
// Audio streaming setup
let audioContext = null;
let nextStartTime = 0;
let audioQueue = [];
let isPlaying = false;
function initAudioContext() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
return audioContext;
}
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
async function playAudioChunk(wavBase64) {
const ctx = initAudioContext();
const arrayBuffer = base64ToArrayBuffer(wavBase64);
try {
const audioBuffer = await ctx.decodeAudioData(arrayBuffer);
const source = ctx.createBufferSource();
source.buffer = audioBuffer;
source.connect(ctx.destination);
const currentTime = ctx.currentTime;
const startTime = Math.max(currentTime, nextStartTime);
source.start(startTime);
nextStartTime = startTime + audioBuffer.duration;
return audioBuffer.duration;
} catch (err) {
console.error('Error playing audio chunk:', err);
return 0;
}
}
form.addEventListener('submit', async e => {
e.preventDefault();
const out = document.getElementById('output');
const audioDiv = document.getElementById('audio-out');
const status = document.getElementById('status');
out.textContent = 'Generating text…';
audioDiv.innerHTML = '';
status.textContent = '';
// Reset audio state
if (audioContext) {
nextStartTime = audioContext.currentTime;
}
const formData = new FormData(form);
try {
const resp = await fetch('/generate_stream', { method: 'POST', body: formData });
if (!resp.ok) {
out.textContent = 'Server error: ' + resp.statusText;
return;
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let textReceived = false;
let audioChunks = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\\n');
buffer = lines.pop(); // Keep incomplete line in buffer
for (const line of lines) {
if (!line.trim() || !line.startsWith('data: ')) continue;
try {
const data = JSON.parse(line.slice(6));
if (data.error) {
out.textContent = 'Error: ' + data.error;
status.textContent = '';
return;
}
if (data.type === 'text') {
out.textContent = data.text;
textReceived = true;
status.textContent = 'Text received, generating audio...';
}
if (data.type === 'audio_chunk' && data.audio_base64) {
audioChunks++;
status.textContent = `Streaming audio... (chunk ${audioChunks})`;
await playAudioChunk(data.audio_base64);
}
if (data.type === 'complete') {
status.textContent = `Complete! Text: ${data.timings.text_seconds}s, TTS: ${data.timings.tts_seconds}s, Total: ${data.timings.total_seconds}s`;
}
} catch (err) {
console.error('Error parsing SSE:', err, line);
}
}
}
} catch (err) {
console.error(err);
out.textContent = 'Fetch error: ' + err.message;
status.textContent = '';
}
});
</script>
</body>
</html>
"""
client = genai.Client(api_key="AIzaSyDolbPUZBPUPvQUu-RGktJmvnUpkcEKIYo")
def wrap_pcm_to_wav(pcm_data: bytes, sample_rate=24000, num_channels=1, bits_per_sample=16) -> bytes:
byte_rate = sample_rate * num_channels * bits_per_sample // 8
block_align = num_channels * bits_per_sample // 8
data_size = len(pcm_data)
header = b"RIFF" + struct.pack("<I", 36 + data_size) + b"WAVE"
header += b"fmt " + struct.pack("<IHHIIHH", 16, 1, num_channels, sample_rate, byte_rate, block_align, bits_per_sample)
header += b"data" + struct.pack("<I", data_size)
return header + pcm_data
def extract_text(resp) -> str:
if getattr(resp, "text", None): return resp.text
parts_text = []
for cand in getattr(resp, "candidates", []) or []:
content = getattr(cand, "content", None)
parts = getattr(content, "parts", None) or []
for p in parts:
if getattr(p, "text", None):
parts_text.append(p.text)
return "\n".join(parts_text).strip()
@app.route('/')
def index():
return render_template_string(HTML)
@app.route('/generate_stream', methods=['POST'])
def generate_stream():
def generate():
t_start = time.perf_counter()
prompt = (request.form.get("text") or "").strip()
file = request.files.get("image")
voice = (request.form.get("voice") or "Sadachbia").strip()
accent = (request.form.get("accent") or "British").strip()
tone = (request.form.get("tone") or "casual and friendly").strip()
if not prompt and not file:
yield f"data: {jsonify({'error': 'No input provided'}).get_data(as_text=True)}\n\n"
return
# Build multimodal input
parts = []
if prompt:
parts.append(types.Part.from_text(text=prompt))
if file:
parts.append(types.Part.from_bytes(data=file.read(), mime_type=file.mimetype or "image/png"))
# 1) Generate text
t0 = time.perf_counter()
try:
gen_resp = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=[types.Content(role="user", parts=parts)],
config=types.GenerateContentConfig(response_mime_type="text/plain"),
)
except Exception as e:
yield f"data: {jsonify({'error': f'text generation failed: {str(e)}'}).get_data(as_text=True)}\n\n"
return
t1 = time.perf_counter()
final_text = extract_text(gen_resp)
if not final_text:
yield f"data: {jsonify({'error': 'Text generation returned empty'}).get_data(as_text=True)}\n\n"
return
# Send text immediately
yield f"data: {jsonify({'type': 'text', 'text': final_text}).get_data(as_text=True)}\n\n"
# 2) Stream TTS audio
style_prompt = f"Say the following in a {accent} accent with a {tone} tone:\n\n{final_text}"
tts_start = time.perf_counter()
try:
# Use streaming for TTS
tts_stream = client.models.generate_content_stream(
model= "gemini-2.5-flash-preview-tts",
contents=[types.Content(role="user", parts=[types.Part.from_text(text=style_prompt)])],
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice)
)
)
)
)
for chunk in tts_stream:
for cand in getattr(chunk, "candidates", []) or []:
for p in getattr(cand.content, "parts", []):
if getattr(p, "inline_data", None) and p.inline_data.data:
pcm_bytes = p.inline_data.data
wav = wrap_pcm_to_wav(pcm_bytes)
audio_b64 = base64.b64encode(wav).decode("ascii")
yield f"data: {jsonify({'type': 'audio_chunk', 'audio_base64': audio_b64}).get_data(as_text=True)}\n\n"
except Exception as e:
yield f"data: {jsonify({'error': f'tts streaming failed: {str(e)}', 'text': final_text}).get_data(as_text=True)}\n\n"
return
tts_end = time.perf_counter()
t_total = time.perf_counter() - t_start
# Send completion signal
yield f"data: {jsonify({'type': 'complete', 'timings': {'text_seconds': round(t1 - t0, 3), 'tts_seconds': round(tts_end - tts_start, 3), 'total_seconds': round(t_total, 3)}}).get_data(as_text=True)}\n\n"
return Response(stream_with_context(generate()), mimetype='text/event-stream')
# Keep the original endpoint for compatibility
@app.route('/generate', methods=['POST'])
def generate():
t_start = time.perf_counter()
prompt = (request.form.get("text") or "").strip()
file = request.files.get("image")
voice = (request.form.get("voice") or "Sadachbia").strip()
accent = (request.form.get("accent") or "British").strip()
tone = (request.form.get("tone") or "casual and friendly").strip()
if not prompt and not file:
return jsonify({"error": "No input provided"}), 400
parts = []
if prompt:
parts.append(types.Part.from_text(text=prompt))
if file:
parts.append(types.Part.from_bytes(data=file.read(), mime_type=file.mimetype or "image/png"))
t0 = time.perf_counter()
try:
gen_resp = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=[types.Content(role="user", parts=parts)],
config=types.GenerateContentConfig(response_mime_type="text/plain"),
)
except Exception as e:
return jsonify({"error": f"text generation failed: {str(e)}"}), 500
t1 = time.perf_counter()
final_text = extract_text(gen_resp)
if not final_text:
return jsonify({"error": "Text generation returned empty"}), 500
style_prompt = f"Say the following in a {accent} accent with a {tone} tone:\n\n{final_text}"
tts_start = time.perf_counter()
try:
tts_resp = client.models.generate_content(
model="gemini-2.5-flash-preview-tts",
contents=[types.Content(role="user", parts=[types.Part.from_text(text=style_prompt)])],
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice)
)
)
)
)
except Exception as e:
return jsonify({"error": f"tts generation failed: {str(e)}", "text": final_text}), 500
tts_end = time.perf_counter()
pcm_bytes = None
for cand in getattr(tts_resp, "candidates", []) or []:
for p in getattr(cand.content, "parts", []):
if getattr(p, "inline_data", None) and p.inline_data.data:
pcm_bytes = p.inline_data.data
break
if pcm_bytes: break
if not pcm_bytes:
return jsonify({"error": "TTS returned no audio", "text": final_text}), 500
wav = wrap_pcm_to_wav(pcm_bytes)
audio_b64 = base64.b64encode(wav).decode("ascii")
t_total = time.perf_counter() - t_start
return jsonify({
"text": final_text,
"audio_base64": audio_b64,
"timings": {
"text_seconds": round(t1 - t0, 3),
"tts_seconds": round(tts_end - tts_start, 3),
"total_seconds": round(t_total, 3)
}
})
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port) |