לא מצליח להשמיעה קבצים
-
אני רציתי שישירות אחרי שאוה מבי את התשובה יבא את התשובה לממיר טקסט לקול שלGENIMI ואז ישמיעה את הקובץ למשתמש וזה לא משמיעה את הקובץ זה מעביר להודעה TTS רגילה של ימות בלי האמרה
import requests from flask import Flask, request, Response import warnings import re from google import genai from google.genai import types import wave import io # הקוד הזה מסתיר את אזהרות ה-SSL הלא קריטיות שהופיעו קודם from requests.packages.urllib3.exceptions import InsecureRequestWarning warnings.simplefilter('ignore', InsecureRequestWarning) app = Flask(__name__) # פונקציה לשמירת האודיו לקובץ במדיום זיכרון במקום לשמור כקובץ def wave_file_in_memory(pcm, channels=1, rate=24000, sample_width=2): buf = io.BytesIO() with wave.open(buf, "wb") as wf: wf.setnchannels(channels) wf.setsampwidth(sample_width) wf.setframerate(rate) wf.writeframes(pcm) buf.seek(0) return buf @app.route('/app.py', methods=['GET']) def handle_gemini_request(): print(">>> Request received! Processing with Gemini...") txt = request.args.get('txt') if not txt or len(txt.strip()) < 2: return "read=t-אנא הקלד שאלה ברורה ומלאה.=txt,,,,,HebrewKeyboard," # ==================== המפתח שלך ==================== api_key = "AIzaSyB6AxGaSia5qH43lOp2v268mMWEpwKRDqA" # ================================================== # שימוש בשם מודל מהדור החדש, לפי התיעוד model = "gemini-2.0-flash" api_url = f"https://generativelanguage.googleapis.com/v1/models/{model}:generateContent?key={api_key}" headers = {'Content-Type': 'application/json'} data = { 'contents': [{ 'parts': [{'text': txt}] }] } try: response = requests.post(api_url, json=data, headers=headers, verify=False, timeout=20) print(f">>> Raw response status code: {response.status_code}") print(f">>> Raw response text: {response.text}") response.raise_for_status() response_json = response.json() if 'candidates' not in response_json or not response_json['candidates']: print("!!! Gemini response is missing 'candidates'. Possibly blocked by safety filters.") return "read=t-השאלה שלך נחסמה או שלא התקבלה תשובה ברורה. נסה לשאול אחרת.=txt,,,,,HebrewKeyboard," generated_text = response_json['candidates'][0]['content']['parts'][0]['text'] print(f">>> Gemini Response: {generated_text}") except requests.exceptions.Timeout: print("!!! Request to Google API timed out!") return "read=t-לשרת לוקח יותר מדי זמן לענות. נסה שוב מאוחר יותר.=txt,,,,,HebrewKeyboard," except requests.exceptions.HTTPError as e: print("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print(">>> GOOGLE API RETURNED AN HTTP ERROR!") print(f">>> Status Code: {e.response.status_code}") print(f">>> Response Body: {e.response.text}") print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n") return "read=t-שגיאה בתקשורת עם הבינה המלאכותית. ייתכן ששם המודל אינו נכון.=txt,,,,,HebrewKeyboard," except Exception as e: print(f"!!! An unexpected error occurred: {e}") return "read=t-אירעה שגיאה לא צפויה.=txt,,,,,HebrewKeyboard," # ---- עיבוד התשובה וחיתוך למקטעים ---- generated_text = re.sub(r'[^A-Za-z0-9א-ת ]', '', generated_text) # הסרת סימנים מיוחדים כמו ** # המרת טקסט לדיבור באמצעות Gemini API (TTS) client = genai.Client() response = client.models.generate_content( model="gemini-2.5-flash-preview-tts", # או המודל הרלוונטי לך contents=generated_text, config=types.GenerateContentConfig( response_modalities=["AUDIO"], speech_config=types.SpeechConfig( voice_config=types.VoiceConfig( prebuilt_voice_config=types.PrebuiltVoiceConfig( voice_name='Kore', # בחירת הקול מתוך המובנים ) ) ) ) ) data = response.candidates[0].content.parts[0].inline_data.data # שמירת האודיו במדיום זיכרון buf = wave_file_in_memory(data) # החזרת האודיו ישירות כתגובה ב-HTTP return Response(buf, mimetype='audio/wav') if __name__ == '__main__': app.run(host='0.0.0.0', port=5001, debug=True)
הקוד שעובד בלא המרה לאודיו את התשובה
import requests from flask import Flask, request import warnings import re # הקוד הזה מסתיר את אזהרות ה-SSL הלא קריטיות שהופיעו קודם from requests.packages.urllib3.exceptions import InsecureRequestWarning warnings.simplefilter('ignore', InsecureRequestWarning) app = Flask(__name__) @app.route('/app.py', methods=['GET']) def handle_gemini_request(): print(">>> Request received! Processing with Gemini...") txt = request.args.get('txt') if not txt or len(txt.strip()) < 2: return "read=t-אנא הקלד שאלה ברורה ומלאה.=txt,,,,,HebrewKeyboard," api_key = "AIzaSyB6AxGaSia5qH43lOp2v268mMWEpwKRDqA" model = "gemini-2.0-flash" api_url = f"https://generativelanguage.googleapis.com/v1/models/{model}:generateContent?key={api_key}" headers = {'Content-Type': 'application/json'} data = { 'contents': [{ 'parts': [{'text': txt}] }] } try: response = requests.post(api_url, json=data, headers=headers, verify=False, timeout=20) print(f">>> Raw response status code: {response.status_code}") print(f">>> Raw response text: {response.text}") response.raise_for_status() response_json = response.json() if 'candidates' not in response_json or not response_json['candidates']: print("!!! Gemini response is missing 'candidates'. Possibly blocked by safety filters.") return "read=t-השאלה שלך נחסמה או שלא התקבלה תשובה ברורה. נסה לשאול אחרת.=txt,,,,,HebrewKeyboard," generated_text = response_json['candidates'][0]['content']['parts'][0]['text'] print(f">>> Gemini Response: {generated_text}") except requests.exceptions.Timeout: print("!!! Request to Google API timed out!") return "read=t-לשרת לוקח יותר מדי זמן לענות. נסה שוב מאוחר יותר.=txt,,,,,HebrewKeyboard," except requests.exceptions.HTTPError as e: print("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print(">>> GOOGLE API RETURNED AN HTTP ERROR!") print(f">>> Status Code: {e.response.status_code}") print(f">>> Response Body: {e.response.text}") print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n") return "read=t-שגיאה בתקשורת עם הבינה המלאכותית. ייתכן ששם המודל אינו נכון.=txt,,,,,HebrewKeyboard," except Exception as e: print(f"!!! An unexpected error occurred: {e}") return "read=t-אירעה שגיאה לא צפויה.=txt,,,,,HebrewKeyboard," # ---- עיבוד התשובה וחיתוך למקטעים ---- # הסרת סימנים מיוחדים מהתשובה כמו ** וכו' generated_text = re.sub(r'[^A-Za-z0-9א-ת ]', '', generated_text) # מסיר כל תו שלא אות או מספר # חילוק למילים והוספת פסיק אחרי כל 10 מילים words = generated_text.split() chunks = [] for i in range(0, len(words), 10): # כל 10 מילים chunk = ' '.join(words[i:i+10]) chunks.append(chunk + ',') # הוספת פסיק בסוף כל 10 מילים # מחבר את כל הקטעים חזרה לשורה אחת result = ' '.join(chunks) return f"id_list_message=t-{result}" if __name__ == '__main__': app.run(host='0.0.0.0', port=5001, debug=True)
-
@טנטפון אני לא יודע אולי מישהו אחר ידע
-
@טנטפון
הכנסת בשלוחה את הלינק בתוספת/app.py
?
לדוגמא:api_link=https://example.com/YemotApi/app.py
חוץ מזה כדאי שתבדוק מה השרת כן מחזיר בתגובה - לפעמים זה טקסט בעייתי וכדו'
תבדוק בלוגים בשרת מה חוזר והאם הבקשה מתקבלת. -
@y6714453 כתב באין מענה משרת API:
@טנטפון
הכנסת בשלוחה את הלינק בתוספת/app.py
?
לדוגמא:api_link=https://example.com/YemotApi/app.py
חוץ מזה כדאי שתבדוק מה השרת כן מחזיר בתגובה - לפעמים זה טקסט בעייתי וכדו'
תבדוק בלוגים בשרת מה חוזר והאם הבקשה מתקבלת.כן והשרת מחזיר תשובה רק המערכת לא מקריאה אותו
-
@יעקב-קליין ככל הנראה טקסט בעייתי
תעלה את התשובה / הטקסט שהשרת מחזיר -
@y6714453 כתב באין מענה משרת API:
ן ככל הנראה טקסט בעייתי
תעלה את התשובה / הטקסט שהשרת מחזירהטקסט אינו בעיתי בדוק הבעיה כרגע לא ברורה אבל בדוק שזה לא הטקסט הבעיתי: זה הטקסט(אחד מהטקסטים)לסיכום, " היא חצר חסידית קנאית, המדגישה יראת שמיים עמוקה, סגפנות, עבודת ה' פנימית וטהורה, והתרחקות מכל השפעה חיצונית, על פי דרכו של האדמו"ר רבי" זצ"ל
-
@יעקב-קליין
אתה רוצה שהמערכת תקריא את התשובה עם המנוע הקראה של ימות?
הגדרת בשלוחה?say_api_answer=yes
-
@y6714453 כתב באין מענה משרת API:
אתה רוצה שהמערכת תקריא את התשובה עם המנוע הקראה של ימות?
הגדרת בשלוחה?
say_api_answer=yesלא צריך, כיון שהוא כתב בקוד id_list_message=t-
-
@פלמנמוני בסדר הסתדתי תודה
-
@טנטפון תשתף אותנו איך
-
@פלמנמוני אנה הקוד אבל יש לי בעיה קטנה אני רציתי שישירות אחרי שאוה מבי את התשובה יבא את התשובה לממיר טקסט לקול שלהם ואז ישמיעה את הקובץ למשתמש וזה לא משמיעה את הקובץ
import requests from flask import Flask, request, Response import warnings import re from google import genai from google.genai import types import wave import io # הקוד הזה מסתיר את אזהרות ה-SSL הלא קריטיות שהופיעו קודם from requests.packages.urllib3.exceptions import InsecureRequestWarning warnings.simplefilter('ignore', InsecureRequestWarning) app = Flask(__name__) # פונקציה לשמירת האודיו לקובץ במדיום זיכרון במקום לשמור כקובץ def wave_file_in_memory(pcm, channels=1, rate=24000, sample_width=2): buf = io.BytesIO() with wave.open(buf, "wb") as wf: wf.setnchannels(channels) wf.setsampwidth(sample_width) wf.setframerate(rate) wf.writeframes(pcm) buf.seek(0) return buf @app.route('/app.py', methods=['GET']) def handle_gemini_request(): print(">>> Request received! Processing with Gemini...") txt = request.args.get('txt') if not txt or len(txt.strip()) < 2: return "read=t-אנא הקלד שאלה ברורה ומלאה.=txt,,,,,HebrewKeyboard," # ==================== המפתח שלך ==================== api_key = "AIzaSyB6AxGaSia5qH43lOp2v268mMWEpwKRDqA" # ================================================== # שימוש בשם מודל מהדור החדש, לפי התיעוד model = "gemini-2.0-flash" api_url = f"https://generativelanguage.googleapis.com/v1/models/{model}:generateContent?key={api_key}" headers = {'Content-Type': 'application/json'} data = { 'contents': [{ 'parts': [{'text': txt}] }] } try: response = requests.post(api_url, json=data, headers=headers, verify=False, timeout=20) print(f">>> Raw response status code: {response.status_code}") print(f">>> Raw response text: {response.text}") response.raise_for_status() response_json = response.json() if 'candidates' not in response_json or not response_json['candidates']: print("!!! Gemini response is missing 'candidates'. Possibly blocked by safety filters.") return "read=t-השאלה שלך נחסמה או שלא התקבלה תשובה ברורה. נסה לשאול אחרת.=txt,,,,,HebrewKeyboard," generated_text = response_json['candidates'][0]['content']['parts'][0]['text'] print(f">>> Gemini Response: {generated_text}") except requests.exceptions.Timeout: print("!!! Request to Google API timed out!") return "read=t-לשרת לוקח יותר מדי זמן לענות. נסה שוב מאוחר יותר.=txt,,,,,HebrewKeyboard," except requests.exceptions.HTTPError as e: print("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print(">>> GOOGLE API RETURNED AN HTTP ERROR!") print(f">>> Status Code: {e.response.status_code}") print(f">>> Response Body: {e.response.text}") print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n") return "read=t-שגיאה בתקשורת עם הבינה המלאכותית. ייתכן ששם המודל אינו נכון.=txt,,,,,HebrewKeyboard," except Exception as e: print(f"!!! An unexpected error occurred: {e}") return "read=t-אירעה שגיאה לא צפויה.=txt,,,,,HebrewKeyboard," # ---- עיבוד התשובה וחיתוך למקטעים ---- generated_text = re.sub(r'[^A-Za-z0-9א-ת ]', '', generated_text) # הסרת סימנים מיוחדים כמו ** # המרת טקסט לדיבור באמצעות Gemini API (TTS) client = genai.Client() response = client.models.generate_content( model="gemini-2.5-flash-preview-tts", # או המודל הרלוונטי לך contents=generated_text, config=types.GenerateContentConfig( response_modalities=["AUDIO"], speech_config=types.SpeechConfig( voice_config=types.VoiceConfig( prebuilt_voice_config=types.PrebuiltVoiceConfig( voice_name='Kore', # בחירת הקול מתוך המובנים ) ) ) ) ) data = response.candidates[0].content.parts[0].inline_data.data # שמירת האודיו במדיום זיכרון buf = wave_file_in_memory(data) # החזרת האודיו ישירות כתגובה ב-HTTP return Response(buf, mimetype='audio/wav') if __name__ == '__main__': app.run(host='0.0.0.0', port=5001, debug=True)
הקוד שעובד בלא המרה לאודיו את התשובה
import requests from flask import Flask, request import warnings import re # הקוד הזה מסתיר את אזהרות ה-SSL הלא קריטיות שהופיעו קודם from requests.packages.urllib3.exceptions import InsecureRequestWarning warnings.simplefilter('ignore', InsecureRequestWarning) app = Flask(__name__) @app.route('/app.py', methods=['GET']) def handle_gemini_request(): print(">>> Request received! Processing with Gemini...") txt = request.args.get('txt') if not txt or len(txt.strip()) < 2: return "read=t-אנא הקלד שאלה ברורה ומלאה.=txt,,,,,HebrewKeyboard," api_key = "AIzaSyB6AxGaSia5qH43lOp2v268mMWEpwKRDqA" model = "gemini-2.0-flash" api_url = f"https://generativelanguage.googleapis.com/v1/models/{model}:generateContent?key={api_key}" headers = {'Content-Type': 'application/json'} data = { 'contents': [{ 'parts': [{'text': txt}] }] } try: response = requests.post(api_url, json=data, headers=headers, verify=False, timeout=20) print(f">>> Raw response status code: {response.status_code}") print(f">>> Raw response text: {response.text}") response.raise_for_status() response_json = response.json() if 'candidates' not in response_json or not response_json['candidates']: print("!!! Gemini response is missing 'candidates'. Possibly blocked by safety filters.") return "read=t-השאלה שלך נחסמה או שלא התקבלה תשובה ברורה. נסה לשאול אחרת.=txt,,,,,HebrewKeyboard," generated_text = response_json['candidates'][0]['content']['parts'][0]['text'] print(f">>> Gemini Response: {generated_text}") except requests.exceptions.Timeout: print("!!! Request to Google API timed out!") return "read=t-לשרת לוקח יותר מדי זמן לענות. נסה שוב מאוחר יותר.=txt,,,,,HebrewKeyboard," except requests.exceptions.HTTPError as e: print("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print(">>> GOOGLE API RETURNED AN HTTP ERROR!") print(f">>> Status Code: {e.response.status_code}") print(f">>> Response Body: {e.response.text}") print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n") return "read=t-שגיאה בתקשורת עם הבינה המלאכותית. ייתכן ששם המודל אינו נכון.=txt,,,,,HebrewKeyboard," except Exception as e: print(f"!!! An unexpected error occurred: {e}") return "read=t-אירעה שגיאה לא צפויה.=txt,,,,,HebrewKeyboard," # ---- עיבוד התשובה וחיתוך למקטעים ---- # הסרת סימנים מיוחדים מהתשובה כמו ** וכו' generated_text = re.sub(r'[^A-Za-z0-9א-ת ]', '', generated_text) # מסיר כל תו שלא אות או מספר # חילוק למילים והוספת פסיק אחרי כל 10 מילים words = generated_text.split() chunks = [] for i in range(0, len(words), 10): # כל 10 מילים chunk = ' '.join(words[i:i+10]) chunks.append(chunk + ',') # הוספת פסיק בסוף כל 10 מילים # מחבר את כל הקטעים חזרה לשורה אחת result = ' '.join(chunks) return f"id_list_message=t-{result}" if __name__ == '__main__': app.run(host='0.0.0.0', port=5001, debug=True)