Hamed744 commited on
Commit
ff24def
·
verified ·
1 Parent(s): 54a4d17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -68
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - نسخه نهایی: انتخاب تصادفی + تلاش ۵۰ باره + بدون حذف کلیدها
2
 
3
  import os
4
  import sys
@@ -12,6 +12,8 @@ import logging
12
  import mimetypes
13
  import threading
14
  import random
 
 
15
  from fastapi import FastAPI, HTTPException
16
  from pydantic import BaseModel
17
  from google import genai
@@ -36,35 +38,27 @@ def _init_api_keys():
36
  global ALL_API_KEYS
37
  all_keys_string = os.environ.get("ALL_GEMINI_API_KEYS")
38
  if all_keys_string:
39
- # کلیدها را فقط می‌خوانیم و در لیست نگه می‌داریم
40
  ALL_API_KEYS = [key.strip() for key in all_keys_string.split(',') if key.strip()]
41
  logging.info(f"✅ تعداد {len(ALL_API_KEYS)} کلید API جیمینای شناسایی و بارگذاری شد.")
42
  if not ALL_API_KEYS:
43
  logging.warning("⛔️ هشدار: هیچ Secret با نام ALL_GEMINI_API_KEYS یافت نشد!")
44
 
45
  def get_random_api_key_and_client():
46
- """
47
- یک کلید را به صورت کاملاً تصادفی انتخاب می‌کند.
48
- """
49
  if not ALL_API_KEYS:
50
  return None, None
51
-
52
- # انتخاب تصادفی از لیست ثابت
53
  key_to_use = random.choice(ALL_API_KEYS)
54
-
55
  with CLIENT_CACHE_LOCK:
56
  if key_to_use in GEMINI_CLIENTS_CACHE:
57
  client = GEMINI_CLIENTS_CACHE[key_to_use]
58
  else:
59
- # ساخت کلاینت جدید و ذخیره در کش
60
  client = genai.Client(api_key=key_to_use)
61
  GEMINI_CLIENTS_CACHE[key_to_use] = client
62
-
63
  return key_to_use, client
64
 
65
- FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts"
 
66
  DEFAULT_MAX_CHUNK_SIZE = 3800
67
- DEFAULT_SLEEP_BETWEEN_REQUESTS = 5 # کمی کاهش وقفه چون کلیدها تصادفی هستند
68
 
69
  def save_binary_file(file_name, data):
70
  try:
@@ -123,82 +117,152 @@ def merge_audio_files_func(file_paths, output_path):
123
  return True
124
  except Exception as e: logging.error(f"❌ خطا در ادغام فایل‌های صوتی: {e}"); return False
125
 
126
- # --- منطق اصلی با انتخاب تصادفی و حفظ کلیدها ---
127
- def generate_audio_chunk_with_retry(chunk_text, prompt_text, voice, temp, session_id):
128
- if not ALL_API_KEYS: raise Exception("هیچ کلید API برای پردازش در دسترس نیست.")
 
 
 
129
 
130
- MAX_RETRIES = 50 # تلاش تا ۵۰ بار
 
 
 
 
 
 
 
 
131
 
132
  for attempt in range(MAX_RETRIES):
133
- # 1. انتخاب تصادفی کلید
134
- selected_api_key, client = get_random_api_key_and_client()
135
 
136
- if not client:
137
- logging.error(f"[{session_id}] کلاینت یافت نشد.")
138
- break
 
 
 
 
 
139
 
140
  try:
141
- # logging.info(f"[{session_id}] تلاش {attempt+1}/{MAX_RETRIES} با کلید تصادفی ...{selected_api_key[-4:]}")
 
 
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  final_text = f'{chunk_text}({prompt_text})' if prompt_text and prompt_text.strip() else chunk_text
144
  contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
145
  config = types.GenerateContentConfig(temperature=temp, response_modalities=["audio"],
146
  speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
147
  prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice))))
148
 
149
- response = client.models.generate_content(model=FIXED_MODEL_NAME, contents=contents, config=config)
150
-
151
  if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
152
- logging.info(f"[{session_id}] ✅ قطعه با موفقیت در تلاش {attempt+1} تولید شد.")
153
  return response.candidates[0].content.parts[0].inline_data
154
-
155
  except Exception as e:
156
- # فقط لاگ می‌کنیم و ادامه می‌دهیم. کلید را حذف نمی‌کنیم.
157
- logging.warning(f"[{session_id}] ⚠️ خطا در تلاش {attempt+1} (کلید ...{selected_api_key[-4:]}): {e}")
158
-
159
- # وقفه کوتاه (نیم ثانیه) قبل از انتخاب تصادفی بعدی
160
  time.sleep(0.5)
161
-
162
  return None
163
 
164
- def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, session_id):
165
- logging.info(f"[{session_id}] 🚀 شروع فرآیند تولید صدا.")
166
  temp_dir = f"temp_{session_id}"
167
  os.makedirs(temp_dir, exist_ok=True)
168
  output_base_name = f"{temp_dir}/audio_session_{session_id}"
169
- if not text_input or not text_input.strip(): raise ValueError("متن ورودی خالی است.")
170
- text_chunks = smart_text_split(text_input, DEFAULT_MAX_CHUNK_SIZE)
171
- if not text_chunks: raise ValueError("متن قابل پردازش به قطعات کوچکتر نیست.")
172
- generated_files = []
173
  try:
174
- for i, chunk in enumerate(text_chunks):
175
- logging.info(f"[{session_id}] 🔊 پردازش قطعه {i+1}/{len(text_chunks)}...")
176
- inline_data = generate_audio_chunk_with_retry(chunk, prompt_input, selected_voice, temperature_val, session_id)
177
- if inline_data:
178
- data_buffer = inline_data.data
179
- ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
180
- if "audio/L" in inline_data.mime_type and ext == ".wav":
181
- data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
182
- if not ext.startswith("."): ext = "." + ext
183
- fpath = save_binary_file(f"{output_base_name}_part{i+1:03d}{ext}", data_buffer)
184
- if fpath: generated_files.append(fpath)
 
185
  else:
186
- # اگر بعد از ۵۰ بار تلاش تصادفی باز هم نشد
187
- raise Exception(f"تولید قطعه {i+1} پس از ۵۰ بار تلاش تصادفی ناموفق بود. ترافیک سرورها بسیار بالاست.")
188
- if i < len(text_chunks) - 1 and len(text_chunks) > 1: time.sleep(DEFAULT_SLEEP_BETWEEN_REQUESTS)
189
- if not generated_files: raise Exception("هیچ فایل صوتی تولید نشد.")
190
- final_output_path = f"output_{session_id}.wav"
191
- if len(generated_files) > 1:
192
- if PYDUB_AVAILABLE and merge_audio_files_func(generated_files, final_output_path):
193
- final_audio_file = final_output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  else:
195
  shutil.move(generated_files[0], final_output_path)
196
- final_audio_file = final_output_path
197
- else:
198
- shutil.move(generated_files[0], final_output_path)
199
- final_audio_file = final_output_path
200
- logging.info(f"[{session_id}] ✅ فایل صوتی نهایی با موفقیت تولید شد: {os.path.basename(final_audio_file)}")
201
- return final_audio_file
202
  finally:
203
  if os.path.exists(temp_dir):
204
  shutil.rmtree(temp_dir)
@@ -212,34 +276,33 @@ class TTSRequest(BaseModel):
212
  prompt: str | None = ""
213
  speaker: str
214
  temperature: float
 
215
 
216
  @app.post("/generate")
217
  def generate_audio_endpoint(request: TTSRequest):
218
  session_id = str(uuid.uuid4())[:8]
219
- logging.info(f"[{session_id}] 🏁 درخواست جدید API در این Worker دریافت شد.")
220
  try:
221
  final_path = core_generate_audio(
222
  text_input=request.text,
223
  prompt_input=request.prompt,
224
  selected_voice=request.speaker,
225
  temperature_val=request.temperature,
226
- session_id=session_id
 
227
  )
228
  if final_path and os.path.exists(final_path):
229
  from fastapi.responses import FileResponse
230
  return FileResponse(path=final_path, media_type='audio/wav', filename=os.path.basename(final_path), background=shutil.rmtree(os.path.dirname(final_path), ignore_errors=True))
231
  else:
232
- raise HTTPException(status_code=500, detail="خطا در تولید فایل صوتی در Worker.")
233
  except Exception as e:
234
- logging.error(f"[{session_id}] ❌ خطای کلی در Worker: {e}")
235
  raise HTTPException(status_code=500, detail=str(e))
236
 
237
  @app.get("/")
238
  def health_check():
239
  return {"status": "ok", "message": "TTS Worker is running."}
240
 
241
- logging.info("✅✅✅ Application logic initialized successfully. Starting Uvicorn server...")
242
-
243
  if __name__ == "__main__":
244
  port = int(os.environ.get("PORT", 7860))
245
  uvicorn.run(app, host="0.0.0.0", port=port, reload=False)
 
1
+ # app.py - نسخه Worker با پشتیبانی از Gemini Live و Standard
2
 
3
  import os
4
  import sys
 
12
  import mimetypes
13
  import threading
14
  import random
15
+ import asyncio
16
+ import wave
17
  from fastapi import FastAPI, HTTPException
18
  from pydantic import BaseModel
19
  from google import genai
 
38
  global ALL_API_KEYS
39
  all_keys_string = os.environ.get("ALL_GEMINI_API_KEYS")
40
  if all_keys_string:
 
41
  ALL_API_KEYS = [key.strip() for key in all_keys_string.split(',') if key.strip()]
42
  logging.info(f"✅ تعداد {len(ALL_API_KEYS)} کلید API جیمینای شناسایی و بارگذاری شد.")
43
  if not ALL_API_KEYS:
44
  logging.warning("⛔️ هشدار: هیچ Secret با نام ALL_GEMINI_API_KEYS یافت نشد!")
45
 
46
  def get_random_api_key_and_client():
 
 
 
47
  if not ALL_API_KEYS:
48
  return None, None
 
 
49
  key_to_use = random.choice(ALL_API_KEYS)
 
50
  with CLIENT_CACHE_LOCK:
51
  if key_to_use in GEMINI_CLIENTS_CACHE:
52
  client = GEMINI_CLIENTS_CACHE[key_to_use]
53
  else:
 
54
  client = genai.Client(api_key=key_to_use)
55
  GEMINI_CLIENTS_CACHE[key_to_use] = client
 
56
  return key_to_use, client
57
 
58
+ FIXED_MODEL_NAME_STANDARD = "gemini-2.5-flash-preview-tts"
59
+ FIXED_MODEL_NAME_LIVE = "models/gemini-2.5-flash-native-audio-preview-12-2025" # مدل لایف
60
  DEFAULT_MAX_CHUNK_SIZE = 3800
61
+ DEFAULT_SLEEP_BETWEEN_REQUESTS = 5
62
 
63
  def save_binary_file(file_name, data):
64
  try:
 
117
  return True
118
  except Exception as e: logging.error(f"❌ خطا در ادغام فایل‌های صوتی: {e}"); return False
119
 
120
+ # --- منطق Gemini Live دید) ---
121
+ async def generate_audio_live_with_retry(text, prompt, voice, session_id):
122
+ """
123
+ اتصال به مدل لایف با استفاده از وب‌سوکت و دریافت صدا.
124
+ """
125
+ MAX_RETRIES = 50
126
 
127
+ # تنظیمات مدل لایف
128
+ live_config = types.LiveConnectConfig(
129
+ response_modalities=["AUDIO"],
130
+ speech_config=types.SpeechConfig(
131
+ voice_config=types.VoiceConfig(
132
+ prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice)
133
+ )
134
+ ),
135
+ )
136
 
137
  for attempt in range(MAX_RETRIES):
138
+ selected_api_key, _ = get_random_api_key_and_client()
139
+ if not selected_api_key: break
140
 
141
+ # برای لایف نیاز به کلاینت Async جدید داریم که با کلید خاص ساخته شود
142
+ # چون کلاینت‌های کش شده ممکن است سینک باشند یا تنظیمات متفاوتی داشته باشند
143
+ client = genai.Client(http_options={"api_version": "v1beta"}, api_key=selected_api_key)
144
+
145
+ unique_id_for_req = str(uuid.uuid4())[:8]
146
+ tts_prompt = f"Please read the following text naturally: '{text}' [ID: {unique_id_for_req}]"
147
+ if prompt:
148
+ tts_prompt = f"With a {prompt} tone, please read: '{text}'"
149
 
150
  try:
151
+ logging.info(f"[{session_id}] (Live) تلاش {attempt+1} با کلید ...{selected_api_key[-4:]}")
152
+
153
+ audio_buffer = bytearray()
154
 
155
+ async with client.aio.live.connect(model=FIXED_MODEL_NAME_LIVE, config=live_config) as session:
156
+ await session.send(input=tts_prompt, end_of_turn=True)
157
+
158
+ # دریافت استریم
159
+ async for response in session.receive():
160
+ if response.data:
161
+ audio_buffer.extend(response.data)
162
+ if response.text:
163
+ pass # متن را نادیده می‌گیریم
164
+
165
+ if len(audio_buffer) > 0:
166
+ logging.info(f"[{session_id}] ✅ (Live) دریافت موفقیت‌آمیز {len(audio_buffer)} بایت.")
167
+ return audio_buffer
168
+ else:
169
+ raise Exception("بافر صوتی خالی بود.")
170
+
171
+ except Exception as e:
172
+ logging.warning(f"[{session_id}] ⚠️ (Live) خطا در تلاش {attempt+1}: {e}")
173
+ time.sleep(0.5)
174
+
175
+ return None
176
+
177
+ def save_pcm_to_wav(pcm_data, output_path):
178
+ """ذخیره دیتای خام PCM مدل لایف به فرمت WAV استاندارد"""
179
+ try:
180
+ with wave.open(output_path, 'wb') as wf:
181
+ wf.setnchannels(1) # Mono
182
+ wf.setsampwidth(2) # 16-bit
183
+ wf.setframerate(24000) # 24kHz (استاندارد مدل لایف)
184
+ wf.writeframes(pcm_data)
185
+ return True
186
+ except Exception as e:
187
+ logging.error(f"خطا در تبدیل PCM به WAV: {e}")
188
+ return False
189
+
190
+ # --- منطق Gemini Standard (قدیمی) ---
191
+ def generate_audio_chunk_standard_with_retry(chunk_text, prompt_text, voice, temp, session_id):
192
+ if not ALL_API_KEYS: raise Exception("هیچ کلید API برای پردازش در دسترس نیست.")
193
+ MAX_RETRIES = 50
194
+ for attempt in range(MAX_RETRIES):
195
+ selected_api_key, client = get_random_api_key_and_client()
196
+ if not client: break
197
+ try:
198
  final_text = f'{chunk_text}({prompt_text})' if prompt_text and prompt_text.strip() else chunk_text
199
  contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
200
  config = types.GenerateContentConfig(temperature=temp, response_modalities=["audio"],
201
  speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
202
  prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice))))
203
 
204
+ response = client.models.generate_content(model=FIXED_MODEL_NAME_STANDARD, contents=contents, config=config)
 
205
  if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
206
+ logging.info(f"[{session_id}] ✅ (Standard) قطعه تولید شد.")
207
  return response.candidates[0].content.parts[0].inline_data
 
208
  except Exception as e:
209
+ logging.warning(f"[{session_id}] ⚠️ (Standard) خطا در تلاش {attempt+1}: {e}")
 
 
 
210
  time.sleep(0.5)
 
211
  return None
212
 
213
+ def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, session_id, use_live_model=False):
214
+ logging.info(f"[{session_id}] 🚀 شروع پردازش (Live Mode: {use_live_model})")
215
  temp_dir = f"temp_{session_id}"
216
  os.makedirs(temp_dir, exist_ok=True)
217
  output_base_name = f"{temp_dir}/audio_session_{session_id}"
218
+ final_output_path = f"output_{session_id}.wav"
219
+
 
 
220
  try:
221
+ # --- مسیر ۱: استفاده از مدل لای�� ---
222
+ if use_live_model:
223
+ # در مدل لایف، متن را تکه تکه نمی‌کنیم (چون شرط <500 کاراکتر چک شده)
224
+ # باید تابع async را در محیط sync اجرا کنیم
225
+ pcm_data = asyncio.run(generate_audio_live_with_retry(text_input, prompt_input, selected_voice, session_id))
226
+
227
+ if pcm_data:
228
+ if save_pcm_to_wav(pcm_data, final_output_path):
229
+ logging.info(f"[{session_id}] فایل لایف ذخیره شد.")
230
+ return final_output_path
231
+ else:
232
+ raise Exception("خطا در ذخیره فایل WAV لایف.")
233
  else:
234
+ raise Exception("تولید صدا با مدل لایف پس از تلاش‌های مکرر ناموفق بود.")
235
+
236
+ # --- مسیر ۲: استفاده از مدل استاندارد ---
237
+ else:
238
+ text_chunks = smart_text_split(text_input, DEFAULT_MAX_CHUNK_SIZE)
239
+ generated_files = []
240
+ for i, chunk in enumerate(text_chunks):
241
+ inline_data = generate_audio_chunk_standard_with_retry(chunk, prompt_input, selected_voice, temperature_val, session_id)
242
+ if inline_data:
243
+ data_buffer = inline_data.data
244
+ ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
245
+ if "audio/L" in inline_data.mime_type and ext == ".wav":
246
+ data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
247
+ if not ext.startswith("."): ext = "." + ext
248
+ fpath = save_binary_file(f"{output_base_name}_part{i+1:03d}{ext}", data_buffer)
249
+ if fpath: generated_files.append(fpath)
250
+ else:
251
+ raise Exception(f"تولید قطعه {i+1} استاندارد ناموفق بود.")
252
+ if i < len(text_chunks) - 1: time.sleep(DEFAULT_SLEEP_BETWEEN_REQUESTS)
253
+
254
+ if not generated_files: raise Exception("هیچ فایلی تولید نشد.")
255
+
256
+ if len(generated_files) > 1:
257
+ if PYDUB_AVAILABLE and merge_audio_files_func(generated_files, final_output_path):
258
+ pass
259
+ else:
260
+ shutil.move(generated_files[0], final_output_path)
261
  else:
262
  shutil.move(generated_files[0], final_output_path)
263
+
264
+ return final_output_path
265
+
 
 
 
266
  finally:
267
  if os.path.exists(temp_dir):
268
  shutil.rmtree(temp_dir)
 
276
  prompt: str | None = ""
277
  speaker: str
278
  temperature: float
279
+ use_live_model: bool = False # پارامتر جدید
280
 
281
  @app.post("/generate")
282
  def generate_audio_endpoint(request: TTSRequest):
283
  session_id = str(uuid.uuid4())[:8]
 
284
  try:
285
  final_path = core_generate_audio(
286
  text_input=request.text,
287
  prompt_input=request.prompt,
288
  selected_voice=request.speaker,
289
  temperature_val=request.temperature,
290
+ session_id=session_id,
291
+ use_live_model=request.use_live_model
292
  )
293
  if final_path and os.path.exists(final_path):
294
  from fastapi.responses import FileResponse
295
  return FileResponse(path=final_path, media_type='audio/wav', filename=os.path.basename(final_path), background=shutil.rmtree(os.path.dirname(final_path), ignore_errors=True))
296
  else:
297
+ raise HTTPException(status_code=500, detail="خطا در تولید فایل صوتی.")
298
  except Exception as e:
299
+ logging.error(f"[{session_id}] ❌ خطا: {e}")
300
  raise HTTPException(status_code=500, detail=str(e))
301
 
302
  @app.get("/")
303
  def health_check():
304
  return {"status": "ok", "message": "TTS Worker is running."}
305
 
 
 
306
  if __name__ == "__main__":
307
  port = int(os.environ.get("PORT", 7860))
308
  uvicorn.run(app, host="0.0.0.0", port=port, reload=False)