Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py - نسخه
|
| 2 |
|
| 3 |
import os
|
| 4 |
import sys
|
|
@@ -11,6 +11,9 @@ import shutil
|
|
| 11 |
import logging
|
| 12 |
import mimetypes
|
| 13 |
import threading
|
|
|
|
|
|
|
|
|
|
| 14 |
from fastapi import FastAPI, HTTPException
|
| 15 |
from pydantic import BaseModel
|
| 16 |
from google import genai
|
|
@@ -25,46 +28,37 @@ except ImportError:
|
|
| 25 |
|
| 26 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
| 27 |
|
|
|
|
| 28 |
GEMINI_CLIENTS_CACHE = {}
|
| 29 |
CLIENT_CACHE_LOCK = threading.Lock()
|
| 30 |
|
| 31 |
ALL_API_KEYS: list[str] = []
|
| 32 |
-
NEXT_KEY_INDEX: int = 0
|
| 33 |
-
KEY_LOCK: threading.Lock = threading.Lock()
|
| 34 |
|
| 35 |
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 |
ALL_API_KEYS = [key.strip() for key in all_keys_string.split(',') if key.strip()]
|
| 40 |
-
logging.info(f"✅ تعداد {len(ALL_API_KEYS)} کلید API جیمینای بارگذاری شد.")
|
| 41 |
if not ALL_API_KEYS:
|
| 42 |
logging.warning("⛔️ هشدار: هیچ Secret با نام ALL_GEMINI_API_KEYS یافت نشد!")
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
return None, None, -1
|
| 49 |
-
|
| 50 |
-
current_index = NEXT_KEY_INDEX % len(ALL_API_KEYS)
|
| 51 |
-
key_to_use = ALL_API_KEYS[current_index]
|
| 52 |
-
key_display_index = current_index + 1
|
| 53 |
-
NEXT_KEY_INDEX += 1
|
| 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 |
-
logging.info(f"Creating new Gemini client for key ending in ...{key_to_use[-4:]}")
|
| 60 |
client = genai.Client(api_key=key_to_use)
|
| 61 |
GEMINI_CLIENTS_CACHE[key_to_use] = client
|
| 62 |
-
|
| 63 |
-
return key_to_use, client, key_display_index
|
| 64 |
|
| 65 |
-
|
|
|
|
| 66 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 67 |
-
DEFAULT_SLEEP_BETWEEN_REQUESTS =
|
| 68 |
|
| 69 |
def save_binary_file(file_name, data):
|
| 70 |
try:
|
|
@@ -96,21 +90,9 @@ def parse_audio_mime_type(mime_type: str) -> dict[str, int]:
|
|
| 96 |
return {"bits_per_sample": bits, "rate": rate}
|
| 97 |
|
| 98 |
def smart_text_split(text, max_size=3800):
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
for sentence in sentences:
|
| 103 |
-
if len(current_chunk) + len(sentence) + 1 > max_size:
|
| 104 |
-
if current_chunk: chunks.append(current_chunk.strip())
|
| 105 |
-
current_chunk = sentence
|
| 106 |
-
while len(current_chunk) > max_size:
|
| 107 |
-
split_idx = next((i for i in range(max_size - 1, max_size // 2, -1) if current_chunk[i] in ['،', ',', ';', ':', ' ']), -1)
|
| 108 |
-
part, current_chunk = (current_chunk[:split_idx+1], current_chunk[split_idx+1:]) if split_idx != -1 else (current_chunk[:max_size], current_chunk[max_size:])
|
| 109 |
-
chunks.append(part.strip())
|
| 110 |
-
else: current_chunk += (" " if current_chunk else "") + sentence
|
| 111 |
-
if current_chunk: chunks.append(current_chunk.strip())
|
| 112 |
-
final_chunks = [c for c in chunks if c]
|
| 113 |
-
return final_chunks
|
| 114 |
|
| 115 |
def merge_audio_files_func(file_paths, output_path):
|
| 116 |
if not PYDUB_AVAILABLE: logging.warning("⚠️ pydub برای ادغام در دسترس نیست."); return False
|
|
@@ -123,72 +105,145 @@ 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 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
try:
|
|
|
|
| 136 |
final_text = f'{chunk_text}({prompt_text})' if prompt_text and prompt_text.strip() else chunk_text
|
| 137 |
contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
|
| 138 |
config = types.GenerateContentConfig(temperature=temp, response_modalities=["audio"],
|
| 139 |
speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
|
| 140 |
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice))))
|
| 141 |
-
response = client.models.generate_content(model=FIXED_MODEL_NAME, contents=contents, config=config)
|
| 142 |
|
|
|
|
| 143 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
| 144 |
-
logging.info(f"[{session_id}] ✅
|
| 145 |
return response.candidates[0].content.parts[0].inline_data
|
| 146 |
except Exception as e:
|
| 147 |
-
logging.
|
| 148 |
-
|
| 149 |
-
with CLIENT_CACHE_LOCK:
|
| 150 |
-
if selected_api_key in GEMINI_CLIENTS_CACHE:
|
| 151 |
-
del GEMINI_CLIENTS_CACHE[selected_api_key]
|
| 152 |
-
logging.warning(f"Client for key ...{selected_api_key[-4:]} removed from cache due to auth error.")
|
| 153 |
return None
|
| 154 |
|
| 155 |
-
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, session_id):
|
| 156 |
-
logging.info(f"[{session_id}] 🚀
|
| 157 |
temp_dir = f"temp_{session_id}"
|
| 158 |
os.makedirs(temp_dir, exist_ok=True)
|
| 159 |
output_base_name = f"{temp_dir}/audio_session_{session_id}"
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
if not text_chunks: raise ValueError("متن قابل پردازش به قطعات کوچکتر نیست.")
|
| 163 |
-
generated_files = []
|
| 164 |
try:
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
if
|
| 169 |
-
|
| 170 |
-
ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
|
| 171 |
-
if "audio/L" in inline_data.mime_type and ext == ".wav":
|
| 172 |
-
data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
| 173 |
-
if not ext.startswith("."): ext = "." + ext
|
| 174 |
-
fpath = save_binary_file(f"{output_base_name}_part{i+1:03d}{ext}", data_buffer)
|
| 175 |
-
if fpath: generated_files.append(fpath)
|
| 176 |
else:
|
| 177 |
-
raise Exception(
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
else:
|
| 185 |
shutil.move(generated_files[0], final_output_path)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
final_audio_file = final_output_path
|
| 190 |
-
logging.info(f"[{session_id}] ✅ فایل صوتی نهایی با موفقیت تولید شد: {os.path.basename(final_audio_file)}")
|
| 191 |
-
return final_audio_file
|
| 192 |
finally:
|
| 193 |
if os.path.exists(temp_dir):
|
| 194 |
shutil.rmtree(temp_dir)
|
|
@@ -202,38 +257,37 @@ class TTSRequest(BaseModel):
|
|
| 202 |
prompt: str | None = ""
|
| 203 |
speaker: str
|
| 204 |
temperature: float
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
# --- START: تغییر اصلی برای اجرای همزمان واقعی ---
|
| 207 |
-
# کلمه کلیدی async از تعریف تابع حذف شده است.
|
| 208 |
-
# این به FastAPI میگوید که این تابع سنگین را در یک thread جداگانه اجرا کند.
|
| 209 |
@app.post("/generate")
|
| 210 |
def generate_audio_endpoint(request: TTSRequest):
|
| 211 |
-
# --- END: تغییر اصلی ---
|
| 212 |
session_id = str(uuid.uuid4())[:8]
|
| 213 |
-
logging.info(f"[{session_id}] 🏁 درخواست جدید API در این Worker دریافت شد.")
|
| 214 |
try:
|
| 215 |
final_path = core_generate_audio(
|
| 216 |
text_input=request.text,
|
| 217 |
prompt_input=request.prompt,
|
| 218 |
selected_voice=request.speaker,
|
| 219 |
temperature_val=request.temperature,
|
| 220 |
-
session_id=session_id
|
|
|
|
|
|
|
|
|
|
| 221 |
)
|
| 222 |
if final_path and os.path.exists(final_path):
|
| 223 |
from fastapi.responses import FileResponse
|
| 224 |
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))
|
| 225 |
else:
|
| 226 |
-
raise HTTPException(status_code=500, detail="خطا در تولید فایل
|
| 227 |
except Exception as e:
|
| 228 |
-
logging.error(f"[{session_id}] ❌
|
| 229 |
raise HTTPException(status_code=500, detail=str(e))
|
| 230 |
|
| 231 |
@app.get("/")
|
| 232 |
def health_check():
|
| 233 |
return {"status": "ok", "message": "TTS Worker is running."}
|
| 234 |
|
| 235 |
-
logging.info("✅✅✅ Application logic initialized successfully. Starting Uvicorn server...")
|
| 236 |
-
|
| 237 |
if __name__ == "__main__":
|
| 238 |
port = int(os.environ.get("PORT", 7860))
|
| 239 |
uvicorn.run(app, host="0.0.0.0", port=port, reload=False)
|
|
|
|
| 1 |
+
# app.py - نسخه Worker بدون تقسیم متن (No Splitting)
|
| 2 |
|
| 3 |
import os
|
| 4 |
import sys
|
|
|
|
| 11 |
import logging
|
| 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
|
|
|
|
| 28 |
|
| 29 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
| 30 |
|
| 31 |
+
# --- تنظیمات مدیریت کلیدها ---
|
| 32 |
GEMINI_CLIENTS_CACHE = {}
|
| 33 |
CLIENT_CACHE_LOCK = threading.Lock()
|
| 34 |
|
| 35 |
ALL_API_KEYS: list[str] = []
|
|
|
|
|
|
|
| 36 |
|
| 37 |
def _init_api_keys():
|
| 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:
|
|
|
|
| 90 |
return {"bits_per_sample": bits, "rate": rate}
|
| 91 |
|
| 92 |
def smart_text_split(text, max_size=3800):
|
| 93 |
+
# تغییر مهم: حذف کامل تقسیمبندی متن
|
| 94 |
+
# کل متن به عنوان یک تکه بازگردانده میشود تا هوش مصنوعی یکجا آن را پردازش کند
|
| 95 |
+
return [text]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
def merge_audio_files_func(file_paths, output_path):
|
| 98 |
if not PYDUB_AVAILABLE: logging.warning("⚠️ pydub برای ادغام در دسترس نیست."); return False
|
|
|
|
| 105 |
return True
|
| 106 |
except Exception as e: logging.error(f"❌ خطا در ادغام فایلهای صوتی: {e}"); return False
|
| 107 |
|
| 108 |
+
# --- منطق Gemini Live ---
|
| 109 |
+
async def generate_audio_live_with_retry(text, prompt, voice, session_id):
|
| 110 |
+
MAX_RETRIES = 50
|
| 111 |
+
live_config = types.LiveConnectConfig(
|
| 112 |
+
response_modalities=["AUDIO"],
|
| 113 |
+
speech_config=types.SpeechConfig(
|
| 114 |
+
voice_config=types.VoiceConfig(
|
| 115 |
+
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice)
|
| 116 |
+
)
|
| 117 |
+
),
|
| 118 |
+
)
|
| 119 |
+
for attempt in range(MAX_RETRIES):
|
| 120 |
+
selected_api_key, _ = get_random_api_key_and_client()
|
| 121 |
+
if not selected_api_key: break
|
| 122 |
+
client = genai.Client(http_options={"api_version": "v1beta"}, api_key=selected_api_key)
|
| 123 |
+
unique_id_for_req = str(uuid.uuid4())[:8]
|
| 124 |
+
tts_prompt = f"Please read the following text naturally: '{text}' [ID: {unique_id_for_req}]"
|
| 125 |
+
if prompt: tts_prompt = f"With a {prompt} tone, please read: '{text}'"
|
| 126 |
+
try:
|
| 127 |
+
logging.info(f"[{session_id}] (Live) تلاش {attempt+1} با کلید ...{selected_api_key[-4:]}")
|
| 128 |
+
audio_buffer = bytearray()
|
| 129 |
+
async with client.aio.live.connect(model=FIXED_MODEL_NAME_LIVE, config=live_config) as session:
|
| 130 |
+
await session.send(input=tts_prompt, end_of_turn=True)
|
| 131 |
+
async for response in session.receive():
|
| 132 |
+
if response.data: audio_buffer.extend(response.data)
|
| 133 |
+
if len(audio_buffer) > 0:
|
| 134 |
+
logging.info(f"[{session_id}] ✅ (Live) موفقیتآمیز.")
|
| 135 |
+
return audio_buffer
|
| 136 |
+
else: raise Exception("بافر صوتی خالی بود.")
|
| 137 |
+
except Exception as e:
|
| 138 |
+
logging.warning(f"[{session_id}] ⚠️ (Live) خطا در تلاش {attempt+1}: {e}")
|
| 139 |
+
time.sleep(0.5)
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
def save_pcm_to_wav(pcm_data, output_path):
|
| 143 |
+
try:
|
| 144 |
+
with wave.open(output_path, 'wb') as wf:
|
| 145 |
+
wf.setnchannels(1)
|
| 146 |
+
wf.setsampwidth(2)
|
| 147 |
+
wf.setframerate(24000)
|
| 148 |
+
wf.writeframes(pcm_data)
|
| 149 |
+
return True
|
| 150 |
+
except Exception as e:
|
| 151 |
+
logging.error(f"خطا در تبدیل PCM به WAV: {e}")
|
| 152 |
+
return False
|
| 153 |
|
| 154 |
+
# --- منطق Gemini Standard (اصلاح شده با retry_limit) ---
|
| 155 |
+
def generate_audio_chunk_standard_with_retry(chunk_text, prompt_text, voice, temp, session_id, retry_limit):
|
| 156 |
+
if not ALL_API_KEYS: raise Exception("هیچ کلید API در دسترس نیست.")
|
| 157 |
+
|
| 158 |
+
# استفاده از محدودیت تعیین شده توسط Manager
|
| 159 |
+
MAX_RETRIES = retry_limit
|
| 160 |
+
|
| 161 |
+
for attempt in range(MAX_RETRIES):
|
| 162 |
+
selected_api_key, client = get_random_api_key_and_client()
|
| 163 |
+
if not client: break
|
| 164 |
try:
|
| 165 |
+
# logging.info(f"[{session_id}] (Standard) تلاش {attempt+1}/{MAX_RETRIES} با کلید ...{selected_api_key[-4:]}")
|
| 166 |
final_text = f'{chunk_text}({prompt_text})' if prompt_text and prompt_text.strip() else chunk_text
|
| 167 |
contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
|
| 168 |
config = types.GenerateContentConfig(temperature=temp, response_modalities=["audio"],
|
| 169 |
speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
|
| 170 |
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice))))
|
|
|
|
| 171 |
|
| 172 |
+
response = client.models.generate_content(model=FIXED_MODEL_NAME_STANDARD, contents=contents, config=config)
|
| 173 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
| 174 |
+
logging.info(f"[{session_id}] ✅ (Standard) موفقیت در تلاش {attempt+1}.")
|
| 175 |
return response.candidates[0].content.parts[0].inline_data
|
| 176 |
except Exception as e:
|
| 177 |
+
logging.warning(f"[{session_id}] ⚠️ (Standard) خطا در تلاش {attempt+1}: {e}")
|
| 178 |
+
time.sleep(0.5)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
return None
|
| 180 |
|
| 181 |
+
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, session_id, use_live_model=False, retry_limit=50, fallback_to_live=False):
|
| 182 |
+
logging.info(f"[{session_id}] 🚀 شروع: Live={use_live_model}, Retry={retry_limit}, Fallback={fallback_to_live}")
|
| 183 |
temp_dir = f"temp_{session_id}"
|
| 184 |
os.makedirs(temp_dir, exist_ok=True)
|
| 185 |
output_base_name = f"{temp_dir}/audio_session_{session_id}"
|
| 186 |
+
final_output_path = f"output_{session_id}.wav"
|
| 187 |
+
|
|
|
|
|
|
|
| 188 |
try:
|
| 189 |
+
# 1. اگر دستور مستقیم استفاده از لایف باشد (مثلاً کاربر رایگان)
|
| 190 |
+
if use_live_model:
|
| 191 |
+
pcm_data = asyncio.run(generate_audio_live_with_retry(text_input, prompt_input, selected_voice, session_id))
|
| 192 |
+
if pcm_data and save_pcm_to_wav(pcm_data, final_output_path):
|
| 193 |
+
return final_output_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
else:
|
| 195 |
+
raise Exception("تولید صدا با مدل لایف ناموفق بود.")
|
| 196 |
+
|
| 197 |
+
# 2. استفاده از مدل استاندارد
|
| 198 |
+
else:
|
| 199 |
+
# تقسیمبندی هوشمند حذف شده و فقط یک چانک (کل متن) برمیگرداند
|
| 200 |
+
text_chunks = smart_text_split(text_input, DEFAULT_MAX_CHUNK_SIZE)
|
| 201 |
+
generated_files = []
|
| 202 |
+
standard_failed = False
|
| 203 |
+
|
| 204 |
+
for i, chunk in enumerate(text_chunks):
|
| 205 |
+
# تلاش با مدل استاندارد به تعداد retry_limit
|
| 206 |
+
inline_data = generate_audio_chunk_standard_with_retry(chunk, prompt_input, selected_voice, temperature_val, session_id, retry_limit)
|
| 207 |
+
|
| 208 |
+
if inline_data:
|
| 209 |
+
data_buffer = inline_data.data
|
| 210 |
+
ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
|
| 211 |
+
if "audio/L" in inline_data.mime_type and ext == ".wav":
|
| 212 |
+
data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
| 213 |
+
if not ext.startswith("."): ext = "." + ext
|
| 214 |
+
fpath = save_binary_file(f"{output_base_name}_part{i+1:03d}{ext}", data_buffer)
|
| 215 |
+
if fpath: generated_files.append(fpath)
|
| 216 |
+
else:
|
| 217 |
+
standard_failed = True
|
| 218 |
+
break # شکست در تولید یکی از چانکها (در اینجا کل متن)
|
| 219 |
+
|
| 220 |
+
# 3. بررسی شکست و Fallback
|
| 221 |
+
if standard_failed:
|
| 222 |
+
if fallback_to_live:
|
| 223 |
+
logging.info(f"[{session_id}] 🔄 مدل استاندارد شکست خورد. سوییچ به مدل لایف (Fallback)...")
|
| 224 |
+
generated_files = []
|
| 225 |
+
# فراخوانی مدل لایف برای کل متن
|
| 226 |
+
pcm_data = asyncio.run(generate_audio_live_with_retry(text_input, prompt_input, selected_voice, session_id))
|
| 227 |
+
if pcm_data and save_pcm_to_wav(pcm_data, final_output_path):
|
| 228 |
+
return final_output_path
|
| 229 |
+
else:
|
| 230 |
+
raise Exception("هم مدل استاندارد و هم مدل لایف (Fallback) شکست خوردند.")
|
| 231 |
+
else:
|
| 232 |
+
raise Exception(f"تولید صدا با مدل استاندارد پس از {retry_limit} تلاش ناموفق بود.")
|
| 233 |
+
|
| 234 |
+
# اگر استاندارد موفق بود، فایلها را ادغام کن (در اینجا معمولاً فقط یک فایل است)
|
| 235 |
+
if not generated_files: raise Exception("هیچ فایلی تولید نشد.")
|
| 236 |
+
|
| 237 |
+
if len(generated_files) > 1:
|
| 238 |
+
if PYDUB_AVAILABLE and merge_audio_files_func(generated_files, final_output_path):
|
| 239 |
+
pass
|
| 240 |
+
else:
|
| 241 |
+
shutil.move(generated_files[0], final_output_path)
|
| 242 |
else:
|
| 243 |
shutil.move(generated_files[0], final_output_path)
|
| 244 |
+
|
| 245 |
+
return final_output_path
|
| 246 |
+
|
|
|
|
|
|
|
|
|
|
| 247 |
finally:
|
| 248 |
if os.path.exists(temp_dir):
|
| 249 |
shutil.rmtree(temp_dir)
|
|
|
|
| 257 |
prompt: str | None = ""
|
| 258 |
speaker: str
|
| 259 |
temperature: float
|
| 260 |
+
use_live_model: bool = False
|
| 261 |
+
retry_limit: int = 50 # پارامتر جدید
|
| 262 |
+
fallback_to_live: bool = False # پارامتر جدید
|
| 263 |
|
|
|
|
|
|
|
|
|
|
| 264 |
@app.post("/generate")
|
| 265 |
def generate_audio_endpoint(request: TTSRequest):
|
|
|
|
| 266 |
session_id = str(uuid.uuid4())[:8]
|
|
|
|
| 267 |
try:
|
| 268 |
final_path = core_generate_audio(
|
| 269 |
text_input=request.text,
|
| 270 |
prompt_input=request.prompt,
|
| 271 |
selected_voice=request.speaker,
|
| 272 |
temperature_val=request.temperature,
|
| 273 |
+
session_id=session_id,
|
| 274 |
+
use_live_model=request.use_live_model,
|
| 275 |
+
retry_limit=request.retry_limit,
|
| 276 |
+
fallback_to_live=request.fallback_to_live
|
| 277 |
)
|
| 278 |
if final_path and os.path.exists(final_path):
|
| 279 |
from fastapi.responses import FileResponse
|
| 280 |
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))
|
| 281 |
else:
|
| 282 |
+
raise HTTPException(status_code=500, detail="خطا در تولید فایل صوتی.")
|
| 283 |
except Exception as e:
|
| 284 |
+
logging.error(f"[{session_id}] ❌ خطا: {e}")
|
| 285 |
raise HTTPException(status_code=500, detail=str(e))
|
| 286 |
|
| 287 |
@app.get("/")
|
| 288 |
def health_check():
|
| 289 |
return {"status": "ok", "message": "TTS Worker is running."}
|
| 290 |
|
|
|
|
|
|
|
| 291 |
if __name__ == "__main__":
|
| 292 |
port = int(os.environ.get("PORT", 7860))
|
| 293 |
uvicorn.run(app, host="0.0.0.0", port=port, reload=False)
|