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,100 +59,109 @@ language_dict_persian_keys = {
|
|
| 59 |
}
|
| 60 |
|
| 61 |
async def translate_text_gemini_async(text, target_language="English"):
|
| 62 |
-
|
| 63 |
-
if not
|
| 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 "
|
| 72 |
-
except Exception as e: logging.error(f"Gemini translation error: {e}", exc_info=True); return f"
|
| 73 |
|
| 74 |
async def text_to_speech_edge_tts_async(text_to_speak, tts_voice_key, rate, volume, pitch):
|
| 75 |
-
|
| 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"
|
| 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 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 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[:
|
| 114 |
-
loop = get_event_loop()
|
| 115 |
|
|
|
|
|
|
|
| 116 |
if not GOOGLE_API_KEY or not model:
|
| 117 |
-
msg = "خطا: سرویس ترجمه پیکربندی نشده است. لطفاً از تنظیم GOOGLE_API_KEY
|
| 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 |
-
|
|
|
|
| 136 |
err_msg = f"{translated_text}\n(خطای TTS: {tts_status_msg})"
|
| 137 |
-
logging.error(err_msg); return err_msg, None
|
| 138 |
-
|
| 139 |
-
|
|
|
|
| 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
|
| 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 = "#
|
| 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,176 +170,400 @@ app_theme = gr.themes.Soft(
|
|
| 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');
|
| 171 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
| 172 |
:root {{
|
| 173 |
-
--fly-primary: {FLY_PRIMARY_COLOR_HEX};
|
| 174 |
-
--fly-
|
| 175 |
-
--fly-
|
| 176 |
-
--fly-
|
| 177 |
-
--fly-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
--global-font: 'Vazirmatn', 'Inter', 'Poppins', Arial, sans-serif;
|
| 179 |
--english-font: 'Poppins', 'Inter', Arial, sans-serif;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
}}
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 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.
|
| 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 |
-
|
| 212 |
}}
|
| 213 |
.gr-input > label + div > textarea:focus,
|
| 214 |
-
.gr-
|
| 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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
}}
|
| 219 |
-
/* عدم استفاده از ::after برای دراپ داون در این مرحله */
|
| 220 |
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
| 222 |
background-color: var(--fly-panel-bg) !important;
|
| 223 |
-
border-color: #A5D5FE !important;
|
| 224 |
-
min-height:
|
| 225 |
font-family: var(--english-font) !important;
|
| 226 |
-
font-size:
|
|
|
|
|
|
|
| 227 |
}}
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
.gr-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
border-radius:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
body {{font-size: 16px;}}
|
| 254 |
-
.gradio-container {{
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
.main-content-area-fly {{padding: 0;}}
|
| 258 |
-
|
| 259 |
-
.main-content-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
.
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
default_english_tts_voice = 'انگلیسی (آمریکا) - جنی (زن)'
|
| 271 |
-
if not 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 |
-
|
| 275 |
-
|
|
|
|
| 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
|
| 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 |
-
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
["قیمت این لباس چقدر است؟", voice_keys[voice1_idx], 0, 0, 0],
|
| 314 |
-
["میتوانید آدرس را روی نقشه به من نشان دهید؟", voice_keys[voice2_idx],
|
| 315 |
-
["ببخشید، متوجه نشدم. امکان دارد تکرار کنید؟", voice_keys[voice3_idx], -10,
|
|
|
|
| 316 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
|
|
|
| 327 |
|
| 328 |
-
submit_button.click(
|
| 329 |
-
fn=translate_and_speak_sync_wrapper,
|
| 330 |
-
inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
|
| 331 |
-
outputs=[output_text_translated, output_audio]
|
| 332 |
-
)
|
| 333 |
|
| 334 |
if __name__ == "__main__":
|
| 335 |
-
if not language_dict_persian_keys:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
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 |
+
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 |
+
# Ensure tmp_path is correctly defined and used
|
| 81 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
| 82 |
+
tmp_path = tmp_file.name
|
| 83 |
+
await communicate.save(tmp_path) # save to the path
|
| 84 |
+
return "TTS موفق", tmp_path
|
| 85 |
+
except Exception as e: logging.error(f"Edge-TTS error: {e}", exc_info=True); return f"خطا در TTS: {type(e).__name__}", None
|
| 86 |
|
|
|
|
| 87 |
_thread_local = threading.local()
|
| 88 |
|
| 89 |
def get_event_loop():
|
| 90 |
+
if not hasattr(_thread_local, 'loop') or _thread_local.loop.is_closed():
|
| 91 |
_thread_local.loop = asyncio.new_event_loop()
|
| 92 |
+
logging.info(f"Created or reopened new event loop for thread {threading.get_ident()}")
|
| 93 |
|
|
|
|
|
|
|
| 94 |
try:
|
| 95 |
+
current_loop = asyncio.get_event_loop_policy().get_event_loop()
|
| 96 |
+
if current_loop is not _thread_local.loop:
|
| 97 |
+
asyncio.set_event_loop(_thread_local.loop)
|
| 98 |
+
except RuntimeError: # No current event loop or loop is different
|
| 99 |
asyncio.set_event_loop(_thread_local.loop)
|
| 100 |
+
logging.info(f"Set event loop for thread {threading.get_ident()} as no current loop was found or it was different.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
return _thread_local.loop
|
| 102 |
|
| 103 |
|
| 104 |
def translate_and_speak_sync_wrapper(persian_text, english_tts_voice_key, rate, volume, pitch):
|
| 105 |
+
logging.info(f"Wrapper called. Text: '{persian_text[:30]}...' Voice: {english_tts_voice_key}")
|
| 106 |
+
loop = get_event_loop()
|
| 107 |
|
| 108 |
+
audio_file_to_clean = None # Variable to store path for cleanup
|
| 109 |
+
|
| 110 |
if not GOOGLE_API_KEY or not model:
|
| 111 |
+
msg = "خطا: سرویس ترجمه پیکربندی نشده است. لطفاً از تنظیم GOOGLE_API_KEY اطمینان حاصل کنید."
|
| 112 |
logging.error(msg); return msg, None
|
| 113 |
if not persian_text or not persian_text.strip():
|
| 114 |
msg = "لطفاً متن فارسی را برای ترجمه وارد کنید."
|
| 115 |
logging.warning(msg); return msg, None
|
| 116 |
+
if not english_tts_voice_key or english_tts_voice_key == "لیست خالی":
|
| 117 |
+
msg = "لطفاً یک صدای گوینده انتخاب کنید."
|
| 118 |
+
# Return Persian text if no voice selected, so user sees their input
|
| 119 |
+
logging.warning(msg); return persian_text, None
|
| 120 |
+
|
| 121 |
try:
|
|
|
|
| 122 |
translation_status_msg, translated_text = loop.run_until_complete(
|
| 123 |
translate_text_gemini_async(persian_text)
|
| 124 |
)
|
| 125 |
+
if "خطا" in translation_status_msg.lower() or not translated_text:
|
| 126 |
err_msg = f"ترجمه ناموفق: {translation_status_msg} {translated_text or ''}"
|
| 127 |
logging.error(err_msg); return err_msg, None
|
| 128 |
|
|
|
|
| 129 |
tts_status_msg, audio_path = loop.run_until_complete(
|
| 130 |
text_to_speech_edge_tts_async(translated_text, english_tts_voice_key, rate, volume, pitch)
|
| 131 |
)
|
| 132 |
+
|
| 133 |
+
if "خطا" in tts_status_msg.lower() or not audio_path:
|
| 134 |
err_msg = f"{translated_text}\n(خطای TTS: {tts_status_msg})"
|
| 135 |
+
logging.error(err_msg); return err_msg, None # Return translated text with TTS error
|
| 136 |
+
|
| 137 |
+
audio_file_to_clean = audio_path # Mark for potential cleanup if needed by Gradio
|
| 138 |
+
logging.info(f"عملیات موفق. متن ترجمه شده: '{translated_text[:30]}...', مسیر صوت: {audio_path}")
|
| 139 |
return translated_text, audio_path
|
| 140 |
+
|
| 141 |
except Exception as e:
|
| 142 |
logging.error(f"خطای غیرمنتظره در wrapper: {e}", exc_info=True)
|
| 143 |
+
# Clean up temp file if an unexpected error occurs after its creation
|
| 144 |
+
if audio_file_to_clean and os.path.exists(audio_file_to_clean):
|
| 145 |
+
try:
|
| 146 |
+
os.remove(audio_file_to_clean)
|
| 147 |
+
logging.info(f"Cleaned up temporary audio file: {audio_file_to_clean}")
|
| 148 |
+
except OSError as oe:
|
| 149 |
+
logging.error(f"Error cleaning up temp file {audio_file_to_clean}: {oe}")
|
| 150 |
return f"خطای داخلی سرور: {type(e).__name__}", None
|
| 151 |
|
| 152 |
+
# --- تعریف تم و CSS بهبود یافته ---
|
| 153 |
FLY_PRIMARY_COLOR_HEX = "#2563EB"
|
| 154 |
FLY_SECONDARY_COLOR_HEX = "#059669"
|
| 155 |
+
FLY_ACCENT_COLOR_HEX = "#D97706" # نارنجی برای دکمه اصلی
|
| 156 |
FLY_TEXT_COLOR_HEX = "#1F2937"
|
| 157 |
FLY_SUBTLE_TEXT_HEX = "#6B7280"
|
| 158 |
+
FLY_LIGHT_BACKGROUND_HEX = "#F3F4F6" # کمی رو��نتر از قبل
|
| 159 |
FLY_WHITE_HEX = "#FFFFFF"
|
| 160 |
FLY_BORDER_COLOR_HEX = "#D1D5DB"
|
| 161 |
FLY_INPUT_BG_HEX = "#FFFFFF"
|
| 162 |
+
FLY_PANEL_BG_HEX = "#E0F2FE" # آبی بسیار روشن برای پنل ترجمه
|
| 163 |
+
FLY_SUCCESS_GREEN_HEX = "#059669"
|
| 164 |
+
FLY_ERROR_RED_HEX = "#DC2626"
|
| 165 |
|
| 166 |
app_theme = gr.themes.Soft(
|
| 167 |
primary_hue=gr.themes.colors.blue,
|
|
|
|
| 170 |
font=[gr.themes.GoogleFont("Vazirmatn"), "Arial", "sans-serif"],
|
| 171 |
).set(
|
| 172 |
body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
|
| 173 |
+
button_primary_background_fill=FLY_ACCENT_COLOR_HEX,
|
| 174 |
+
button_primary_background_fill_hover=f"{FLY_ACCENT_COLOR_HEX}E0",
|
| 175 |
+
button_primary_text_color=FLY_WHITE_HEX,
|
| 176 |
)
|
| 177 |
|
| 178 |
+
# --- CSS بهبود یافته با دقت در f-string ---
|
| 179 |
+
# IMPORTANT: Using ''' """ ''' to define the multi-line string to avoid f-string parsing issues with CSS's own curly braces.
|
| 180 |
+
# If we were using f-string for CSS, all CSS '{' and '}' would need to be '{{' and '}}'.
|
| 181 |
custom_css = f"""
|
| 182 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700&display=swap');
|
| 183 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
|
| 184 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
| 185 |
:root {{
|
| 186 |
+
--fly-primary: {FLY_PRIMARY_COLOR_HEX};
|
| 187 |
+
--fly-secondary: {FLY_SECONDARY_COLOR_HEX};
|
| 188 |
+
--fly-accent: {FLY_ACCENT_COLOR_HEX};
|
| 189 |
+
--fly-text: {FLY_TEXT_COLOR_HEX};
|
| 190 |
+
--fly-subtle-text: {FLY_SUBTLE_TEXT_HEX};
|
| 191 |
+
--fly-light-bg: {FLY_LIGHT_BACKGROUND_HEX};
|
| 192 |
+
--fly-white: {FLY_WHITE_HEX};
|
| 193 |
+
--fly-border: {FLY_BORDER_COLOR_HEX};
|
| 194 |
+
--fly-input-bg: {FLY_INPUT_BG_HEX};
|
| 195 |
+
--fly-panel-bg: {FLY_PANEL_BG_HEX};
|
| 196 |
+
--fly-success: {FLY_SUCCESS_GREEN_HEX};
|
| 197 |
+
--fly-error: {FLY_ERROR_RED_HEX};
|
| 198 |
--global-font: 'Vazirmatn', 'Inter', 'Poppins', Arial, sans-serif;
|
| 199 |
--english-font: 'Poppins', 'Inter', Arial, sans-serif;
|
| 200 |
+
--border-radius-sm: 6px;
|
| 201 |
+
--border-radius-md: 8px;
|
| 202 |
+
--border-radius-lg: 12px;
|
| 203 |
+
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
|
| 204 |
+
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
| 205 |
+
}}
|
| 206 |
+
body {{
|
| 207 |
+
font-family: var(--global-font);
|
| 208 |
+
direction: rtl;
|
| 209 |
+
background-color: var(--fly-light-bg);
|
| 210 |
+
color: var(--fly-text);
|
| 211 |
+
line-height: 1.7;
|
| 212 |
+
-webkit-font-smoothing: antialiased;
|
| 213 |
+
-moz-osx-font-smoothing: grayscale;
|
| 214 |
+
font-size: 15px;
|
| 215 |
+
}}
|
| 216 |
+
.gradio-container {{
|
| 217 |
+
max-width: 100% !important;
|
| 218 |
+
width: 100% !important;
|
| 219 |
+
min-height: 100vh;
|
| 220 |
+
margin: 0 auto !important;
|
| 221 |
+
padding: 0 !important;
|
| 222 |
+
border-radius: 0 !important;
|
| 223 |
+
box-shadow: none !important;
|
| 224 |
+
background-color: var(--fly-light-bg) !important;
|
| 225 |
+
display: flex;
|
| 226 |
+
flex-direction: column;
|
| 227 |
+
}}
|
| 228 |
+
|
| 229 |
+
.app-header-fly {{
|
| 230 |
+
text-align: center;
|
| 231 |
+
padding: 24px 15px;
|
| 232 |
+
background: linear-gradient(135deg, var(--fly-primary) 0%, var(--fly-secondary) 100%);
|
| 233 |
+
color: white;
|
| 234 |
+
margin: 0 0 1.5rem 0;
|
| 235 |
+
border-bottom-left-radius: 20px;
|
| 236 |
+
border-bottom-right-radius: 20px;
|
| 237 |
+
box-shadow: 0 4px 12px -2px rgba(37, 99, 235, 0.2);
|
| 238 |
+
}}
|
| 239 |
+
.app-header-fly h1 {{
|
| 240 |
+
font-size: 1.8em !important;
|
| 241 |
+
font-weight: 700 !important;
|
| 242 |
+
margin: 0 0 6px 0;
|
| 243 |
+
font-family: var(--english-font);
|
| 244 |
+
letter-spacing: 0.5px;
|
| 245 |
+
}}
|
| 246 |
+
.app-header-fly p {{
|
| 247 |
+
font-size: 0.95em !important;
|
| 248 |
+
margin-top: 4px;
|
| 249 |
+
font-weight: 400;
|
| 250 |
+
color: rgba(255, 255, 255, 0.9) !important;
|
| 251 |
+
}}
|
| 252 |
+
|
| 253 |
+
.main-content-area-fly {{
|
| 254 |
+
flex-grow: 1;
|
| 255 |
+
padding: 0 1rem;
|
| 256 |
}}
|
| 257 |
+
.content-wrapper {{
|
| 258 |
+
background-color: var(--fly-white);
|
| 259 |
+
padding: 1.5rem;
|
| 260 |
+
border-radius: var(--border-radius-lg);
|
| 261 |
+
box-shadow: var(--shadow-md);
|
| 262 |
+
margin-bottom: 1.5rem;
|
| 263 |
+
}}
|
| 264 |
+
|
| 265 |
+
/* --- Styling inputs --- */
|
| 266 |
+
.gr-input > label > span.label-text, .gr-dropdown > label > span.label-text {{
|
| 267 |
+
font-weight: 600 !important;
|
| 268 |
+
color: #374151 !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
font-size: 0.9em !important;
|
| 270 |
+
margin-bottom: 6px !important;
|
| 271 |
+
display: inline-block;
|
| 272 |
+
}}
|
| 273 |
+
.gr-input > label + div > textarea,
|
| 274 |
+
.gr-dropdown > label + div > div > input, /* For searchable dropdown */
|
| 275 |
+
.gr-dropdown > label + div > div > select {{
|
| 276 |
+
border-radius: var(--border-radius-md) !important;
|
| 277 |
+
border: 1px solid var(--fly-border) !important;
|
| 278 |
+
font-size: 0.95em !important;
|
| 279 |
background-color: var(--fly-input-bg) !important;
|
| 280 |
padding: 10px 12px !important;
|
| 281 |
+
line-height: 1.6;
|
| 282 |
width: 100% !important;
|
| 283 |
box-sizing: border-box !important;
|
| 284 |
+
-webkit-tap-highlight-color: transparent;
|
| 285 |
+
font-family: var(--global-font) !important;
|
| 286 |
color: var(--fly-text) !important;
|
| 287 |
+
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
| 288 |
}}
|
| 289 |
.gr-input > label + div > textarea:focus,
|
| 290 |
+
.gr-dropdown > label + div > div > input:focus,
|
| 291 |
.gr-dropdown > label + div > div > select:focus {{
|
| 292 |
border-color: var(--fly-primary) !important;
|
| 293 |
+
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2) !important;
|
| 294 |
+
outline: none;
|
| 295 |
+
}}
|
| 296 |
+
.gr-dropdown svg.icon {{
|
| 297 |
+
right: auto !important;
|
| 298 |
+
left: 10px !important; /* برای RTL */
|
| 299 |
}}
|
|
|
|
| 300 |
|
| 301 |
+
/* Output Textbox styling */
|
| 302 |
+
/* Targeting both old and new Gradio versions for output textbox */
|
| 303 |
+
.gr-textbox[label*="ترجمه انگلیسی"] > label + div > textarea,
|
| 304 |
+
.gradio-interface .output_text .gr-textbox[data-testid="textbox"] > label + div > textarea {{
|
| 305 |
background-color: var(--fly-panel-bg) !important;
|
| 306 |
+
border-color: #A5D5FE !important;
|
| 307 |
+
min-height: 100px;
|
| 308 |
font-family: var(--english-font) !important;
|
| 309 |
+
font-size: 1em !important;
|
| 310 |
+
color: #0C4A6E !important;
|
| 311 |
+
font-weight: 500;
|
| 312 |
}}
|
| 313 |
+
|
| 314 |
+
/* Accordion styling */
|
| 315 |
+
.gr-accordion > button.gr-button {{ /* Accordion Header Button */
|
| 316 |
+
font-weight: 600 !important;
|
| 317 |
+
padding: 10px 12px !important;
|
| 318 |
+
border-radius: var(--border-radius-md) !important;
|
| 319 |
+
background-color: #E5E7EB !important;
|
| 320 |
+
color: var(--fly-text) !important;
|
| 321 |
+
border: 1px solid #D1D5DB !important;
|
| 322 |
+
font-size: 0.9em;
|
| 323 |
+
margin-bottom: 0.5rem;
|
| 324 |
+
transition: background-color 0.2s ease;
|
| 325 |
+
}}
|
| 326 |
+
.gr-accordion > button.gr-button:hover {{
|
| 327 |
+
background-color: #D1D5DB !important;
|
| 328 |
+
}}
|
| 329 |
+
.gr-accordion > div.gr-panel {{ /* Accordion Content Panel */
|
| 330 |
+
border-radius: var(--border-radius-md) !important;
|
| 331 |
+
border: 1px solid var(--fly-border) !important;
|
| 332 |
+
background-color: var(--fly-white) !important;
|
| 333 |
+
padding: 1rem !important;
|
| 334 |
+
box-shadow: none;
|
| 335 |
+
}}
|
| 336 |
+
.gr-slider {{
|
| 337 |
+
padding: 8px 0 !important;
|
| 338 |
+
}}
|
| 339 |
+
.gr-slider label span {{
|
| 340 |
+
font-size: 0.85em !important;
|
| 341 |
+
color: var(--fly-subtle-text);
|
| 342 |
+
}}
|
| 343 |
+
|
| 344 |
+
/* Submit Button - Relies on app_theme for primary color */
|
| 345 |
+
.fly-submit-button .gr-button {{
|
| 346 |
+
width: 100% !important;
|
| 347 |
+
padding: 12px 20px !important;
|
| 348 |
+
font-size: 1em !important;
|
| 349 |
+
font-weight: 600 !important;
|
| 350 |
+
border-radius: var(--border-radius-md) !important;
|
| 351 |
+
margin-top: 1rem !important;
|
| 352 |
+
text-transform: uppercase;
|
| 353 |
+
letter-spacing: 0.5px;
|
| 354 |
+
transition: background-color 0.2s ease, transform 0.1s ease;
|
| 355 |
+
}}
|
| 356 |
+
.fly-submit-button .gr-button:hover {{
|
| 357 |
+
transform: translateY(-2px);
|
| 358 |
+
}}
|
| 359 |
+
|
| 360 |
+
/* Examples Section */
|
| 361 |
+
div[id*="examples_section"] {{ /* More specific selector */
|
| 362 |
+
margin-top: 1.5rem;
|
| 363 |
+
}}
|
| 364 |
+
div[id*="examples_section"] > .gr-panel {{
|
| 365 |
+
background-color: transparent !important;
|
| 366 |
+
border: none !important;
|
| 367 |
+
padding: 0 !important;
|
| 368 |
+
box-shadow: none !important;
|
| 369 |
+
}}
|
| 370 |
+
div[id*="examples_section"] > .gr-form > button.gr-button.gr-button-secondary, /* Gradio 3.x */
|
| 371 |
+
div[id*="examples_section"] .gr-sample-button /* Gradio 4.x */ {{
|
| 372 |
+
background-color: #E0E7FF !important;
|
| 373 |
+
color: var(--fly-primary) !important;
|
| 374 |
+
border-radius: var(--border-radius-sm) !important;
|
| 375 |
+
font-size: 0.85em !important;
|
| 376 |
+
padding: 5px 10px !important;
|
| 377 |
+
border: 1px solid #C7D2FE !important;
|
| 378 |
+
transition: background-color 0.2s ease;
|
| 379 |
+
}}
|
| 380 |
+
div[id*="examples_section"] > .gr-form > button.gr-button.gr-button-secondary:hover,
|
| 381 |
+
div[id*="examples_section"] .gr-sample-button:hover {{
|
| 382 |
+
background-color: #C7D2FE !important;
|
| 383 |
+
}}
|
| 384 |
+
div[id*="examples_section"] .gr-samples-header {{
|
| 385 |
+
font-weight: 600;
|
| 386 |
+
color: #4B5563;
|
| 387 |
+
font-size: 0.95em;
|
| 388 |
+
margin-bottom: 0.8rem;
|
| 389 |
+
}}
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
.custom-hr-fly {{
|
| 393 |
+
height: 1px;
|
| 394 |
+
background-color: var(--fly-border);
|
| 395 |
+
margin: 1.8rem 0;
|
| 396 |
+
border: none;
|
| 397 |
+
}}
|
| 398 |
+
.api-warning-message-fly {{
|
| 399 |
+
background-color: #FFFBEB !important;
|
| 400 |
+
color: #92400E !important;
|
| 401 |
+
padding: 12px 15px !important;
|
| 402 |
+
border-radius: var(--border-radius-md) !important;
|
| 403 |
+
border: 1px solid #FDE68A !important;
|
| 404 |
+
text-align: center !important;
|
| 405 |
+
margin: 0 0.5rem 1rem 0.5rem !important;
|
| 406 |
+
font-size: 0.9em !important;
|
| 407 |
+
font-weight: 500;
|
| 408 |
+
}}
|
| 409 |
+
.app-footer-fly {{
|
| 410 |
+
text-align:center;
|
| 411 |
+
font-size:0.8em;
|
| 412 |
+
color: var(--fly-subtle-text);
|
| 413 |
+
margin-top:2rem;
|
| 414 |
+
padding-bottom: 1rem;
|
| 415 |
+
}}
|
| 416 |
+
footer, .gradio-footer {{
|
| 417 |
+
display: none !important;
|
| 418 |
+
}}
|
| 419 |
+
|
| 420 |
+
/* Desktop improvements */
|
| 421 |
+
@media (min-width: 768px) {{
|
| 422 |
body {{font-size: 16px;}}
|
| 423 |
+
.gradio-container {{
|
| 424 |
+
max-width: 800px !important;
|
| 425 |
+
padding: 1.5rem !important;
|
| 426 |
+
margin: 2rem auto !important;
|
| 427 |
+
background-color: var(--fly-light-bg) !important;
|
| 428 |
+
border-radius: 0;
|
| 429 |
+
box-shadow: none;
|
| 430 |
+
}}
|
| 431 |
+
.app-header-fly {{
|
| 432 |
+
border-radius: var(--border-radius-lg);
|
| 433 |
+
margin: -1.5rem -1.5rem 2rem -1.5rem; /* Extend to edges of container */
|
| 434 |
+
}}
|
| 435 |
+
.app-header-fly h1 {{ font-size: 2em !important; }}
|
| 436 |
+
.app-header-fly p {{ font-size: 1em !important; }}
|
| 437 |
.main-content-area-fly {{padding: 0;}}
|
| 438 |
+
|
| 439 |
+
.main-content-columns-fly {{
|
| 440 |
+
display: flex;
|
| 441 |
+
flex-direction: row;
|
| 442 |
+
gap: 1.5rem;
|
| 443 |
+
}}
|
| 444 |
+
.main-content-columns-fly > .gr-column:nth-child(1) {{
|
| 445 |
+
flex: 3; /* Input column wider */
|
| 446 |
+
}}
|
| 447 |
+
.main-content-columns-fly > .gr-column:nth-child(2) {{
|
| 448 |
+
flex: 2; /* Output column */
|
| 449 |
+
}}
|
| 450 |
+
|
| 451 |
+
.fly-submit-button .gr-button {{
|
| 452 |
+
width: auto !important;
|
| 453 |
+
min-width: 200px;
|
| 454 |
+
}}
|
| 455 |
+
.api-warning-message-fly {{
|
| 456 |
+
margin-left: 0 !important;
|
| 457 |
+
margin-right: 0 !important;
|
| 458 |
+
font-size: 0.9em;
|
| 459 |
+
}}
|
| 460 |
+
}}
|
| 461 |
+
|
| 462 |
+
.result-area-fly {{
|
| 463 |
+
margin-top: 1rem;
|
| 464 |
+
}}
|
| 465 |
+
.result-area-fly > .gr-block > .gr-form > .gr-input,
|
| 466 |
+
.result-area-fly > .gr-block > .gr-form > .gr-audio {{ /* Ensure output elements also have some margin */
|
| 467 |
+
margin-bottom: 0.8rem;
|
| 468 |
+
}}
|
| 469 |
+
""" # End of f-string for CSS
|
| 470 |
|
| 471 |
default_english_tts_voice = 'انگلیسی (آمریکا) - جنی (زن)'
|
| 472 |
+
if not language_dict_persian_keys :
|
| 473 |
+
logging.warning("Language dictionary is empty!")
|
| 474 |
+
default_english_tts_voice = None
|
| 475 |
+
elif default_english_tts_voice not in language_dict_persian_keys:
|
| 476 |
default_english_tts_voice = list(language_dict_persian_keys.keys())[0] if language_dict_persian_keys else None
|
| 477 |
|
| 478 |
+
# --- Gradio UI با ساختار بهبود یافته ---
|
| 479 |
+
with gr.Blocks(theme=app_theme, css=custom_css, title="آموزش زبان فلای | Fly Language Learning") as demo:
|
| 480 |
+
gr.HTML(f"""<div class="app-header-fly"><h1>Fly Language Learning 🚀</h1><p>ترجمه فارسی به انگلیسی و تلفظ با لهجه دلخواه</p></div>""")
|
| 481 |
|
| 482 |
with gr.Column(elem_classes=["main-content-area-fly"]):
|
| 483 |
if not GOOGLE_API_KEY or not model:
|
| 484 |
+
missing_key_msg = "⚠️ **هشدار سرویس ترجمه:** "
|
| 485 |
+
if not GOOGLE_API_KEY: missing_key_msg += "کلید API گوگل (GOOGLE_API_KEY) تنظیم نشده است."
|
| 486 |
+
elif not model: missing_key_msg += "خطا در بارگذاری مدل Gemini."
|
| 487 |
+
gr.Markdown(f"<div class='api-warning-message-fly'>{missing_key_msg} بخش ترجمه غیرفعال خواهد بود. لطفاً تنظیمات Secrets ��ا بررسی کنید.</div>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
|
| 489 |
+
with gr.Box(elem_classes=["content-wrapper"]): # Wrapper for card styling
|
| 490 |
+
with gr.Row(elem_classes=["main-content-columns-fly"]):
|
| 491 |
+
with gr.Column(scale=3):
|
| 492 |
+
input_text_persian = gr.Textbox(
|
| 493 |
+
lines=4, label="📝 متن فارسی خود را وارد کنید:", placeholder="مثال: سلام، حال شما چطور است؟",
|
| 494 |
+
elem_id="persian_input_textbox"
|
| 495 |
+
)
|
| 496 |
+
language_dropdown_tts_english = gr.Dropdown(
|
| 497 |
+
choices=list(language_dict_persian_keys.keys()) if language_dict_persian_keys else ["لیست خالی"],
|
| 498 |
+
value=default_english_tts_voice if default_english_tts_voice else "لیست خالی",
|
| 499 |
+
label="🗣️ گوینده و لهجه انگلیسی را انتخاب کنید:",
|
| 500 |
+
interactive=bool(language_dict_persian_keys and default_english_tts_voice is not None)
|
| 501 |
+
)
|
| 502 |
+
with gr.Accordion("⚙️ تنظیمات پیشرفته صدا", open=False):
|
| 503 |
+
rate_slider = gr.Slider(minimum=-100, maximum=100, value=0, step=10, label="سرعت گفتار (Rate)")
|
| 504 |
+
volume_slider = gr.Slider(minimum=-100, maximum=100, value=0, step=10, label="بلندی صدا (Volume)")
|
| 505 |
+
pitch_slider = gr.Slider(minimum=-50, maximum=50, value=0, step=5, label="زیر و بمی صدا (Pitch)")
|
| 506 |
+
|
| 507 |
+
with gr.Box(elem_classes=["fly-submit-button"]):
|
| 508 |
+
submit_button = gr.Button("ترجمه و پخش صدا", variant="primary", icon="▶️") # type: ignore
|
| 509 |
|
| 510 |
+
with gr.Column(scale=2, elem_classes=["result-area-fly"]):
|
| 511 |
+
output_text_translated = gr.Textbox(
|
| 512 |
+
label="📜 ترجمه انگلیسی:", interactive=False, lines=5,
|
| 513 |
+
placeholder="ترجمه متن شما در اینجا نمایش داده میشود...",
|
| 514 |
+
elem_id="english_output_textbox"
|
| 515 |
+
)
|
| 516 |
+
output_audio = gr.Audio(label="🎧 فایل صوتی:", type="filepath", format="mp3", interactive=False)
|
| 517 |
+
|
| 518 |
+
if language_dict_persian_keys and default_english_tts_voice:
|
| 519 |
+
gr.HTML("<hr class='custom-hr-fly'>")
|
| 520 |
+
num_voices = len(language_dict_persian_keys)
|
| 521 |
+
voice_keys = list(language_dict_persian_keys.keys())
|
| 522 |
+
|
| 523 |
+
voice1_idx = 0
|
| 524 |
+
voice2_idx = min(7, num_voices - 1) if num_voices > 1 else 0
|
| 525 |
+
voice3_idx = min(13, num_voices - 1) if num_voices > 1 else 0
|
| 526 |
+
|
| 527 |
+
example_list_data = [
|
| 528 |
["قیمت این لباس چقدر است؟", voice_keys[voice1_idx], 0, 0, 0],
|
| 529 |
+
["میتوانید آدرس را روی نقشه به من نشان دهید؟", voice_keys[voice2_idx], 5, 0, 0],
|
| 530 |
+
["ببخشید، متوجه نشدم. امکان دارد تکرار کنید؟", voice_keys[voice3_idx], -10, 10, 0],
|
| 531 |
+
["یک قهوه و یک کیک لطفا.", voice_keys[min(3, num_voices -1) if num_voices > 0 else 0], 0, 0, 0],
|
| 532 |
]
|
| 533 |
+
# Filter out examples if voice keys are not valid (e.g. num_voices is 0)
|
| 534 |
+
valid_example_list = []
|
| 535 |
+
if num_voices > 0:
|
| 536 |
+
valid_example_list = example_list_data
|
| 537 |
+
else: # No voices, no examples
|
| 538 |
+
logging.warning("No voices available for examples.")
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
if valid_example_list:
|
| 542 |
+
gr.Examples(
|
| 543 |
+
examples=valid_example_list,
|
| 544 |
+
inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
|
| 545 |
+
outputs=[output_text_translated, output_audio],
|
| 546 |
+
fn=translate_and_speak_sync_wrapper,
|
| 547 |
+
label="💡 نمونههای آماده (برای امتحان کلیک کنید):",
|
| 548 |
+
elem_id="examples_section"
|
| 549 |
+
)
|
| 550 |
|
| 551 |
+
gr.Markdown("<p class='app-footer-fly'>✨ Fly Language Learning © ۲۰۲۴ - قدرت گرفته از Gemini و EdgeTTS ✨</p>")
|
| 552 |
+
|
| 553 |
+
if 'submit_button' in locals(): # Check if button is defined (it should be)
|
| 554 |
+
submit_button.click(
|
| 555 |
+
fn=translate_and_speak_sync_wrapper,
|
| 556 |
+
inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
|
| 557 |
+
outputs=[output_text_translated, output_audio]
|
| 558 |
+
)
|
| 559 |
+
else:
|
| 560 |
+
logging.error("Submit button was not initialized correctly.")
|
| 561 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
|
| 563 |
if __name__ == "__main__":
|
| 564 |
+
if not language_dict_persian_keys:
|
| 565 |
+
logging.critical("CRITICAL: Voice dictionary (language_dict_persian_keys) is empty! The application might not function correctly.")
|
| 566 |
+
elif not default_english_tts_voice:
|
| 567 |
+
logging.warning("WARNING: No default English TTS voice could be set. Dropdown might be empty or non-interactive.")
|
| 568 |
+
|
| 569 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|