File size: 2,322 Bytes
6b17775
57bb9a0
 
 
 
 
 
e355f70
 
 
 
 
 
 
 
 
6512a89
 
 
 
 
b06881a
6512a89
b06881a
6512a89
b06881a
 
e355f70
 
b06881a
 
e355f70
 
b06881a
e355f70
b06881a
e355f70
 
 
 
 
 
b06881a
e355f70
 
 
 
 
 
 
 
b06881a
 
 
 
 
 
 
6512a89
b06881a
 
e355f70
b06881a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import gradio as gr
from google.generativeai import GenerativeModel, configure
from gtts import gTTS
import speech_recognition as sr
import os
import tempfile

# βœ… Load API key from environment variable
GOOGLE_API_KEY = os.getenv("GEMINI_API_KEY")
if not GOOGLE_API_KEY:
    raise ValueError("❌ Missing API Key! Please set GEMINI_API_KEY as an environment variable.")

# βœ… Configure Gemini securely
configure(api_key=GOOGLE_API_KEY)
gemini_model = GenerativeModel("models/gemini-1.5-flash")

def transcribe_audio(audio_path):
    recognizer = sr.Recognizer()
    with sr.AudioFile(audio_path) as source:
        audio = recognizer.record(source)
    try:
        return recognizer.recognize_google(audio, language='en-US')
    except sr.UnknownValueError:
        return "❌ Could not understand the audio."
    except sr.RequestError:
        return "❌ Could not connect to Google Speech API."

def get_gemini_response(query):
    try:
        # Request Gemini model to answer in English
        response = gemini_model.generate_content(f"Answer in English: {query}")
        return response.text.replace('*', '')
    except Exception as e:
        return f"❌ Error from Gemini: {str(e)}"

def text_to_speech(text, lang='en'):
    tts = gTTS(text=text, lang=lang)
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
    tts.save(temp_file.name)
    return temp_file.name

# ---------------------------
# Combined function to handle voice query
# ---------------------------
def handle_voice_query(audio_file):
    query = transcribe_audio(audio_file)
    response = get_gemini_response(query)
    audio_path = text_to_speech(response)
    return query, response, audio_path

with gr.Blocks() as demo:
    gr.Markdown("# πŸ—£οΈ **Ask by Voice**")
    gr.Markdown("### Speak your question aloud (in English)")
    audio_input = gr.Audio(type="filepath", label="🎀 Speak your question")
    query_text = gr.Textbox(label="πŸ” Spoken Question")
    gemini_response = gr.Textbox(label="πŸ“œ Gemini Response")
    audio_output = gr.Audio(label="πŸ”Š Voice Response")
    submit_btn = gr.Button("➑️ Get Answer")
    submit_btn.click(fn=handle_voice_query,
                     inputs=[audio_input],
                     outputs=[query_text, gemini_response, audio_output])

demo.launch()