File size: 2,134 Bytes
8b1e1fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
import gradio as gr
import requests
from gtts import gTTS
import tempfile
import os

# πŸ”‘ OpenRouter API key (Replace this securely in HF secrets later)
OPENROUTER_API_KEY = "YOUR_API_KEY"

# 🧠 Get AI response
def get_ai_response(user_input):
    url = "https://openrouter.ai/api/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json"
    }

    data = {
        "model": "mistralai/mistral-7b-instruct:free",
        "max_tokens": 100,
        "temperature": 0.7,
        "messages": [
            {"role": "system", "content": "You are a helpful and friendly AI assistant. Keep answers short."},
            {"role": "user", "content": user_input}
        ]
    }

    response = requests.post(url, headers=headers, json=data)
    if response.ok:
        result = response.json()
        return result["choices"][0]["message"]["content"]
    else:
        return "⚠️ OpenRouter error"

# πŸŽ™οΈ Speech-to-text β†’ AI β†’ Text-to-speech
def process_audio(audio):
    if audio is None:
        return "No audio provided", None

    import speech_recognition as sr
    recognizer = sr.Recognizer()
    with sr.AudioFile(audio) as source:
        audio_data = recognizer.record(source)
        try:
            text = recognizer.recognize_google(audio_data)
        except:
            return "Sorry, I couldn't understand you.", None

    ai_response = get_ai_response(text)

    # πŸ”Š Convert to speech
    tts = gTTS(text=ai_response, lang="en")
    with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
        tts.save(f.name)
        return ai_response, f.name

# πŸ–ΌοΈ Gradio UI
demo = gr.Interface(
    fn=process_audio,
    inputs=gr.Audio(source="microphone", type="filepath", label="πŸŽ™οΈ Speak now"),
    outputs=[
        gr.Text(label="🧠 AI Response"),
        gr.Audio(label="πŸ”Š AI Voice")
    ],
    title="🎀 Voice Assistant with OpenRouter AI",
    description="Speak your question. The AI will respond by voice."
)

demo.launch()