Update app.py
Browse files
app.py
CHANGED
|
@@ -9,7 +9,7 @@ import google.generativeai as genai
|
|
| 9 |
import logging
|
| 10 |
|
| 11 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
|
| 12 |
-
logging.info(f"Gradio version: {gr.__version__}")
|
| 13 |
|
| 14 |
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
|
| 15 |
model = None
|
|
@@ -23,7 +23,7 @@ if GOOGLE_API_KEY:
|
|
| 23 |
else:
|
| 24 |
logging.warning("کلید API گوگل (GOOGLE_API_KEY) تنظیم نشده است.")
|
| 25 |
|
| 26 |
-
# --- دیکشنری کامل صداهای انگلیسی
|
| 27 |
language_dict_persian_keys = {
|
| 28 |
'انگلیسی (آمریکا) - جنی (زن)': 'en-US-JennyNeural', 'انگلیسی (آمریکا) - گای (مرد)': 'en-US-GuyNeural',
|
| 29 |
'انگلیسی (آمریکا) - آنا (زن، صدای کودک)': 'en-US-AnaNeural', 'انگلیسی (آمریکا) - آریا (زن)': 'en-US-AriaNeural',
|
|
@@ -59,120 +59,95 @@ language_dict_persian_keys = {
|
|
| 59 |
}
|
| 60 |
|
| 61 |
async def translate_text_gemini_async(text, target_language="English"):
|
| 62 |
-
if not model: logging.error("Gemini model not loaded."); return "
|
| 63 |
-
if not text or not text.strip(): logging.warning("Translate: Empty input text."); return "
|
| 64 |
try:
|
| 65 |
prompt = f"Translate the following Persian text to {target_language}. Provide only the translated English text, naturally and fluently, without any extra phrases, explanations, or markdown formatting. Be concise and accurate.\n\nPersian: \"{text}\"\n{target_language}:"
|
| 66 |
response = await model.generate_content_async(prompt)
|
| 67 |
translated_text = response.text.strip()
|
| 68 |
if translated_text.lower().startswith(f"{target_language.lower()}:"):
|
| 69 |
translated_text = translated_text[len(target_language)+1:].strip()
|
| 70 |
-
return "
|
| 71 |
-
except Exception as e: logging.error(f"Gemini translation error: {e}", exc_info=True); return f"
|
| 72 |
|
| 73 |
async def text_to_speech_edge_tts_async(text_to_speak, tts_voice_key, rate, volume, pitch):
|
| 74 |
-
if not text_to_speak or not text_to_speak.strip(): logging.warning("TTS: Empty input text."); return "
|
| 75 |
voice_id = language_dict_persian_keys.get(tts_voice_key)
|
| 76 |
-
if voice_id is None: logging.error(f"TTS: Voice key '{tts_voice_key}' not found."); return f"
|
| 77 |
try:
|
| 78 |
rate_str, volume_str, pitch_str = f"{int(rate):+g}%", f"{int(volume):+g}%", f"{int(pitch):+g}Hz"
|
| 79 |
communicate = edge_tts.Communicate(text_to_speak, voice_id, rate=rate_str, volume=volume_str, pitch=pitch_str)
|
| 80 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: tmp_path = tmp_file.name
|
| 81 |
await communicate.save(tmp_path)
|
| 82 |
-
return "TTS
|
| 83 |
-
except Exception as e: logging.error(f"Edge-TTS error: {e}", exc_info=True); return f"
|
| 84 |
|
| 85 |
_thread_local = threading.local()
|
| 86 |
|
| 87 |
def get_event_loop():
|
| 88 |
if not hasattr(_thread_local, 'loop') or _thread_local.loop.is_closed():
|
| 89 |
_thread_local.loop = asyncio.new_event_loop()
|
| 90 |
-
logging.info(f"Created new event loop for thread {threading.get_ident()}")
|
| 91 |
|
| 92 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
asyncio.set_event_loop(_thread_local.loop)
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
"There is no current event loop in thread" not in str(e):
|
| 97 |
-
logging.warning(f"RuntimeError setting event loop (possibly already running or other issue): {e}")
|
| 98 |
-
if asyncio.get_event_loop_policy().get_event_loop() is not _thread_local.loop:
|
| 99 |
-
try:
|
| 100 |
-
asyncio.set_event_loop(_thread_local.loop)
|
| 101 |
-
except RuntimeError as e_retry:
|
| 102 |
-
logging.warning(f"Retry setting event loop failed: {e_retry}")
|
| 103 |
return _thread_local.loop
|
| 104 |
|
|
|
|
| 105 |
def translate_and_speak_sync_wrapper(persian_text, english_tts_voice_key, rate, volume, pitch):
|
| 106 |
logging.info(f"Wrapper called. Text: '{persian_text[:30]}...' Voice: {english_tts_voice_key}")
|
| 107 |
loop = get_event_loop()
|
| 108 |
|
| 109 |
if not GOOGLE_API_KEY or not model:
|
| 110 |
-
msg = "خطا: سرویس ترجمه پیکربندی نشده است. لطفاً از تنظیم GOOGLE_API_KEY
|
| 111 |
logging.error(msg); return msg, None
|
| 112 |
if not persian_text or not persian_text.strip():
|
| 113 |
msg = "لطفاً متن فارسی را برای ترجمه وارد کنید."
|
| 114 |
logging.warning(msg); return msg, None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
try:
|
| 116 |
translation_status_msg, translated_text = loop.run_until_complete(
|
| 117 |
translate_text_gemini_async(persian_text)
|
| 118 |
)
|
| 119 |
-
if "
|
| 120 |
err_msg = f"ترجمه ناموفق: {translation_status_msg} {translated_text or ''}"
|
| 121 |
logging.error(err_msg); return err_msg, None
|
| 122 |
|
| 123 |
tts_status_msg, audio_path = loop.run_until_complete(
|
| 124 |
text_to_speech_edge_tts_async(translated_text, english_tts_voice_key, rate, volume, pitch)
|
| 125 |
)
|
| 126 |
-
if "
|
| 127 |
-
err_msg = f"{translated_text}\n(خطای TTS: {tts_status_msg})"
|
| 128 |
logging.error(err_msg); return err_msg, None
|
| 129 |
|
| 130 |
-
logging.info(f"عملیات موفق. مسیر صوت: {audio_path}")
|
| 131 |
return translated_text, audio_path
|
| 132 |
-
except RuntimeError as e:
|
| 133 |
-
if "cannot be started when it is already running" in str(e) or \
|
| 134 |
-
"This event loop is already running" in str(e):
|
| 135 |
-
logging.error(f"Asyncio runtime error (loop already running): {e}", exc_info=True)
|
| 136 |
-
new_loop = asyncio.new_event_loop()
|
| 137 |
-
asyncio.set_event_loop(new_loop)
|
| 138 |
-
try:
|
| 139 |
-
logging.info("Retrying with a new event loop due to runtime error.")
|
| 140 |
-
translation_status_msg, translated_text = new_loop.run_until_complete(
|
| 141 |
-
translate_text_gemini_async(persian_text)
|
| 142 |
-
)
|
| 143 |
-
if "error" in translation_status_msg.lower() or not translated_text or "خطا" in translation_status_msg.lower() :
|
| 144 |
-
err_msg = f"ترجمه ناموفق (retry): {translation_status_msg} {translated_text or ''}"
|
| 145 |
-
logging.error(err_msg); return err_msg, None
|
| 146 |
-
|
| 147 |
-
tts_status_msg, audio_path = new_loop.run_until_complete(
|
| 148 |
-
text_to_speech_edge_tts_async(translated_text, english_tts_voice_key, rate, volume, pitch)
|
| 149 |
-
)
|
| 150 |
-
if "error" in tts_status_msg.lower() or not audio_path or "خطا" in tts_status_msg.lower():
|
| 151 |
-
err_msg = f"{translated_text}\n(خطای TTS (retry): {tts_status_msg})"
|
| 152 |
-
logging.error(err_msg); return err_msg, None
|
| 153 |
-
|
| 154 |
-
logging.info(f"عملیات موفق (retry). مسیر صوت: {audio_path}")
|
| 155 |
-
return translated_text, audio_path
|
| 156 |
-
finally:
|
| 157 |
-
new_loop.close()
|
| 158 |
-
else:
|
| 159 |
-
logging.error(f"خطای غیرمنتظره در wrapper (RuntimeError): {e}", exc_info=True)
|
| 160 |
-
return f"خطای داخلی سرور (RuntimeError): {type(e).__name__}", None
|
| 161 |
except Exception as e:
|
| 162 |
logging.error(f"خطای غیرمنتظره در wrapper: {e}", exc_info=True)
|
| 163 |
return f"خطای داخلی سرور: {type(e).__name__}", None
|
| 164 |
|
| 165 |
-
|
| 166 |
FLY_PRIMARY_COLOR_HEX = "#2563EB"
|
| 167 |
FLY_SECONDARY_COLOR_HEX = "#059669"
|
| 168 |
-
FLY_ACCENT_COLOR_HEX = "#
|
| 169 |
FLY_TEXT_COLOR_HEX = "#1F2937"
|
| 170 |
-
FLY_SUBTLE_TEXT_HEX = "#
|
| 171 |
-
FLY_LIGHT_BACKGROUND_HEX = "#F3F4F6"
|
| 172 |
FLY_WHITE_HEX = "#FFFFFF"
|
| 173 |
FLY_BORDER_COLOR_HEX = "#D1D5DB"
|
| 174 |
FLY_INPUT_BG_HEX = "#FFFFFF"
|
| 175 |
-
FLY_PANEL_BG_HEX = "#E0F2FE"
|
|
|
|
|
|
|
| 176 |
|
| 177 |
app_theme = gr.themes.Soft(
|
| 178 |
primary_hue=gr.themes.colors.blue,
|
|
@@ -181,11 +156,12 @@ app_theme = gr.themes.Soft(
|
|
| 181 |
font=[gr.themes.GoogleFont("Vazirmatn"), "Arial", "sans-serif"],
|
| 182 |
).set(
|
| 183 |
body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
button_primary_text_color=
|
| 187 |
)
|
| 188 |
|
|
|
|
| 189 |
custom_css = f"""
|
| 190 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700&display=swap');
|
| 191 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
|
|
@@ -196,9 +172,10 @@ custom_css = f"""
|
|
| 196 |
--fly-subtle-text: {FLY_SUBTLE_TEXT_HEX}; --fly-light-bg: {FLY_LIGHT_BACKGROUND_HEX};
|
| 197 |
--fly-white: {FLY_WHITE_HEX}; --fly-border: {FLY_BORDER_COLOR_HEX};
|
| 198 |
--fly-input-bg: {FLY_INPUT_BG_HEX}; --fly-panel-bg: {FLY_PANEL_BG_HEX};
|
|
|
|
| 199 |
--global-font: 'Vazirmatn', 'Inter', 'Poppins', Arial, sans-serif;
|
| 200 |
--english-font: 'Poppins', 'Inter', Arial, sans-serif;
|
| 201 |
-
--border-radius-sm: 6px; --border-radius-md:
|
| 202 |
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
|
| 203 |
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
| 204 |
}}
|
|
@@ -207,206 +184,193 @@ body {{font-family: var(--global-font); direction: rtl; background-color: var(--
|
|
| 207 |
|
| 208 |
.app-header-fly {{
|
| 209 |
text-align: center; padding: 24px 15px;
|
| 210 |
-
background
|
| 211 |
-
color: white; margin: 0 0 1.5rem 0;
|
| 212 |
-
|
| 213 |
-
box-shadow: var(--shadow-md);
|
| 214 |
}}
|
| 215 |
-
.app-header-fly h1 {{font-size: 1.8em !important; font-weight: 700 !important; margin: 0 0 6px 0; font-family: var(--english-font); letter-spacing:
|
| 216 |
.app-header-fly p {{font-size: 0.95em !important; margin-top: 4px; font-weight: 400; color: rgba(255, 255, 255, 0.9) !important;}}
|
| 217 |
|
| 218 |
-
.main-content-area-fly {{
|
| 219 |
-
|
| 220 |
-
max-width: 700px;
|
| 221 |
-
width: 100%;
|
| 222 |
-
margin: 0 auto;
|
| 223 |
-
}}
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
.gr-
|
| 229 |
-
.gr-dropdown > label + div > div >
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
font-
|
| 234 |
-
background-color: var(--fly-input-bg) !important;
|
| 235 |
-
padding: 10px 14px !important;
|
| 236 |
-
line-height: 1.6;
|
| 237 |
-
width: 100% !important;
|
| 238 |
-
box-sizing: border-box !important;
|
| 239 |
-
font-family: var(--global-font) !important;
|
| 240 |
-
color: var(--fly-text) !important;
|
| 241 |
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
| 242 |
}}
|
| 243 |
.gr-input > label + div > textarea:focus,
|
| 244 |
.gr-dropdown > label + div > div > input:focus,
|
| 245 |
-
.gr-dropdown select:focus {{
|
| 246 |
border-color: var(--fly-primary) !important;
|
| 247 |
-
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2) !important;
|
| 248 |
}}
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
font-family: var(--english-font) !important;
|
| 255 |
-
|
| 256 |
-
color: var(--fly-text) !important;
|
| 257 |
-
box-shadow: inset 0 1px 2px rgba(0,0,0,0.05);
|
| 258 |
}}
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
margin-bottom: 0.5rem;
|
|
|
|
| 265 |
}}
|
| 266 |
-
.gr-accordion
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
padding: 1rem !important;
|
| 270 |
-
margin-top: 0 !important; box-shadow: var(--shadow-sm);
|
| 271 |
}}
|
| 272 |
-
|
| 273 |
-
.gr-slider {{ padding: 4px 0 !important;}}
|
| 274 |
.gr-slider label span {{font-size: 0.85em !important; color: var(--fly-subtle-text);}}
|
| 275 |
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
box-shadow: var(--shadow-md) !important; width: 100% !important;
|
| 282 |
-
font-size: 1em !important; display: flex; align-items: center; justify-content: center;
|
| 283 |
-
letter-spacing: 0.5px;
|
| 284 |
-
}}
|
| 285 |
-
.fly-submit-button-container .gr-button:hover {{
|
| 286 |
-
background: linear-gradient(135deg, #F97316, var(--fly-accent)) !important;
|
| 287 |
-
transform: translateY(-2px) !important; box-shadow: 0 6px 12px -2px rgba(234, 88, 12, 0.4) !important;
|
| 288 |
-
}}
|
| 289 |
-
|
| 290 |
-
/* Examples Section Styling Changes */
|
| 291 |
-
.examples-section-fly .gr-button.gr-button-tool {{
|
| 292 |
-
background-color: #E0E7FF !important; color: var(--fly-primary) !important;
|
| 293 |
-
border-radius: var(--border-radius-sm) !important; font-size: 0.8em !important; padding: 6px 10px !important;
|
| 294 |
-
border: 1px solid #C7D2FE !important; margin: 2px !important;
|
| 295 |
transition: background-color 0.2s ease, transform 0.1s ease;
|
| 296 |
}}
|
| 297 |
-
.
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
| 303 |
}}
|
|
|
|
|
|
|
| 304 |
|
| 305 |
|
| 306 |
-
.custom-hr-fly {{height: 1px; background-color: var(--fly-border); margin: 1.
|
| 307 |
-
.api-warning-message-fly {{
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
.app-footer-fly {{text-align:center; font-size:0.8em; color: var(--fly-subtle-text); margin-top:2rem; padding-bottom: 1rem;}}
|
| 309 |
footer, .gradio-footer {{display: none !important;}}
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
@media (min-width: 640px) {{
|
| 314 |
body {{font-size: 16px;}}
|
| 315 |
-
.gradio-container {{
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
border-radius: 0 !important;
|
| 320 |
-
box-shadow: none !important;
|
| 321 |
-
}}
|
| 322 |
-
.app-header-fly {{
|
| 323 |
-
border-bottom-left-radius: var(--border-radius-lg);
|
| 324 |
-
border-bottom-right-radius: var(--border-radius-lg);
|
| 325 |
-
margin-left: auto; margin-right: auto;
|
| 326 |
-
}}
|
| 327 |
-
.app-header-fly h1 {{ font-size: 2em !important; }} .app-header-fly p {{ font-size: 1em !important; }}
|
| 328 |
-
|
| 329 |
-
.main-content-area-fly {{padding: 0 1.5rem 1.5rem 1.5rem;}}
|
| 330 |
-
|
| 331 |
-
.api-warning-message-fly {{font-size: 0.9em;}}
|
| 332 |
-
|
| 333 |
-
.main-inputs-row-fly {{ display: flex; flex-direction: row; gap: 1.5rem; align-items: flex-start;}}
|
| 334 |
-
.main-inputs-row-fly > .gr-column:nth-child(1) {{ flex: 3; }}
|
| 335 |
-
.main-inputs-row-fly > .gr-column:nth-child(2) {{ flex: 2; }}
|
| 336 |
|
| 337 |
-
.
|
|
|
|
|
|
|
| 338 |
|
| 339 |
-
.
|
| 340 |
-
.
|
| 341 |
-
.app-footer-fly {{font-size:0.85em;}}
|
| 342 |
}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
"""
|
| 344 |
|
| 345 |
default_english_tts_voice = 'انگلیسی (آمریکا) - جنی (زن)'
|
| 346 |
-
if not language_dict_persian_keys
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
|
| 350 |
-
|
|
|
|
| 351 |
|
| 352 |
with gr.Column(elem_classes=["main-content-area-fly"]):
|
| 353 |
if not GOOGLE_API_KEY or not model:
|
| 354 |
-
missing_key_msg = "⚠️ **ترجمه
|
| 355 |
-
if not GOOGLE_API_KEY: missing_key_msg += "کلید API گوگل تنظیم نشده."
|
| 356 |
-
elif not model: missing_key_msg += "خطا در مدل Gemini."
|
| 357 |
-
gr.Markdown(f"<div class='api-warning-message-fly'>{missing_key_msg} لطفاً Secrets را بررسی کنید.</div>")
|
| 358 |
-
|
| 359 |
-
with gr.Row(elem_classes=["main-inputs-row-fly"]):
|
| 360 |
-
with gr.Column(scale=3):
|
| 361 |
-
input_text_persian = gr.Textbox(
|
| 362 |
-
lines=4, label="📝 متن فارسی خود را وارد کنید:", placeholder="مثال: سلام، حال شما چطور است؟",
|
| 363 |
-
elem_id="persian-input-textbox"
|
| 364 |
-
)
|
| 365 |
-
language_dropdown_tts_english = gr.Dropdown(
|
| 366 |
-
choices=list(language_dict_persian_keys.keys()) if language_dict_persian_keys else ["لیست صداها خالی است"],
|
| 367 |
-
value=default_english_tts_voice, label="🗣️ گوینده و لهجه انگلیسی را انتخاب کنید:", interactive=bool(language_dict_persian_keys)
|
| 368 |
-
)
|
| 369 |
-
with gr.Accordion("⚙️ تنظیمات پیشرفته صدا", open=False):
|
| 370 |
-
rate_slider = gr.Slider(-100, 100, 0, step=10, label="سرعت گفتار")
|
| 371 |
-
volume_slider = gr.Slider(-100, 100, 0, step=10, label="بلندی صدا")
|
| 372 |
-
pitch_slider = gr.Slider(-50, 50, 0, step=5, label="زیر و بمی صدا (Pitch)")
|
| 373 |
-
|
| 374 |
-
with gr.Group(elem_classes=["fly-submit-button-container"]):
|
| 375 |
-
submit_button = gr.Button("🚀 ترجمه و پخش صدا", variant="primary")
|
| 376 |
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
-
|
| 398 |
-
# MODIFICATION: Wrap gr.Examples in gr.Group and apply elem_classes to the Group
|
| 399 |
-
with gr.Group(elem_classes=["examples-section-fly"]):
|
| 400 |
-
gr.Examples(
|
| 401 |
-
examples=example_list,
|
| 402 |
-
inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
|
| 403 |
-
outputs=[output_text_translated, output_audio],
|
| 404 |
-
fn=translate_and_speak_sync_wrapper,
|
| 405 |
-
label="💡 چند نمونه برای شروع:",
|
| 406 |
-
# elem_classes=["examples-section-fly"] # REMOVED from here
|
| 407 |
-
)
|
| 408 |
-
|
| 409 |
-
gr.Markdown("<p class='app-footer-fly'>ساخته شده با ❤️ برای یادگیری زبان فلای © ۲۰۲۴</p>")
|
| 410 |
|
| 411 |
submit_button.click(
|
| 412 |
fn=translate_and_speak_sync_wrapper,
|
|
@@ -415,5 +379,9 @@ with gr.Blocks(theme=app_theme, css=custom_css, title="آموزش زبان فل
|
|
| 415 |
)
|
| 416 |
|
| 417 |
if __name__ == "__main__":
|
| 418 |
-
if not language_dict_persian_keys:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|
|
|
|
| 9 |
import logging
|
| 10 |
|
| 11 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
|
| 12 |
+
logging.info(f"Gradio version: {gr.__version__}")
|
| 13 |
|
| 14 |
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
|
| 15 |
model = None
|
|
|
|
| 23 |
else:
|
| 24 |
logging.warning("کلید API گوگل (GOOGLE_API_KEY) تنظیم نشده است.")
|
| 25 |
|
| 26 |
+
# --- دیکشنری کامل صداهای انگلیسی ---
|
| 27 |
language_dict_persian_keys = {
|
| 28 |
'انگلیسی (آمریکا) - جنی (زن)': 'en-US-JennyNeural', 'انگلیسی (آمریکا) - گای (مرد)': 'en-US-GuyNeural',
|
| 29 |
'انگلیسی (آمریکا) - آنا (زن، صدای کودک)': 'en-US-AnaNeural', 'انگلیسی (آمریکا) - آریا (زن)': 'en-US-AriaNeural',
|
|
|
|
| 59 |
}
|
| 60 |
|
| 61 |
async def translate_text_gemini_async(text, target_language="English"):
|
| 62 |
+
if not model: logging.error("Gemini model not loaded."); return "خطا: سرویس ترجمه در دسترس نیست.", None
|
| 63 |
+
if not text or not text.strip(): logging.warning("Translate: Empty input text."); return "خطا: متن ورودی خالی است.", None
|
| 64 |
try:
|
| 65 |
prompt = f"Translate the following Persian text to {target_language}. Provide only the translated English text, naturally and fluently, without any extra phrases, explanations, or markdown formatting. Be concise and accurate.\n\nPersian: \"{text}\"\n{target_language}:"
|
| 66 |
response = await model.generate_content_async(prompt)
|
| 67 |
translated_text = response.text.strip()
|
| 68 |
if translated_text.lower().startswith(f"{target_language.lower()}:"):
|
| 69 |
translated_text = translated_text[len(target_language)+1:].strip()
|
| 70 |
+
return "ترجمه موفق", translated_text
|
| 71 |
+
except Exception as e: logging.error(f"Gemini translation error: {e}", exc_info=True); return f"خطا در ترجمه: {type(e).__name__}", None
|
| 72 |
|
| 73 |
async def text_to_speech_edge_tts_async(text_to_speak, tts_voice_key, rate, volume, pitch):
|
| 74 |
+
if not text_to_speak or not text_to_speak.strip(): logging.warning("TTS: Empty input text."); return "خطا در TTS: متن ورودی خالی است.", None
|
| 75 |
voice_id = language_dict_persian_keys.get(tts_voice_key)
|
| 76 |
+
if voice_id is None: logging.error(f"TTS: Voice key '{tts_voice_key}' not found."); return f"خطا در TTS: صدای '{tts_voice_key}' یافت نشد.", None
|
| 77 |
try:
|
| 78 |
rate_str, volume_str, pitch_str = f"{int(rate):+g}%", f"{int(volume):+g}%", f"{int(pitch):+g}Hz"
|
| 79 |
communicate = edge_tts.Communicate(text_to_speak, voice_id, rate=rate_str, volume=volume_str, pitch=pitch_str)
|
| 80 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: tmp_path = tmp_file.name
|
| 81 |
await communicate.save(tmp_path)
|
| 82 |
+
return "TTS موفق", tmp_path
|
| 83 |
+
except Exception as e: logging.error(f"Edge-TTS error: {e}", exc_info=True); return f"خطا در TTS: {type(e).__name__}", None
|
| 84 |
|
| 85 |
_thread_local = threading.local()
|
| 86 |
|
| 87 |
def get_event_loop():
|
| 88 |
if not hasattr(_thread_local, 'loop') or _thread_local.loop.is_closed():
|
| 89 |
_thread_local.loop = asyncio.new_event_loop()
|
| 90 |
+
logging.info(f"Created or reopened new event loop for thread {threading.get_ident()}")
|
| 91 |
|
| 92 |
try:
|
| 93 |
+
current_loop = asyncio.get_event_loop_policy().get_event_loop()
|
| 94 |
+
if current_loop is not _thread_local.loop:
|
| 95 |
+
asyncio.set_event_loop(_thread_local.loop)
|
| 96 |
+
except RuntimeError as e: # No current event loop
|
| 97 |
asyncio.set_event_loop(_thread_local.loop)
|
| 98 |
+
logging.info(f"Set event loop for thread {threading.get_ident()} as no current loop was found or it was different.")
|
| 99 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
return _thread_local.loop
|
| 101 |
|
| 102 |
+
|
| 103 |
def translate_and_speak_sync_wrapper(persian_text, english_tts_voice_key, rate, volume, pitch):
|
| 104 |
logging.info(f"Wrapper called. Text: '{persian_text[:30]}...' Voice: {english_tts_voice_key}")
|
| 105 |
loop = get_event_loop()
|
| 106 |
|
| 107 |
if not GOOGLE_API_KEY or not model:
|
| 108 |
+
msg = "خطا: سرویس ترجمه پیکربندی نشده است. لطفاً از تنظیم GOOGLE_API_KEY اطمینان حاصل کنید."
|
| 109 |
logging.error(msg); return msg, None
|
| 110 |
if not persian_text or not persian_text.strip():
|
| 111 |
msg = "لطفاً متن فارسی را برای ترجمه وارد کنید."
|
| 112 |
logging.warning(msg); return msg, None
|
| 113 |
+
if not english_tts_voice_key or english_tts_voice_key == "لیست خالی":
|
| 114 |
+
msg = "لطفاً یک صدای گوینده انتخاب کنید."
|
| 115 |
+
logging.warning(msg); return persian_text, None # برگرداندن متن فارسی اگر صدا انتخاب نشده
|
| 116 |
+
|
| 117 |
try:
|
| 118 |
translation_status_msg, translated_text = loop.run_until_complete(
|
| 119 |
translate_text_gemini_async(persian_text)
|
| 120 |
)
|
| 121 |
+
if "خطا" in translation_status_msg.lower() or not translated_text:
|
| 122 |
err_msg = f"ترجمه ناموفق: {translation_status_msg} {translated_text or ''}"
|
| 123 |
logging.error(err_msg); return err_msg, None
|
| 124 |
|
| 125 |
tts_status_msg, audio_path = loop.run_until_complete(
|
| 126 |
text_to_speech_edge_tts_async(translated_text, english_tts_voice_key, rate, volume, pitch)
|
| 127 |
)
|
| 128 |
+
if "خطا" in tts_status_msg.lower() or not audio_path:
|
| 129 |
+
err_msg = f"{translated_text}\n(خطای TTS: {tts_status_msg})" # نمایش متن ترجمه شده همراه با خطای TTS
|
| 130 |
logging.error(err_msg); return err_msg, None
|
| 131 |
|
| 132 |
+
logging.info(f"عملیات موفق. متن ترجمه شده: '{translated_text[:30]}...', مسیر صوت: {audio_path}")
|
| 133 |
return translated_text, audio_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
except Exception as e:
|
| 135 |
logging.error(f"خطای غیرمنتظره در wrapper: {e}", exc_info=True)
|
| 136 |
return f"خطای داخلی سرور: {type(e).__name__}", None
|
| 137 |
|
| 138 |
+
# --- تعریف تم و CSS بهبود یافته ---
|
| 139 |
FLY_PRIMARY_COLOR_HEX = "#2563EB"
|
| 140 |
FLY_SECONDARY_COLOR_HEX = "#059669"
|
| 141 |
+
FLY_ACCENT_COLOR_HEX = "#D97706" # نارنجی برای دکمه اصلی
|
| 142 |
FLY_TEXT_COLOR_HEX = "#1F2937"
|
| 143 |
+
FLY_SUBTLE_TEXT_HEX = "#6B7280"
|
| 144 |
+
FLY_LIGHT_BACKGROUND_HEX = "#F3F4F6" # کمی روشنتر از قبل
|
| 145 |
FLY_WHITE_HEX = "#FFFFFF"
|
| 146 |
FLY_BORDER_COLOR_HEX = "#D1D5DB"
|
| 147 |
FLY_INPUT_BG_HEX = "#FFFFFF"
|
| 148 |
+
FLY_PANEL_BG_HEX = "#E0F2FE" # آبی بسیار روشن برای پنل ترجمه
|
| 149 |
+
FLY_SUCCESS_GREEN_HEX = "#059669" # سبز برای پیام موفقیت (مثلا)
|
| 150 |
+
FLY_ERROR_RED_HEX = "#DC2626" # قرمز برای پیام خطا
|
| 151 |
|
| 152 |
app_theme = gr.themes.Soft(
|
| 153 |
primary_hue=gr.themes.colors.blue,
|
|
|
|
| 156 |
font=[gr.themes.GoogleFont("Vazirmatn"), "Arial", "sans-serif"],
|
| 157 |
).set(
|
| 158 |
body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
|
| 159 |
+
button_primary_background_fill=FLY_ACCENT_COLOR_HEX, # دکمه اصلی نارنجی
|
| 160 |
+
button_primary_background_fill_hover=f"{FLY_ACCENT_COLOR_HEX}E0", # کمی تیرهتر در هاور
|
| 161 |
+
button_primary_text_color=FLY_WHITE_HEX,
|
| 162 |
)
|
| 163 |
|
| 164 |
+
# --- CSS بهبود یافته ---
|
| 165 |
custom_css = f"""
|
| 166 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700&display=swap');
|
| 167 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
|
|
|
|
| 172 |
--fly-subtle-text: {FLY_SUBTLE_TEXT_HEX}; --fly-light-bg: {FLY_LIGHT_BACKGROUND_HEX};
|
| 173 |
--fly-white: {FLY_WHITE_HEX}; --fly-border: {FLY_BORDER_COLOR_HEX};
|
| 174 |
--fly-input-bg: {FLY_INPUT_BG_HEX}; --fly-panel-bg: {FLY_PANEL_BG_HEX};
|
| 175 |
+
--fly-success: {FLY_SUCCESS_GREEN_HEX}; --fly-error: {FLY_ERROR_RED_HEX};
|
| 176 |
--global-font: 'Vazirmatn', 'Inter', 'Poppins', Arial, sans-serif;
|
| 177 |
--english-font: 'Poppins', 'Inter', Arial, sans-serif;
|
| 178 |
+
--border-radius-sm: 6px; --border-radius-md: 8px; --border-radius-lg: 12px;
|
| 179 |
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
|
| 180 |
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
| 181 |
}}
|
|
|
|
| 184 |
|
| 185 |
.app-header-fly {{
|
| 186 |
text-align: center; padding: 24px 15px;
|
| 187 |
+
background: linear-gradient(135deg, var(--fly-primary) 0%, var(--fly-secondary) 100%);
|
| 188 |
+
color: white; margin: 0 0 1.5rem 0; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px;
|
| 189 |
+
box-shadow: 0 4px 12px -2px rgba(37, 99, 235, 0.2);
|
|
|
|
| 190 |
}}
|
| 191 |
+
.app-header-fly h1 {{font-size: 1.8em !important; font-weight: 700 !important; margin: 0 0 6px 0; font-family: var(--english-font); letter-spacing: 0.5px;}}
|
| 192 |
.app-header-fly p {{font-size: 0.95em !important; margin-top: 4px; font-weight: 400; color: rgba(255, 255, 255, 0.9) !important;}}
|
| 193 |
|
| 194 |
+
.main-content-area-fly {{flex-grow: 1; padding: 0 1rem; }}
|
| 195 |
+
.content-wrapper {{ background-color: var(--fly-white); padding: 1.5rem; border-radius: var(--border-radius-lg); box-shadow: var(--shadow-md); margin-bottom: 1.5rem; }}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
/* --- Styling inputs --- */
|
| 198 |
+
.gr-input > label > span.label-text, .gr-dropdown > label > span.label-text {{font-weight: 600 !important; color: #374151 !important; font-size: 0.9em !important; margin-bottom: 6px !important; display: inline-block;}}
|
| 199 |
+
.gr-input > label + div > textarea,
|
| 200 |
+
.gr-dropdown > label + div > div > input, /* For searchable dropdown */
|
| 201 |
+
.gr-dropdown > label + div > div > select {{
|
| 202 |
+
border-radius: var(--border-radius-md) !important; border: 1px solid var(--fly-border) !important;
|
| 203 |
+
font-size: 0.95em !important; background-color: var(--fly-input-bg) !important;
|
| 204 |
+
padding: 10px 12px !important; line-height: 1.6; width: 100% !important; box-sizing: border-box !important;
|
| 205 |
+
-webkit-tap-highlight-color: transparent; font-family: var(--global-font) !important; color: var(--fly-text) !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
| 207 |
}}
|
| 208 |
.gr-input > label + div > textarea:focus,
|
| 209 |
.gr-dropdown > label + div > div > input:focus,
|
| 210 |
+
.gr-dropdown > label + div > div > select:focus {{
|
| 211 |
border-color: var(--fly-primary) !important;
|
| 212 |
+
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2) !important; outline: none;
|
| 213 |
}}
|
| 214 |
+
.gr-dropdown svg.icon {{ right: auto !important; left: 10px !important; /* برای RTL */}}
|
| 215 |
|
| 216 |
+
/* Output Textbox styling */
|
| 217 |
+
.gr-textbox[label*="ترجمه انگلیسی"] > label + div > textarea,
|
| 218 |
+
.gr-textbox[data-testid="textbox"][label*="ترجمه انگلیسی"] > label + div > textarea /* Gradio 4+ */ {{
|
| 219 |
+
background-color: var(--fly-panel-bg) !important; border-color: #A5D5FE !important;
|
| 220 |
+
min-height: 100px; font-family: var(--english-font) !important; font-size: 1em !important;
|
| 221 |
+
color: #0C4A6E !important; font-weight: 500;
|
|
|
|
|
|
|
| 222 |
}}
|
| 223 |
|
| 224 |
+
/* Accordion styling */
|
| 225 |
+
.gr-accordion > button.gr-button {{ /* Accordion Header Button */
|
| 226 |
+
font-weight: 600 !important; padding: 10px 12px !important; border-radius: var(--border-radius-md) !important;
|
| 227 |
+
background-color: #E5E7EB !important; color: var(--fly-text) !important;
|
| 228 |
+
border: 1px solid #D1D5DB !important; font-size: 0.9em; margin-bottom: 0.5rem;
|
| 229 |
+
transition: background-color 0.2s ease;
|
| 230 |
}}
|
| 231 |
+
.gr-accordion > button.gr-button:hover {{ background-color: #D1D5DB !important; }}
|
| 232 |
+
.gr-accordion > div.gr-panel {{ /* Accordion Content Panel */
|
| 233 |
+
border-radius: var(--border-radius-md) !important; border: 1px solid var(--fly-border) !important;
|
| 234 |
+
background-color: var(--fly-white) !important; padding: 1rem !important; box-shadow: none;
|
|
|
|
| 235 |
}}
|
| 236 |
+
.gr-slider {{ padding: 8px 0 !important;}}
|
|
|
|
| 237 |
.gr-slider label span {{font-size: 0.85em !important; color: var(--fly-subtle-text);}}
|
| 238 |
|
| 239 |
+
/* Submit Button - Relies on app_theme for primary color */
|
| 240 |
+
.fly-submit-button .gr-button {{
|
| 241 |
+
width: 100% !important; padding: 12px 20px !important; font-size: 1em !important;
|
| 242 |
+
font-weight: 600 !important; border-radius: var(--border-radius-md) !important;
|
| 243 |
+
margin-top: 1rem !important; text-transform: uppercase; letter-spacing: 0.5px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
transition: background-color 0.2s ease, transform 0.1s ease;
|
| 245 |
}}
|
| 246 |
+
.fly-submit-button .gr-button:hover {{ transform: translateY(-2px); }}
|
| 247 |
+
|
| 248 |
+
/* Examples Section */
|
| 249 |
+
div[id*="examples"] { margin-top: 1.5rem; }
|
| 250 |
+
div[id*="examples"] > .gr-panel {{ background-color: transparent !important; border: none !important; padding: 0 !important; box-shadow: none !important;}}
|
| 251 |
+
div[id*="examples"] > .gr-form > .gr-button.gr-button-secondary {{ /* Example items */
|
| 252 |
+
background-color: #E0E7FF !important; color: var(--fly-primary) !important;
|
| 253 |
+
border-radius: var(--border-radius-sm) !important; font-size: 0.85em !important; padding: 5px 10px !important;
|
| 254 |
+
border: 1px solid #C7D2FE !important; transition: background-color 0.2s ease;
|
| 255 |
}}
|
| 256 |
+
div[id*="examples"] > .gr-form > .gr-button.gr-button-secondary:hover {{ background-color: #C7D2FE !important; }}
|
| 257 |
+
div[id*="examples"] .gr-samples-header {{ font-weight: 600; color: #4B5563; font-size: 0.95em; margin-bottom: 0.8rem;}}
|
| 258 |
|
| 259 |
|
| 260 |
+
.custom-hr-fly {{height: 1px; background-color: var(--fly-border); margin: 1.8rem 0; border: none;}}
|
| 261 |
+
.api-warning-message-fly {{
|
| 262 |
+
background-color: #FFFBEB !important; color: #92400E !important; padding: 12px 15px !important;
|
| 263 |
+
border-radius: var(--border-radius-md) !important; border: 1px solid #FDE68A !important;
|
| 264 |
+
text-align: center !important; margin: 0 0.5rem 1rem 0.5rem !important; font-size: 0.9em !important; font-weight: 500;
|
| 265 |
+
}}
|
| 266 |
.app-footer-fly {{text-align:center; font-size:0.8em; color: var(--fly-subtle-text); margin-top:2rem; padding-bottom: 1rem;}}
|
| 267 |
footer, .gradio-footer {{display: none !important;}}
|
| 268 |
|
| 269 |
+
/* Desktop improvements */
|
| 270 |
+
@media (min-width: 768px) {{
|
|
|
|
| 271 |
body {{font-size: 16px;}}
|
| 272 |
+
.gradio-container {{max-width: 800px !important; padding: 1.5rem !important; margin: 2rem auto !important; background-color: var(--fly-light-bg) !important; border-radius: 0; box-shadow: none;}}
|
| 273 |
+
.app-header-fly {{ border-radius: var(--border-radius-lg); margin: -1.5rem -1.5rem 2rem -1.5rem; /* Extend to edges of container */ }}
|
| 274 |
+
.app-header-fly h1 {{ font-size: 2em !important; }} .app-header-fly p {{ font-size: 1em !important; }}
|
| 275 |
+
.main-content-area-fly {{padding: 0;}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
+
.main-content-columns-fly {{ display: flex; flex-direction: row; gap: 1.5rem; }}
|
| 278 |
+
.main-content-columns-fly > .gr-column:nth-child(1) {{ flex: 3; }} /* Input column wider */
|
| 279 |
+
.main-content-columns-fly > .gr-column:nth-child(2) {{ flex: 2; }} /* Output column */
|
| 280 |
|
| 281 |
+
.fly-submit-button .gr-button {{ width: auto !important; min-width: 200px;}}
|
| 282 |
+
.api-warning-message-fly {{margin-left: 0 !important; margin-right: 0 !important; font-size: 0.9em;}}
|
|
|
|
| 283 |
}}
|
| 284 |
+
|
| 285 |
+
/* Specific for Gradio 4+ output textbox if needed */
|
| 286 |
+
.gradio-interface .output_text .gr-textbox[data-testid="textbox"] {
|
| 287 |
+
/* Custom styles for Gradio 4+ output textbox if the general one doesn't catch */
|
| 288 |
+
}
|
| 289 |
+
.result-area-fly { margin-top: 1rem; }
|
| 290 |
+
.result-area-fly > .gr-block > .gr-form > .gr-input,
|
| 291 |
+
.result-area-fly > .gr-block > .gr-form > .gr-audio { /* Ensure output elements also have some margin */
|
| 292 |
+
margin-bottom: 0.8rem;
|
| 293 |
+
}
|
| 294 |
"""
|
| 295 |
|
| 296 |
default_english_tts_voice = 'انگلیسی (آمریکا) - جنی (زن)'
|
| 297 |
+
if not language_dict_persian_keys :
|
| 298 |
+
logging.warning("Language dictionary is empty!")
|
| 299 |
+
default_english_tts_voice = None
|
| 300 |
+
elif default_english_tts_voice not in language_dict_persian_keys:
|
| 301 |
+
default_english_tts_voice = list(language_dict_persian_keys.keys())[0]
|
| 302 |
|
| 303 |
+
# --- Gradio UI با ساختار بهبود یافته ---
|
| 304 |
+
with gr.Blocks(theme=app_theme, css=custom_css, title="آموزش زبان فلای | Fly Language Learning") as demo:
|
| 305 |
+
gr.HTML(f"""<div class="app-header-fly"><h1>Fly Language Learning 🚀</h1><p>ترجمه فارسی به انگلیسی و تلفظ با لهجه دلخواه</p></div>""")
|
| 306 |
|
| 307 |
with gr.Column(elem_classes=["main-content-area-fly"]):
|
| 308 |
if not GOOGLE_API_KEY or not model:
|
| 309 |
+
missing_key_msg = "⚠️ **هشدار سرویس ترجمه:** "
|
| 310 |
+
if not GOOGLE_API_KEY: missing_key_msg += "کلید API گوگل (GOOGLE_API_KEY) تنظیم نشده است."
|
| 311 |
+
elif not model: missing_key_msg += "خطا در بارگذاری مدل Gemini."
|
| 312 |
+
gr.Markdown(f"<div class='api-warning-message-fly'>{missing_key_msg} بخش ترجمه غیرفعال خواهد بود. لطفاً تنظیمات Secrets را بررسی کنید.</div>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
+
# Wrapper for content to apply card styling on desktop
|
| 315 |
+
with gr.Box(elem_classes=["content-wrapper"]):
|
| 316 |
+
with gr.Row(elem_classes=["main-content-columns-fly"]): # For desktop two-column layout
|
| 317 |
+
with gr.Column(scale=3): # Input column
|
| 318 |
+
input_text_persian = gr.Textbox(
|
| 319 |
+
lines=4, label="📝 متن فارسی خود را وارد کنید:", placeholder="مثال: سلام، حال شما چطور است؟",
|
| 320 |
+
elem_id="persian_input_textbox"
|
| 321 |
+
)
|
| 322 |
+
language_dropdown_tts_english = gr.Dropdown(
|
| 323 |
+
choices=list(language_dict_persian_keys.keys()) if language_dict_persian_keys else ["لیست خالی"],
|
| 324 |
+
value=default_english_tts_voice if default_english_tts_voice else "لیست خالی",
|
| 325 |
+
label="🗣️ گوینده و لهجه انگلیسی را انتخاب کنید:",
|
| 326 |
+
interactive=bool(language_dict_persian_keys and default_english_tts_voice is not None)
|
| 327 |
+
)
|
| 328 |
+
with gr.Accordion("⚙️ تنظیمات پیشرفته صدا", open=False):
|
| 329 |
+
rate_slider = gr.Slider(-100, 100, 0, step=10, label="سرعت گفتار (Rate)")
|
| 330 |
+
volume_slider = gr.Slider(-100, 100, 0, step=10, label="بلندی صدا (Volume)")
|
| 331 |
+
pitch_slider = gr.Slider(-50, 50, 0, step=5, label="زیر و بمی صدا (Pitch)")
|
| 332 |
+
|
| 333 |
+
with gr.Box(elem_classes=["fly-submit-button"]): # Using Box for better CSS control
|
| 334 |
+
submit_button = gr.Button("ترجمه و پخش صدا", variant="primary", icon="▶️")
|
| 335 |
|
| 336 |
+
with gr.Column(scale=2, elem_classes=["result-area-fly"]): # Output column
|
| 337 |
+
output_text_translated = gr.Textbox(
|
| 338 |
+
label="📜 ترجمه انگلیسی:", interactive=False, lines=5,
|
| 339 |
+
placeholder="ترجمه متن شما در اینجا نمایش داده میشود...",
|
| 340 |
+
elem_id="english_output_textbox"
|
| 341 |
+
)
|
| 342 |
+
output_audio = gr.Audio(label="🎧 فایل صوتی:", type="filepath", format="mp3", interactive=False)
|
| 343 |
+
|
| 344 |
+
if language_dict_persian_keys and default_english_tts_voice:
|
| 345 |
+
gr.HTML("<hr class='custom-hr-fly'>")
|
| 346 |
+
num_voices = len(language_dict_persian_keys)
|
| 347 |
+
voice_keys = list(language_dict_persian_keys.keys())
|
| 348 |
+
|
| 349 |
+
# Ensure indices are within bounds
|
| 350 |
+
voice1_idx = 0
|
| 351 |
+
voice2_idx = min(7, num_voices - 1) if num_voices > 1 else 0
|
| 352 |
+
voice3_idx = min(13, num_voices - 1) if num_voices > 1 else 0
|
| 353 |
+
|
| 354 |
+
example_list = [
|
| 355 |
+
["قیمت این لباس چقدر است؟", voice_keys[voice1_idx], 0, 0, 0],
|
| 356 |
+
["میتوانید آدرس را روی نقشه به من نشان دهید؟", voice_keys[voice2_idx], 5, 0, 0],
|
| 357 |
+
["ببخشید، متوجه نشدم. امکان دارد تکرار کنید؟", voice_keys[voice3_idx], -10, 10, 0],
|
| 358 |
+
["یک قهوه و یک کیک لطفا.", voice_keys[0], 0, 0, 0], # Default to first voice if specific indices are not distinct
|
| 359 |
]
|
| 360 |
+
if not (language_dict_persian_keys and default_english_tts_voice):
|
| 361 |
+
example_list = [] # No examples if no voices
|
| 362 |
+
|
| 363 |
+
if example_list:
|
| 364 |
+
gr.Examples(
|
| 365 |
+
examples=example_list,
|
| 366 |
+
inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
|
| 367 |
+
outputs=[output_text_translated, output_audio],
|
| 368 |
+
fn=translate_and_speak_sync_wrapper,
|
| 369 |
+
label="💡 نمونههای آماده (برای امتحان کلیک کنید):",
|
| 370 |
+
elem_id="examples_section" # For CSS styling
|
| 371 |
+
)
|
| 372 |
|
| 373 |
+
gr.Markdown("<p class='app-footer-fly'>✨ Fly Language Learning © ��۰۲۴ - قدرت گرفته از Gemini و EdgeTTS ✨</p>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
submit_button.click(
|
| 376 |
fn=translate_and_speak_sync_wrapper,
|
|
|
|
| 379 |
)
|
| 380 |
|
| 381 |
if __name__ == "__main__":
|
| 382 |
+
if not language_dict_persian_keys:
|
| 383 |
+
logging.critical("CRITICAL: Voice dictionary (language_dict_persian_keys) is empty! The application might not function correctly.")
|
| 384 |
+
elif not default_english_tts_voice:
|
| 385 |
+
logging.warning("WARNING: No default English TTS voice could be set. Dropdown might be empty or non-interactive.")
|
| 386 |
+
|
| 387 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|