Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,23 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import mimetypes
|
| 4 |
import os
|
|
|
|
|
|
|
| 5 |
import re
|
| 6 |
import struct
|
| 7 |
import time
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from google import genai
|
| 12 |
from google.genai import types
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
try:
|
| 17 |
from pydub import AudioSegment
|
|
@@ -19,56 +25,31 @@ try:
|
|
| 19 |
except ImportError:
|
| 20 |
PYDUB_AVAILABLE = False
|
| 21 |
|
| 22 |
-
# ---
|
| 23 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
| 24 |
-
# --- END: پیکربندی لاگینگ ---
|
| 25 |
|
| 26 |
-
# --- START:
|
|
|
|
|
|
|
| 27 |
ALL_API_KEYS: list[str] = []
|
| 28 |
NEXT_KEY_INDEX: int = 0
|
| 29 |
KEY_LOCK: threading.Lock = threading.Lock()
|
| 30 |
|
| 31 |
def _init_api_keys():
|
| 32 |
-
"""
|
| 33 |
-
کلیدهای API را از یک متغیر محیطی واحد شناسایی میکند.
|
| 34 |
-
"""
|
| 35 |
global ALL_API_KEYS
|
| 36 |
all_keys_string = os.environ.get("ALL_GEMINI_API_KEYS")
|
| 37 |
if all_keys_string:
|
| 38 |
ALL_API_KEYS = [key.strip() for key in all_keys_string.split(',') if key.strip()]
|
| 39 |
logging.info(f"✅ تعداد {len(ALL_API_KEYS)} کلید API جیمینای بارگذاری شد.")
|
| 40 |
if not ALL_API_KEYS:
|
| 41 |
-
logging.warning("⛔️
|
| 42 |
-
|
| 43 |
-
_init_api_keys()
|
| 44 |
-
|
| 45 |
-
def get_next_api_key():
|
| 46 |
-
"""
|
| 47 |
-
کلید API بعدی را به صورت چرخشی برمیگرداند.
|
| 48 |
-
"""
|
| 49 |
-
global NEXT_KEY_INDEX, ALL_API_KEYS, KEY_LOCK
|
| 50 |
-
with KEY_LOCK:
|
| 51 |
-
if not ALL_API_KEYS:
|
| 52 |
-
return None, None
|
| 53 |
-
key_to_use = ALL_API_KEYS[NEXT_KEY_INDEX % len(ALL_API_KEYS)]
|
| 54 |
-
key_display_index = (NEXT_KEY_INDEX % len(ALL_API_KEYS)) + 1
|
| 55 |
-
NEXT_KEY_INDEX += 1
|
| 56 |
-
return key_to_use, key_display_index
|
| 57 |
-
# --- END: منطق مدیریت API Key ---
|
| 58 |
|
| 59 |
# --- ثابتها ---
|
| 60 |
-
SPEAKER_VOICES = [
|
| 61 |
-
"Achird", "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager",
|
| 62 |
-
"Sulafat", "Laomedeia", "Achernar", "Alnilam", "Schedar", "Gacrux",
|
| 63 |
-
"Pulcherrima", "Umbriel", "Algieba", "Despina", "Erinome", "Algenib",
|
| 64 |
-
"Rasalthgeti", "Orus", "Aoede", "Callirrhoe", "Autonoe", "Enceladus",
|
| 65 |
-
"Iapetus", "Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda"
|
| 66 |
-
]
|
| 67 |
FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts"
|
| 68 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 69 |
DEFAULT_SLEEP_BETWEEN_REQUESTS = 8
|
| 70 |
|
| 71 |
-
# --- توابع کمکی
|
| 72 |
def save_binary_file(file_name, data):
|
| 73 |
try:
|
| 74 |
with open(file_name, "wb") as f: f.write(data)
|
|
@@ -126,21 +107,22 @@ def merge_audio_files_func(file_paths, output_path):
|
|
| 126 |
return True
|
| 127 |
except Exception as e: logging.error(f"❌ خطا در ادغام فایلهای صوتی: {e}"); return False
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
return
|
| 137 |
|
|
|
|
|
|
|
|
|
|
| 138 |
for _ in range(len(ALL_API_KEYS)):
|
| 139 |
selected_api_key, key_idx_display = get_next_api_key()
|
| 140 |
-
if not selected_api_key:
|
| 141 |
-
|
| 142 |
-
break
|
| 143 |
-
logging.info(f"[{session_id}] ⚙️ تلاش برای تولید قطعه با کلید API شماره {key_idx_display} (...{selected_api_key[-4:]})")
|
| 144 |
try:
|
| 145 |
client = genai.Client(api_key=selected_api_key)
|
| 146 |
final_text = f'"{prompt_text}"\n{chunk_text}' if prompt_text and prompt_text.strip() else chunk_text
|
|
@@ -152,37 +134,18 @@ def generate_audio_chunk_with_retry(chunk_text, prompt_text, voice, temp, sessio
|
|
| 152 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
| 153 |
logging.info(f"[{session_id}] ✅ قطعه با موفقیت توسط کلید شماره {key_idx_display} تولید شد.")
|
| 154 |
return response.candidates[0].content.parts[0].inline_data
|
| 155 |
-
else:
|
| 156 |
-
logging.warning(f"[{session_id}] ⚠️ پاسخ API برای قطعه با کلید شماره {key_idx_display} بدون داده صوتی بود.")
|
| 157 |
except Exception as e:
|
| 158 |
logging.error(f"[{session_id}] ❌ خطا در تولید قطعه با کلید شماره {key_idx_display}: {e}.")
|
| 159 |
-
logging.error(f"[{session_id}] ❌ تمام کلیدهای API امتحان شدند اما هیچکدام موفق به تولید قطعه نشدند.")
|
| 160 |
return None
|
| 161 |
|
| 162 |
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, session_id):
|
| 163 |
-
"""
|
| 164 |
-
هسته اصلی تولید صدا، اکنون با شناسه جلسه برای مدیریت فایلها.
|
| 165 |
-
"""
|
| 166 |
logging.info(f"[{session_id}] 🚀 شروع فرآیند تولید صدا.")
|
| 167 |
-
|
| 168 |
-
# تغییر: ایجاد یک دایرکتوری موقت منحصر به فرد برای هر درخواست
|
| 169 |
temp_dir = f"temp_{session_id}"
|
| 170 |
os.makedirs(temp_dir, exist_ok=True)
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
if not text_input or not text_input.strip():
|
| 176 |
-
logging.error(f"[{session_id}] ❌ متن ورودی خالی است.")
|
| 177 |
-
shutil.rmtree(temp_dir)
|
| 178 |
-
return None
|
| 179 |
-
|
| 180 |
-
text_chunks = smart_text_split(text_input, max_chunk)
|
| 181 |
-
if not text_chunks:
|
| 182 |
-
logging.error(f"[{session_id}] ❌ متن قابل پردازش به قطعات کوچکتر نیست.")
|
| 183 |
-
shutil.rmtree(temp_dir)
|
| 184 |
-
return None
|
| 185 |
-
|
| 186 |
generated_files = []
|
| 187 |
try:
|
| 188 |
for i, chunk in enumerate(text_chunks):
|
|
@@ -194,183 +157,76 @@ def core_generate_audio(text_input, prompt_input, selected_voice, temperature_va
|
|
| 194 |
if "audio/L" in inline_data.mime_type and ext == ".wav":
|
| 195 |
data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
| 196 |
if not ext.startswith("."): ext = "." + ext
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
fpath = save_binary_file(f"{fname_base}{ext}", data_buffer)
|
| 200 |
-
if fpath:
|
| 201 |
-
generated_files.append(fpath)
|
| 202 |
-
else:
|
| 203 |
-
logging.error(f"[{session_id}] ❌ موفق به ذخیره فایل برای قطعه {i+1} نشدیم.")
|
| 204 |
-
continue
|
| 205 |
else:
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
if not generated_files:
|
| 212 |
-
logging.error(f"[{session_id}] ❌ هیچ فایل صوتی تولید نشد.")
|
| 213 |
-
return None
|
| 214 |
-
|
| 215 |
-
final_audio_file = None
|
| 216 |
-
# نام فایل نهایی نیز منحصر به فرد خواهد بود
|
| 217 |
-
final_output_path = f"output_{session_id}.wav"
|
| 218 |
-
|
| 219 |
if len(generated_files) > 1:
|
| 220 |
-
if PYDUB_AVAILABLE:
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
else: # در صورت شکست ادغام، اولین قطعه را برگردان
|
| 224 |
-
shutil.move(generated_files[0], final_output_path)
|
| 225 |
-
final_audio_file = final_output_path
|
| 226 |
-
else:
|
| 227 |
-
logging.warning(f"[{session_id}] ⚠️ pydub در دسترس نیست. اولین قطعه صوتی ارائه میشود.")
|
| 228 |
shutil.move(generated_files[0], final_output_path)
|
| 229 |
final_audio_file = final_output_path
|
| 230 |
-
|
| 231 |
shutil.move(generated_files[0], final_output_path)
|
| 232 |
final_audio_file = final_output_path
|
| 233 |
-
|
| 234 |
-
if final_audio_file and os.path.exists(final_audio_file):
|
| 235 |
-
logging.info(f"[{session_id}] ✅ فایل صوتی نهایی با موفقیت تولید شد: {os.path.basename(final_audio_file)}")
|
| 236 |
-
else:
|
| 237 |
-
logging.error(f"[{session_id}] ❓ وضعیت نامشخص برای فایل نهایی.")
|
| 238 |
-
return None
|
| 239 |
-
|
| 240 |
return final_audio_file
|
| 241 |
finally:
|
| 242 |
-
# پاکسازی دایرکتوری موقت پس از اتمام کار
|
| 243 |
if os.path.exists(temp_dir):
|
| 244 |
shutil.rmtree(temp_dir)
|
| 245 |
-
logging.info(f"[{session_id}] 🧹 دایرکتوری موقت '{temp_dir}' پاکسازی شد.")
|
| 246 |
|
| 247 |
-
# --- END: م
|
| 248 |
|
| 249 |
-
def gradio_tts_interface(use_file_input, uploaded_file, text_to_speak, speech_prompt, speaker_voice, temperature, progress=gr.Progress(track_tqdm=True)):
|
| 250 |
-
# تغییر: ایجاد یک شناسه منحصر به فرد برای هر بار اجرای این تابع
|
| 251 |
-
session_id = str(uuid.uuid4())[:8] # استفاده از ۸ کاراکتر اول UUID
|
| 252 |
-
logging.info(f"[{session_id}] 🏁 درخواست جدید دریافت شد.")
|
| 253 |
-
|
| 254 |
-
actual_text = ""
|
| 255 |
-
if use_file_input:
|
| 256 |
-
if uploaded_file:
|
| 257 |
-
try:
|
| 258 |
-
with open(uploaded_file.name, 'r', encoding='utf-8') as f: actual_text = f.read().strip()
|
| 259 |
-
if not actual_text:
|
| 260 |
-
logging.error(f"[{session_id}] ❌ فایل آپلود شده خالی است."); return None
|
| 261 |
-
except Exception as e:
|
| 262 |
-
logging.error(f"[{session_id}] ❌ خطا در خواندن فایل آپلود شده: {e}"); return None
|
| 263 |
-
else:
|
| 264 |
-
logging.warning(f"[{session_id}] ❌ گزینه استفاده از فایل انتخاب شده اما فایلی آپلود نشده."); return None
|
| 265 |
-
else:
|
| 266 |
-
actual_text = text_to_speak
|
| 267 |
-
if not actual_text or not actual_text.strip():
|
| 268 |
-
logging.warning(f"[{session_id}] ❌ متن ورودی برای تبدیل خالی است."); return None
|
| 269 |
-
|
| 270 |
-
# ارسال session_id به تابع اصلی
|
| 271 |
-
final_path = core_generate_audio(actual_text, speech_prompt, speaker_voice, temperature, session_id)
|
| 272 |
-
return final_path
|
| 273 |
|
| 274 |
-
# ---
|
| 275 |
-
|
| 276 |
-
RESTART_INTERVAL_SECONDS = 24 * 60 * 60
|
| 277 |
-
logging.info(f"سرویس برای ریاستارت خودکار پس از {RESTART_INTERVAL_SECONDS / 3600:.0f} ساعت زمانبندی شده است.")
|
| 278 |
-
time.sleep(RESTART_INTERVAL_SECONDS)
|
| 279 |
-
logging.info(f"زمان ریاستارت خودکار فرا رسیده است. برنامه برای ریاستارت خارج میشود...")
|
| 280 |
-
os._exit(1)
|
| 281 |
|
| 282 |
-
# ---
|
| 283 |
-
|
| 284 |
-
custom_css_inspired_by_image = f"""
|
| 285 |
-
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700;800&display=swap');
|
| 286 |
-
:root {{
|
| 287 |
-
--app-font: 'Vazirmatn', sans-serif;
|
| 288 |
-
--app-header-grad-start: #2980b9;
|
| 289 |
-
--app-header-grad-end: #2ecc71;
|
| 290 |
-
--app-panel-bg: #FFFFFF;
|
| 291 |
-
--app-input-bg: #F7F7F7;
|
| 292 |
-
--app-button-bg: #2979FF;
|
| 293 |
-
--app-main-bg: linear-gradient(170deg, #E0F2FE 0%, #F3E8FF 100%);
|
| 294 |
-
--app-text-primary: #333;
|
| 295 |
-
--app-text-secondary: #555;
|
| 296 |
-
--app-border-color: #E0E0E0;
|
| 297 |
-
--radius-card: 20px;
|
| 298 |
-
--radius-input: 8px;
|
| 299 |
-
--shadow-card: 0 10px 30px -5px rgba(0,0,0,0.1);
|
| 300 |
-
--shadow-button: 0 4px 10px -2px rgba(41,121,255,0.5);
|
| 301 |
-
}}
|
| 302 |
-
body, .gradio-container {{ font-family: var(--app-font); direction: rtl; background: var(--app-main-bg); color: var(--app-text-primary); font-size: 16px; line-height: 1.65; }}
|
| 303 |
-
.gradio-container {{ max-width:100% !important; min-height:100vh; margin:0 !important; padding:0 !important; display:flex; flex-direction:column; }}
|
| 304 |
-
.app-header-alpha {{ padding: 3rem 1.5rem 4rem 1.5rem; text-align: center; background-image: linear-gradient(135deg, var(--app-header-grad-start) 0%, var(--app-header-grad-end) 100%); color: white; border-bottom-left-radius: var(--radius-card); border-bottom-right-radius: var(--radius-card); box-shadow: 0 6px 20px -5px rgba(0,0,0,0.2); }}
|
| 305 |
-
.app-header-alpha h1 {{ font-size: 2.4em; font-weight: 800; margin:0 0 0.5rem 0; text-shadow: 0 2px 4px rgba(0,0,0,0.15); }}
|
| 306 |
-
.app-header-alpha p {{ font-size: 1.1em; color: rgba(255,255,255,0.9); margin-top:0; opacity: 0.9; }}
|
| 307 |
-
.main-content-panel-alpha {{ padding: 1.8rem 1.5rem; max-width: 680px; margin: -2.5rem auto 2rem auto; width: 90%; background-color: var(--app-panel-bg); border-radius: var(--radius-card); box-shadow: var(--shadow-card); position:relative; z-index:10; }}
|
| 308 |
-
@media (max-width: 768px) {{ .main-content-panel-alpha {{ width: 95%; padding: 1.5rem 1rem; margin-top: -2rem; }} .app-header-alpha h1 {{font-size:2em;}} .app-header-alpha p {{font-size:1em;}} }}
|
| 309 |
-
footer {{display:none !important;}}
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
label > .label-text {{ font-weight: 700 !important; color: var(--app-text-primary) !important; font-size: 0.95em !important; margin-bottom: 0.5rem !important; }}
|
| 317 |
-
.section-title-main-alpha {{ font-size: 1.1em; color: var(--app-text-secondary); margin-bottom:1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--app-border-color); font-weight:500; text-align:right; }}
|
| 318 |
-
label > .label-text::before {{ margin-left: 8px; vertical-align: middle; opacity: 0.7; }}
|
| 319 |
-
label[for*="text_input_main_alpha_v3"] > .label-text::before {{ content: '📝'; }}
|
| 320 |
-
label[for*="speech_prompt_alpha_v3"] > .label-text::before {{ content: '🗣️'; }}
|
| 321 |
-
label[for*="speaker_voice_alpha_v3"] > .label-text::before {{ content: '🎤'; }}
|
| 322 |
-
label[for*="temperature_slider_alpha_v3"] > .label-text::before {{ content: '🌡️'; }}
|
| 323 |
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
<p>جادوی تبدیل متن به صدا در دستان شما</p>
|
| 333 |
-
</div>
|
| 334 |
-
"""
|
| 335 |
|
| 336 |
-
|
| 337 |
-
gr.HTML(alpha_header_html_v3)
|
| 338 |
-
with gr.Column(elem_classes=["main-content-panel-alpha"]):
|
| 339 |
-
use_file_input_cb = gr.Checkbox(label="📄 استفاده از فایل متنی (.txt)", value=False, elem_id="use_file_cb_alpha_v3")
|
| 340 |
-
uploaded_file_input = gr.File(label=" ", file_types=['.txt'], visible=False, elem_id="file_uploader_alpha_main_v3")
|
| 341 |
-
text_to_speak_tb = gr.Textbox(label="متن فارسی برای تبدیل", placeholder="مثال: سلام، فردا هوا چطور است؟", lines=5, value="", visible=True, elem_id="text_input_main_alpha_v3")
|
| 342 |
-
use_file_input_cb.change(
|
| 343 |
-
fn=lambda x: (gr.update(visible=x, label=" " if x else "متن فارسی برای تبدیل"), gr.update(visible=not x)),
|
| 344 |
-
inputs=use_file_input_cb,
|
| 345 |
-
outputs=[uploaded_file_input, text_to_speak_tb]
|
| 346 |
-
)
|
| 347 |
-
speech_prompt_tb = gr.Textbox(label="سبک گفتار (اختیاری)", placeholder="مثال: با لحنی شاد و پرانرژی", value="با لحنی دوستانه و رسا صحبت کن.", lines=2, elem_id="speech_prompt_alpha_v3")
|
| 348 |
-
speaker_voice_dd = gr.Dropdown(SPEAKER_VOICES, label="انتخاب گوینده و لهجه", value="Charon", elem_id="speaker_voice_alpha_v3")
|
| 349 |
-
temperature_slider = gr.Slider(minimum=0.1, maximum=1.5, step=0.05, value=0.9, label="میزان خلاقیت صدا", elem_id="temperature_slider_alpha_v3")
|
| 350 |
-
gr.Markdown("<p class='temp_description_class_alpha_v3'>مقادیر بالاتر = تنوع بیشتر، مقادیر پایینتر = یکنواختی بیشتر.</p>")
|
| 351 |
-
generate_button = gr.Button("🚀 تولید و پخش صدا", elem_classes=["generate-button-final"], elem_id="generate_button_alpha_v3")
|
| 352 |
-
output_audio = gr.Audio(label=" ", type="filepath", elem_id="output_audio_player_alpha_v3")
|
| 353 |
-
generate_button.click(
|
| 354 |
-
fn=gradio_tts_interface,
|
| 355 |
-
inputs=[use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider],
|
| 356 |
-
outputs=[output_audio]
|
| 357 |
-
)
|
| 358 |
-
gr.Markdown("<h3 class='section-title-main-alpha' style='margin-top:2.5rem; text-align:center; border-bottom:none;'>نمونههای کاربردی</h3>", elem_id="examples_section_title_v3")
|
| 359 |
-
gr.Examples(
|
| 360 |
-
examples=[
|
| 361 |
-
[False, None, "سلام بر شما، امیدوارم روز خوبی داشته باشید.", "با لحنی گرم و صمیمی.", "Zephyr", 0.85],
|
| 362 |
-
[False, None, "این یک آزمایش برای بررسی کیفیت صدای تولید شده توسط هوش مصنوعی آلفا است.", "با صدایی طبیعی و روان.", "Charon", 0.9],
|
| 363 |
-
],
|
| 364 |
-
inputs=[use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider],
|
| 365 |
-
outputs=[output_audio],
|
| 366 |
-
fn=gradio_tts_interface,
|
| 367 |
-
cache_examples=False
|
| 368 |
-
)
|
| 369 |
-
gr.Markdown("<p class='app-footer-final'>Alpha Language Learning © 2024</p>")
|
| 370 |
|
|
|
|
| 371 |
if __name__ == "__main__":
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py - نسخه کامل و نهایی برای تمام اسپیسهای Hugging Face
|
| 2 |
+
|
|
|
|
| 3 |
import os
|
| 4 |
+
import sys
|
| 5 |
+
import traceback
|
| 6 |
import re
|
| 7 |
import struct
|
| 8 |
import time
|
| 9 |
+
import uuid
|
| 10 |
+
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
|
| 17 |
from google.genai import types
|
| 18 |
+
|
| 19 |
+
# اضافه کردن uvicorn برای اجرا از داخل اسکریپت
|
| 20 |
+
import uvicorn
|
| 21 |
|
| 22 |
try:
|
| 23 |
from pydub import AudioSegment
|
|
|
|
| 25 |
except ImportError:
|
| 26 |
PYDUB_AVAILABLE = False
|
| 27 |
|
| 28 |
+
# --- پیکربندی لاگینگ ---
|
| 29 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
|
|
|
| 30 |
|
| 31 |
+
# --- START: تعریف تمام توابع کمکی ---
|
| 32 |
+
|
| 33 |
+
# --- منطق مدیریت API Key ---
|
| 34 |
ALL_API_KEYS: list[str] = []
|
| 35 |
NEXT_KEY_INDEX: int = 0
|
| 36 |
KEY_LOCK: threading.Lock = threading.Lock()
|
| 37 |
|
| 38 |
def _init_api_keys():
|
|
|
|
|
|
|
|
|
|
| 39 |
global ALL_API_KEYS
|
| 40 |
all_keys_string = os.environ.get("ALL_GEMINI_API_KEYS")
|
| 41 |
if all_keys_string:
|
| 42 |
ALL_API_KEYS = [key.strip() for key in all_keys_string.split(',') if key.strip()]
|
| 43 |
logging.info(f"✅ تعداد {len(ALL_API_KEYS)} کلید API جیمینای بارگذاری شد.")
|
| 44 |
if not ALL_API_KEYS:
|
| 45 |
+
logging.warning("⛔️ هشدار: هیچ Secret با نام ALL_GEMINI_API_KEYS یافت نشد! برنامه بدون کلید API کار نخواهد کرد.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
# --- ثابتها ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts"
|
| 49 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 50 |
DEFAULT_SLEEP_BETWEEN_REQUESTS = 8
|
| 51 |
|
| 52 |
+
# --- توابع کمکی فایل و صدا ---
|
| 53 |
def save_binary_file(file_name, data):
|
| 54 |
try:
|
| 55 |
with open(file_name, "wb") as f: f.write(data)
|
|
|
|
| 107 |
return True
|
| 108 |
except Exception as e: logging.error(f"❌ خطا در ادغام فایلهای صوتی: {e}"); return False
|
| 109 |
|
| 110 |
+
def get_next_api_key():
|
| 111 |
+
global NEXT_KEY_INDEX, ALL_API_KEYS, KEY_LOCK
|
| 112 |
+
with KEY_LOCK:
|
| 113 |
+
if not ALL_API_KEYS: return None, None
|
| 114 |
+
key_to_use = ALL_API_KEYS[NEXT_KEY_INDEX % len(ALL_API_KEYS)]
|
| 115 |
+
key_display_index = (NEXT_KEY_INDEX % len(ALL_API_KEYS)) + 1
|
| 116 |
+
NEXT_KEY_INDEX += 1
|
| 117 |
+
return key_to_use, key_display_index
|
| 118 |
|
| 119 |
+
# --- منطق اصلی تولید صدا ---
|
| 120 |
+
def generate_audio_chunk_with_retry(chunk_text, prompt_text, voice, temp, session_id):
|
| 121 |
+
if not ALL_API_KEYS: raise Exception("هیچ کلید API برای پردازش در دسترس نیست.")
|
| 122 |
for _ in range(len(ALL_API_KEYS)):
|
| 123 |
selected_api_key, key_idx_display = get_next_api_key()
|
| 124 |
+
if not selected_api_key: break
|
| 125 |
+
logging.info(f"[{session_id}] ⚙️ تلاش برای تولید قطعه با کلید API شماره {key_idx_display}")
|
|
|
|
|
|
|
| 126 |
try:
|
| 127 |
client = genai.Client(api_key=selected_api_key)
|
| 128 |
final_text = f'"{prompt_text}"\n{chunk_text}' if prompt_text and prompt_text.strip() else chunk_text
|
|
|
|
| 134 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
| 135 |
logging.info(f"[{session_id}] ✅ قطعه با موفقیت توسط کلید شماره {key_idx_display} تولید شد.")
|
| 136 |
return response.candidates[0].content.parts[0].inline_data
|
|
|
|
|
|
|
| 137 |
except Exception as e:
|
| 138 |
logging.error(f"[{session_id}] ❌ خطا در تولید قطعه با کلید شماره {key_idx_display}: {e}.")
|
|
|
|
| 139 |
return None
|
| 140 |
|
| 141 |
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, session_id):
|
|
|
|
|
|
|
|
|
|
| 142 |
logging.info(f"[{session_id}] 🚀 شروع فرآیند تولید صدا.")
|
|
|
|
|
|
|
| 143 |
temp_dir = f"temp_{session_id}"
|
| 144 |
os.makedirs(temp_dir, exist_ok=True)
|
| 145 |
+
output_base_name = f"{temp_dir}/audio_session_{session_id}"
|
| 146 |
+
if not text_input or not text_input.strip(): raise ValueError("متن ورودی خالی است.")
|
| 147 |
+
text_chunks = smart_text_split(text_input, DEFAULT_MAX_CHUNK_SIZE)
|
| 148 |
+
if not text_chunks: raise ValueError("متن قابل پردازش به قطعات کوچکتر نیست.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
generated_files = []
|
| 150 |
try:
|
| 151 |
for i, chunk in enumerate(text_chunks):
|
|
|
|
| 157 |
if "audio/L" in inline_data.mime_type and ext == ".wav":
|
| 158 |
data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
| 159 |
if not ext.startswith("."): ext = "." + ext
|
| 160 |
+
fpath = save_binary_file(f"{output_base_name}_part{i+1:03d}{ext}", data_buffer)
|
| 161 |
+
if fpath: generated_files.append(fpath)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
else:
|
| 163 |
+
raise Exception(f"فرآیند متوقف شد زیرا تولید قطعه {i+1} با تمام کلیدهای موجود ناموفق بود.")
|
| 164 |
+
if i < len(text_chunks) - 1 and len(text_chunks) > 1: time.sleep(DEFAULT_SLEEP_BETWEEN_REQUESTS)
|
| 165 |
+
if not generated_files: raise Exception("هیچ فایل صوتی تولید نشد.")
|
| 166 |
+
final_output_path = f"output_{session_id}.wav"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
if len(generated_files) > 1:
|
| 168 |
+
if PYDUB_AVAILABLE and merge_audio_files_func(generated_files, final_output_path):
|
| 169 |
+
final_audio_file = final_output_path
|
| 170 |
+
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
shutil.move(generated_files[0], final_output_path)
|
| 172 |
final_audio_file = final_output_path
|
| 173 |
+
else:
|
| 174 |
shutil.move(generated_files[0], final_output_path)
|
| 175 |
final_audio_file = final_output_path
|
| 176 |
+
logging.info(f"[{session_id}] ✅ فایل صوتی نهایی با موفقیت تولید شد: {os.path.basename(final_audio_file)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
return final_audio_file
|
| 178 |
finally:
|
|
|
|
| 179 |
if os.path.exists(temp_dir):
|
| 180 |
shutil.rmtree(temp_dir)
|
|
|
|
| 181 |
|
| 182 |
+
# --- END: تعریف تمام توابع کمکی ---
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
# --- اجرای کدهای اولیه برنامه ---
|
| 186 |
+
_init_api_keys()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
+
# --- تعریف اپلیکیشن FastAPI ---
|
| 189 |
+
app = FastAPI(title="Alpha TTS Worker API")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
+
class TTSRequest(BaseModel):
|
| 192 |
+
text: str
|
| 193 |
+
prompt: str | None = ""
|
| 194 |
+
speaker: str
|
| 195 |
+
temperature: float
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
@app.post("/generate")
|
| 198 |
+
async def generate_audio_endpoint(request: TTSRequest):
|
| 199 |
+
session_id = str(uuid.uuid4())[:8]
|
| 200 |
+
logging.info(f"[{session_id}] 🏁 درخواست جدید API در این Worker دریافت شد.")
|
| 201 |
+
try:
|
| 202 |
+
final_path = core_generate_audio(
|
| 203 |
+
text_input=request.text,
|
| 204 |
+
prompt_input=request.prompt,
|
| 205 |
+
selected_voice=request.speaker,
|
| 206 |
+
temperature_val=request.temperature,
|
| 207 |
+
session_id=session_id
|
| 208 |
+
)
|
| 209 |
+
if final_path and os.path.exists(final_path):
|
| 210 |
+
from fastapi.responses import FileResponse
|
| 211 |
+
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))
|
| 212 |
+
else:
|
| 213 |
+
raise HTTPException(status_code=500, detail="خطا در تولید فایل صوتی در Worker.")
|
| 214 |
+
except Exception as e:
|
| 215 |
+
logging.error(f"[{session_id}] ❌ خطای کلی در Worker: {e}")
|
| 216 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 217 |
|
| 218 |
+
@app.get("/")
|
| 219 |
+
def health_check():
|
| 220 |
+
return {"status": "ok", "message": "TTS Worker is running."}
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
logging.info("✅✅✅ Application logic initialized successfully. Starting Uvicorn server...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
+
# --- START: بخش جدید برای اجرای سرور ---
|
| 225 |
if __name__ == "__main__":
|
| 226 |
+
# پورت را از متغیرهای محیطی هاگینگ فیس یا به صورت پیشفرض 7860 بخوان
|
| 227 |
+
port = int(os.environ.get("PORT", 7860))
|
| 228 |
+
|
| 229 |
+
# اجرای سرور Uvicorn از داخل کد پایتون
|
| 230 |
+
# reload=False برای محیط production مهم است
|
| 231 |
+
uvicorn.run(app, host="0.0.0.0", port=port, reload=False)
|
| 232 |
+
# --- END: بخش جدید برای اجرای سرور ---
|