Spaces:
Runtime error
Runtime error
Update app.py
Browse files4 unmodified lines56789101112131418 unmodified lines3334353637383940414243444546474849505152535455565758596061626364659 unmodified lines757677787980818283848586877 unmodified lines95969798991001011021031041051061071081091101111122 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871884 unmodified linesimport tempfile# -------------------- API Configuration --------------------# Set your API keys as environment variables in Hugging Face Spaces settings# GROQ_API_KEY = "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"# os.environ["GOOGLE_API_KEY"] = "AIzaSyD2DMFgcL0kWTQYhii8wseSHY3BRGWSebk"# Initialize clientsclient = Groq(api_key="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")llm = ChatGoogleGenerativeAI(18 unmodified linesreturn f"Error in transcription: {str(e)}", Nonedef get_ai_response(text, detected_language="ar"):"""Get AI response from Gemini with language-aware system prompt"""try:# Create system prompt based on detected languageif detected_language == "ar":system_prompt = """أنت مساعد ذكي ومفيد. يجب عليك الرد باللغة العربية واستخدام نفس اللهجة التي يستخدمها المستخدم.قواعد مهمة:- إذا تحدث المستخدم بالعربية الفصحى، رد بالفصحى- إذا تحدث المستخدم بلهجة عامية (مصرية، خليجية، شامية، مغاربية، إلخ)، رد بنفس اللهجة- حافظ على نفس الأسلوب والنبرة التي يستخدمها المستخدم- كن طبيعياً ومحادثاً ومفيداً- إذا لم تتأكد من اللهجة، استخدم العربية الفصحى المبسطةالرد يجب أن يكون مختصراً ومفيداً وواضحاً."""else:system_prompt = """You are a helpful and intelligent assistant. You must respond in the EXACT same language, dialect, and style that the user uses.Important rules:- Match the user's language exactly (English, Spanish, French, etc.)- Match their dialect or regional variation (American English, British English, etc.)- Match their tone and formality level (casual, formal, slang, etc.)- Be natural, conversational, and helpful- Keep responses concise and clearRespond in the same language as the user's input."""# Create messages with system promptfrom langchain_core.messages import HumanMessage, SystemMessagemessages = [9 unmodified linesdef text_to_speech(text, language="ar"):"""Convert text to speech using Groq TTS"""try:# Select voice based on languageif language == "ar":voice = "Amira-PlayAI"model = "playai-tts-arabic"else:voice = "alloy" # Default English voicemodel = "playai-tts"response = client.audio.speech.create(model=model,7 unmodified linesresponse.write_to_file(temp_file.name)return temp_file.nameexcept Exception as e:return None# -------------------- Gradio Interface Function --------------------def process_voice_chat(audio, language_choice):"""Main function to process voice input and generate response"""if audio is None:return "Please provide an audio input", "", None# Map language choice to codelang_map = {"Arabic": "ar", "English": "en"}lang_code = lang_map.get(language_choice, "ar")# Step 1: Transcribe audiotranscription, detected_lang = transcribe_audio(audio, lang_code)2 unmodified linesreturn transcription, "", None# Step 2: Get AI responseai_response = get_ai_response(transcription)if ai_response.startswith("Error"):return transcription, ai_response, None# Step 3: Convert response to speech# Use detected language if available, otherwise use selected languageoutput_lang = detected_lang if detected_lang else lang_codeaudio_output = text_to_speech(ai_response, output_lang)return transcription, ai_response, audio_output# -------------------- Gradio Interface --------------------with gr.Blocks(title="Voice Chat Assistant", theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🎤 Voice Chat AssistantUpload an audio file or record your voice to chat with AI.The AI will respond in the same language!""")with gr.Row():with gr.Column():language = gr.Radio(choices=["Arabic", "English"],value="Arabic",label="Select Language")audio_input = gr.Audio(sources=["microphone", "upload"],type="filepath",label="Record or Upload Audio")submit_btn = gr.Button("Process", variant="primary", size="lg")with gr.Column():transcription_output = gr.Textbox(label="Your Message (Transcription)",lines=3)ai_response_output = gr.Textbox(label="AI Response",lines=5)audio_output = gr.Audio(label="AI Voice Response",type="filepath")# Button actionsubmit_btn.click(fn=process_voice_chat,inputs=[audio_input, language],outputs=[transcription_output, ai_response_output, audio_output])gr.Markdown("""### 📝 Instructions:1. Select your language (Arabic or English)2. Record your voice using the microphone or upload an audio file3. Click "Process" to get AI response with voice output### 🔑 Setup for Hugging Face Spaces:Add these secrets in your Space settings:- `GROQ_API_KEY`: Your Groq API key- `GOOGLE_API_KEY`: Your Google API key""")4 unmodified lines567891018 unmodified lines29303132333435363738394041424344459 unmodified lines5556575859606162637 unmodified lines717273747576777879808182838485868788892 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621634 unmodified linesimport tempfile# -------------------- API Configuration --------------------# Initialize clientsclient = Groq(api_key="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")llm = ChatGoogleGenerativeAI(18 unmodified linesreturn f"Error in transcription: {str(e)}", Nonedef get_ai_response(text, detected_language="ar"):"""Get AI response from Gemini with Arabic system prompt"""try:system_prompt = """أنت مساعد ذكي ومفيد. يجب عليك الرد باللغة العربية واستخدام نفس اللهجة التي يستخدمها المستخدم.قواعد مهمة:- إذا تحدث المستخدم بالعربية الفصحى، رد بالفصحى- إذا تحدث المستخدم بلهجة عامية (مصرية، خليجية، شامية، مغاربية، إلخ)، رد بنفس اللهجة- حافظ على نفس الأسلوب والنبرة التي يستخدمها المستخدم- كن طبيعياً ومحادثاً ومفيداً- الرد يجب أن يكون مختصراً ومفيداً وواضحاً."""from langchain_core.messages import HumanMessage, SystemMessagemessages = [9 unmodified linesdef text_to_speech(text, language="ar"):"""Convert text to speech using Groq TTS"""try:# Always use Arabic voicevoice = "Amira-PlayAI"model = "playai-tts-arabic"response = client.audio.speech.create(model=model,7 unmodified linesresponse.write_to_file(temp_file.name)return temp_file.nameexcept Exception as e:print(f"TTS Error: {str(e)}") # Debug print# Return error message instead of Nonereturn f"Error generating audio: {str(e)}"# -------------------- Gradio Interface Function --------------------def process_voice_chat(audio):"""Main function to process voice input and generate response"""if audio is None:return "يرجى تقديم مدخل صوتي", "", None# Always use Arabiclang_code = "ar"# Step 1: Transcribe audiotranscription, detected_lang = transcribe_audio(audio, lang_code)2 unmodified linesreturn transcription, "", None# Step 2: Get AI responseai_response = get_ai_response(transcription, detected_lang or lang_code)if ai_response.startswith("Error"):return transcription, ai_response, None# Step 3: Convert response to speech (always Arabic)audio_output = text_to_speech(ai_response, "ar")# Check if audio generation failedif isinstance(audio_output, str) and audio_output.startswith("Error"):return transcription, ai_response, Nonereturn transcription, ai_response, audio_output# -------------------- Gradio Interface --------------------with gr.Blocks(title="مساعد المحادثة الصوتية", theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🎤 مساعد المحادثة الصوتيةسجل صوتك أو ارفع ملف صوتي للمحادثة مع الذكاء الاصطناعي""")with gr.Row():with gr.Column():audio_input = gr.Audio(sources=["microphone", "upload"],type="filepath",label="سجل أو ارفع ملف صوتي")submit_btn = gr.Button("معالجة", variant="primary", size="lg")with gr.Column():transcription_output = gr.Textbox(label="رسالتك (النص المنسوخ)",lines=3,rtl=True)ai_response_output = gr.Textbox(label="رد الذكاء الاصطناعي",lines=5,rtl=True)audio_output = gr.Audio(label="الرد الصوتي",type="filepath",autoplay=True)# Button actionsubmit_btn.click(fn=process_voice_chat,inputs=[audio_input],outputs=[transcription_output, ai_response_output, audio_output])gr.Markdown("""### 📝 التعليمات:1. سجل صوتك باستخدام الميكروفون أو ارفع ملف صوتي2. اضغط على "معالجة" للحصول على رد الذكاء الاصطناعي مع صوت### 🔑 للنشر على Hugging Face Spaces:أضف هذه الأسرار في إعدادات المساحة:- `GROQ_API_KEY`: مفتاح Groq API الخاص بك- `GOOGLE_API_KEY`: مفتاح Google API الخاص بك""")
app.py+43-68