Update app.py
Browse files
app.py
CHANGED
|
@@ -7,36 +7,32 @@ import io
|
|
| 7 |
from scipy.io.wavfile import write as write_wav
|
| 8 |
import numpy as np
|
| 9 |
import traceback
|
|
|
|
| 10 |
|
| 11 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 12 |
if not GOOGLE_API_KEY:
|
| 13 |
raise ValueError("GOOGLE_API_KEY not found in environment variables.")
|
| 14 |
genai.configure(api_key=GOOGLE_API_KEY)
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
| 17 |
AVAILABLE_VOICES = ["پیشفرض (مدل انتخاب کند)"]
|
| 18 |
|
| 19 |
def generate_audio(text_to_speak, selected_voice_name="پیشفرض (مدل انتخاب کند)"):
|
| 20 |
if not text_to_speak:
|
| 21 |
raise gr.Error("لطفاً متنی را برای تبدیل به صدا وارد کنید.")
|
| 22 |
-
print(f"درخواست TTS برای متن: '{text_to_speak[:50]}...' با گوینده: {selected_voice_name}")
|
| 23 |
|
| 24 |
try:
|
| 25 |
-
# اطمینان از اینکه نام مدل با پیشوند models/ ارسال میشود، همانطور که پیام خطای قبلی نشان داد
|
| 26 |
model = genai.GenerativeModel(f"models/{TTS_MODEL_NAME}")
|
| 27 |
|
| 28 |
-
|
| 29 |
-
# مدل TTS باید به طور خودکار بداند که خروجی صوتی تولید کند.
|
| 30 |
-
# اگر نیاز به تنظیمات خاصی برای voice یا کیفیت باشد، باید در اینجا اضافه شود.
|
| 31 |
-
generation_config_params = {}
|
| 32 |
|
| 33 |
-
# برای انتخاب گوینده، این بخش نیاز به اطلاعات از مستندات دارد
|
| 34 |
if selected_voice_name != "پیشفرض (مدل انتخاب کند)":
|
| 35 |
-
# مثال: generation_config_params["voice"] = selected_voice_name
|
| 36 |
-
# یا ساختار دقیقتری اگر مستندات مشخص کند.
|
| 37 |
print(f"توجه: انتخاب گوینده ('{selected_voice_name}') هنوز به طور کامل پیادهسازی نشده است.")
|
| 38 |
|
| 39 |
-
# فقط اگر generation_config_params خالی نیست، آن را بسازید
|
| 40 |
generation_config_to_pass = None
|
| 41 |
if generation_config_params:
|
| 42 |
generation_config_to_pass = genai.types.GenerationConfig(**generation_config_params)
|
|
@@ -44,14 +40,11 @@ def generate_audio(text_to_speak, selected_voice_name="پیشفرض (مدل
|
|
| 44 |
else:
|
| 45 |
print("ارسال درخواست به Gemini بدون generation_config خاص (با تنظیمات پیشفرض مدل).")
|
| 46 |
|
| 47 |
-
|
| 48 |
response = model.generate_content(
|
| 49 |
text_to_speak,
|
| 50 |
-
generation_config=generation_config_to_pass
|
| 51 |
)
|
| 52 |
-
# --- پایان تغییرات ---
|
| 53 |
|
| 54 |
-
# ... (بقیه کد پردازش پاسخ و ذخیره فایل صوتی بدون تغییر نسبت به نسخه قبلی که تورفتگیاش درست بود) ...
|
| 55 |
audio_bytes = None
|
| 56 |
generated_mime_type = None
|
| 57 |
sample_rate = 24000
|
|
@@ -108,35 +101,30 @@ def generate_audio(text_to_speak, selected_voice_name="پیشفرض (مدل
|
|
| 108 |
print(f"خطای کلی در تولید صدا: {e}")
|
| 109 |
traceback.print_exc()
|
| 110 |
error_message_from_api = ""
|
|
|
|
| 111 |
if hasattr(e, 'args') and e.args:
|
| 112 |
-
if isinstance(e.args[0], str) and "HttpError" in e.args[0]:
|
| 113 |
-
error_message_from_api = str(e.args[0])
|
| 114 |
-
# تلاش برای استخراج جزئیات بیشتر اگر JSON است
|
| 115 |
try:
|
| 116 |
details_start = error_message_from_api.find('{')
|
| 117 |
if details_start != -1:
|
| 118 |
json_str_candidate = error_message_from_api[details_start:]
|
| 119 |
-
# تمیز کردن رشته JSON از کاراکترهای کنترلی ناخواسته
|
| 120 |
-
import json
|
| 121 |
cleaned_json_str = ''.join(c for c in json_str_candidate if ord(c) >= 32 or c in ('\t','\r','\n')).strip()
|
| 122 |
error_obj = json.loads(cleaned_json_str)
|
| 123 |
if 'error' in error_obj and 'message' in error_obj['error']:
|
| 124 |
error_message_from_api = error_obj['error']['message']
|
| 125 |
-
elif 'message' in error_obj :
|
| 126 |
error_message_from_api = error_obj['message']
|
| 127 |
-
|
| 128 |
except Exception as json_e:
|
| 129 |
print(f"خطا در parse کردن جزئیات JSON از پیام خطای API: {json_e}")
|
| 130 |
else:
|
| 131 |
error_message_from_api = str(e.args[0])
|
| 132 |
-
elif hasattr(e, 'message') and isinstance(e.message, str):
|
| 133 |
error_message_from_api = e.message
|
| 134 |
|
| 135 |
-
|
| 136 |
final_error_message = f"خطا در ارتباط با Gemini API یا پردازش صدا: {str(e)}"
|
| 137 |
if error_message_from_api and error_message_from_api not in final_error_message :
|
| 138 |
final_error_message += f" | پیام دقیقتر API: {error_message_from_api}"
|
| 139 |
-
|
| 140 |
raise gr.Error(final_error_message)
|
| 141 |
|
| 142 |
|
|
@@ -144,14 +132,12 @@ def generate_audio(text_to_speak, selected_voice_name="پیشفرض (مدل
|
|
| 144 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 145 |
gr.Markdown("# تبدیل متن به صدا با Gemini ♊")
|
| 146 |
gr.Markdown("متن خود را وارد کنید تا با استفاده از مدلهای جدید Gemini به صدا تبدیل شود.")
|
| 147 |
-
|
| 148 |
with gr.Row():
|
| 149 |
with gr.Column(scale=2):
|
| 150 |
text_input = gr.Textbox(lines=5, label="متن ورودی", placeholder="متن خود را اینجا بنویسید...")
|
| 151 |
submit_button = gr.Button("🔊 تبدیل به صدا", variant="primary")
|
| 152 |
with gr.Column(scale=1):
|
| 153 |
audio_output = gr.Audio(label="خروجی صدا", type="filepath")
|
| 154 |
-
|
| 155 |
gr.Examples(
|
| 156 |
examples=[
|
| 157 |
["سلام، حال شما چطور است؟"],
|
|
@@ -160,16 +146,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 160 |
],
|
| 161 |
inputs=[text_input]
|
| 162 |
)
|
| 163 |
-
|
| 164 |
submit_button.click(
|
| 165 |
fn=generate_audio,
|
| 166 |
inputs=[text_input],
|
| 167 |
outputs=[audio_output],
|
| 168 |
api_name="text_to_speech"
|
| 169 |
)
|
| 170 |
-
|
| 171 |
gr.Markdown("---")
|
| 172 |
-
gr.Markdown(f"مدل مورد استفاده: `models/{TTS_MODEL_NAME}`")
|
| 173 |
gr.Markdown("توجه: برای انتخاب گویندههای مختلف، نیاز به بررسی مستندات دقیق مدل TTS و بروزرسانی کد است.")
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|
|
|
|
| 7 |
from scipy.io.wavfile import write as write_wav
|
| 8 |
import numpy as np
|
| 9 |
import traceback
|
| 10 |
+
import json # برای parse کردن خطای JSON احتمالی
|
| 11 |
|
| 12 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 13 |
if not GOOGLE_API_KEY:
|
| 14 |
raise ValueError("GOOGLE_API_KEY not found in environment variables.")
|
| 15 |
genai.configure(api_key=GOOGLE_API_KEY)
|
| 16 |
|
| 17 |
+
# --- تغییر نام مدل به نسخه Pro TTS ---
|
| 18 |
+
TTS_MODEL_NAME = "gemini-2.5-pro-preview-tts"
|
| 19 |
+
# --- پایان تغییر ---
|
| 20 |
+
|
| 21 |
AVAILABLE_VOICES = ["پیشفرض (مدل انتخاب کند)"]
|
| 22 |
|
| 23 |
def generate_audio(text_to_speak, selected_voice_name="پیشفرض (مدل انتخاب کند)"):
|
| 24 |
if not text_to_speak:
|
| 25 |
raise gr.Error("لطفاً متنی را برای تبدیل به صدا وارد کنید.")
|
| 26 |
+
print(f"درخواست TTS برای متن: '{text_to_speak[:50]}...' با گوینده: {selected_voice_name} و مدل: models/{TTS_MODEL_NAME}")
|
| 27 |
|
| 28 |
try:
|
|
|
|
| 29 |
model = genai.GenerativeModel(f"models/{TTS_MODEL_NAME}")
|
| 30 |
|
| 31 |
+
generation_config_params = {} # فعلاً بدون پارامتر خاص برای generation_config
|
|
|
|
|
|
|
|
|
|
| 32 |
|
|
|
|
| 33 |
if selected_voice_name != "پیشفرض (مدل انتخاب کند)":
|
|
|
|
|
|
|
| 34 |
print(f"توجه: انتخاب گوینده ('{selected_voice_name}') هنوز به طور کامل پیادهسازی نشده است.")
|
| 35 |
|
|
|
|
| 36 |
generation_config_to_pass = None
|
| 37 |
if generation_config_params:
|
| 38 |
generation_config_to_pass = genai.types.GenerationConfig(**generation_config_params)
|
|
|
|
| 40 |
else:
|
| 41 |
print("ارسال درخواست به Gemini بدون generation_config خاص (با تنظیمات پیشفرض مدل).")
|
| 42 |
|
|
|
|
| 43 |
response = model.generate_content(
|
| 44 |
text_to_speak,
|
| 45 |
+
generation_config=generation_config_to_pass
|
| 46 |
)
|
|
|
|
| 47 |
|
|
|
|
| 48 |
audio_bytes = None
|
| 49 |
generated_mime_type = None
|
| 50 |
sample_rate = 24000
|
|
|
|
| 101 |
print(f"خطای کلی در تولید صدا: {e}")
|
| 102 |
traceback.print_exc()
|
| 103 |
error_message_from_api = ""
|
| 104 |
+
# ... (بقیه کد مدیریت خطا که قبلاً داشتیم) ...
|
| 105 |
if hasattr(e, 'args') and e.args:
|
| 106 |
+
if isinstance(e.args[0], str) and "HttpError" in e.args[0]:
|
| 107 |
+
error_message_from_api = str(e.args[0])
|
|
|
|
| 108 |
try:
|
| 109 |
details_start = error_message_from_api.find('{')
|
| 110 |
if details_start != -1:
|
| 111 |
json_str_candidate = error_message_from_api[details_start:]
|
|
|
|
|
|
|
| 112 |
cleaned_json_str = ''.join(c for c in json_str_candidate if ord(c) >= 32 or c in ('\t','\r','\n')).strip()
|
| 113 |
error_obj = json.loads(cleaned_json_str)
|
| 114 |
if 'error' in error_obj and 'message' in error_obj['error']:
|
| 115 |
error_message_from_api = error_obj['error']['message']
|
| 116 |
+
elif 'message' in error_obj :
|
| 117 |
error_message_from_api = error_obj['message']
|
|
|
|
| 118 |
except Exception as json_e:
|
| 119 |
print(f"خطا در parse کردن جزئیات JSON از پیام خطای API: {json_e}")
|
| 120 |
else:
|
| 121 |
error_message_from_api = str(e.args[0])
|
| 122 |
+
elif hasattr(e, 'message') and isinstance(e.message, str):
|
| 123 |
error_message_from_api = e.message
|
| 124 |
|
|
|
|
| 125 |
final_error_message = f"خطا در ارتباط با Gemini API یا پردازش صدا: {str(e)}"
|
| 126 |
if error_message_from_api and error_message_from_api not in final_error_message :
|
| 127 |
final_error_message += f" | پیام دقیقتر API: {error_message_from_api}"
|
|
|
|
| 128 |
raise gr.Error(final_error_message)
|
| 129 |
|
| 130 |
|
|
|
|
| 132 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 133 |
gr.Markdown("# تبدیل متن به صدا با Gemini ♊")
|
| 134 |
gr.Markdown("متن خود را وارد کنید تا با استفاده از مدلهای جدید Gemini به صدا تبدیل شود.")
|
|
|
|
| 135 |
with gr.Row():
|
| 136 |
with gr.Column(scale=2):
|
| 137 |
text_input = gr.Textbox(lines=5, label="متن ورودی", placeholder="متن خود را اینجا بنویسید...")
|
| 138 |
submit_button = gr.Button("🔊 تبدیل به صدا", variant="primary")
|
| 139 |
with gr.Column(scale=1):
|
| 140 |
audio_output = gr.Audio(label="خروجی صدا", type="filepath")
|
|
|
|
| 141 |
gr.Examples(
|
| 142 |
examples=[
|
| 143 |
["سلام، حال شما چطور است؟"],
|
|
|
|
| 146 |
],
|
| 147 |
inputs=[text_input]
|
| 148 |
)
|
|
|
|
| 149 |
submit_button.click(
|
| 150 |
fn=generate_audio,
|
| 151 |
inputs=[text_input],
|
| 152 |
outputs=[audio_output],
|
| 153 |
api_name="text_to_speech"
|
| 154 |
)
|
|
|
|
| 155 |
gr.Markdown("---")
|
| 156 |
+
gr.Markdown(f"مدل مورد استفاده: `models/{TTS_MODEL_NAME}`") # نام مدل به روز شده را نمایش میدهد
|
| 157 |
gr.Markdown("توجه: برای انتخاب گویندههای مختلف، نیاز به بررسی مستندات دقیق مدل TTS و بروزرسانی کد است.")
|
| 158 |
|
| 159 |
if __name__ == "__main__":
|