Hamed744 commited on
Commit
f0c997f
·
verified ·
1 Parent(s): ee3c00f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -274
app.py CHANGED
@@ -9,6 +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
 
13
  GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
14
  model = None
@@ -22,7 +23,7 @@ if GOOGLE_API_KEY:
22
  else:
23
  logging.warning("کلید API گوگل (GOOGLE_API_KEY) تنظیم نشده است.")
24
 
25
- # --- دیکشنری کامل صداهای انگلیسی ---
26
  language_dict_persian_keys = {
27
  'انگلیسی (آمریکا) - جنی (زن)': 'en-US-JennyNeural', 'انگلیسی (آمریکا) - گای (مرد)': 'en-US-GuyNeural',
28
  'انگلیسی (آمریکا) - آنا (زن، صدای کودک)': 'en-US-AnaNeural', 'انگلیسی (آمریکا) - آریا (زن)': 'en-US-AriaNeural',
@@ -58,341 +59,278 @@ language_dict_persian_keys = {
58
  }
59
 
60
  async def translate_text_gemini_async(text, target_language="English"):
61
- if not model: logging.error("Gemini model not loaded."); return "خطا: سرویس ترجمه در دسترس نیست.", None
62
- if not text or not text.strip(): logging.warning("Translate: Empty input text."); return "خطا: متن ورودی خالی است.", None
 
63
  try:
64
  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}:"
65
  response = await model.generate_content_async(prompt)
66
  translated_text = response.text.strip()
67
  if translated_text.lower().startswith(f"{target_language.lower()}:"):
68
  translated_text = translated_text[len(target_language)+1:].strip()
69
- return "ترجمه موفق", translated_text
70
- except Exception as e: logging.error(f"Gemini translation error: {e}", exc_info=True); return f"خطا در ترجمه: {type(e).__name__}", None
71
 
72
  async def text_to_speech_edge_tts_async(text_to_speak, tts_voice_key, rate, volume, pitch):
73
- if not text_to_speak or not text_to_speak.strip(): logging.warning("TTS: Empty input text."); return "خطا در TTS: متن ورودی خالی است.", None
 
74
  voice_id = language_dict_persian_keys.get(tts_voice_key)
75
- if voice_id is None: logging.error(f"TTS: Voice key '{tts_voice_key}' not found."); return f"خطا در TTS: صدای '{tts_voice_key}' یافت نشد.", None
76
  try:
77
  rate_str, volume_str, pitch_str = f"{int(rate):+g}%", f"{int(volume):+g}%", f"{int(pitch):+g}Hz"
78
  communicate = edge_tts.Communicate(text_to_speak, voice_id, rate=rate_str, volume=volume_str, pitch=pitch_str)
79
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
80
- 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:
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
  return _thread_local.loop
100
 
101
 
102
  def translate_and_speak_sync_wrapper(persian_text, english_tts_voice_key, rate, volume, pitch):
103
- logging.info(f"Wrapper called. Text: '{persian_text[:30]}...' Voice: {english_tts_voice_key}")
104
- loop = get_event_loop()
105
- audio_file_to_clean = None
106
-
107
- # Default status update (invisible)
108
- status_update = gr.update(value=None, visible=False)
109
-
110
  if not GOOGLE_API_KEY or not model:
111
- msg = "خطا: سرویس ترجمه پیکربندی نشده است. لطفاً از تنظیم GOOGLE_API_KEY اطمینان حاصل کنید."
112
- logging.error(msg)
113
- status_update = gr.update(value=f"🚫 {msg}", visible=True)
114
- return msg, None, status_update
115
  if not persian_text or not persian_text.strip():
116
  msg = "لطفاً متن فارسی را برای ترجمه وارد کنید."
117
- logging.warning(msg)
118
- status_update = gr.update(value=f"⚠️ {msg}", visible=True)
119
- return msg, None, status_update
120
- if not english_tts_voice_key or english_tts_voice_key == "لیست خالی":
121
- msg = "لطفاً یک صدای گوینده انتخاب کنید."
122
- logging.warning(msg)
123
- status_update = gr.update(value=f"⚠️ {msg}", visible=True)
124
- return persian_text, None, status_update # Return Persian text so user sees their input
125
-
126
  try:
 
127
  translation_status_msg, translated_text = loop.run_until_complete(
128
  translate_text_gemini_async(persian_text)
129
  )
130
- if "خطا" in translation_status_msg.lower() or not translated_text:
131
  err_msg = f"ترجمه ناموفق: {translation_status_msg} {translated_text or ''}"
132
- logging.error(err_msg)
133
- status_update = gr.update(value=f"🚫 {err_msg}", visible=True)
134
- return err_msg, None, status_update
135
 
 
136
  tts_status_msg, audio_path = loop.run_until_complete(
137
  text_to_speech_edge_tts_async(translated_text, english_tts_voice_key, rate, volume, pitch)
138
  )
139
-
140
- if "خطا" in tts_status_msg.lower() or not audio_path:
141
- err_msg = f"خطای TTS: {tts_status_msg}" # Don't repeat translated text here, it's already in output
142
- logging.error(f"Translated: '{translated_text}', TTS Error: {err_msg}")
143
- status_update = gr.update(value=f"⚠️ {err_msg}", visible=True)
144
- return translated_text, None, status_update # Return translated text even if TTS fails
145
-
146
- audio_file_to_clean = audio_path
147
- logging.info(f"عملیات موفق. متن ترجمه شده: '{translated_text[:30]}...', مسیر صوت: {audio_path}")
148
- status_update = gr.update(value="✅ ترجمه و تولید صدا موفقیت آمیز بود!", visible=True)
149
- return translated_text, audio_path, status_update
150
-
151
  except Exception as e:
152
  logging.error(f"خطای غیرمنتظره در wrapper: {e}", exc_info=True)
153
- if audio_file_to_clean and os.path.exists(audio_file_to_clean):
154
- try:
155
- os.remove(audio_file_to_clean)
156
- logging.info(f"Cleaned up temporary audio file: {audio_file_to_clean}")
157
- except OSError as oe:
158
- logging.error(f"Error cleaning up temp file {audio_file_to_clean}: {oe}")
159
- status_update = gr.update(value=f"🚫 خطای داخلی سرور: {type(e).__name__}", visible=True)
160
- return f"خطای داخلی سرور: {type(e).__name__}", None, status_update
161
-
162
- # --- تعریف تم و CSS بسیار زیباتر ---
163
- FLY_PRIMARY_COLOR_HEX = "#4F46E5" # Indigo
164
- FLY_SECONDARY_COLOR_HEX = "#10B981" # Emerald
165
- FLY_ACCENT_COLOR_HEX = "#F59E0B" # Amber
166
- FLY_TEXT_COLOR_HEX = "#111827" # Gray 900
167
- FLY_SUBTLE_TEXT_HEX = "#6B7280" # Gray 500
168
- FLY_LIGHT_BACKGROUND_HEX = "#F9FAFB" # Gray 50
169
  FLY_WHITE_HEX = "#FFFFFF"
170
- FLY_BORDER_COLOR_HEX = "#D1D5DB" # Gray 300
171
- FLY_INPUT_BG_HEX = "#FFFFFF"
172
- FLY_PANEL_BG_HEX = "#E0E7FF" # Indigo 100
173
-
174
- app_theme = gr.themes.Base(
175
- font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"],
 
 
 
176
  ).set(
177
  body_background_fill=FLY_LIGHT_BACKGROUND_HEX,
178
  )
179
 
 
 
180
  custom_css = f"""
181
- @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
182
- @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap');
183
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
184
-
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-primary: {FLY_TEXT_COLOR_HEX};
190
- --fly-text-secondary: {FLY_SUBTLE_TEXT_HEX};
191
- --fly-bg-light: {FLY_LIGHT_BACKGROUND_HEX};
192
- --fly-bg-white: {FLY_WHITE_HEX};
193
- --fly-border-color: {FLY_BORDER_COLOR_HEX};
194
- --fly-input-bg: {FLY_INPUT_BG_HEX};
195
- --fly-panel-bg: {FLY_PANEL_BG_HEX};
196
-
197
- --font-global: 'Vazirmatn', 'Inter', 'Poppins', system-ui, sans-serif;
198
- --font-english: 'Poppins', 'Inter', system-ui, sans-serif;
199
-
200
- --radius-sm: 0.375rem; --radius-md: 0.5rem; --radius-lg: 0.75rem; --radius-xl: 1rem; --radius-full: 9999px;
201
- --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
202
- --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
203
- --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
204
- --shadow-xl: 0 20px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1);
205
- --transition-fast: all 0.15s ease-in-out;
206
- --transition-normal: all 0.25s ease-in-out;
207
- --fly-primary-rgb: 79, 70, 229; /* For Indigo #4F46E5 */
208
- --fly-accent-rgb: 245, 158, 11; /* For Amber #F59E0B */
209
  }}
210
-
211
- body {{font-family: var(--font-global); direction: rtl; background-color: var(--fly-bg-light); color: var(--fly-text-primary); line-height: 1.7; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-size: 16px;}}
212
- .gradio-container {{max-width: 100% !important; width: 100% !important; min-height: 100vh; margin: 0 auto !important; padding: 0 !important; border-radius: 0 !important; box-shadow: none !important; background: linear-gradient(170deg, #E0F2FE 0%, #F3E8FF 100%); display: flex; flex-direction: column;}}
213
-
214
- .app-title-card {{text-align: center; padding: 2.5rem 1rem; margin: 0; background: linear-gradient(135deg, var(--fly-primary) 0%, var(--fly-secondary) 100%); color: var(--fly-bg-white); border-bottom-left-radius: var(--radius-xl); border-bottom-right-radius: var(--radius-xl); box-shadow: var(--shadow-lg); position: relative; overflow: hidden;}}
215
- .app-title-card::before {{content: ''; position: absolute; top: -50px; right: -50px; width: 150px; height: 150px; background: rgba(255,255,255,0.1); border-radius: var(--radius-full); opacity: 0.5; transform: rotate(45deg);}}
216
- .app-title-card h1 {{font-size: 2.25em !important; font-weight: 800 !important; margin: 0 0 0.5rem 0; font-family: var(--font-english); letter-spacing: -0.5px; text-shadow: 0 2px 4px rgba(0,0,0,0.1);}}
217
- .app-title-card p {{font-size: 1em !important; margin-top: 0.25rem; font-weight: 400; color: rgba(255, 255, 255, 0.85) !important;}}
218
-
219
- .main-content-area-fly {{flex-grow: 1; padding: 1.5rem; max-width: 900px; width: 100%; margin: 0 auto;}}
220
- .content-panel {{background-color: var(--fly-bg-white); padding: 1.5rem; border-radius: var(--radius-xl); box-shadow: var(--shadow-xl); margin-top: -2rem; position: relative; z-index: 10; margin-bottom: 2rem;}}
221
-
222
- .gr-input > label > span.label-text, .gr-dropdown > label > span.label-text, .gr-slider > label > span.label-text {{font-weight: 600 !important; color: var(--fly-text-primary) !important; font-size: 0.9em !important; margin-bottom: 0.5rem !important; display: block;}}
223
- .gr-input > label + div > textarea, .gr-dropdown > label + div > div > input, .gr-dropdown > label + div > div > select {{border-radius: var(--radius-md) !important; border: 1px solid var(--fly-border-color) !important; font-size: 1em !important; background-color: var(--fly-input-bg) !important; padding: 0.75rem 1rem !important; line-height: 1.6; width: 100% !important; box-sizing: border-box !important; font-family: var(--font-global) !important; color: var(--fly-text-primary) !important; transition: var(--transition-normal); box-shadow: var(--shadow-sm);}}
224
- .gr-input > label + div > textarea:focus, .gr-dropdown > label + div > div > input:focus, .gr-dropdown > label + div > div > select:focus {{border-color: var(--fly-primary) !important; box-shadow: 0 0 0 3px rgba(var(--fly-primary-rgb), 0.3) !important; outline: none; transform: translateY(-1px);}}
225
- .gr-dropdown svg.icon {{right: auto !important; left: 1rem !important; color: var(--fly-subtle-text) !important;}}
226
-
227
- .output-text-container .gr-textbox[label*="ترجمه انگلیسی"] > label + div > textarea, .output-text-container .gradio-interface .output_text .gr-textbox[data-testid="textbox"] > label + div > textarea {{background-color: var(--fly-panel-bg) !important; border: 1px solid var(--fly-primary) !important; border-radius: var(--radius-md) !important; min-height: 120px; font-family: var(--font-english) !important; font-size: 1.05em !important; color: var(--fly-primary) !important; font-weight: 500; padding: 0.75rem 1rem !important; box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);}}
228
- .output-audio-container .gr-audio {{border-radius: var(--radius-md); box-shadow: var(--shadow-sm);}}
229
- .output-audio-container .gr-audio audio {{border-radius: var(--radius-md);}}
230
-
231
- .gr-accordion > button.gr-button {{font-weight: 600 !important; padding: 0.75rem 1rem !important; border-radius: var(--radius-md) !important; background-color: #EDF2F7 !important; color: var(--fly-text-primary) !important; border: 1px solid var(--fly-border-color) !important; font-size: 0.95em; margin-bottom: 0.5rem; transition: var(--transition-normal); text-align: right;}}
232
- .gr-accordion > button.gr-button:hover {{background-color: #E2E8F0 !important; border-color: var(--fly-primary) !important; color: var(--fly-primary) !important;}}
233
- .gr-accordion > div.gr-panel {{border-radius: var(--radius-md) !important; border: 1px solid var(--fly-border-color) !important; background-color: var(--fly-bg-white) !important; padding: 1.25rem !important; box-shadow: none; margin-top: -0.5rem; position: relative; z-index: 5;}}
234
- .gr-slider {{padding: 0.5rem 0 !important;}}
235
- .gr-slider input[type="range"]::-webkit-slider-thumb {{background: var(--fly-primary) !important; box-shadow: var(--shadow-sm) !important;}}
236
- .gr-slider input[type="range"]::-moz-range-thumb {{background: var(--fly-primary) !important; box-shadow: var(--shadow-sm) !important;}}
237
-
238
- .action-button-container .gr-button.gr-button-primary {{width: 100% !important; padding: 0.85rem 1.5rem !important; font-size: 1.05em !important; font-weight: 700 !important; border-radius: var(--radius-md) !important; margin-top: 1.5rem !important; letter-spacing: 0.5px; color: var(--fly-bg-white) !important; background: linear-gradient(135deg, var(--fly-accent) 0%, #F97316 100%) !important; border: none !important; box-shadow: var(--shadow-md), 0 0 15px rgba(var(--fly-accent-rgb), 0.3); transition: var(--transition-normal), transform 0.1s ease-out; cursor: pointer;}}
239
- .action-button-container .gr-button.gr-button-primary:hover {{transform: translateY(-3px) scale(1.02); box-shadow: var(--shadow-lg), 0 0 25px rgba(var(--fly-accent-rgb), 0.4);}}
240
- .action-button-container .gr-button.gr-button-primary:active {{transform: translateY(-1px) scale(0.98); box-shadow: var(--shadow-sm), 0 0 10px rgba(var(--fly-accent-rgb), 0.2);}}
241
-
242
- div#examples_section {{margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--fly-border-color);}}
243
- div#examples_section > .gr-panel {{background-color: transparent !important; border: none !important; padding: 0 !important; box-shadow: none !important;}}
244
- div#examples_section .gr-samples-header {{font-weight: 700; color: var(--fly-text-primary); font-size: 1.1em; margin-bottom: 1rem; text-align: right;}}
245
- div#examples_section .gr-sample-button, div#examples_section table tbody tr td button.gr-button-secondary {{background-color: var(--fly-input-bg) !important; color: var(--fly-primary) !important; border-radius: var(--radius-md) !important; font-size: 0.9em !important; padding: 0.5rem 1rem !important; border: 1px solid var(--fly-primary) !important; transition: var(--transition-normal); box-shadow: var(--shadow-sm); font-weight: 500;}}
246
- div#examples_section .gr-sample-button:hover, div#examples_section table tbody tr td button.gr-button-secondary:hover {{background-color: var(--fly-primary) !important; color: var(--fly-bg-white) !important; transform: translateY(-2px); box-shadow: var(--shadow-md);}}
247
-
248
- .status-message-fly {{padding: 0.75rem 1rem; margin-top: 1.5rem; border-radius: var(--radius-md); font-weight: 500; text-align: center; font-size: 0.95em; box-shadow: var(--shadow-sm);}}
249
- .status-message-fly.success {{background-color: #D1FAE5; color: #065F46; border: 1px solid #A7F3D0;}}
250
- .status-message-fly.error {{background-color: #FEE2E2; color: #991B1B; border: 1px solid #FECACA;}}
251
-
252
- .custom-hr-fly {{height: 1px; background-color: var(--fly-border-color); margin: 2rem 0; border: none;}}
253
- .api-warning-message-fly {{background-color: #FEF3C7 !important; color: #92400E !important; padding: 0.75rem 1rem !important; border-radius: var(--radius-md) !important; border: 1px solid #FDE68A !important; text-align: center !important; margin: 0 0.5rem 1.5rem 0.5rem !important; font-size: 0.9em !important; font-weight: 500; box-shadow: var(--shadow-sm);}}
254
- .app-footer-fly {{text-align:center; font-size:0.85em; color: var(--fly-text-secondary); margin-top:2.5rem; padding: 1rem 0; background-color: rgba(255,255,255,0.3); backdrop-filter: blur(5px); border-top: 1px solid var(--fly-border-color);}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  footer, .gradio-footer {{display: none !important;}}
256
 
257
- @media (min-width: 768px) {{
258
- .main-content-columns-fly {{display: flex; flex-direction: row; gap: 2rem; align-items: flex-start;}}
259
- .main-content-columns-fly > .gr-column:nth-child(1) {{flex: 3;}}
260
- .main-content-columns-fly > .gr-column:nth-child(2) {{flex: 2; position: sticky; top: 1.5rem;}}
261
- .action-button-container .gr-button.gr-button-primary {{width: auto !important; min-width: 220px; align-self: flex-end;}}
262
- .app-title-card h1 {{font-size: 2.75em !important;}}
263
- .app-title-card p {{font-size: 1.1em !important;}}
264
- .content-panel {{padding: 2rem;}}
 
 
 
 
 
 
 
265
  }}
266
  """
267
 
268
  default_english_tts_voice = 'انگلیسی (آمریکا) - جنی (زن)'
269
- if not language_dict_persian_keys :
270
- logging.warning("Language dictionary is empty!")
271
- default_english_tts_voice = None
272
- elif default_english_tts_voice not in language_dict_persian_keys:
273
  default_english_tts_voice = list(language_dict_persian_keys.keys())[0] if language_dict_persian_keys else None
274
 
275
- logging.info(f"Gradio version: {gr.__version__}")
276
-
277
- with gr.Blocks(theme=app_theme, css=custom_css, title="آموزش زبان ��لای | Fly Language Learning") as demo:
278
- gr.HTML(f"""
279
- <div class="app-title-card">
280
- <h1>🚀 Fly Language Learning</h1>
281
- <p>جادوی ترجمه و تلفظ در دستان شما</p>
282
- </div>
283
- """)
284
 
285
  with gr.Column(elem_classes=["main-content-area-fly"]):
286
  if not GOOGLE_API_KEY or not model:
287
- missing_key_msg = "⚠️ **هشدار سرویس ترجمه:** "
288
- if not GOOGLE_API_KEY: missing_key_msg += "کلید API گوگل (GOOGLE_API_KEY) تنظیم نشده است."
289
- elif not model: missing_key_msg += "خطا در بارگذاری مدل Gemini."
290
- gr.Markdown(f"<div class='api-warning-message-fly'>{missing_key_msg} بخش ترجمه غیرفعال خواهد بود. لطفاً تنظیمات Secrets را بررسی کنید.</div>")
291
-
292
- with gr.Group(elem_classes=["content-panel"]):
293
- with gr.Row(elem_classes=["main-content-columns-fly"]):
294
- with gr.Column(scale=3, elem_id="input_column"):
295
- input_text_persian = gr.Textbox(
296
- lines=5, label="📝 متن فارسی خود را بنویسید:",
297
- placeholder="مثال: جهان شگفت‌انگیز زبان‌ها را کاوش کنید...",
298
- elem_id="persian_input_textbox"
299
- )
300
- language_dropdown_tts_english = gr.Dropdown(
301
- choices=list(language_dict_persian_keys.keys()) if language_dict_persian_keys else ["لیست خالی"],
302
- value=default_english_tts_voice if default_english_tts_voice else "لیست خالی",
303
- label="🗣️ گوینده و لهجه انگلیسی:",
304
- interactive=bool(language_dict_persian_keys and default_english_tts_voice is not None)
305
- )
306
- with gr.Accordion("🎧 تنظیمات پیشرفته صدا", open=False):
307
- rate_slider = gr.Slider(minimum=-100, maximum=100, value=0, step=10, label="سرعت گفتار")
308
- volume_slider = gr.Slider(minimum=-100, maximum=100, value=0, step=10, label="بلندی صدا")
309
- pitch_slider = gr.Slider(minimum=-50, maximum=50, value=0, step=5, label="زیر و بمی صدا")
310
-
311
- with gr.Column(elem_classes=["action-button-container"]):
312
- submit_button = gr.Button("✨ ترجمه و پخش جادویی ✨", variant="primary")
313
-
314
- with gr.Column(scale=2, elem_id="output_column", elem_classes=["result-area-fly"]):
315
- with gr.Group(elem_classes=["output-text-container"]):
316
- output_text_translated = gr.Textbox(
317
- label="📜 ترجمه انگلیسی روان:", interactive=False, lines=6,
318
- placeholder="ترجمه در اینجا پدیدار خواهد شد...",
319
- elem_id="english_output_textbox"
320
- )
321
- with gr.Group(elem_classes=["output-audio-container"]):
322
- output_audio = gr.Audio(label="🎤 بشنوید:", type="filepath", format="mp3", interactive=False)
323
-
324
- status_message = gr.Markdown(visible=False, elem_classes=["status-message-fly"]) # Base class only
325
-
326
-
327
- if language_dict_persian_keys and default_english_tts_voice:
328
- gr.HTML("<hr class='custom-hr-fly'>")
329
- num_voices = len(language_dict_persian_keys)
330
- voice_keys = list(language_dict_persian_keys.keys())
331
 
332
- valid_example_list = []
333
- if num_voices > 0:
334
- voice1_idx, voice2_idx, voice3_idx, voice4_idx = 0, min(7, num_voices - 1), min(13, num_voices - 1), min(3, num_voices - 1)
335
- example_list_data = [
336
- ["قیمت این لباس چقدر است؟", voice_keys[voice1_idx], 0, 0, 0],
337
- ["می‌توانید آدرس را روی نقشه به من نشان دهید؟", voice_keys[voice2_idx], 5, 0, 0],
338
- ["ببخشید، متوجه نشدم. امکان دارد تکرار کنید؟", voice_keys[voice3_idx], -10, 10, 0],
339
- ["یک قهوه و یک کیک لطفا.", voice_keys[voice4_idx], 0, 0, 0],
340
- ]
341
- valid_example_list = example_list_data
342
- else: logging.warning("No voices available for examples.")
343
 
344
- if valid_example_list:
345
- gr.Examples(
346
- examples=valid_example_list,
347
- inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
348
- outputs=[output_text_translated, output_audio, status_message],
349
- fn=translate_and_speak_sync_wrapper, # Direct call, status will be handled by its return
350
- label="🌟 نمونه‌های الهام‌بخش (برای امتحان کلیک کنید):",
351
- elem_id="examples_section"
352
- )
353
-
354
- gr.Markdown("<p class='app-footer-fly'>ساخته شده با ❤️ و ☕ توسط تیم فلای | Fly Language Learning © ۲۰۲۴</p>")
355
 
356
- if 'submit_button' in locals() and submit_button is not None:
357
- def handle_submit_click_ui_update(persian_text, english_tts_voice_key, rate, volume, pitch):
358
- # Call the core logic function
359
- translated_text, audio_path, status_update_dict = translate_and_speak_sync_wrapper(
360
- persian_text, english_tts_voice_key, rate, volume, pitch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  )
362
-
363
- # Prepare the status message UI update based on the dictionary returned
364
- current_value = None
365
- is_visible = False
366
- status_class_list = ["status-message-fly"] # Base class
367
-
368
- if status_update_dict and isinstance(status_update_dict, dict):
369
- current_value = status_update_dict.get("value")
370
- is_visible = status_update_dict.get("visible", False) # Default to False if not specified
371
-
372
- if current_value: # Only add specific class if there's a message
373
- if "موفقیت" in current_value or "✅" in current_value:
374
- status_class_list.append("success")
375
- elif "خطا" in current_value or "⚠️" in current_value or "🚫" in current_value:
376
- status_class_list.append("error")
377
-
378
- updated_status_message_ui = gr.update(value=current_value,
379
- visible=is_visible,
380
- elem_classes=status_class_list)
381
-
382
- return translated_text, audio_path, updated_status_message_ui
383
 
384
- submit_button.click(
385
- fn=handle_submit_click_ui_update,
386
- inputs=[input_text_persian, language_dropdown_tts_english, rate_slider, volume_slider, pitch_slider],
387
- outputs=[output_text_translated, output_audio, status_message]
388
- )
389
- else:
390
- logging.error("Submit button was not initialized correctly or is None.")
391
 
392
  if __name__ == "__main__":
393
- if not language_dict_persian_keys:
394
- logging.critical("CRITICAL: Voice dictionary (language_dict_persian_keys) is empty!")
395
- elif not default_english_tts_voice:
396
- logging.warning("WARNING: No default English TTS voice could be set.")
397
-
398
- demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=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
+ # 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,
159
+ secondary_hue=gr.themes.colors.emerald,
160
+ neutral_hue=gr.themes.colors.slate,
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}; --fly-secondary: {FLY_SECONDARY_COLOR_HEX};
174
+ --fly-accent: {FLY_ACCENT_COLOR_HEX}; --fly-text: {FLY_TEXT_COLOR_HEX};
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,
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: logging.critical("دیکشنری صداها خالی است!")
336
+ demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)