Update app.py
Browse files
app.py
CHANGED
|
@@ -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,95 +59,100 @@ language_dict_persian_keys = {
|
|
| 59 |
}
|
| 60 |
|
| 61 |
async def translate_text_gemini_async(text, target_language="English"):
|
| 62 |
-
|
| 63 |
-
if not
|
|
|
|
| 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 |
-
|
|
|
|
| 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')
|
| 89 |
_thread_local.loop = asyncio.new_event_loop()
|
| 90 |
-
logging.info(f"Created
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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[:
|
| 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})"
|
| 130 |
logging.error(err_msg); return err_msg, None
|
| 131 |
|
| 132 |
-
logging.info(f"عملیات موفق. م
|
| 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 = "#
|
| 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,12 +161,10 @@ app_theme = gr.themes.Soft(
|
|
| 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 |
-
#
|
|
|
|
| 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,205 +175,155 @@ custom_css = f"""
|
|
| 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 |
}}
|
| 182 |
-
body {{font-family: var(--global-font); direction: rtl; background-color: var(--fly-light-bg); color: var(--fly-text); line-height: 1.
|
| 183 |
-
.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-color: var(--fly-light-bg) !important; display: flex; flex-direction: column;}}
|
| 184 |
-
|
| 185 |
-
.app-header-fly {{
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
}}
|
| 191 |
-
.
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
.
|
| 195 |
-
.
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
-webkit-tap-highlight-color: transparent;
|
| 206 |
-
|
|
|
|
|
|
|
| 207 |
}}
|
| 208 |
.gr-input > label + div > textarea:focus,
|
| 209 |
-
.gr-
|
| 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.
|
| 213 |
}}
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
/*
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
}}
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 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
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
}}
|
| 236 |
-
|
| 237 |
-
.gr-slider
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
.
|
| 241 |
-
|
| 242 |
-
|
| 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 |
-
.
|
| 247 |
-
|
| 248 |
-
|
| 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 |
-
|
| 270 |
-
@media (min-width: 768px) {{
|
| 271 |
body {{font-size: 16px;}}
|
| 272 |
-
.gradio-container {{max-width:
|
| 273 |
-
.app-header-fly {{ border-radius:
|
| 274 |
-
.app-header-fly h1 {{ font-size:
|
| 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 |
-
|
| 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 |
-
|
| 304 |
-
|
| 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 گوگل
|
| 311 |
-
elif not model: missing_key_msg += "خطا در
|
| 312 |
-
gr.Markdown(f"<div class='api-warning-message-fly'>{missing_key_msg}
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
)
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 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 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
|
|
|
|
|
|
| 353 |
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
["قیمت این لباس چقدر است؟", voice_keys[voice1_idx], 0, 0, 0],
|
| 356 |
-
["میتوانید آدرس را روی نقشه به من نشان دهید؟", voice_keys[voice2_idx],
|
| 357 |
-
["ببخشید، متوجه نشدم. امکان دارد تکرار کنید؟", voice_keys[voice3_idx], -10,
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
submit_button.click(
|
| 376 |
fn=translate_and_speak_sync_wrapper,
|
|
@@ -379,9 +332,5 @@ with gr.Blocks(theme=app_theme, css=custom_css, title="آموزش زبان فل
|
|
| 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)
|
|
|
|
| 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 |
+
# logging.debug(f"Translate: '{text[:20]}...'")
|
| 63 |
+
if not model: logging.error("Gemini model not loaded."); return "Error: Translation service unavailable.", None
|
| 64 |
+
if not text or not text.strip(): logging.warning("Translate: Empty input text."); return "Error: Input text is empty.", None
|
| 65 |
try:
|
| 66 |
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}:"
|
| 67 |
response = await model.generate_content_async(prompt)
|
| 68 |
translated_text = response.text.strip()
|
| 69 |
if translated_text.lower().startswith(f"{target_language.lower()}:"):
|
| 70 |
translated_text = translated_text[len(target_language)+1:].strip()
|
| 71 |
+
return "Translation successful", translated_text
|
| 72 |
+
except Exception as e: logging.error(f"Gemini translation error: {e}", exc_info=True); return f"Translation error: {type(e).__name__}", None
|
| 73 |
|
| 74 |
async def text_to_speech_edge_tts_async(text_to_speak, tts_voice_key, rate, volume, pitch):
|
| 75 |
+
# logging.debug(f"TTS: '{text_to_speak[:20]}...' Voice: {tts_voice_key}")
|
| 76 |
+
if not text_to_speak or not text_to_speak.strip(): logging.warning("TTS: Empty input text."); return "TTS Error: Input text is empty.", None
|
| 77 |
voice_id = language_dict_persian_keys.get(tts_voice_key)
|
| 78 |
+
if voice_id is None: logging.error(f"TTS: Voice key '{tts_voice_key}' not found."); return f"TTS Error: Voice '{tts_voice_key}' not found.", None
|
| 79 |
try:
|
| 80 |
rate_str, volume_str, pitch_str = f"{int(rate):+g}%", f"{int(volume):+g}%", f"{int(pitch):+g}Hz"
|
| 81 |
communicate = edge_tts.Communicate(text_to_speak, voice_id, rate=rate_str, volume=volume_str, pitch=pitch_str)
|
| 82 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: tmp_path = tmp_file.name
|
| 83 |
await communicate.save(tmp_path)
|
| 84 |
+
return "TTS successful", tmp_path
|
| 85 |
+
except Exception as e: logging.error(f"Edge-TTS error: {e}", exc_info=True); return f"TTS Error: {type(e).__name__}", None
|
| 86 |
|
| 87 |
+
# --- مدیریت Event Loop (نسخه پایدارتر و دقیقتر) ---
|
| 88 |
_thread_local = threading.local()
|
| 89 |
|
| 90 |
def get_event_loop():
|
| 91 |
+
if not hasattr(_thread_local, 'loop'):
|
| 92 |
_thread_local.loop = asyncio.new_event_loop()
|
| 93 |
+
logging.info(f"Created new event loop for thread {threading.get_ident()}")
|
| 94 |
|
| 95 |
+
# همیشه قبل از استفاده، لوپ را برای ترد فعلی تنظیم کنید
|
| 96 |
+
# این کار از بسیاری از خطاهای مربوط به "no current event loop" جلوگیری میکند
|
| 97 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
asyncio.set_event_loop(_thread_local.loop)
|
| 99 |
+
except RuntimeError as e:
|
| 100 |
+
# اگر لوپ در حال اجرا باشد، ممکن است این خطا رخ دهد.
|
| 101 |
+
# معمولا اگر get_event_loop() به درستی استفاده شود و لوپ بسته نشود،
|
| 102 |
+
# این حالت نباید زیاد پیش بیاید.
|
| 103 |
+
if "cannot be called from a running event loop" not in str(e).lower():
|
| 104 |
+
logging.warning(f"RuntimeError setting event loop (possibly already running): {e}")
|
| 105 |
+
# با این حال، اطمینان حاصل میکنیم که لوپ ما لوپ فعلی است
|
| 106 |
+
if asyncio.get_event_loop_policy().get_event_loop() is not _thread_local.loop:
|
| 107 |
+
asyncio.set_event_loop(_thread_local.loop) # تلاش مجدد اگر لوپ فعلی متفاوت بود
|
| 108 |
|
| 109 |
return _thread_local.loop
|
| 110 |
|
| 111 |
|
| 112 |
def translate_and_speak_sync_wrapper(persian_text, english_tts_voice_key, rate, volume, pitch):
|
| 113 |
+
logging.info(f"Wrapper called. Text: '{persian_text[:20]}...' Voice: {english_tts_voice_key}")
|
| 114 |
+
loop = get_event_loop() # <<<<<<<<<<<<<<<<<<<<<<<<<< استفاده از get_event_loop اصلاح شده
|
| 115 |
|
| 116 |
if not GOOGLE_API_KEY or not model:
|
| 117 |
+
msg = "خطا: سرویس ترجمه پیکربندی نشده است. لطفاً از تنظیم GOOGLE_API_KEY در Secrets اطمینان حاصل کنید."
|
| 118 |
logging.error(msg); return msg, None
|
| 119 |
if not persian_text or not persian_text.strip():
|
| 120 |
msg = "لطفاً متن فارسی را برای ترجمه وارد کنید."
|
| 121 |
logging.warning(msg); return msg, None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
try:
|
| 123 |
+
# ترجمه
|
| 124 |
translation_status_msg, translated_text = loop.run_until_complete(
|
| 125 |
translate_text_gemini_async(persian_text)
|
| 126 |
)
|
| 127 |
+
if "خطا" in translation_status_msg.lower() or not translated_text: # بررسی دقیقتر خطا
|
| 128 |
err_msg = f"ترجمه ناموفق: {translation_status_msg} {translated_text or ''}"
|
| 129 |
logging.error(err_msg); return err_msg, None
|
| 130 |
|
| 131 |
+
# تبدیل به گفتار
|
| 132 |
tts_status_msg, audio_path = loop.run_until_complete(
|
| 133 |
text_to_speech_edge_tts_async(translated_text, english_tts_voice_key, rate, volume, pitch)
|
| 134 |
)
|
| 135 |
+
if "خطا" in tts_status_msg.lower() or not audio_path: # بررسی دقیقتر خطا
|
| 136 |
+
err_msg = f"{translated_text}\n(خطای TTS: {tts_status_msg})"
|
| 137 |
logging.error(err_msg); return err_msg, None
|
| 138 |
|
| 139 |
+
logging.info(f"عملیات موفق. مسیر صوت: {audio_path}")
|
| 140 |
return translated_text, audio_path
|
| 141 |
except Exception as e:
|
| 142 |
logging.error(f"خطای غیرمنتظره در wrapper: {e}", exc_info=True)
|
| 143 |
return f"خطای داخلی سرور: {type(e).__name__}", None
|
| 144 |
|
| 145 |
+
# --- تعریف تم و CSS (همان CSS زیبا با اصلاحات جزئی) ---
|
| 146 |
FLY_PRIMARY_COLOR_HEX = "#2563EB"
|
| 147 |
FLY_SECONDARY_COLOR_HEX = "#059669"
|
| 148 |
+
FLY_ACCENT_COLOR_HEX = "#D97706"
|
| 149 |
FLY_TEXT_COLOR_HEX = "#1F2937"
|
| 150 |
FLY_SUBTLE_TEXT_HEX = "#6B7280"
|
| 151 |
+
FLY_LIGHT_BACKGROUND_HEX = "#F9FAFB"
|
| 152 |
FLY_WHITE_HEX = "#FFFFFF"
|
| 153 |
FLY_BORDER_COLOR_HEX = "#D1D5DB"
|
| 154 |
FLY_INPUT_BG_HEX = "#FFFFFF"
|
| 155 |
+
FLY_PANEL_BG_HEX = "#E0F2FE"
|
|
|
|
|
|
|
| 156 |
|
| 157 |
app_theme = gr.themes.Soft(
|
| 158 |
primary_hue=gr.themes.colors.blue,
|
|
|
|
| 161 |
font=[gr.themes.GoogleFont("Vazirmatn"), "Arial", "sans-serif"],
|
| 162 |
).set(
|
| 163 |
body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
|
|
|
|
|
|
|
|
|
|
| 164 |
)
|
| 165 |
|
| 166 |
+
# CSS قبلی که زیبا بود، با اصلاحات بسیار جزئی و محتاطانه
|
| 167 |
+
# تمرکز بر عدم دستکاری زیاد در ظاهر پیشفرض المانهای ورودی
|
| 168 |
custom_css = f"""
|
| 169 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700&display=swap');
|
| 170 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
|
|
|
|
| 175 |
--fly-subtle-text: {FLY_SUBTLE_TEXT_HEX}; --fly-light-bg: {FLY_LIGHT_BACKGROUND_HEX};
|
| 176 |
--fly-white: {FLY_WHITE_HEX}; --fly-border: {FLY_BORDER_COLOR_HEX};
|
| 177 |
--fly-input-bg: {FLY_INPUT_BG_HEX}; --fly-panel-bg: {FLY_PANEL_BG_HEX};
|
|
|
|
| 178 |
--global-font: 'Vazirmatn', 'Inter', 'Poppins', Arial, sans-serif;
|
| 179 |
--english-font: 'Poppins', 'Inter', Arial, sans-serif;
|
|
|
|
|
|
|
|
|
|
| 180 |
}}
|
| 181 |
+
body {{font-family: var(--global-font); direction: rtl; background-color: var(--fly-light-bg); color: var(--fly-text); line-height: 1.6; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-size: 15px;}}
|
| 182 |
+
.gradio-container {{max-width: 100% !important; width: 100% !important; min-height: 100vh; margin: 0 auto !important; padding: 0.8rem 0.6rem !important; border-radius: 0 !important; box-shadow: none !important; background-color: var(--fly-light-bg) !important; display: flex; flex-direction: column;}}
|
| 183 |
+
.app-header-fly {{text-align: center; padding: 18px 10px; background-image: linear-gradient(125deg, var(--fly-primary) 0%, var(--fly-secondary) 100%); color: white; margin: 0 0 1.2rem 0; border-radius: 14px; box-shadow: 0 3px 10px -2px rgba(37, 99, 235, 0.18);}}
|
| 184 |
+
.app-header-fly h1 {{font-size: 1.5em !important; font-weight: 700 !important; margin: 0 0 4px 0; font-family: var(--english-font);}}
|
| 185 |
+
.app-header-fly p {{font-size: 0.85em !important; margin-top: 2px; font-weight: 400; color: rgba(255, 255, 255, 0.95) !important;}}
|
| 186 |
+
.main-content-area-fly {{flex-grow: 1; padding: 0 0.3rem;}}
|
| 187 |
+
.fly-submit-button-container .gr-button {{
|
| 188 |
+
background: var(--fly-accent) !important; margin-top: 0.8rem !important; padding: 11px 18px !important;
|
| 189 |
+
transition: all 0.25s ease-in-out !important; color: white !important; font-weight: 600 !important;
|
| 190 |
+
border-radius: 8px !important; border: none !important;
|
| 191 |
+
box-shadow: 0 2px 6px -1px rgba(217, 119, 6, 0.25) !important; width: 100% !important;
|
| 192 |
+
font-size: 0.95em !important; display: flex; align-items: center; justify-content: center;
|
| 193 |
}}
|
| 194 |
+
.fly-submit-button-container .gr-button:hover {{background: #B45309 !important; transform: translateY(-1px) !important; box-shadow: 0 4px 8px -1px rgba(217, 119, 6, 0.35) !important;}}
|
| 195 |
+
|
| 196 |
+
/* --- استایل ورودیها با حداقل تغییرات ممکن برای حفظ عملکرد --- */
|
| 197 |
+
.gr-input > label + div > textarea, /* Textbox */
|
| 198 |
+
.gr-input > label + div > input, /* Text (اگر استفاده شود) */
|
| 199 |
+
.gr-dropdown > label + div > div > select {{ /* Dropdown */
|
| 200 |
+
border-radius: 8px !important;
|
| 201 |
+
border: 1.5px solid var(--fly-border) !important;
|
| 202 |
+
font-size: 0.9em !important;
|
| 203 |
+
background-color: var(--fly-input-bg) !important;
|
| 204 |
+
padding: 10px 12px !important;
|
| 205 |
+
line-height: 1.5;
|
| 206 |
+
width: 100% !important;
|
| 207 |
+
box-sizing: border-box !important;
|
| 208 |
+
-webkit-tap-highlight-color: transparent;
|
| 209 |
+
font-family: var(--global-font) !important;
|
| 210 |
+
color: var(--fly-text) !important;
|
| 211 |
+
/* appearance: none; -webkit-appearance: none; -moz-appearance: none; /* موقتا حذف برای تست */
|
| 212 |
}}
|
| 213 |
.gr-input > label + div > textarea:focus,
|
| 214 |
+
.gr-input > label + div > input:focus,
|
| 215 |
.gr-dropdown > label + div > div > select:focus {{
|
| 216 |
border-color: var(--fly-primary) !important;
|
| 217 |
+
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15) !important;
|
| 218 |
}}
|
| 219 |
+
/* عدم استفاده از ::after برای دراپ داون در این مرحله */
|
| 220 |
+
|
| 221 |
+
.gr-textbox[label*="ترجمه انگلیسی"] > label + div > textarea {{ /* اطمینان از اینکه target درست است */
|
| 222 |
+
background-color: var(--fly-panel-bg) !important;
|
| 223 |
+
border-color: #A5D5FE !important;
|
| 224 |
+
min-height: 90px;
|
| 225 |
+
font-family: var(--english-font) !important;
|
| 226 |
+
font-size: 0.95em !important;
|
| 227 |
}}
|
| 228 |
+
.gr-panel, div[label="تنظیمات صدا"] > .gr-accordion > .gr-panel {{
|
| 229 |
+
border-radius: 8px !important; border: 1px solid var(--fly-border) !important;
|
| 230 |
+
background-color: var(--fly-light-bg) !important;
|
| 231 |
+
padding: 0.7rem 0.9rem !important;
|
| 232 |
+
margin-top: 0.5rem; box-shadow: none;
|
|
|
|
|
|
|
| 233 |
}}
|
| 234 |
+
div[label="تنظیمات صدا"] > .gr-accordion > button.gr-button {{
|
| 235 |
+
font-weight: 500 !important; padding: 7px 9px !important; border-radius: 6px !important;
|
| 236 |
+
background-color: #E5E7EB !important; color: var(--fly-text) !important;
|
| 237 |
+
border: 1px solid #D1D5DB !important; font-size: 0.85em;
|
| 238 |
}}
|
| 239 |
+
label > span {{font-weight: 500 !important; color: #4B5563 !important; font-size: 0.85em !important; margin-bottom: 5px !important; display: inline-block;}}
|
| 240 |
+
.gr-slider {{ padding: 2px 0 !important;}}
|
| 241 |
+
.gr-slider label span {{font-size: 0.8em !important; color: var(--fly-subtle-text);}}
|
| 242 |
+
div[label="💡 نمونه"] {{margin-top: 1.2rem;}}
|
| 243 |
+
div[label="💡 نمونه"] .gr-button.gr-button-tool {{
|
| 244 |
+
background-color: #E0E7FF !important; color: var(--fly-primary) !important;
|
| 245 |
+
border-radius: 6px !important; font-size: 0.75em !important; padding: 3px 7px !important;
|
|
|
|
|
|
|
| 246 |
}}
|
| 247 |
+
.custom-hr-fly {{height: 1px; background-color: var(--fly-border); margin: 1.2rem 0; border: none;}}
|
| 248 |
+
.api-warning-message-fly {{background-color: #FFFBEB !important; color: #92400E !important; padding: 8px 10px !important; border-radius: 6px !important; border: 1px solid #FDE68A !important; text-align: center !important; margin: 0 0.2rem 0.8rem 0.2rem !important; font-size: 0.75em !important;}}
|
| 249 |
+
.app-footer-fly {{text-align:center; font-size:0.7em; color: #6B7280; margin-top:1.5rem; padding-bottom: 0.8rem;}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
footer, .gradio-footer {{display: none !important;}}
|
| 251 |
|
| 252 |
+
@media (min-width: 640px) {{
|
|
|
|
| 253 |
body {{font-size: 16px;}}
|
| 254 |
+
.gradio-container {{max-width: 600px !important; padding: 1rem !important; margin: 1rem auto !important; background-color: var(--fly-white) !important; border-radius: 16px !important; box-shadow: 0 5px 15px rgba(0,0,0,0.05) !important;}}
|
| 255 |
+
.app-header-fly {{ border-radius: 10px; padding: 18px 12px; margin: -1rem -1rem 1.5rem -1rem; }}
|
| 256 |
+
.app-header-fly h1 {{ font-size: 1.6em !important; }} .app-header-fly p {{ font-size: 0.9em !important; }}
|
| 257 |
.main-content-area-fly {{padding: 0;}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
.api-warning-message-fly {{margin-left: 0 !important; margin-right: 0 !important; font-size: 0.9em;}}
|
| 259 |
+
.main-content-row-fly > .gr-column {{ margin-bottom: 0 !important; }}
|
| 260 |
+
.main-content-row-fly {{ display: flex; flex-direction: row; gap: 1rem; }}
|
| 261 |
+
.main-content-row-fly > .gr-column:nth-child(1) {{ flex: 2; }}
|
| 262 |
+
.main-content-row-fly > .gr-column:nth-child(2) {{ flex: 1; }}
|
| 263 |
+
.fly-submit-button-container .gr-button {{ width: auto !important; align-self: flex-start; }}
|
| 264 |
+
.gr-input textarea, .gr-input input, .gr-dropdown select, .gr-textbox textarea {{ font-size: 0.95em; }}
|
| 265 |
+
label > span {{ font-size: 0.9em; }}
|
| 266 |
+
.app-footer-fly {{font-size:0.8em;}}
|
| 267 |
}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
"""
|
| 269 |
|
| 270 |
default_english_tts_voice = 'انگلیسی (آمریکا) - جنی (زن)'
|
| 271 |
+
if not language_dict_persian_keys or default_english_tts_voice not in language_dict_persian_keys:
|
| 272 |
+
default_english_tts_voice = list(language_dict_persian_keys.keys())[0] if language_dict_persian_keys else None
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
with gr.Blocks(theme=app_theme, css=custom_css, title="آموزش زبان فلای") as demo:
|
| 275 |
+
gr.HTML(f"""<div class="app-header-fly"><h1>Fly Language Learning</h1><p>ترجمه فارسی به انگلیسی و تلفظ با لهجه دلخواه</p></div>""")
|
|
|
|
| 276 |
|
| 277 |
with gr.Column(elem_classes=["main-content-area-fly"]):
|
| 278 |
if not GOOGLE_API_KEY or not model:
|
| 279 |
+
missing_key_msg = "⚠️ **ترجمه غیرفعال:** "
|
| 280 |
+
if not GOOGLE_API_KEY: missing_key_msg += "کلید API گوگل تنظیم نشده."
|
| 281 |
+
elif not model: missing_key_msg += "خطا در مدل Gemini."
|
| 282 |
+
gr.Markdown(f"<div class='api-warning-message-fly'>{missing_key_msg} لطفاً Secrets را بررسی کنید.</div>")
|
| 283 |
+
|
| 284 |
+
with gr.Row(elem_classes=["main-content-row-fly"]):
|
| 285 |
+
with gr.Column():
|
| 286 |
+
input_text_persian = gr.Textbox(
|
| 287 |
+
lines=3, label="📝 متن فارسی:", placeholder="اینجا بنویسید...",
|
| 288 |
+
)
|
| 289 |
+
language_dropdown_tts_english = gr.Dropdown(
|
| 290 |
+
choices=list(language_dict_persian_keys.keys()) if language_dict_persian_keys else ["لیست خالی"],
|
| 291 |
+
value=default_english_tts_voice, label="🗣️ انتخاب گوینده:", interactive=bool(language_dict_persian_keys)
|
| 292 |
+
)
|
| 293 |
+
with gr.Accordion("تنظیمات صدا", open=False): # اطمینان از لیبل صحیح برای CSS
|
| 294 |
+
rate_slider = gr.Slider(-100, 100, 0, step=10, label="سرعت")
|
| 295 |
+
volume_slider = gr.Slider(-100, 100, 0, step=10, label="حجم")
|
| 296 |
+
pitch_slider = gr.Slider(-50, 50, 0, step=5, label="گام")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
+
with gr.Group(elem_classes=["fly-submit-button-container"]): # استفاده از Group
|
| 299 |
+
submit_button = gr.Button("🚀 ترجمه و تلفظ", variant="primary")
|
| 300 |
+
|
| 301 |
+
with gr.Column():
|
| 302 |
+
output_text_translated = gr.Textbox( label="📜 ترجمه انگلیسی:", interactive=False, lines=4, placeholder="ترجمه یا پیام خطا..." )
|
| 303 |
+
output_audio = gr.Audio(label="🎧 صوت:", type="filepath", format="mp3", interactive=False)
|
| 304 |
|
| 305 |
+
gr.HTML("<hr class='custom-hr-fly'>")
|
| 306 |
+
|
| 307 |
+
example_list = []
|
| 308 |
+
if language_dict_persian_keys and default_english_tts_voice :
|
| 309 |
+
num_voices = len(language_dict_persian_keys)
|
| 310 |
+
voice_keys = list(language_dict_persian_keys.keys())
|
| 311 |
+
voice1_idx, voice2_idx, voice3_idx = 0, min(7, num_voices-1), min(13, num_voices-1)
|
| 312 |
+
example_list = [
|
| 313 |
["قیمت این لباس چقدر است؟", voice_keys[voice1_idx], 0, 0, 0],
|
| 314 |
+
["میتوانید آدرس را روی نقشه به من نشان دهید؟", voice_keys[voice2_idx], 0, 0, 0],
|
| 315 |
+
["ببخشید، متوجه نشدم. امکان دارد تکرار کنید؟", voice_keys[voice3_idx], -10, 0, 0],
|
|
|
|
| 316 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
+
if example_list:
|
| 319 |
+
gr.Examples(
|
| 320 |
+
examples=example_list,
|
| 321 |
+
inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
|
| 322 |
+
outputs=[output_text_translated, output_audio],
|
| 323 |
+
fn=translate_and_speak_sync_wrapper, label="💡 نمونه" # اطمینان از لیبل صحیح
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
gr.Markdown("<p class='app-footer-fly'>Fly Language Learning © ۲۰۲۴</p>")
|
| 327 |
|
| 328 |
submit_button.click(
|
| 329 |
fn=translate_and_speak_sync_wrapper,
|
|
|
|
| 332 |
)
|
| 333 |
|
| 334 |
if __name__ == "__main__":
|
| 335 |
+
if not language_dict_persian_keys: logging.critical("دیکشنری صداها خالی است!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|