Update app.py
Browse files
app.py
CHANGED
|
@@ -1,25 +1,26 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
import mimetypes
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
import struct
|
| 7 |
import time
|
| 8 |
-
|
| 9 |
from google import genai
|
| 10 |
-
from google.genai import types
|
| 11 |
-
|
| 12 |
-
import logging
|
| 13 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 14 |
|
| 15 |
try:
|
| 16 |
from pydub import AudioSegment
|
| 17 |
PYDUB_AVAILABLE = True
|
| 18 |
except ImportError:
|
| 19 |
PYDUB_AVAILABLE = False
|
| 20 |
-
logging.warning("Pydub (for audio merging) not found. Merging will be disabled if multiple audio chunks are generated.")
|
| 21 |
|
| 22 |
-
# --- START:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
SPEAKER_VOICES = [
|
| 24 |
"Achird", "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager",
|
| 25 |
"Sulafat", "Laomedeia", "Achernar", "Alnilam", "Schedar", "Gacrux",
|
|
@@ -27,14 +28,24 @@ SPEAKER_VOICES = [
|
|
| 27 |
"Rasalthgeti", "Orus", "Aoede", "Callirrhoe", "Autonoe", "Enceladus",
|
| 28 |
"Iapetus", "Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda"
|
| 29 |
]
|
| 30 |
-
FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts"
|
| 31 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 32 |
DEFAULT_SLEEP_BETWEEN_REQUESTS = 8
|
| 33 |
DEFAULT_OUTPUT_FILENAME_BASE = "alpha_tts_audio"
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
log_list.append(message)
|
| 37 |
-
logging.info(f"[AlphaTTS_LOG_INTERNAL] {message}")
|
| 38 |
|
| 39 |
def save_binary_file(file_name, data, log_list):
|
| 40 |
try:
|
|
@@ -60,16 +71,16 @@ def parse_audio_mime_type(mime_type: str) -> dict[str, int]:
|
|
| 60 |
param = param.strip()
|
| 61 |
if param.lower().startswith("rate="):
|
| 62 |
try: rate = int(param.split("=", 1)[1])
|
| 63 |
-
except
|
| 64 |
elif param.startswith("audio/L"):
|
| 65 |
try: bits = int(param.split("L", 1)[1])
|
| 66 |
-
except
|
| 67 |
return {"bits_per_sample": bits, "rate": rate}
|
| 68 |
|
| 69 |
def smart_text_split(text, max_size=3800, log_list=None):
|
| 70 |
if len(text) <= max_size: return [text]
|
| 71 |
chunks, current_chunk = [], ""
|
| 72 |
-
sentences = re.split(r'(?<=[
|
| 73 |
for sentence in sentences:
|
| 74 |
if len(current_chunk) + len(sentence) + 1 > max_size:
|
| 75 |
if current_chunk: chunks.append(current_chunk.strip())
|
|
@@ -85,24 +96,13 @@ def smart_text_split(text, max_size=3800, log_list=None):
|
|
| 85 |
return final_chunks
|
| 86 |
|
| 87 |
def merge_audio_files_func(file_paths, output_path, log_list):
|
| 88 |
-
if not PYDUB_AVAILABLE: _log("❌ pydub در دسترس نیست.", log_list); return False
|
| 89 |
try:
|
| 90 |
_log(f"🔗 ادغام {len(file_paths)} فایل صوتی...", log_list)
|
| 91 |
combined = AudioSegment.empty()
|
| 92 |
for i, fp in enumerate(file_paths):
|
| 93 |
-
if os.path.exists(fp):
|
| 94 |
-
try:
|
| 95 |
-
segment = AudioSegment.from_file(fp)
|
| 96 |
-
combined += segment
|
| 97 |
-
if i < len(file_paths) - 1:
|
| 98 |
-
combined += AudioSegment.silent(duration=150)
|
| 99 |
-
except Exception as e_pydub:
|
| 100 |
-
_log(f"⚠️ خطای Pydub در پردازش فایل '{fp}': {e_pydub}. این فایل نادیده گرفته می شود.", log_list)
|
| 101 |
-
continue
|
| 102 |
else: _log(f"⚠️ فایل پیدا نشد: {fp}", log_list)
|
| 103 |
-
if len(combined) == 0:
|
| 104 |
-
_log("❌ هیچ قطعه صوتی معتبری برای ادغام یافت نشد.", log_list)
|
| 105 |
-
return False
|
| 106 |
combined.export(output_path, format="wav")
|
| 107 |
_log(f"✅ فایل ادغام شده: {output_path}", log_list); return True
|
| 108 |
except Exception as e: _log(f"❌ خطا در ادغام: {e}", log_list); return False
|
|
@@ -110,46 +110,48 @@ def merge_audio_files_func(file_paths, output_path, log_list):
|
|
| 110 |
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, log_list):
|
| 111 |
output_base_name = DEFAULT_OUTPUT_FILENAME_BASE
|
| 112 |
max_chunk, sleep_time = DEFAULT_MAX_CHUNK_SIZE, DEFAULT_SLEEP_BETWEEN_REQUESTS
|
| 113 |
-
_log(
|
| 114 |
-
|
| 115 |
-
if not
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
text_chunks = smart_text_split(text_input, max_chunk, log_list)
|
| 120 |
-
if not text_chunks: _log("❌ متن قابل پردازش
|
| 121 |
|
| 122 |
generated_files = []
|
| 123 |
for i, chunk in enumerate(text_chunks):
|
| 124 |
-
_log(f"🔊 پردازش قطعه {i+1}/{len(text_chunks)}
|
| 125 |
final_text = f'"{prompt_input}"\n{chunk}' if prompt_input and prompt_input.strip() else chunk
|
| 126 |
-
contents = [
|
| 127 |
-
config =
|
| 128 |
-
speech_config=
|
| 129 |
-
prebuilt_voice_config=
|
| 130 |
fname_base = f"{output_base_name}_part{i+1:03d}"
|
| 131 |
try:
|
| 132 |
response = client.models.generate_content(model=FIXED_MODEL_NAME, contents=contents, config=config)
|
| 133 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
| 134 |
inline_data = response.candidates[0].content.parts[0].inline_data
|
| 135 |
data_buffer = inline_data.data
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
ext = mimetypes.guess_extension(mime_type) or ".wav"
|
| 139 |
-
if "audio/L" in mime_type and ext == ".wav":
|
| 140 |
-
_log(f"تبدیل صدای خام PCM (MIME: {mime_type}) به WAV برای قطعه {i+1}.", log_list)
|
| 141 |
-
data_buffer = convert_to_wav(data_buffer, mime_type)
|
| 142 |
if not ext.startswith("."): ext = "." + ext
|
| 143 |
fpath = save_binary_file(f"{fname_base}{ext}", data_buffer, log_list)
|
| 144 |
if fpath: generated_files.append(fpath)
|
| 145 |
-
else: _log(f"⚠️ پاسخ API برای قطعه {i+1} بدون داده
|
| 146 |
-
except Exception as e: _log(f"❌ خطا در تولید قطعه {i+1}: {e}", log_list); continue
|
| 147 |
-
if i < len(text_chunks) - 1 and len(text_chunks) > 1:
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
if not generated_files: _log("❌ هیچ فایلی تولید نشد.", log_list); return None
|
| 152 |
-
_log(f"🎉 {len(generated_files)} فایل(های) صوتی تولید شد.", log_list)
|
| 153 |
|
| 154 |
final_audio_file = None
|
| 155 |
final_output_path_base = f"{output_base_name}_final"
|
|
@@ -157,371 +159,395 @@ def core_generate_audio(text_input, prompt_input, selected_voice, temperature_va
|
|
| 157 |
if len(generated_files) > 1:
|
| 158 |
if PYDUB_AVAILABLE:
|
| 159 |
merged_fn = f"{final_output_path_base}.wav"
|
| 160 |
-
if os.path.exists(merged_fn):
|
| 161 |
-
try: os.remove(merged_fn)
|
| 162 |
-
except Exception as e_rm: _log(f"⚠️ خطا در حذف فایل ادغام شده قبلی '{merged_fn}': {e_rm}", log_list)
|
| 163 |
if merge_audio_files_func(generated_files, merged_fn, log_list):
|
| 164 |
final_audio_file = merged_fn
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
except: pass
|
| 169 |
-
else:
|
| 170 |
-
if generated_files:
|
| 171 |
try:
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
if os.path.
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
for i_gf in range(1, len(generated_files)):
|
| 180 |
-
try: os.remove(generated_files[i_gf])
|
| 181 |
-
except: pass
|
| 182 |
-
except Exception as e_rename:
|
| 183 |
-
_log(f"خطا در تغییر نام فایل اولین قطعه: {e_rename}", log_list)
|
| 184 |
final_audio_file = generated_files[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
else:
|
| 186 |
-
_log("⚠️ pydub نیست. اولین قطعه ارائه میشود.", log_list)
|
| 187 |
if generated_files:
|
| 188 |
try:
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
if os.path.
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
_log(f"خطا در تغییر نام فایل اولین قطعه (بدون pydub): {e_rename_single}", log_list)
|
| 201 |
final_audio_file = generated_files[0]
|
|
|
|
| 202 |
elif len(generated_files) == 1:
|
| 203 |
try:
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
if os.path.
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
final_audio_file = target_path
|
| 210 |
except Exception as e_rename_single_final:
|
| 211 |
_log(f"خطا در تغییر نام فایل تکی نهایی: {e_rename_single_final}", log_list)
|
| 212 |
final_audio_file = generated_files[0]
|
| 213 |
|
| 214 |
if final_audio_file and not os.path.exists(final_audio_file):
|
| 215 |
-
_log(f"⚠️ فایل نهایی '{final_audio_file}' وجود ندارد!", log_list)
|
| 216 |
-
return None
|
| 217 |
-
|
|
|
|
| 218 |
|
| 219 |
def gradio_tts_interface(use_file_input, uploaded_file, text_to_speak, speech_prompt, speaker_voice, temperature, progress=gr.Progress(track_tqdm=True)):
|
| 220 |
-
logs = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
actual_text = ""
|
| 222 |
if use_file_input:
|
| 223 |
if uploaded_file:
|
| 224 |
try:
|
| 225 |
with open(uploaded_file.name, 'r', encoding='utf-8') as f: actual_text = f.read().strip()
|
| 226 |
-
if not actual_text:
|
| 227 |
-
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
else:
|
| 230 |
actual_text = text_to_speak
|
| 231 |
-
if not actual_text or not actual_text.strip():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
-
|
| 234 |
-
# for log_entry in logs:
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
|
| 239 |
-
# --- START:
|
| 240 |
FLY_PRIMARY_COLOR_HEX = "#4F46E5"
|
| 241 |
FLY_SECONDARY_COLOR_HEX = "#10B981"
|
| 242 |
-
FLY_ACCENT_COLOR_HEX = "#D97706"
|
| 243 |
FLY_TEXT_COLOR_HEX = "#1F2937"
|
| 244 |
FLY_SUBTLE_TEXT_HEX = "#6B7280"
|
| 245 |
FLY_LIGHT_BACKGROUND_HEX = "#F9FAFB"
|
| 246 |
FLY_WHITE_HEX = "#FFFFFF"
|
| 247 |
FLY_BORDER_COLOR_HEX = "#D1D5DB"
|
| 248 |
FLY_INPUT_BG_HEX_SIMPLE = "#F3F4F6"
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"],
|
| 252 |
).set(
|
| 253 |
body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
|
| 254 |
)
|
| 255 |
|
| 256 |
-
|
| 257 |
-
final_combined_css_v3 = f"""
|
| 258 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
| 259 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap');
|
| 260 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
|
| 261 |
-
|
| 262 |
:root {{
|
| 263 |
-
--fly-primary: {FLY_PRIMARY_COLOR_HEX};
|
| 264 |
-
--fly-
|
| 265 |
-
--fly-
|
| 266 |
-
--fly-
|
| 267 |
-
--fly-
|
| 268 |
-
--
|
| 269 |
-
--
|
| 270 |
-
--
|
| 271 |
-
--
|
| 272 |
-
--fly-primary-rgb: 79,70,229;
|
| 273 |
-
--fly-accent-rgb: 217,119,6;
|
| 274 |
-
|
| 275 |
-
--radius-sm: 0.375rem; --radius-md: 0.5rem; --radius-lg: 0.75rem; --radius-xl: 1rem;
|
| 276 |
--shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1),0 4px 6px -4px rgba(0,0,0,0.1);
|
| 277 |
--shadow-xl: 0 20px 25px -5px rgba(0,0,0,0.1),0 8px 10px -6px rgba(0,0,0,0.1);
|
| 278 |
-
|
| 279 |
-
--font-global: 'Vazirmatn', 'Inter', 'Poppins', system-ui, sans-serif;
|
| 280 |
-
--font-english: 'Poppins', 'Inter', system-ui, sans-serif;
|
| 281 |
-
|
| 282 |
-
--app-button-bg-original: #2979FF;
|
| 283 |
-
--radius-input-original: 8px;
|
| 284 |
-
}}
|
| 285 |
-
|
| 286 |
-
body {{
|
| 287 |
-
font-family: var(--font-global);
|
| 288 |
-
direction: rtl;
|
| 289 |
-
background-color: var(--fly-bg-light) !important;
|
| 290 |
-
color: var(--fly-text-primary);
|
| 291 |
-
line-height: 1.7;
|
| 292 |
-
font-size: 16px;
|
| 293 |
}}
|
| 294 |
-
|
| 295 |
-
.gradio-container {{
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
}}
|
| 301 |
-
|
| 302 |
-
.
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
.
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
.app-header-alphatts-v2 h1 {{
|
| 315 |
-
font-size:2.25em !important; font-weight:800 !important; margin:0 0 0.5rem 0;
|
| 316 |
-
font-family:var(--font-english); letter-spacing:-0.5px; text-shadow:0 2px 4px rgba(0,0,0,0.1);
|
| 317 |
-
}}
|
| 318 |
-
.app-header-alphatts-v2 p {{
|
| 319 |
-
font-size:1em !important; margin-top:0.25rem; font-weight:400;
|
| 320 |
-
color:rgba(255,255,255,0.85) !important;
|
| 321 |
-
}}
|
| 322 |
-
|
| 323 |
-
.main-content-area-alphatts-v2 {{
|
| 324 |
-
flex-grow:1; padding:0.75rem; width:100%; margin:0 auto; box-sizing:border-box;
|
| 325 |
}}
|
| 326 |
-
.content-panel-
|
| 327 |
-
background
|
| 328 |
-
|
| 329 |
-
|
| 330 |
}}
|
| 331 |
|
| 332 |
-
|
| 333 |
-
.content-panel-
|
| 334 |
-
.content-panel-
|
| 335 |
-
.content-panel-
|
| 336 |
-
.content-panel-
|
| 337 |
-
.content-panel-alphatts-v2 #file_uploader_alpha_main_v3 .upload-button, /* File input button part */
|
| 338 |
-
.content-panel-alphatts-v2 #temperature_slider_alpha_v3 input[type="range"]
|
| 339 |
{{
|
| 340 |
-
border-radius:var(--
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
background-color:var(--fly-input-bg-simple) !important;
|
| 344 |
-
padding:10px 12px !important;
|
| 345 |
-
color:var(--fly-text-primary) !important;
|
| 346 |
-
box-shadow: none !important;
|
| 347 |
}}
|
|
|
|
| 348 |
|
| 349 |
-
|
| 350 |
-
.content-panel-
|
| 351 |
-
.content-panel-
|
| 352 |
-
.content-panel-
|
| 353 |
-
.content-panel-
|
| 354 |
-
.content-panel-alphatts-v2 #file_uploader_alpha_main_v3 .upload-button:focus-within
|
| 355 |
{{
|
| 356 |
border-color:var(--fly-primary) !important;
|
| 357 |
box-shadow:0 0 0 3px rgba(var(--fly-primary-rgb),0.12) !important;
|
| 358 |
background-color:var(--fly-bg-white) !important;
|
| 359 |
}}
|
| 360 |
-
.content-panel-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
transition:all 0.25s ease-in-out !important; color:white !important; font-weight:600 !important;
|
| 370 |
-
border-radius:var(--radius-input-original) !important; border:none !important;
|
| 371 |
-
box-shadow:0 3px 8px -1px rgba(var(--fly-accent-rgb),0.3) !important;
|
| 372 |
-
width:100% !important; font-size:1.05em !important;
|
| 373 |
-
display:flex; align-items:center; justify-content:center;
|
| 374 |
-
}}
|
| 375 |
-
.content-panel-alphatts-v2 .gr-button#generate_button_alpha_v3:hover
|
| 376 |
-
{{
|
| 377 |
-
background:#B45309 !important; transform:translateY(-1px) !important;
|
| 378 |
-
box-shadow:0 5px 10px -1px rgba(var(--fly-accent-rgb),0.4) !important;
|
| 379 |
}}
|
| 380 |
|
| 381 |
-
|
| 382 |
-
.content-panel-
|
| 383 |
-
.content-panel-alphatts-v2 .gr-form .gr-input-label > label > .label-text span /* More specific for Gradio 3.x+ labels */
|
| 384 |
{{
|
| 385 |
-
|
| 386 |
-
|
|
|
|
| 387 |
}}
|
| 388 |
-
.content-panel-
|
| 389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
}}
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
}}
|
| 396 |
|
| 397 |
-
|
| 398 |
-
.content-panel-
|
| 399 |
-
{{
|
| 400 |
-
background-color:#E0E7FF !important; color:var(--fly-primary) !important;
|
| 401 |
-
border-radius:var(--radius-sm) !important; font-size:0.78em !important; padding:4px 8px !important;
|
| 402 |
-
}}
|
| 403 |
-
.content-panel-alphatts-v2 .custom-hr {{height:1px;background-color:var(--fly-border-color);margin:1.5rem 0;border:none;}}
|
| 404 |
|
| 405 |
-
.app-footer-alphatts-v2 {{
|
| 406 |
-
text-align:center;font-size:0.85em;color:var(--fly-text-secondary);margin-top:2.5rem;
|
| 407 |
-
padding:1rem 0;background-color:rgba(255,255,255,0.3);backdrop-filter:blur(5px);
|
| 408 |
-
border-top:1px solid var(--fly-border-color);
|
| 409 |
-
}}
|
| 410 |
-
footer, .gradio-footer, .flagging-container, .footer-utils {{
|
| 411 |
-
display:none !important; visibility:hidden !important;
|
| 412 |
-
}}
|
| 413 |
|
| 414 |
@media (min-width:640px) {{
|
| 415 |
-
.main-content-area
|
| 416 |
-
.content-panel-
|
| 417 |
-
.app-
|
| 418 |
-
.app-
|
| 419 |
}}
|
| 420 |
@media (min-width:768px) {{
|
| 421 |
-
.main-content-area
|
| 422 |
-
.content-panel-
|
| 423 |
-
.content-panel-
|
| 424 |
-
{{
|
| 425 |
-
|
| 426 |
-
}}
|
| 427 |
-
.app-
|
| 428 |
-
.app-
|
| 429 |
}}
|
| 430 |
"""
|
|
|
|
| 431 |
|
| 432 |
-
|
| 433 |
-
with gr.Blocks(theme=
|
|
|
|
| 434 |
gr.HTML(f"""
|
| 435 |
-
<div class=
|
| 436 |
<h1>🚀 Alpha TTS</h1>
|
| 437 |
-
<p>جادوی تبدیل متن به صدا در دستان
|
| 438 |
</div>
|
| 439 |
""")
|
| 440 |
|
| 441 |
-
with gr.Column(elem_classes=["main-content-area
|
| 442 |
-
with gr.
|
| 443 |
-
|
| 444 |
-
if not
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
|
|
|
|
|
|
|
|
|
| 449 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
uploaded_file_input = gr.File(
|
| 451 |
-
label=" ",
|
| 452 |
file_types=['.txt'],
|
| 453 |
visible=False,
|
| 454 |
-
elem_id="
|
| 455 |
)
|
| 456 |
-
|
| 457 |
text_to_speak_tb = gr.Textbox(
|
| 458 |
-
label="متن فارسی برای تبدیل",
|
| 459 |
-
placeholder="مثال: سلام،
|
| 460 |
lines=5,
|
| 461 |
-
value="",
|
| 462 |
visible=True,
|
| 463 |
-
elem_id="
|
| 464 |
)
|
| 465 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
use_file_input_cb.change(
|
| 467 |
-
fn=
|
| 468 |
inputs=use_file_input_cb,
|
| 469 |
outputs=[uploaded_file_input, text_to_speak_tb]
|
| 470 |
)
|
| 471 |
|
| 472 |
speech_prompt_tb = gr.Textbox(
|
| 473 |
-
label="سبک گفتار (اختیاری)",
|
| 474 |
-
placeholder="مثال: با لحنی شاد و پرانرژی",
|
| 475 |
value="با لحنی دوستانه و رسا صحبت کن.",
|
| 476 |
-
lines=2, elem_id="
|
| 477 |
)
|
| 478 |
-
|
| 479 |
speaker_voice_dd = gr.Dropdown(
|
| 480 |
-
SPEAKER_VOICES,
|
|
|
|
|
|
|
|
|
|
| 481 |
)
|
| 482 |
-
|
| 483 |
temperature_slider = gr.Slider(
|
| 484 |
-
minimum=0.1, maximum=1.5, step=0.05, value=0.9,
|
| 485 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 486 |
)
|
| 487 |
-
gr.Markdown("<p class='temp_description_class_alpha_v3'>مقادیر بالاتر = تنوع بیشتر، مقادیر پایینتر = یکنواختی بیشتر.</p>")
|
| 488 |
-
|
| 489 |
-
generate_button = gr.Button("🚀 تولید و پخش صدا", elem_id="generate_button_alpha_v3") # YOUR ID
|
| 490 |
|
| 491 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 492 |
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
|
|
|
| 496 |
)
|
| 497 |
-
|
| 498 |
-
|
|
|
|
|
|
|
| 499 |
[False, None, "سلام بر شما، امیدوارم روز خوبی داشته باشید.", "با لحنی گرم و صمیمی.", "Zephyr", 0.85],
|
| 500 |
[False, None, "این یک آزمایش برای بررسی کیفیت صدای تولید شده توسط هوش مصنوعی آلفا است.", "با صدایی طبیعی و روان.", "Charon", 0.9],
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
|
| 508 |
-
|
|
|
|
| 509 |
|
| 510 |
-
if generate_button is not None:
|
| 511 |
-
generate_button.click(
|
| 512 |
-
fn=gradio_tts_interface,
|
| 513 |
-
inputs=[use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider, gr.Progress(track_tqdm=True)],
|
| 514 |
-
outputs=[output_audio]
|
| 515 |
-
)
|
| 516 |
-
else:
|
| 517 |
-
logging.error("دکمه تولید صدا (generate_button_alpha_v3) در UI یافت نشد.")
|
| 518 |
|
| 519 |
if __name__ == "__main__":
|
| 520 |
-
if not
|
| 521 |
-
logging.warning("
|
| 522 |
-
|
| 523 |
-
logging.warning("GEMINI_API_KEY environment variable not set. TTS functionality WILL FAIL.")
|
| 524 |
-
|
| 525 |
demo.launch(
|
| 526 |
server_name="0.0.0.0",
|
| 527 |
server_port=int(os.getenv("PORT", 7860)),
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import base64
|
| 3 |
import mimetypes
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
import struct
|
| 7 |
import time
|
| 8 |
+
import zipfile
|
| 9 |
from google import genai
|
| 10 |
+
from google.genai import types
|
| 11 |
+
import logging # اضافه شده برای هماهنگی با پیامهای لاگ
|
|
|
|
|
|
|
| 12 |
|
| 13 |
try:
|
| 14 |
from pydub import AudioSegment
|
| 15 |
PYDUB_AVAILABLE = True
|
| 16 |
except ImportError:
|
| 17 |
PYDUB_AVAILABLE = False
|
|
|
|
| 18 |
|
| 19 |
+
# --- START: پیکربندی لاگینگ مشابه کد اول (فقط برای پیامهای هشدار و خطا) ---
|
| 20 |
+
# این بخش برای نمایش بهتر خطاها در کنسول مفید است، نه برای نمایش در UI
|
| 21 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 22 |
+
# --- END: پیکربندی لاگینگ ---
|
| 23 |
+
|
| 24 |
SPEAKER_VOICES = [
|
| 25 |
"Achird", "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager",
|
| 26 |
"Sulafat", "Laomedeia", "Achernar", "Alnilam", "Schedar", "Gacrux",
|
|
|
|
| 28 |
"Rasalthgeti", "Orus", "Aoede", "Callirrhoe", "Autonoe", "Enceladus",
|
| 29 |
"Iapetus", "Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda"
|
| 30 |
]
|
| 31 |
+
FIXED_MODEL_NAME = "gemini-2.5-flash-preview-tts" # این مدل برای TTS استفاده میشود و نباید تغییر کند
|
| 32 |
DEFAULT_MAX_CHUNK_SIZE = 3800
|
| 33 |
DEFAULT_SLEEP_BETWEEN_REQUESTS = 8
|
| 34 |
DEFAULT_OUTPUT_FILENAME_BASE = "alpha_tts_audio"
|
| 35 |
|
| 36 |
+
# متغیر بررسی وجود کلید API Gemini مشابه کد اول، اما برای یک کلید
|
| 37 |
+
GEMINI_API_KEY_TTS = os.environ.get("GEMINI_API_KEY")
|
| 38 |
+
if not GEMINI_API_KEY_TTS:
|
| 39 |
+
logging.error(
|
| 40 |
+
'خطای حیاتی: Secret با نام GEMINI_API_KEY یافت نشد! ' +
|
| 41 |
+
'قابلیت تبدیل متن به گفتار غیرفعال خواهد بود. لطفاً Secret را در تنظیمات Space خود اضافه کنید.'
|
| 42 |
+
)
|
| 43 |
+
else:
|
| 44 |
+
logging.info("کلید API جیمینای (GEMINI_API_KEY) برای TTS بارگذاری شد.")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _log(message, log_list): # این تابع برای دیباگ داخلی خود کد دوم است و حفظ میشود
|
| 48 |
log_list.append(message)
|
|
|
|
| 49 |
|
| 50 |
def save_binary_file(file_name, data, log_list):
|
| 51 |
try:
|
|
|
|
| 71 |
param = param.strip()
|
| 72 |
if param.lower().startswith("rate="):
|
| 73 |
try: rate = int(param.split("=", 1)[1])
|
| 74 |
+
except: pass
|
| 75 |
elif param.startswith("audio/L"):
|
| 76 |
try: bits = int(param.split("L", 1)[1])
|
| 77 |
+
except: pass
|
| 78 |
return {"bits_per_sample": bits, "rate": rate}
|
| 79 |
|
| 80 |
def smart_text_split(text, max_size=3800, log_list=None):
|
| 81 |
if len(text) <= max_size: return [text]
|
| 82 |
chunks, current_chunk = [], ""
|
| 83 |
+
sentences = re.split(r'(?<=[.!?؟])\s+', text)
|
| 84 |
for sentence in sentences:
|
| 85 |
if len(current_chunk) + len(sentence) + 1 > max_size:
|
| 86 |
if current_chunk: chunks.append(current_chunk.strip())
|
|
|
|
| 96 |
return final_chunks
|
| 97 |
|
| 98 |
def merge_audio_files_func(file_paths, output_path, log_list):
|
| 99 |
+
if not PYDUB_AVAILABLE: _log("❌ pydub در دسترس نیست. نمیتوان فایلها را ادغام کرد.", log_list); return False
|
| 100 |
try:
|
| 101 |
_log(f"🔗 ادغام {len(file_paths)} فایل صوتی...", log_list)
|
| 102 |
combined = AudioSegment.empty()
|
| 103 |
for i, fp in enumerate(file_paths):
|
| 104 |
+
if os.path.exists(fp): combined += AudioSegment.from_file(fp) + (AudioSegment.silent(duration=150) if i < len(file_paths) - 1 else AudioSegment.empty())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
else: _log(f"⚠️ فایل پیدا نشد: {fp}", log_list)
|
|
|
|
|
|
|
|
|
|
| 106 |
combined.export(output_path, format="wav")
|
| 107 |
_log(f"✅ فایل ادغام شده: {output_path}", log_list); return True
|
| 108 |
except Exception as e: _log(f"❌ خطا در ادغام: {e}", log_list); return False
|
|
|
|
| 110 |
def core_generate_audio(text_input, prompt_input, selected_voice, temperature_val, log_list):
|
| 111 |
output_base_name = DEFAULT_OUTPUT_FILENAME_BASE
|
| 112 |
max_chunk, sleep_time = DEFAULT_MAX_CHUNK_SIZE, DEFAULT_SLEEP_BETWEEN_REQUESTS
|
| 113 |
+
_log("🚀 شروع فرآیند تولید صدا...", log_list)
|
| 114 |
+
|
| 115 |
+
if not GEMINI_API_KEY_TTS: # استفاده از متغیر بررسی شده در ابتدای اسکریپت
|
| 116 |
+
_log("❌ کلید API جیمینای (GEMINI_API_KEY) تنظیم نشده است. تولید صدا ممکن نیست.", log_list)
|
| 117 |
+
# برگرداندن پیام خطا برای نمایش در UI
|
| 118 |
+
# این پیام در output_text_translated (که اینجا معادلش وجود ندارد) یا یک کامپوننت پیام خطا نمایش داده میشود.
|
| 119 |
+
# فعلا فقط لاگ میکنیم، تابع gradio_tts_interface باید این را مدیریت کند.
|
| 120 |
+
return None, "خطا: کلید API جیمینای برای سرویس TTS تنظیم نشده است."
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
try: client = genai.Client(api_key=GEMINI_API_KEY_TTS)
|
| 124 |
+
except Exception as e: _log(f"❌ خطا در ایجاد کلاینت Gemini: {e}", log_list); return None, f"خطا در اتصال به Gemini: {e}"
|
| 125 |
+
if not text_input or not text_input.strip(): _log("❌ متن ورودی خالی است.", log_list); return None, "خطا: متن ورودی برای تبدیل به گفتار خالی است."
|
| 126 |
+
|
| 127 |
text_chunks = smart_text_split(text_input, max_chunk, log_list)
|
| 128 |
+
if not text_chunks: _log("❌ متن قابل پردازش نیست یا به قطعات خالی تقسیم شده.", log_list); return None, "خطا: متن ورودی پس از پردازش، خالی است."
|
| 129 |
|
| 130 |
generated_files = []
|
| 131 |
for i, chunk in enumerate(text_chunks):
|
| 132 |
+
_log(f"🔊 پردازش قطعه {i+1}/{len(text_chunks)}...", log_list)
|
| 133 |
final_text = f'"{prompt_input}"\n{chunk}' if prompt_input and prompt_input.strip() else chunk
|
| 134 |
+
contents = [types.Content(role="user", parts=[types.Part.from_text(text=final_text)])]
|
| 135 |
+
config = types.GenerateContentConfig(temperature=temperature_val, response_modalities=["audio"],
|
| 136 |
+
speech_config=types.SpeechConfig(voice_config=types.VoiceConfig(
|
| 137 |
+
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=selected_voice))))
|
| 138 |
fname_base = f"{output_base_name}_part{i+1:03d}"
|
| 139 |
try:
|
| 140 |
response = client.models.generate_content(model=FIXED_MODEL_NAME, contents=contents, config=config)
|
| 141 |
if response.candidates and response.candidates[0].content and response.candidates[0].content.parts and response.candidates[0].content.parts[0].inline_data:
|
| 142 |
inline_data = response.candidates[0].content.parts[0].inline_data
|
| 143 |
data_buffer = inline_data.data
|
| 144 |
+
ext = mimetypes.guess_extension(inline_data.mime_type) or ".wav"
|
| 145 |
+
if "audio/L" in inline_data.mime_type and ext == ".wav": data_buffer = convert_to_wav(data_buffer, inline_data.mime_type)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
if not ext.startswith("."): ext = "." + ext
|
| 147 |
fpath = save_binary_file(f"{fname_base}{ext}", data_buffer, log_list)
|
| 148 |
if fpath: generated_files.append(fpath)
|
| 149 |
+
else: _log(f"⚠️ پاسخ API برای قطعه {i+1} بدون داده صوتی معتبر.", log_list)
|
| 150 |
+
except Exception as e: _log(f"❌ خطا در تولید قطعه {i+1}: {e}", log_list); continue # ادامه با قطعه بعدی اگر خطایی رخ دهد
|
| 151 |
+
if i < len(text_chunks) - 1 and len(text_chunks) > 1: time.sleep(sleep_time)
|
| 152 |
+
|
| 153 |
+
if not generated_files: _log("❌ هیچ فایل صوتی تولید نشد.", log_list); return None, "خطا: هیچ فایل صوتی تولید نشد. (ممکن است مشکل از API یا متن ورودی باشد)."
|
| 154 |
+
_log(f"🎉 {len(generated_files)} فایل(های) صوتی با موفقیت تولید شد.", log_list)
|
|
|
|
|
|
|
| 155 |
|
| 156 |
final_audio_file = None
|
| 157 |
final_output_path_base = f"{output_base_name}_final"
|
|
|
|
| 159 |
if len(generated_files) > 1:
|
| 160 |
if PYDUB_AVAILABLE:
|
| 161 |
merged_fn = f"{final_output_path_base}.wav"
|
| 162 |
+
if os.path.exists(merged_fn): os.remove(merged_fn)
|
|
|
|
|
|
|
| 163 |
if merge_audio_files_func(generated_files, merged_fn, log_list):
|
| 164 |
final_audio_file = merged_fn
|
| 165 |
+
else:
|
| 166 |
+
_log("⚠️ ادغام فایلها ناموفق بود. اولین قطعه ارائه میشود.", log_list)
|
| 167 |
+
if generated_files: # اگر ادغام ناموفق بود، اولین قطعه با نام استاندارد ارائه میشود
|
|
|
|
|
|
|
|
|
|
| 168 |
try:
|
| 169 |
+
target_ext_fallback = os.path.splitext(generated_files[0])[1]
|
| 170 |
+
fallback_fn = f"{final_output_path_base}{target_ext_fallback}"
|
| 171 |
+
if os.path.exists(fallback_fn): os.remove(fallback_fn)
|
| 172 |
+
os.rename(generated_files[0], fallback_fn)
|
| 173 |
+
final_audio_file = fallback_fn
|
| 174 |
+
except Exception as e_rename_fallback:
|
| 175 |
+
_log(f"خطا در تغییر نام فایل اولین قطعه (پس از شکست ادغام): {e_rename_fallback}", log_list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
final_audio_file = generated_files[0]
|
| 177 |
+
# پاک کردن فایلهای جزئی
|
| 178 |
+
files_to_delete = [fp for fp in generated_files if os.path.abspath(fp) != os.path.abspath(final_audio_file)]
|
| 179 |
+
for fp_del in files_to_delete:
|
| 180 |
+
try: os.remove(fp_del)
|
| 181 |
+
except: pass
|
| 182 |
else:
|
| 183 |
+
_log("⚠️ pydub برای ادغام در دسترس نیست. اولین قطعه ارائه میشود.", log_list)
|
| 184 |
if generated_files:
|
| 185 |
try:
|
| 186 |
+
target_ext_no_pydub = os.path.splitext(generated_files[0])[1]
|
| 187 |
+
no_pydub_fn = f"{final_output_path_base}{target_ext_no_pydub}"
|
| 188 |
+
if os.path.exists(no_pydub_fn): os.remove(no_pydub_fn)
|
| 189 |
+
os.rename(generated_files[0], no_pydub_fn)
|
| 190 |
+
final_audio_file = no_pydub_fn
|
| 191 |
+
# پاک کردن سایر فایلهای جزئی
|
| 192 |
+
for i_gf in range(1, len(generated_files)):
|
| 193 |
+
try: os.remove(generated_files[i_gf])
|
| 194 |
+
except: pass
|
| 195 |
+
except Exception as e_rename_single_no_pydub:
|
| 196 |
+
_log(f"خطا در تغییر نام فایل اولین قطعه (بدون pydub): {e_rename_single_no_pydub}", log_list)
|
|
|
|
| 197 |
final_audio_file = generated_files[0]
|
| 198 |
+
|
| 199 |
elif len(generated_files) == 1:
|
| 200 |
try:
|
| 201 |
+
target_ext_single = os.path.splitext(generated_files[0])[1]
|
| 202 |
+
final_single_fn = f"{final_output_path_base}{target_ext_single}"
|
| 203 |
+
if os.path.exists(final_single_fn): os.remove(final_single_fn)
|
| 204 |
+
os.rename(generated_files[0], final_single_fn)
|
| 205 |
+
final_audio_file = final_single_fn
|
|
|
|
| 206 |
except Exception as e_rename_single_final:
|
| 207 |
_log(f"خطا در تغییر نام فایل تکی نهایی: {e_rename_single_final}", log_list)
|
| 208 |
final_audio_file = generated_files[0]
|
| 209 |
|
| 210 |
if final_audio_file and not os.path.exists(final_audio_file):
|
| 211 |
+
_log(f"⚠️ فایل نهایی '{final_audio_file}' پس از پردازش وجود ندارد!", log_list)
|
| 212 |
+
return None, f"خطای داخلی: فایل صوتی نهایی '{final_audio_file}' یافت نشد."
|
| 213 |
+
|
| 214 |
+
return final_audio_file, "TTS موفق" # پیام موفقیت اضافه شد
|
| 215 |
|
| 216 |
def gradio_tts_interface(use_file_input, uploaded_file, text_to_speak, speech_prompt, speaker_voice, temperature, progress=gr.Progress(track_tqdm=True)):
|
| 217 |
+
logs = [] # لاگهای داخلی تابع core_generate_audio
|
| 218 |
+
status_message_text = "" # متنی برای نمایش پیامهای وضعیت یا خطا
|
| 219 |
+
|
| 220 |
+
if not GEMINI_API_KEY_TTS:
|
| 221 |
+
# این پیام خطا باید در یک Textbox یا Markdown در UI نمایش داده شود
|
| 222 |
+
# تابع اصلی یک فایل صوتی و یک متن برمیگرداند.
|
| 223 |
+
# ما متن را برای پیام خطا استفاده میکنیم.
|
| 224 |
+
status_message_text = (
|
| 225 |
+
"خطا: سرویس تبدیل متن به گفتار پیکربندی نشده است. "
|
| 226 |
+
"کلید API جیمینای (GEMINI_API_KEY) در Secrets این Space یافت نشد. "
|
| 227 |
+
"لطفاً آن را تنظیم کنید."
|
| 228 |
+
)
|
| 229 |
+
# برگرداندن None برای صوت و پیام خطا برای تکست باکس
|
| 230 |
+
return None, status_message_text
|
| 231 |
+
|
| 232 |
actual_text = ""
|
| 233 |
if use_file_input:
|
| 234 |
if uploaded_file:
|
| 235 |
try:
|
| 236 |
with open(uploaded_file.name, 'r', encoding='utf-8') as f: actual_text = f.read().strip()
|
| 237 |
+
if not actual_text:
|
| 238 |
+
status_message_text = "خطا: فایل متنی انتخاب شده خالی است یا محتوایی ندارد."
|
| 239 |
+
return None, status_message_text
|
| 240 |
+
except Exception as e:
|
| 241 |
+
_log(f"❌ خطا در خواندن فایل: {e}", logs)
|
| 242 |
+
status_message_text = f"خطا در خواندن فایل ورودی: {e}"
|
| 243 |
+
return None, status_message_text
|
| 244 |
+
else:
|
| 245 |
+
status_message_text = "خطا: گزینه استفاده از فایل انتخاب شده، اما فایلی آپلود نشده است."
|
| 246 |
+
return None, status_message_text
|
| 247 |
else:
|
| 248 |
actual_text = text_to_speak
|
| 249 |
+
if not actual_text or not actual_text.strip():
|
| 250 |
+
status_message_text = "لطفاً متنی را برای تبدیل به گفتار وارد کنید."
|
| 251 |
+
return None, status_message_text
|
| 252 |
+
|
| 253 |
+
# فراخوانی core_generate_audio که حالا دو مقدار برمیگرداند
|
| 254 |
+
final_path, status_msg_core = core_generate_audio(actual_text, speech_prompt, speaker_voice, temperature, logs)
|
| 255 |
|
| 256 |
+
# برای دیباگ در کنسول Hugging Face Spaces
|
| 257 |
+
# for log_entry in logs:
|
| 258 |
+
# print(log_entry)
|
| 259 |
+
|
| 260 |
+
if final_path and os.path.exists(final_path):
|
| 261 |
+
# اگر موفق بود، پیام خاصی در تکست باکس لازم نیست، یا یک پیام موفقیت کلی
|
| 262 |
+
status_message_text = "صدای درخواستی با موفقیت تولید شد."
|
| 263 |
+
return final_path, status_message_text
|
| 264 |
+
else:
|
| 265 |
+
# اگر final_path نبود یا وجود نداشت، از status_msg_core استفاده کن
|
| 266 |
+
status_message_text = status_msg_core if status_msg_core else "خطای نامشخص در تولید صدا."
|
| 267 |
+
return None, status_message_text
|
| 268 |
|
| 269 |
|
| 270 |
+
# --- START: CSS و متغیرهای رنگی از کد اول (Alpha Translator) ---
|
| 271 |
FLY_PRIMARY_COLOR_HEX = "#4F46E5"
|
| 272 |
FLY_SECONDARY_COLOR_HEX = "#10B981"
|
| 273 |
+
FLY_ACCENT_COLOR_HEX = "#D97706" # این رنگ برای دکمه اصلی در کد اول استفاده شده بود
|
| 274 |
FLY_TEXT_COLOR_HEX = "#1F2937"
|
| 275 |
FLY_SUBTLE_TEXT_HEX = "#6B7280"
|
| 276 |
FLY_LIGHT_BACKGROUND_HEX = "#F9FAFB"
|
| 277 |
FLY_WHITE_HEX = "#FFFFFF"
|
| 278 |
FLY_BORDER_COLOR_HEX = "#D1D5DB"
|
| 279 |
FLY_INPUT_BG_HEX_SIMPLE = "#F3F4F6"
|
| 280 |
+
FLY_PANEL_BG_SIMPLE = "#E0F2FE" # برای پس زمینه بخش ترجمه شده در کد اول
|
| 281 |
|
| 282 |
+
app_theme_outer = gr.themes.Base(
|
| 283 |
font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"],
|
| 284 |
).set(
|
| 285 |
body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
|
| 286 |
)
|
| 287 |
|
| 288 |
+
custom_css = f"""
|
|
|
|
| 289 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
| 290 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap');
|
| 291 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
|
|
|
|
| 292 |
:root {{
|
| 293 |
+
--fly-primary: {FLY_PRIMARY_COLOR_HEX}; --fly-secondary: {FLY_SECONDARY_COLOR_HEX};
|
| 294 |
+
--fly-accent: {FLY_ACCENT_COLOR_HEX}; --fly-text-primary: {FLY_TEXT_COLOR_HEX};
|
| 295 |
+
--fly-text-secondary: {FLY_SUBTLE_TEXT_HEX}; --fly-bg-light: {FLY_LIGHT_BACKGROUND_HEX};
|
| 296 |
+
--fly-bg-white: {FLY_WHITE_HEX}; --fly-border-color: {FLY_BORDER_COLOR_HEX};
|
| 297 |
+
--fly-input-bg-simple: {FLY_INPUT_BG_HEX_SIMPLE}; --fly-panel-bg-simple: {FLY_PANEL_BG_SIMPLE};
|
| 298 |
+
--font-global: 'Vazirmatn', 'Inter', 'Poppins', system-ui, sans-serif;
|
| 299 |
+
--font-english: 'Poppins', 'Inter', system-ui, sans-serif; /* برای متن انگلیسی در صورت نیاز */
|
| 300 |
+
--radius-sm: 0.375rem; --radius-md: 0.5rem; --radius-lg: 0.75rem; --radius-xl: 1rem; --radius-full: 9999px;
|
| 301 |
+
--shadow-sm: 0 1px 2px 0 rgba(0,0,0,0.05); --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1),0 2px 4px -2px rgba(0,0,0,0.1);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
--shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1),0 4px 6px -4px rgba(0,0,0,0.1);
|
| 303 |
--shadow-xl: 0 20px 25px -5px rgba(0,0,0,0.1),0 8px 10px -6px rgba(0,0,0,0.1);
|
| 304 |
+
--fly-primary-rgb: 79,70,229; --fly-accent-rgb: 217,119,6;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
}}
|
| 306 |
+
body {{font-family:var(--font-global);direction:rtl;background-color:var(--fly-bg-light);color:var(--fly-text-primary);line-height:1.7;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:16px;}}
|
| 307 |
+
.gradio-container {{max-width:100% !important;width:100% !important;min-height:100vh;margin:0 auto !important;padding:0 !important;border-radius:0 !important;box-shadow:none !important;background:linear-gradient(170deg, #E0F2FE 0%, #F3E8FF 100%);display:flex;flex-direction:column;}}
|
| 308 |
+
.app-title-card {{text-align:center;padding:2.5rem 1rem;margin:0;background:linear-gradient(135deg,var(--fly-primary) 0%,var(--fly-secondary) 100%);color:var(--fly-bg-white);border-bottom-left-radius:var(--radius-xl);border-bottom-right-radius:var(--radius-xl);box-shadow:var(--shadow-lg);position:relative;overflow:hidden;}}
|
| 309 |
+
.app-title-card::before {{content:'';position:absolute;top:-50px;right:-50px;width:150px;height:150px;background:rgba(255,255,255,0.1);border-radius:var(--radius-full);opacity:0.5;transform:rotate(45deg);}}
|
| 310 |
+
.app-title-card h1 {{font-size:2.25em !important;font-weight:800 !important;margin:0 0 0.5rem 0;font-family:var(--font-english);letter-spacing:-0.5px;text-shadow:0 2px 4px rgba(0,0,0,0.1);}} /* فونت انگلیسی برای عنوان اصلی */
|
| 311 |
+
.app-title-card p {{font-size:1em !important;margin-top:0.25rem;font-weight:400;color:rgba(255,255,255,0.85) !important;}}
|
| 312 |
+
.app-footer-fly {{text-align:center;font-size:0.85em;color:var(--fly-text-secondary);margin-top:2.5rem;padding:1rem 0;background-color:rgba(255,255,255,0.3);backdrop-filter:blur(5px);border-top:1px solid var(--fly-border-color);}}
|
| 313 |
+
footer,.gradio-footer,.flagging-container,.flex.row.gap-2.absolute.bottom-2.right-2.gr-compact.gr-box.gr-text-gray-500,div[data-testid="flag"],button[title="Flag"],button[aria-label="Flag"],.footer-utils {{display:none !important;visibility:hidden !important;}}
|
| 314 |
+
.main-content-area {{flex-grow:1;padding:0.75rem;width:100%;margin:0 auto;box-sizing:border-box;}}
|
| 315 |
+
.content-panel-simple {{background-color:var(--fly-bg-white);padding:1rem;border-radius:var(--radius-xl);box-shadow:var(--shadow-xl);margin-top:-2rem;position:relative;z-index:10;margin-bottom:2rem;width:100%;box-sizing:border-box;}}
|
| 316 |
+
|
| 317 |
+
/* استایل دکمه اصلی با استفاده از رنگ accent کد اول */
|
| 318 |
+
.content-panel-simple .gr-button.lg.primary, .content-panel-simple button[variant="primary"].lg {{
|
| 319 |
+
background:var(--fly-accent) !important;
|
| 320 |
+
margin-top:1rem !important;padding:12px 20px !important;
|
| 321 |
+
transition:all 0.25s ease-in-out !important;color:white !important;
|
| 322 |
+
font-weight:600 !important;border-radius:10px !important;
|
| 323 |
+
border:none !important;box-shadow:0 3px 8px -1px rgba(var(--fly-accent-rgb),0.3) !important;
|
| 324 |
+
width:100% !important;font-size:1em !important;
|
| 325 |
+
display:flex;align-items:center;justify-content:center;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
}}
|
| 327 |
+
.content-panel-simple .gr-button.lg.primary:hover, .content-panel-simple button[variant="primary"].lg:hover {{
|
| 328 |
+
background:#B45309 !important; /* رنگ تیرهتر fly-accent برای هاور */
|
| 329 |
+
transform:translateY(-1px) !important;
|
| 330 |
+
box-shadow:0 5px 10px -1px rgba(var(--fly-accent-rgb),0.4) !important;
|
| 331 |
}}
|
| 332 |
|
| 333 |
+
.content-panel-simple .gr-input > label + div > textarea,
|
| 334 |
+
.content-panel-simple .gr-dropdown > label + div > div > input,
|
| 335 |
+
.content-panel-simple .gr-dropdown > label + div > div > select,
|
| 336 |
+
.content-panel-simple .gr-textbox > label + div > textarea,
|
| 337 |
+
.content-panel-simple .gr-file > label + div /* اضافه شده برای فایل */
|
|
|
|
|
|
|
| 338 |
{{
|
| 339 |
+
border-radius:8px !important;border:1.5px solid var(--fly-border-color) !important;
|
| 340 |
+
font-size:0.95em !important;background-color:var(--fly-input-bg-simple) !important;
|
| 341 |
+
padding:10px 12px !important;color:var(--fly-text-primary) !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
}}
|
| 343 |
+
.content-panel-simple .gr-file > label + div {{ text-align:center; border-style: dashed !important; }} /* استایل برای درگ و دراپ فایل */
|
| 344 |
|
| 345 |
+
.content-panel-simple .gr-input > label + div > textarea:focus,
|
| 346 |
+
.content-panel-simple .gr-dropdown > label + div > div > input:focus,
|
| 347 |
+
.content-panel-simple .gr-dropdown > label + div > div > select:focus,
|
| 348 |
+
.content-panel-simple .gr-textbox > label + div > textarea:focus,
|
| 349 |
+
.content-panel-simple .gr-file > label + div:focus-within /* اضافه شده برای فایل */
|
|
|
|
| 350 |
{{
|
| 351 |
border-color:var(--fly-primary) !important;
|
| 352 |
box-shadow:0 0 0 3px rgba(var(--fly-primary-rgb),0.12) !important;
|
| 353 |
background-color:var(--fly-bg-white) !important;
|
| 354 |
}}
|
| 355 |
+
.content-panel-simple .gr-dropdown select {{font-family:var(--font-global) !important;width:100%;cursor:pointer;}}
|
| 356 |
+
|
| 357 |
+
/* استایل برای تکستباکس خروجی (پیام وضعیت) */
|
| 358 |
+
.content-panel-simple .gr-textbox[label*="وضعیت"] > label + div > textarea,
|
| 359 |
+
.content-panel-simple .gr-textbox[elem_id="status_text_output_tts"] > label + div > textarea {{
|
| 360 |
+
background-color:var(--fly-panel-bg-simple) !important;
|
| 361 |
+
border-color:#A5D5FE !important;min-height:60px; /* ارتفاع کمتر برای پیام وضعیت */
|
| 362 |
+
font-family:var(--font-global); /* فونت فارسی برای پیامها */
|
| 363 |
+
font-size:0.9em !important;line-height:1.5;padding:8px 10px !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
}}
|
| 365 |
|
| 366 |
+
.content-panel-simple .gr-panel,
|
| 367 |
+
.content-panel-simple div[label*="تنظیمات پیشرفته"] > .gr-accordion > .gr-panel /* اگر آکاردئون اضافه شود */
|
|
|
|
| 368 |
{{
|
| 369 |
+
border-radius:8px !important;border:1px solid var(--fly-border-color) !important;
|
| 370 |
+
background-color:var(--fly-input-bg-simple) !important;
|
| 371 |
+
padding:0.8rem 1rem !important;margin-top:0.6rem;box-shadow:none;
|
| 372 |
}}
|
| 373 |
+
.content-panel-simple label > span.label-text {{font-weight:500 !important;color:#4B5563 !important;font-size:0.88em !important;margin-bottom:6px !important;display:inline-block;}}
|
| 374 |
+
.content-panel-simple .gr-slider label span {{font-size:0.82em !important;color:var(--fly-text-secondary);}}
|
| 375 |
+
|
| 376 |
+
.content-panel-simple div[label*="نمونه"], .content-panel-simple .gr-examples[label*="نمونه"] {{margin-top:1.5rem;}}
|
| 377 |
+
.content-panel-simple div[label*="نمونه"] .gr-button.gr-button-tool,
|
| 378 |
+
.content-panel-simple div[label*="نمونه"] .gr-sample-button,
|
| 379 |
+
.content-panel-simple .gr-examples[label*="نمونه"] .gr-button.gr-button-tool,
|
| 380 |
+
.content-panel-simple .gr-examples[label*="نمونه"] .gr-sample-button
|
| 381 |
+
{{
|
| 382 |
+
background-color:#E0E7FF !important;color:var(--fly-primary) !important;
|
| 383 |
+
border-radius:6px !important;font-size:0.78em !important;padding:4px 8px !important;
|
| 384 |
}}
|
| 385 |
+
.content-panel-simple .custom-hr {{height:1px;background-color:var(--fly-border-color);margin:1.5rem 0;border:none;}}
|
| 386 |
+
|
| 387 |
+
/* استایل برای پیام هشدار API Key مشابه کد اول */
|
| 388 |
+
.api-warning-message {{
|
| 389 |
+
background-color:#FFFBEB !important;color:#92400E !important;
|
| 390 |
+
padding:10px 12px !important;border-radius:8px !important;
|
| 391 |
+
border:1px solid #FDE68A !important;text-align:center !important;
|
| 392 |
+
margin:0 0.2rem 1rem 0.2rem !important;font-size:0.85em !important;
|
| 393 |
}}
|
| 394 |
|
| 395 |
+
/* استایل برای پلیر صوتی */
|
| 396 |
+
.content-panel-simple #output_audio_player_tts audio {{ width: 100%; border-radius: var(--radius-input, 8px); margin-top:0.8rem; }}
|
| 397 |
+
.temp_description_class_tts {{ font-size: 0.85em; color: var(--fly-subtle-text, #777); margin-top: -0.4rem; margin-bottom: 1rem; }}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
@media (min-width:640px) {{
|
| 401 |
+
.main-content-area {{padding:1.5rem;max-width:700px;}}
|
| 402 |
+
.content-panel-simple {{padding:1.5rem;}}
|
| 403 |
+
.app-title-card h1 {{font-size:2.5em !important;}}
|
| 404 |
+
.app-title-card p {{font-size:1.05em !important;}}
|
| 405 |
}}
|
| 406 |
@media (min-width:768px) {{
|
| 407 |
+
.main-content-area {{max-width:780px;}}
|
| 408 |
+
.content-panel-simple {{padding:2rem;}}
|
| 409 |
+
/* .content-panel-simple .main-content-row {{display:flex !important;flex-direction:row !important;gap:1.5rem !important;}} */ /* این بخش برای چیدمان دو ستونه بود که در این کد دوم نداریم */
|
| 410 |
+
/* .content-panel-simple .main-content-row > .gr-column:nth-child(1) {{flex-basis:60%;}} */
|
| 411 |
+
/* .content-panel-simple .main-content-row > .gr-column:nth-child(2) {{flex-basis:40%;}} */
|
| 412 |
+
.content-panel-simple .gr-button.lg.primary, .content-panel-simple button[variant="primary"].lg {{width:auto !important;align-self:flex-start;}}
|
| 413 |
+
.app-title-card h1 {{font-size:2.75em !important;}}
|
| 414 |
+
.app-title-card p {{font-size:1.1em !important;}}
|
| 415 |
}}
|
| 416 |
"""
|
| 417 |
+
# --- END: CSS و متغیرهای رنگی ---
|
| 418 |
|
| 419 |
+
|
| 420 |
+
with gr.Blocks(theme=app_theme_outer, css=custom_css, title="آلفا TTS") as demo:
|
| 421 |
+
# هدر مشابه کد اول، با تغییر عنوان و متن
|
| 422 |
gr.HTML(f"""
|
| 423 |
+
<div class="app-title-card">
|
| 424 |
<h1>🚀 Alpha TTS</h1>
|
| 425 |
+
<p>جادوی تبدیل متن به صدا در دستان شما</p>
|
| 426 |
</div>
|
| 427 |
""")
|
| 428 |
|
| 429 |
+
with gr.Column(elem_classes=["main-content-area"]):
|
| 430 |
+
with gr.Group(elem_classes=["content-panel-simple"]):
|
| 431 |
+
# نمایش هشدار اگر کلید API تنظیم نشده باشد (مشابه کد اول)
|
| 432 |
+
if not GEMINI_API_KEY_TTS:
|
| 433 |
+
missing_key_msg_tts = (
|
| 434 |
+
"⚠️ هشدار: قابلیت تبدیل متن به گفتار غیرفعال است. "
|
| 435 |
+
"کلید API جیمینای (GEMINI_API_KEY) "
|
| 436 |
+
"در بخش Secrets این Space یافت نشد. "
|
| 437 |
+
"لطفاً آن را تنظیم کنید."
|
| 438 |
+
)
|
| 439 |
+
gr.Markdown(f"<div class='api-warning-message'>{missing_key_msg_tts}</div>")
|
| 440 |
|
| 441 |
+
# اجزای UI کد دوم در اینجا قرار میگیرند، با حفظ ساختار داخلی آنها
|
| 442 |
+
# اما کلاسهای CSS کد اول به آنها اعمال خواهد شد.
|
| 443 |
+
|
| 444 |
+
use_file_input_cb = gr.Checkbox(
|
| 445 |
+
label="📄 استفاده از فایل متنی (.txt) برای ورود متن", # لیبل واضحتر
|
| 446 |
+
value=False,
|
| 447 |
+
elem_id="use_file_cb_tts" # elem_id حفظ شده
|
| 448 |
+
)
|
| 449 |
uploaded_file_input = gr.File(
|
| 450 |
+
label="انتخاب فایل .txt", # لیبل برای حالت نمایش فایل
|
| 451 |
file_types=['.txt'],
|
| 452 |
visible=False,
|
| 453 |
+
elem_id="file_uploader_tts" # elem_id حفظ شده
|
| 454 |
)
|
|
|
|
| 455 |
text_to_speak_tb = gr.Textbox(
|
| 456 |
+
label="📝 متن فارسی برای تبدیل به گفتار", # آیکون مشابه کد اول
|
| 457 |
+
placeholder="مثال: سلام، امروز هوا بسیار دلپذیر است.",
|
| 458 |
lines=5,
|
| 459 |
+
value="",
|
| 460 |
visible=True,
|
| 461 |
+
elem_id="text_input_tts" # elem_id حفظ شده
|
| 462 |
)
|
| 463 |
|
| 464 |
+
# منطق نمایش/عدم نمایش فیلدها حفظ میشود
|
| 465 |
+
def toggle_input_method(use_file):
|
| 466 |
+
return gr.update(visible=use_file), gr.update(visible=not use_file)
|
| 467 |
+
|
| 468 |
use_file_input_cb.change(
|
| 469 |
+
fn=toggle_input_method,
|
| 470 |
inputs=use_file_input_cb,
|
| 471 |
outputs=[uploaded_file_input, text_to_speak_tb]
|
| 472 |
)
|
| 473 |
|
| 474 |
speech_prompt_tb = gr.Textbox(
|
| 475 |
+
label="🗣️ سبک گفتار (اختیاری)", # آیکون مشابه کد اول
|
| 476 |
+
placeholder="مثال: با لحنی شاد و پرانرژی صحبت کن.",
|
| 477 |
value="با لحنی دوستانه و رسا صحبت کن.",
|
| 478 |
+
lines=2, elem_id="speech_prompt_tts" # elem_id حفظ شده
|
| 479 |
)
|
|
|
|
| 480 |
speaker_voice_dd = gr.Dropdown(
|
| 481 |
+
SPEAKER_VOICES,
|
| 482 |
+
label="🎤 انتخاب گوینده", # آیکون مشابه کد اول (با تغییر متن لیبل)
|
| 483 |
+
value="Charon", # مقدار پیشفرض حفظ شده
|
| 484 |
+
elem_id="speaker_voice_tts" # elem_id حفظ شده
|
| 485 |
)
|
|
|
|
| 486 |
temperature_slider = gr.Slider(
|
| 487 |
+
minimum=0.1, maximum=1.5, step=0.05, value=0.9,
|
| 488 |
+
label="🌡️ میزان خلاقیت صدا (Temperature)", # آیکون مشابه کد اول
|
| 489 |
+
elem_id="temperature_slider_tts" # elem_id حفظ شده
|
| 490 |
+
)
|
| 491 |
+
# توضیح اسلایدر با کلاس CSS مشابه کد اول برای هماهنگی
|
| 492 |
+
gr.Markdown("<p class='temp_description_class_tts'>مقادیر بالاتر = تنوع بیشتر در صدا، مقادیر پایینتر = صدای یکنواختتر.</p>")
|
| 493 |
+
|
| 494 |
+
# دکمه اصلی با استایل کد اول (variant="primary" و elem_classes=["lg"])
|
| 495 |
+
generate_button = gr.Button(
|
| 496 |
+
"🚀 تولید و پخش صدا",
|
| 497 |
+
variant="primary", # برای اعمال استایل دکمه اصلی از کد اول
|
| 498 |
+
elem_classes=["lg"] # برای اعمال استایل دکمه اصلی از کد اول
|
| 499 |
)
|
|
|
|
|
|
|
|
|
|
| 500 |
|
| 501 |
+
# خروجیها: صوت و یک تکستباکس برای پیام وضعیت/خطا
|
| 502 |
+
status_text_output = gr.Textbox(
|
| 503 |
+
label="📜 وضعیت پردازش و پیامها", # لیبل واضحتر
|
| 504 |
+
interactive=False,
|
| 505 |
+
lines=2, # ارتفاع کمتر برای پیامها
|
| 506 |
+
placeholder="پیامهای وضعیت یا خطا در اینجا نمایش داده میشوند...",
|
| 507 |
+
elem_id="status_text_output_tts" # elem_id جدید برای این کامپوننت
|
| 508 |
+
)
|
| 509 |
+
output_audio = gr.Audio(
|
| 510 |
+
label="🎧 فایل صوتی تولید شده", # لیبل واضحتر
|
| 511 |
+
type="filepath",
|
| 512 |
+
interactive=False, # مانند کد اول، غیرفعال
|
| 513 |
+
autoplay=True, # مانند کد اول، پخش خودکار
|
| 514 |
+
elem_id="output_audio_player_tts" # elem_id با پسوند tts برای تمایز
|
| 515 |
+
)
|
| 516 |
|
| 517 |
+
generate_button.click(
|
| 518 |
+
fn=gradio_tts_interface,
|
| 519 |
+
inputs=[use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider],
|
| 520 |
+
outputs=[output_audio, status_text_output] # خروجی دوم برای پیام وضعیت
|
| 521 |
)
|
| 522 |
+
|
| 523 |
+
# بخش نمونهها با استایل مشابه کد اول
|
| 524 |
+
# gr.HTML("<hr class='custom-hr'>") # خط جداکننده از کد اول
|
| 525 |
+
example_list_tts = [
|
| 526 |
[False, None, "سلام بر شما، امیدوارم روز خوبی داشته باشید.", "با لحنی گرم و صمیمی.", "Zephyr", 0.85],
|
| 527 |
[False, None, "این یک آزمایش برای بررسی کیفیت صدای تولید شده توسط هوش مصنوعی آلفا است.", "با صدایی طبیعی و روان.", "Charon", 0.9],
|
| 528 |
+
[False, None, "به دنیای شگفتانگیز تبدیل متن به گفتار خوش آمدید!", "با هیجان و انرژی بالا.", "Achird", 1.0],
|
| 529 |
+
]
|
| 530 |
+
|
| 531 |
+
if example_list_tts: # فقط اگر نمونهای وجود دارد نمایش بده
|
| 532 |
+
gr.Examples(
|
| 533 |
+
examples=example_list_tts,
|
| 534 |
+
inputs=[use_file_input_cb, uploaded_file_input, text_to_speak_tb, speech_prompt_tb, speaker_voice_dd, temperature_slider],
|
| 535 |
+
outputs=[output_audio, status_text_output], # خروجی دوم برای پیام وضعیت
|
| 536 |
+
fn=gradio_tts_interface,
|
| 537 |
+
cache_examples=os.getenv("GRADIO_CACHE_EXAMPLES", "False").lower() == "true", # مشابه کد اول
|
| 538 |
+
label="💡 نمونههای کاربردی" # لیبل مشابه کد اول برای اعمال استایل صحیح
|
| 539 |
+
)
|
| 540 |
+
else:
|
| 541 |
+
gr.Markdown("<p style='text-align:center; color:var(--fly-text-secondary); margin-top:1rem;'>نمونهای برای نمایش موجود نیست.</p>")
|
| 542 |
|
| 543 |
+
# فوتر مشابه کد اول
|
| 544 |
+
gr.Markdown("<p class='app-footer-fly'>Alpha Language Learning © 2024</p>") # سال میتواند 2024 یا 2025 باشد
|
| 545 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
|
| 547 |
if __name__ == "__main__":
|
| 548 |
+
if not GEMINI_API_KEY_TTS: # بررسی مجدد برای اطمینان در زمان اجرا
|
| 549 |
+
logging.warning("هشدار: کلید API جیمینای (GEMINI_API_KEY) برای TTS یافت نشد. برنامه اجرا میشود اما تولید صدا کار نخواهد کرد.")
|
| 550 |
+
|
|
|
|
|
|
|
| 551 |
demo.launch(
|
| 552 |
server_name="0.0.0.0",
|
| 553 |
server_port=int(os.getenv("PORT", 7860)),
|