MuhammadSajid commited on
Commit
86d1c54
·
verified ·
1 Parent(s): 7b114c6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import tempfile
4
+ import pyttsx3
5
+ from faster_whisper import WhisperModel
6
+
7
+ # === Config ===
8
+ GROQ_API_KEY = "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"
9
+ GROQ_MODEL = "llama3-70b-8192"
10
+ GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
+
12
+ # === Init Whisper ===
13
+ whisper = WhisperModel("base", device="cpu", compute_type="int8")
14
+
15
+ # === Init TTS (offline) ===
16
+ tts_engine = pyttsx3.init()
17
+
18
+ def speak_to_file(text, output_file="output.wav"):
19
+ """Save TTS to a file using pyttsx3."""
20
+ tts_engine.save_to_file(text, output_file)
21
+ tts_engine.runAndWait()
22
+ return output_file
23
+
24
+ def process_audio(audio_file):
25
+ # 1. Speech to Text
26
+ segments, _ = whisper.transcribe(audio_file)
27
+ user_text = " ".join([segment.text for segment in segments])
28
+
29
+ # 2. Groq API Call
30
+ headers = {
31
+ "Authorization": f"Bearer {GROQ_API_KEY}",
32
+ "Content-Type": "application/json"
33
+ }
34
+ payload = {
35
+ "model": GROQ_MODEL,
36
+ "messages": [{"role": "user", "content": user_text}],
37
+ "temperature": 0.5
38
+ }
39
+
40
+ response = requests.post(GROQ_API_URL, headers=headers, json=payload)
41
+ if response.status_code != 200:
42
+ return f"Groq API Error: {response.text}", None
43
+
44
+ reply = response.json()["choices"][0]["message"]["content"]
45
+
46
+ # 3. TTS to file
47
+ audio_output = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
48
+ speak_to_file(reply, audio_output.name)
49
+
50
+ return reply, audio_output.name
51
+
52
+ iface = gr.Interface(
53
+ fn=process_audio,
54
+ inputs=gr.Audio(source="microphone", type="filepath", label="🎤 Speak your question"),
55
+ outputs=[
56
+ gr.Textbox(label="🧠 Groq Response"),
57
+ gr.Audio(label="🔊 AI Voice Reply")
58
+ ],
59
+ title="🗣️ Voice AI Assistant (Groq + Whisper + Offline TTS)",
60
+ description="Use your mic. Whisper transcribes, Groq replies, voice response from pyttsx3 (offline).",
61
+ live=True
62
+ )
63
+
64
+ iface.launch()