Update app.py
Browse files
app.py
CHANGED
|
@@ -15,6 +15,41 @@ try:
|
|
| 15 |
except ImportError:
|
| 16 |
PYDUB_AVAILABLE = False
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
SPEAKER_VOICES = [
|
| 19 |
"Achird", "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager",
|
| 20 |
"Sulafat", "Laomedeia", "Achernar", "Alnilam", "Schedar", "Gacrux",
|
|
@@ -25,18 +60,15 @@ SPEAKER_VOICES = [
|
|
| 25 |
FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts"
|
| 26 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 27 |
DEFAULT_SLEEP_BETWEEN_REQUESTS = 8
|
| 28 |
-
DEFAULT_OUTPUT_FILENAME_BASE = "alpha_tts_audio"
|
| 29 |
|
| 30 |
-
def
|
| 31 |
-
log_list.append(message) # برای دیباگ داخلی
|
| 32 |
-
|
| 33 |
-
def save_binary_file(file_name, data, log_list):
|
| 34 |
try:
|
| 35 |
with open(file_name, "wb") as f: f.write(data)
|
| 36 |
-
_log(f"
|
| 37 |
return file_name
|
| 38 |
except Exception as e:
|
| 39 |
-
_log(f"❌ خطا در ذخیره فایل {file_name}: {e}"
|
| 40 |
return None
|
| 41 |
|
| 42 |
def convert_to_wav(audio_data: bytes, mime_type: str) -> bytes:
|
|
@@ -60,7 +92,7 @@ def parse_audio_mime_type(mime_type: str) -> dict[str, int]:
|
|
| 60 |
except: pass
|
| 61 |
return {"bits_per_sample": bits, "rate": rate}
|
| 62 |
|
| 63 |
-
def smart_text_split(text, max_size=3800
|
| 64 |
if len(text) <= max_size: return [text]
|
| 65 |
chunks, current_chunk = [], ""
|
| 66 |
sentences = re.split(r'(?<=[.!?؟])\s+', text)
|
|
@@ -75,42 +107,60 @@ def smart_text_split(text, max_size=3800, log_list=None):
|
|
| 75 |
else: current_chunk += (" " if current_chunk else "") + sentence
|
| 76 |
if current_chunk: chunks.append(current_chunk.strip())
|
| 77 |
final_chunks = [c for c in chunks if c]
|
| 78 |
-
|
| 79 |
return final_chunks
|
| 80 |
|
| 81 |
-
def merge_audio_files_func(file_paths, output_path
|
| 82 |
-
if not PYDUB_AVAILABLE: _log("
|
| 83 |
try:
|
| 84 |
-
_log(f"🔗 ادغام {len(file_paths)} فایل صوتی..."
|
| 85 |
combined = AudioSegment.empty()
|
| 86 |
for i, fp in enumerate(file_paths):
|
| 87 |
if os.path.exists(fp): combined += AudioSegment.from_file(fp) + (AudioSegment.silent(duration=150) if i < len(file_paths) - 1 else AudioSegment.empty())
|
| 88 |
-
else: _log(f"⚠️ فایل پیدا نشد: {fp}"
|
| 89 |
combined.export(output_path, format="wav")
|
| 90 |
-
_log(f"✅ فایل ادغام شده: {output_path}"
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
-
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val
|
| 94 |
-
|
|
|
|
|
|
|
| 95 |
max_chunk, sleep_time = DEFAULT_MAX_CHUNK_SIZE, DEFAULT_SLEEP_BETWEEN_REQUESTS
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
generated_files = []
|
| 106 |
for i, chunk in enumerate(text_chunks):
|
| 107 |
-
_log(f"🔊 پردازش قطعه {i+1}/{len(text_chunks)}..."
|
| 108 |
final_text = f'"{prompt_input}"\n{chunk}' if prompt_input and prompt_input.strip() else chunk
|
| 109 |
contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
|
| 110 |
config = types.GenerateContentConfig(temperature=temperature_val, response_modalities=["audio"],
|
| 111 |
speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
|
| 112 |
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=selected_voice))))
|
| 113 |
-
fname_base = f"{output_base_name}_part{i+1:03d}"
|
| 114 |
try:
|
| 115 |
response = client.models.generate_content(model=FIXED_MODEL_NAME, contents=contents, config=config)
|
| 116 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
|
@@ -119,121 +169,115 @@ def core_generate_audio(text_input, prompt_input, selected_voice, temperature_va
|
|
| 119 |
ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
|
| 120 |
if "audio/L" in inline_data.mime_type and ext == ".wav": data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
| 121 |
if not ext.startswith("."): ext = "." + ext
|
| 122 |
-
fpath = save_binary_file(f"{fname_base}{ext}", data_buffer
|
| 123 |
if fpath: generated_files.append(fpath)
|
| 124 |
-
else: _log(f"⚠️ پاسخ API برای قطعه {i+1} بدون داده
|
| 125 |
-
except Exception as e:
|
|
|
|
|
|
|
| 126 |
if i < len(text_chunks) - 1 and len(text_chunks) > 1: time.sleep(sleep_time)
|
| 127 |
|
| 128 |
-
if not generated_files:
|
| 129 |
-
|
|
|
|
| 130 |
|
| 131 |
final_audio_file = None
|
| 132 |
-
# نام فایل نهایی ادغام شده یا تکی
|
| 133 |
-
# استفاده از یک نام ثابت با افزودن timestamp برای جلوگیری از کش شدن توسط مرورگر یا CDN
|
| 134 |
-
# اما برای سادگی و چون پلیر Gradio معمولا با محتوا آپدیت میشود، فعلا timestamp نمیگذاریم.
|
| 135 |
final_output_path_base = f"{output_base_name}_final"
|
| 136 |
|
| 137 |
if len(generated_files) > 1:
|
| 138 |
if PYDUB_AVAILABLE:
|
| 139 |
-
merged_fn = f"{final_output_path_base}.wav"
|
| 140 |
-
if os.path.exists(merged_fn): os.remove(merged_fn)
|
| 141 |
-
if merge_audio_files_func(generated_files, merged_fn
|
| 142 |
final_audio_file = merged_fn
|
| 143 |
-
|
| 144 |
-
if os.path.abspath(fp) != os.path.abspath(merged_fn):
|
| 145 |
-
try: os.remove(fp)
|
| 146 |
-
except: pass
|
| 147 |
-
else: # اگر ادغام ناموفق بود، اولین قطعه با نام استاندارد ارائه میشود
|
| 148 |
if generated_files:
|
| 149 |
try:
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
| 152 |
except Exception as e_rename:
|
| 153 |
-
_log(f"خطا در تغییر نام فایل اولین
|
| 154 |
-
final_audio_file = generated_files[0]
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
| 161 |
else:
|
| 162 |
-
_log("⚠️ pydub نیست. اولین قطعه ارائه میشود."
|
| 163 |
if generated_files:
|
| 164 |
try:
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
| 167 |
for i_gf in range(1, len(generated_files)): # پاک کردن بقیه فایلهای جزئی
|
| 168 |
try: os.remove(generated_files[i_gf])
|
| 169 |
except: pass
|
| 170 |
except Exception as e_rename_single:
|
| 171 |
-
_log(f"خطا در تغییر نام فایل اولین قطعه (بدون pydub): {e_rename_single}"
|
| 172 |
final_audio_file = generated_files[0]
|
| 173 |
|
| 174 |
-
|
| 175 |
elif len(generated_files) == 1:
|
| 176 |
try:
|
| 177 |
-
# تغییر نام فایل تکی به نام استاندارد نهایی
|
| 178 |
target_ext = os.path.splitext(generated_files[0])[1]
|
| 179 |
final_single_fn = f"{final_output_path_base}{target_ext}"
|
| 180 |
if os.path.exists(final_single_fn): os.remove(final_single_fn)
|
| 181 |
os.rename(generated_files[0], final_single_fn)
|
| 182 |
final_audio_file = final_single_fn
|
| 183 |
except Exception as e_rename_single_final:
|
| 184 |
-
_log(f"خطا در تغییر نام فایل تکی نهایی: {e_rename_single_final}"
|
| 185 |
-
final_audio_file = generated_files[0]
|
| 186 |
|
| 187 |
-
if final_audio_file and
|
| 188 |
-
_log(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
return None
|
|
|
|
| 190 |
return final_audio_file
|
| 191 |
|
| 192 |
def gradio_tts_interface(use_file_input, uploaded_file, text_to_speak, speech_prompt, speaker_voice, temperature, progress=gr.Progress(track_tqdm=True)):
|
| 193 |
-
logs = []
|
| 194 |
actual_text = ""
|
| 195 |
if use_file_input:
|
| 196 |
if uploaded_file:
|
| 197 |
try:
|
| 198 |
with open(uploaded_file.name, 'r', encoding='utf-8') as f: actual_text = f.read().strip()
|
| 199 |
-
if not actual_text: return None
|
| 200 |
-
except Exception as e: _log(f"❌ خطا خواندن
|
| 201 |
-
else: return None
|
| 202 |
else:
|
| 203 |
actual_text = text_to_speak
|
| 204 |
-
if not actual_text or not actual_text.strip(): return None
|
| 205 |
|
| 206 |
-
final_path = core_generate_audio(actual_text, speech_prompt, speaker_voice, temperature
|
| 207 |
-
# for log_entry in logs: print(log_entry) # For debugging in HF console
|
| 208 |
return final_path
|
| 209 |
|
| 210 |
-
# --- CSS
|
| 211 |
-
# متغیرهای رنگی اصلی از تصاویر شما (Alpha Translator)
|
| 212 |
-
APP_HEADER_GRADIENT_START = "#4A00E0" # بنفش تیرهتر
|
| 213 |
-
APP_HEADER_GRADIENT_END = "#8E2DE2" # بنفش روشنتر
|
| 214 |
-
# یا گرادیانت آبی-سبز تصویر:
|
| 215 |
-
APP_HEADER_GRADIENT_START_IMG = "#2980b9" # آبی
|
| 216 |
-
APP_HEADER_GRADIENT_END_IMG = "#2ecc71" # سبز
|
| 217 |
-
|
| 218 |
-
PANEL_BACKGROUND = "#FFFFFF"
|
| 219 |
-
TEXT_INPUT_BG = "#F7F7F7" # یا #FFFFFF اگر در تصویر سفید است
|
| 220 |
-
BUTTON_BG_IMG = "#2979FF" # آبی دکمه در تصویر
|
| 221 |
-
MAIN_BACKGROUND_IMG = "linear-gradient(170deg, #E0F2FE 0%, #F3E8FF 100%)" # پس زمینه کلی تصویر (مایل به بنفش و آبی روشن)
|
| 222 |
-
|
| 223 |
custom_css_inspired_by_image = f"""
|
| 224 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700;800&display=swap');
|
| 225 |
:root {{
|
| 226 |
--app-font: 'Vazirmatn', sans-serif;
|
| 227 |
-
--app-header-grad-start:
|
| 228 |
-
--app-header-grad-end:
|
| 229 |
-
--app-panel-bg:
|
| 230 |
-
--app-input-bg:
|
| 231 |
-
--app-button-bg:
|
| 232 |
-
--app-main-bg:
|
| 233 |
--app-text-primary: #333;
|
| 234 |
--app-text-secondary: #555;
|
| 235 |
--app-border-color: #E0E0E0;
|
| 236 |
-
--radius-card: 20px;
|
| 237 |
--radius-input: 8px;
|
| 238 |
--shadow-card: 0 10px 30px -5px rgba(0,0,0,0.1);
|
| 239 |
--shadow-button: 0 4px 10px -2px rgba(41,121,255,0.5);
|
|
@@ -250,11 +294,10 @@ footer {{display:none !important;}}
|
|
| 250 |
.gr-button.generate-button-final {{ background: var(--app-button-bg) !important; color: white !important; border:none !important; border-radius: var(--radius-input) !important; padding: 0.8rem 1.5rem !important; font-weight: 700 !important; font-size:1.05em !important; transition: all 0.3s ease; box-shadow: var(--shadow-button); width:100%; margin-top:1.5rem !important; }}
|
| 251 |
.gr-button.generate-button-final:hover {{ filter: brightness(1.1); transform: translateY(-2px); box-shadow: 0 6px 12px -3px rgba(41,121,255,0.6);}}
|
| 252 |
.gr-input > label + div > textarea, .gr-dropdown > label + div > div > input, .gr-dropdown > label + div > div > select, .gr-textbox > label + div > textarea, .gr-file > label + div {{ border-radius: var(--radius-input) !important; border: 1px solid var(--app-border-color) !important; background-color: var(--app-input-bg) !important; box-shadow: inset 0 1px 2px rgba(0,0,0,0.05); padding: 0.75rem !important; }}
|
| 253 |
-
.gr-file > label + div {{ text-align:center; border-style: dashed !important; }}
|
| 254 |
.gr-input > label + div > textarea:focus, .gr-dropdown > label + div > div > input:focus, .gr-textbox > label + div > textarea:focus {{ border-color: var(--app-button-bg) !important; box-shadow: 0 0 0 3px rgba(41,121,255,0.2) !important; }}
|
| 255 |
label > .label-text {{ font-weight: 700 !important; color: var(--app-text-primary) !important; font-size: 0.95em !important; margin-bottom: 0.5rem !important; }}
|
| 256 |
.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; }}
|
| 257 |
-
/* آیکونها قبل از لیبلها در تصویر نمونه */
|
| 258 |
label > .label-text::before {{ margin-left: 8px; vertical-align: middle; opacity: 0.7; }}
|
| 259 |
label[for*="text_input_main_alpha_v3"] > .label-text::before {{ content: '📝'; }}
|
| 260 |
label[for*="speech_prompt_alpha_v3"] > .label-text::before {{ content: '🗣️'; }}
|
|
@@ -271,39 +314,36 @@ alpha_header_html_v3 = """
|
|
| 271 |
<h1>Alpha TTS</h1>
|
| 272 |
<p>جادوی تبدیل متن به صدا در دستان شما</p>
|
| 273 |
</div>
|
| 274 |
-
"""
|
| 275 |
|
| 276 |
with gr.Blocks(theme=gr.themes.Base(font=[gr.themes.GoogleFont("Vazirmatn")]), css=custom_css_inspired_by_image, title="آلفا TTS") as demo:
|
| 277 |
gr.HTML(alpha_header_html_v3)
|
| 278 |
|
| 279 |
with gr.Column(elem_classes=["main-content-panel-alpha"]):
|
| 280 |
-
# عنوان بخش حذف شد تا فضا کمتر گرفته شود و شبیه تصویر شود
|
| 281 |
-
# gr.Markdown("<h3 class='section-title-main-alpha'>ورودی متن و تنظیمات</h3>")
|
| 282 |
-
|
| 283 |
use_file_input_cb = gr.Checkbox(label="📄 استفاده از فایل متنی (.txt)", value=False, elem_id="use_file_cb_alpha_v3")
|
| 284 |
uploaded_file_input = gr.File(
|
| 285 |
-
label=" ",
|
| 286 |
file_types=['.txt'],
|
| 287 |
visible=False,
|
| 288 |
elem_id="file_uploader_alpha_main_v3"
|
| 289 |
)
|
| 290 |
text_to_speak_tb = gr.Textbox(
|
| 291 |
-
label="متن فارسی برای تبدیل",
|
| 292 |
-
placeholder="مثال: سلام، فردا هوا چطور است؟",
|
| 293 |
lines=5,
|
| 294 |
-
value="",
|
| 295 |
visible=True,
|
| 296 |
elem_id="text_input_main_alpha_v3"
|
| 297 |
)
|
| 298 |
use_file_input_cb.change(
|
| 299 |
-
fn=lambda x: (gr.update(visible=x, label=" " if x else "متن فارسی برای تبدیل"), gr.update(visible=not x)),
|
| 300 |
inputs=use_file_input_cb,
|
| 301 |
outputs=[uploaded_file_input, text_to_speak_tb]
|
| 302 |
)
|
| 303 |
|
| 304 |
speech_prompt_tb = gr.Textbox(
|
| 305 |
label="سبک گفتار (اختیاری)",
|
| 306 |
-
placeholder="مثال: با لحنی شاد و پرانرژی",
|
| 307 |
value="با لحنی دوستانه و رسا صحبت کن.",
|
| 308 |
lines=2, elem_id="speech_prompt_alpha_v3"
|
| 309 |
)
|
|
@@ -316,36 +356,31 @@ with gr.Blocks(theme=gr.themes.Base(font=[gr.themes.GoogleFont("Vazirmatn")]), c
|
|
| 316 |
)
|
| 317 |
gr.Markdown("<p class='temp_description_class_alpha_v3'>مقادیر بالاتر = تنوع بیشتر، مقادیر پایینتر = یکنواختی بیشتر.</p>")
|
| 318 |
|
| 319 |
-
# فیلد نام فایل خروجی حذف شد
|
| 320 |
-
|
| 321 |
generate_button = gr.Button("🚀 تولید و پخش صدا", elem_classes=["generate-button-final"], elem_id="generate_button_alpha_v3")
|
| 322 |
|
| 323 |
-
|
| 324 |
-
output_audio = gr.Audio(label=" ", type="filepath", elem_id="output_audio_player_alpha_v3") # لیبل خالی
|
| 325 |
|
| 326 |
generate_button.click(
|
| 327 |
fn=gradio_tts_interface,
|
| 328 |
-
inputs=[ use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider ],
|
| 329 |
outputs=[output_audio]
|
| 330 |
)
|
| 331 |
|
| 332 |
-
# بخش Examples با استایل سادهتر و بدون عنوان جداگانه برای تطابق با ظاهر ساده شده
|
| 333 |
-
# برای شباهت بیشتر به تصویر، میتوان Examples را هم حذف کرد یا بسیار سادهتر کرد.
|
| 334 |
-
# فعلا نگه میداریم اما با ظاهر سادهتر.
|
| 335 |
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")
|
| 336 |
gr.Examples(
|
| 337 |
examples=[
|
| 338 |
[False, None, "سلام بر شما، امیدوارم روز خوبی داشته باشید.", "با لحنی گرم و صمیمی.", "Zephyr", 0.85],
|
| 339 |
[False, None, "این یک آزمایش برای بررسی کیفیت صدای تولید شده توسط هوش مصنوعی آلفا است.", "با صدایی طبیعی و روان.", "Charon", 0.9],
|
| 340 |
],
|
| 341 |
-
# ورودیها باید با تابع اصلی مطابقت داشته باشند، output_filename_base_tb حذف شده
|
| 342 |
inputs=[ use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider ],
|
| 343 |
outputs=[output_audio],
|
| 344 |
fn=gradio_tts_interface,
|
| 345 |
cache_examples=False
|
| 346 |
)
|
| 347 |
-
gr.Markdown("<p class='app-footer-final'>Alpha Language Learning © 2024</p>")
|
| 348 |
-
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
except ImportError:
|
| 16 |
PYDUB_AVAILABLE = False
|
| 17 |
|
| 18 |
+
# --- START: منطق چرخش API Key ---
|
| 19 |
+
GEMINI_API_KEYS = []
|
| 20 |
+
i = 1
|
| 21 |
+
while os.environ.get(f"GEMINI_API_KEY_{i}"):
|
| 22 |
+
GEMINI_API_KEYS.append(os.environ.get(f"GEMINI_API_KEY_{i}"))
|
| 23 |
+
i += 1
|
| 24 |
+
|
| 25 |
+
NUM_API_KEYS = len(GEMINI_API_KEYS)
|
| 26 |
+
CURRENT_KEY_INDEX = 0
|
| 27 |
+
|
| 28 |
+
def _log(message):
|
| 29 |
+
"""تابع ساده شده برای لاگ کردن پیامها به کنسول."""
|
| 30 |
+
print(f"[لاگ آلفا TTS] {message}")
|
| 31 |
+
|
| 32 |
+
if NUM_API_KEYS == 0:
|
| 33 |
+
_log("⛔️ خطای حیاتی: هیچ Secret با نام GEMINI_API_KEY_n یافت نشد!")
|
| 34 |
+
_log(" لطفاً Secret ها را مانند GEMINI_API_KEY_1, GEMINI_API_KEY_2, ... در تنظیمات Space خود اضافه کنید.")
|
| 35 |
+
# در یک محیط واقعی، ممکن است بخواهید اینجا برنامه را متوقف کنید
|
| 36 |
+
# exit(1)
|
| 37 |
+
else:
|
| 38 |
+
_log(f"✅ تعداد {NUM_API_KEYS} کلید API جیمینای بارگذاری شد.")
|
| 39 |
+
|
| 40 |
+
def get_next_api_key():
|
| 41 |
+
global CURRENT_KEY_INDEX
|
| 42 |
+
if NUM_API_KEYS == 0:
|
| 43 |
+
_log("⚠️ تلاش برای گرفتن کلید API در حالی که هیچ کلیدی بارگذاری نشده است.")
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
key_to_use = GEMINI_API_KEYS[CURRENT_KEY_INDEX % NUM_API_KEYS]
|
| 47 |
+
key_display_index = (CURRENT_KEY_INDEX % NUM_API_KEYS) + 1
|
| 48 |
+
CURRENT_KEY_INDEX += 1
|
| 49 |
+
# _log(f"🔑 استفاده از کلید API شماره {key_display_index} (اندیس: {CURRENT_KEY_INDEX-1})") # لاگ دقیقتر برای دیباگ
|
| 50 |
+
return key_to_use, key_display_index
|
| 51 |
+
# --- END: منطق چرخش API Key ---
|
| 52 |
+
|
| 53 |
SPEAKER_VOICES = [
|
| 54 |
"Achird", "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager",
|
| 55 |
"Sulafat", "Laomedeia", "Achernar", "Alnilam", "Schedar", "Gacrux",
|
|
|
|
| 60 |
FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts"
|
| 61 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 62 |
DEFAULT_SLEEP_BETWEEN_REQUESTS = 8
|
| 63 |
+
DEFAULT_OUTPUT_FILENAME_BASE = "alpha_tts_audio"
|
| 64 |
|
| 65 |
+
def save_binary_file(file_name, data):
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
with open(file_name, "wb") as f: f.write(data)
|
| 68 |
+
# _log(f"💾 فایل ذخیره شد: {file_name}") # لاگ کمتر
|
| 69 |
return file_name
|
| 70 |
except Exception as e:
|
| 71 |
+
_log(f"❌ خطا در ذخیره فایل {file_name}: {e}")
|
| 72 |
return None
|
| 73 |
|
| 74 |
def convert_to_wav(audio_data: bytes, mime_type: str) -> bytes:
|
|
|
|
| 92 |
except: pass
|
| 93 |
return {"bits_per_sample": bits, "rate": rate}
|
| 94 |
|
| 95 |
+
def smart_text_split(text, max_size=3800):
|
| 96 |
if len(text) <= max_size: return [text]
|
| 97 |
chunks, current_chunk = [], ""
|
| 98 |
sentences = re.split(r'(?<=[.!?؟])\s+', text)
|
|
|
|
| 107 |
else: current_chunk += (" " if current_chunk else "") + sentence
|
| 108 |
if current_chunk: chunks.append(current_chunk.strip())
|
| 109 |
final_chunks = [c for c in chunks if c]
|
| 110 |
+
# _log(f"📊 متن به {len(final_chunks)} قطعه تقسیم شد.") # لاگ کمتر
|
| 111 |
return final_chunks
|
| 112 |
|
| 113 |
+
def merge_audio_files_func(file_paths, output_path):
|
| 114 |
+
if not PYDUB_AVAILABLE: _log("⚠️ pydub برای ادغام در دسترس نیست."); return False
|
| 115 |
try:
|
| 116 |
+
# _log(f"🔗 ادغام {len(file_paths)} فایل صوتی...") # لاگ کمتر
|
| 117 |
combined = AudioSegment.empty()
|
| 118 |
for i, fp in enumerate(file_paths):
|
| 119 |
if os.path.exists(fp): combined += AudioSegment.from_file(fp) + (AudioSegment.silent(duration=150) if i < len(file_paths) - 1 else AudioSegment.empty())
|
| 120 |
+
else: _log(f"⚠️ فایل برای ادغام پیدا نشد: {fp}")
|
| 121 |
combined.export(output_path, format="wav")
|
| 122 |
+
# _log(f"✅ فایل ادغام شده: {output_path}") # لاگ کمتر
|
| 123 |
+
return True
|
| 124 |
+
except Exception as e: _log(f"❌ خطا در ادغام فایلهای صوتی: {e}"); return False
|
| 125 |
|
| 126 |
+
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val):
|
| 127 |
+
_log("🚀 شروع فرآیند تولید صدا...")
|
| 128 |
+
|
| 129 |
+
output_base_name = DEFAULT_OUTPUT_FILENAME_BASE
|
| 130 |
max_chunk, sleep_time = DEFAULT_MAX_CHUNK_SIZE, DEFAULT_SLEEP_BETWEEN_REQUESTS
|
| 131 |
+
|
| 132 |
+
selected_api_key, key_idx_display = get_next_api_key()
|
| 133 |
+
|
| 134 |
+
if not selected_api_key:
|
| 135 |
+
_log("❌ کلید API برای این درخواست در دسترس نیست. لطفاً از تنظیمات Secrets مطمئن شوید.")
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
_log(f"⚙️ استفاده از کلید API شماره {key_idx_display} (پایان یافته با: ...{selected_api_key[-4:]})")
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
client = genai.Client(api_key=selected_api_key)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
_log(f"❌ خطا در مقداردهی اولیه کلاینت Gemini با کلید شماره {key_idx_display}: {e}")
|
| 144 |
+
return None
|
| 145 |
+
|
| 146 |
+
if not text_input or not text_input.strip():
|
| 147 |
+
_log("❌ متن ورودی خالی است.")
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
text_chunks = smart_text_split(text_input, max_chunk)
|
| 151 |
+
if not text_chunks:
|
| 152 |
+
_log("❌ متن قابل پردازش به قطعات کوچکتر نیست.")
|
| 153 |
+
return None
|
| 154 |
|
| 155 |
generated_files = []
|
| 156 |
for i, chunk in enumerate(text_chunks):
|
| 157 |
+
# _log(f"🔊 پردازش قطعه {i+1}/{len(text_chunks)}...") # لاگ کمتر
|
| 158 |
final_text = f'"{prompt_input}"\n{chunk}' if prompt_input and prompt_input.strip() else chunk
|
| 159 |
contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
|
| 160 |
config = types.GenerateContentConfig(temperature=temperature_val, response_modalities=["audio"],
|
| 161 |
speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
|
| 162 |
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=selected_voice))))
|
| 163 |
+
fname_base = f"{output_base_name}_part{i+1:03d}"
|
| 164 |
try:
|
| 165 |
response = client.models.generate_content(model=FIXED_MODEL_NAME, contents=contents, config=config)
|
| 166 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
|
|
|
| 169 |
ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
|
| 170 |
if "audio/L" in inline_data.mime_type and ext == ".wav": data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
| 171 |
if not ext.startswith("."): ext = "." + ext
|
| 172 |
+
fpath = save_binary_file(f"{fname_base}{ext}", data_buffer)
|
| 173 |
if fpath: generated_files.append(fpath)
|
| 174 |
+
else: _log(f"⚠️ پاسخ API برای قطعه {i+1} بدون داده صوتی بود (با کلید شماره {key_idx_display}).")
|
| 175 |
+
except Exception as e:
|
| 176 |
+
_log(f"❌ خطا در تولید قطعه {i+1} با کلید شماره {key_idx_display}: {e}")
|
| 177 |
+
continue
|
| 178 |
if i < len(text_chunks) - 1 and len(text_chunks) > 1: time.sleep(sleep_time)
|
| 179 |
|
| 180 |
+
if not generated_files:
|
| 181 |
+
_log(f"❌ هیچ فایل صوتی با کلید شماره {key_idx_display} تولید نشد.")
|
| 182 |
+
return None
|
| 183 |
|
| 184 |
final_audio_file = None
|
|
|
|
|
|
|
|
|
|
| 185 |
final_output_path_base = f"{output_base_name}_final"
|
| 186 |
|
| 187 |
if len(generated_files) > 1:
|
| 188 |
if PYDUB_AVAILABLE:
|
| 189 |
+
merged_fn = f"{final_output_path_base}.wav"
|
| 190 |
+
if os.path.exists(merged_fn): os.remove(merged_fn)
|
| 191 |
+
if merge_audio_files_func(generated_files, merged_fn):
|
| 192 |
final_audio_file = merged_fn
|
| 193 |
+
else: # اگر ادغام ناموفق بود
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
if generated_files:
|
| 195 |
try:
|
| 196 |
+
target_ext = os.path.splitext(generated_files[0])[1]
|
| 197 |
+
renamed_first_chunk = f"{final_output_path_base}{target_ext}"
|
| 198 |
+
if os.path.exists(renamed_first_chunk): os.remove(renamed_first_chunk)
|
| 199 |
+
os.rename(generated_files[0], renamed_first_chunk)
|
| 200 |
+
final_audio_file = renamed_first_chunk
|
| 201 |
except Exception as e_rename:
|
| 202 |
+
_log(f"خطا در تغییر نام فایل اولین قطعه (پس از ادغام ناموفق): {e_rename}")
|
| 203 |
+
final_audio_file = generated_files[0]
|
| 204 |
+
|
| 205 |
+
# پاک کردن فایلهای جزئی چه ادغام موفق بوده چه ناموفق
|
| 206 |
+
for fp_cleanup in generated_files:
|
| 207 |
+
if final_audio_file and os.path.abspath(fp_cleanup) == os.path.abspath(final_audio_file):
|
| 208 |
+
continue # فایل نهایی را پاک نکن
|
| 209 |
+
try: os.remove(fp_cleanup)
|
| 210 |
+
except: pass
|
| 211 |
+
|
| 212 |
else:
|
| 213 |
+
_log("⚠️ pydub در دسترس نیست. اولین قطعه صوتی ارائه میشود.")
|
| 214 |
if generated_files:
|
| 215 |
try:
|
| 216 |
+
target_ext = os.path.splitext(generated_files[0])[1]
|
| 217 |
+
renamed_first_chunk = f"{final_output_path_base}{target_ext}"
|
| 218 |
+
if os.path.exists(renamed_first_chunk): os.remove(renamed_first_chunk)
|
| 219 |
+
os.rename(generated_files[0], renamed_first_chunk)
|
| 220 |
+
final_audio_file = renamed_first_chunk
|
| 221 |
for i_gf in range(1, len(generated_files)): # پاک کردن بقیه فایلهای جزئی
|
| 222 |
try: os.remove(generated_files[i_gf])
|
| 223 |
except: pass
|
| 224 |
except Exception as e_rename_single:
|
| 225 |
+
_log(f"خطا در تغییر نام فایل اولین قطعه (بدون pydub): {e_rename_single}")
|
| 226 |
final_audio_file = generated_files[0]
|
| 227 |
|
|
|
|
| 228 |
elif len(generated_files) == 1:
|
| 229 |
try:
|
|
|
|
| 230 |
target_ext = os.path.splitext(generated_files[0])[1]
|
| 231 |
final_single_fn = f"{final_output_path_base}{target_ext}"
|
| 232 |
if os.path.exists(final_single_fn): os.remove(final_single_fn)
|
| 233 |
os.rename(generated_files[0], final_single_fn)
|
| 234 |
final_audio_file = final_single_fn
|
| 235 |
except Exception as e_rename_single_final:
|
| 236 |
+
_log(f"خطا در تغییر نام فایل تکی نهایی: {e_rename_single_final}")
|
| 237 |
+
final_audio_file = generated_files[0]
|
| 238 |
|
| 239 |
+
if final_audio_file and os.path.exists(final_audio_file):
|
| 240 |
+
_log(f"✅ فایل صوتی نهایی با موفقیت با کلید شماره {key_idx_display} تولید شد: {os.path.basename(final_audio_file)}")
|
| 241 |
+
elif final_audio_file:
|
| 242 |
+
_log(f"⚠️ فایل نهایی '{final_audio_file}' پس از پردازش وجود ندارد! (با کلید شماره {key_idx_display})")
|
| 243 |
+
return None
|
| 244 |
+
else:
|
| 245 |
+
_log(f"❓ وضعیت نامشخص برای فایل نهایی. (با کلید شماره {key_idx_display})")
|
| 246 |
return None
|
| 247 |
+
|
| 248 |
return final_audio_file
|
| 249 |
|
| 250 |
def gradio_tts_interface(use_file_input, uploaded_file, text_to_speak, speech_prompt, speaker_voice, temperature, progress=gr.Progress(track_tqdm=True)):
|
|
|
|
| 251 |
actual_text = ""
|
| 252 |
if use_file_input:
|
| 253 |
if uploaded_file:
|
| 254 |
try:
|
| 255 |
with open(uploaded_file.name, 'r', encoding='utf-8') as f: actual_text = f.read().strip()
|
| 256 |
+
if not actual_text: _log("❌ فایل آپلود شده خالی است یا خوانده نشد."); return None
|
| 257 |
+
except Exception as e: _log(f"❌ خطا در خواندن فایل آپلود شده: {e}"); return None
|
| 258 |
+
else: _log("❌ گزینه استفاده از فایل انتخاب شده اما فایلی آپلود نشده."); return None
|
| 259 |
else:
|
| 260 |
actual_text = text_to_speak
|
| 261 |
+
if not actual_text or not actual_text.strip(): _log("❌ متن ورودی برای تبدیل خالی است."); return None
|
| 262 |
|
| 263 |
+
final_path = core_generate_audio(actual_text, speech_prompt, speaker_voice, temperature)
|
|
|
|
| 264 |
return final_path
|
| 265 |
|
| 266 |
+
# --- CSS (بدون تغییر نسبت به کد شما) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
custom_css_inspired_by_image = f"""
|
| 268 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700;800&display=swap');
|
| 269 |
:root {{
|
| 270 |
--app-font: 'Vazirmatn', sans-serif;
|
| 271 |
+
--app-header-grad-start: #2980b9; /* آبی */
|
| 272 |
+
--app-header-grad-end: #2ecc71; /* سبز */
|
| 273 |
+
--app-panel-bg: #FFFFFF;
|
| 274 |
+
--app-input-bg: #F7F7F7;
|
| 275 |
+
--app-button-bg: #2979FF;
|
| 276 |
+
--app-main-bg: linear-gradient(170deg, #E0F2FE 0%, #F3E8FF 100%);
|
| 277 |
--app-text-primary: #333;
|
| 278 |
--app-text-secondary: #555;
|
| 279 |
--app-border-color: #E0E0E0;
|
| 280 |
+
--radius-card: 20px;
|
| 281 |
--radius-input: 8px;
|
| 282 |
--shadow-card: 0 10px 30px -5px rgba(0,0,0,0.1);
|
| 283 |
--shadow-button: 0 4px 10px -2px rgba(41,121,255,0.5);
|
|
|
|
| 294 |
.gr-button.generate-button-final {{ background: var(--app-button-bg) !important; color: white !important; border:none !important; border-radius: var(--radius-input) !important; padding: 0.8rem 1.5rem !important; font-weight: 700 !important; font-size:1.05em !important; transition: all 0.3s ease; box-shadow: var(--shadow-button); width:100%; margin-top:1.5rem !important; }}
|
| 295 |
.gr-button.generate-button-final:hover {{ filter: brightness(1.1); transform: translateY(-2px); box-shadow: 0 6px 12px -3px rgba(41,121,255,0.6);}}
|
| 296 |
.gr-input > label + div > textarea, .gr-dropdown > label + div > div > input, .gr-dropdown > label + div > div > select, .gr-textbox > label + div > textarea, .gr-file > label + div {{ border-radius: var(--radius-input) !important; border: 1px solid var(--app-border-color) !important; background-color: var(--app-input-bg) !important; box-shadow: inset 0 1px 2px rgba(0,0,0,0.05); padding: 0.75rem !important; }}
|
| 297 |
+
.gr-file > label + div {{ text-align:center; border-style: dashed !important; }}
|
| 298 |
.gr-input > label + div > textarea:focus, .gr-dropdown > label + div > div > input:focus, .gr-textbox > label + div > textarea:focus {{ border-color: var(--app-button-bg) !important; box-shadow: 0 0 0 3px rgba(41,121,255,0.2) !important; }}
|
| 299 |
label > .label-text {{ font-weight: 700 !important; color: var(--app-text-primary) !important; font-size: 0.95em !important; margin-bottom: 0.5rem !important; }}
|
| 300 |
.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; }}
|
|
|
|
| 301 |
label > .label-text::before {{ margin-left: 8px; vertical-align: middle; opacity: 0.7; }}
|
| 302 |
label[for*="text_input_main_alpha_v3"] > .label-text::before {{ content: '📝'; }}
|
| 303 |
label[for*="speech_prompt_alpha_v3"] > .label-text::before {{ content: '🗣️'; }}
|
|
|
|
| 314 |
<h1>Alpha TTS</h1>
|
| 315 |
<p>جادوی تبدیل متن به صدا در دستان شما</p>
|
| 316 |
</div>
|
| 317 |
+
"""
|
| 318 |
|
| 319 |
with gr.Blocks(theme=gr.themes.Base(font=[gr.themes.GoogleFont("Vazirmatn")]), css=custom_css_inspired_by_image, title="آلفا TTS") as demo:
|
| 320 |
gr.HTML(alpha_header_html_v3)
|
| 321 |
|
| 322 |
with gr.Column(elem_classes=["main-content-panel-alpha"]):
|
|
|
|
|
|
|
|
|
|
| 323 |
use_file_input_cb = gr.Checkbox(label="📄 استفاده از فایل متنی (.txt)", value=False, elem_id="use_file_cb_alpha_v3")
|
| 324 |
uploaded_file_input = gr.File(
|
| 325 |
+
label=" ",
|
| 326 |
file_types=['.txt'],
|
| 327 |
visible=False,
|
| 328 |
elem_id="file_uploader_alpha_main_v3"
|
| 329 |
)
|
| 330 |
text_to_speak_tb = gr.Textbox(
|
| 331 |
+
label="متن فارسی برای تبدیل",
|
| 332 |
+
placeholder="مثال: سلام، فردا هوا چطور است؟",
|
| 333 |
lines=5,
|
| 334 |
+
value="",
|
| 335 |
visible=True,
|
| 336 |
elem_id="text_input_main_alpha_v3"
|
| 337 |
)
|
| 338 |
use_file_input_cb.change(
|
| 339 |
+
fn=lambda x: (gr.update(visible=x, label=" " if x else "متن فارسی برای تبدیل"), gr.update(visible=not x)),
|
| 340 |
inputs=use_file_input_cb,
|
| 341 |
outputs=[uploaded_file_input, text_to_speak_tb]
|
| 342 |
)
|
| 343 |
|
| 344 |
speech_prompt_tb = gr.Textbox(
|
| 345 |
label="سبک گفتار (اختیاری)",
|
| 346 |
+
placeholder="مثال: با لحنی شاد و پرانرژی",
|
| 347 |
value="با لحنی دوستانه و رسا صحبت کن.",
|
| 348 |
lines=2, elem_id="speech_prompt_alpha_v3"
|
| 349 |
)
|
|
|
|
| 356 |
)
|
| 357 |
gr.Markdown("<p class='temp_description_class_alpha_v3'>مقادیر بالاتر = تنوع بیشتر، مقادیر پایینتر = یکنواختی بیشتر.</p>")
|
| 358 |
|
|
|
|
|
|
|
| 359 |
generate_button = gr.Button("🚀 تولید و پخش صدا", elem_classes=["generate-button-final"], elem_id="generate_button_alpha_v3")
|
| 360 |
|
| 361 |
+
output_audio = gr.Audio(label=" ", type="filepath", elem_id="output_audio_player_alpha_v3")
|
|
|
|
| 362 |
|
| 363 |
generate_button.click(
|
| 364 |
fn=gradio_tts_interface,
|
| 365 |
+
inputs=[ use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider ],
|
| 366 |
outputs=[output_audio]
|
| 367 |
)
|
| 368 |
|
|
|
|
|
|
|
|
|
|
| 369 |
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")
|
| 370 |
gr.Examples(
|
| 371 |
examples=[
|
| 372 |
[False, None, "سلام بر شما، امیدوارم روز خوبی داشته باشید.", "با لحنی گرم و صمیمی.", "Zephyr", 0.85],
|
| 373 |
[False, None, "این یک آزمایش برای بررسی کیفیت صدای تولید شده توسط هوش مصنوعی آلفا است.", "با صدایی طبیعی و روان.", "Charon", 0.9],
|
| 374 |
],
|
|
|
|
| 375 |
inputs=[ use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider ],
|
| 376 |
outputs=[output_audio],
|
| 377 |
fn=gradio_tts_interface,
|
| 378 |
cache_examples=False
|
| 379 |
)
|
| 380 |
+
gr.Markdown("<p class='app-footer-final'>Alpha Language Learning © 2024</p>")
|
|
|
|
| 381 |
|
| 382 |
if __name__ == "__main__":
|
| 383 |
+
if NUM_API_KEYS > 0 : # فقط در صورتی که کلید API موجود باشد، برنامه را اجرا کن
|
| 384 |
+
demo.launch()
|
| 385 |
+
else:
|
| 386 |
+
_log("🔴 برنامه به دلیل عدم وجود کلید API جیمینای اجرا نشد. لطفاً Secrets را بررسی کنید.")
|