SpringyBon commited on
Commit
0bb4017
·
verified ·
1 Parent(s): a739009

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -0
app.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import io
4
+ import gradio as gr
5
+ from openai import OpenAI
6
+
7
+ # Read API key from Space secret
8
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
9
+
10
+ SYSTEM_PROMPT = "You are a friendly, concise voice assistant. Keep replies short when spoken (~2-3 sentences)."
11
+
12
+ def ensure_bytesio(obj):
13
+ if isinstance(obj, (bytes, bytearray)):
14
+ return io.BytesIO(obj)
15
+ return obj
16
+
17
+ def chat_fn(history, mic_audio, text_input, voice="alloy", model=None, temperature=0.6):
18
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
19
+ # Convert history (list of [user, assistant]) -> messages
20
+ for pair in history or []:
21
+ if pair[0]:
22
+ messages.append({"role": "user", "content": pair[0]})
23
+ if len(pair) > 1 and pair[1]:
24
+ messages.append({"role": "assistant", "content": pair[1]})
25
+
26
+ user_text = (text_input or "").strip()
27
+
28
+ # If user provided audio, transcribe it
29
+ transcript_text = None
30
+ if mic_audio:
31
+ # mic_audio is a file path (type='filepath')
32
+ with open(mic_audio, "rb") as f:
33
+ tr = client.audio.transcriptions.create(
34
+ model="whisper-1",
35
+ file=f,
36
+ response_format="text"
37
+ )
38
+ transcript_text = tr if isinstance(tr, str) else getattr(tr, "text", None)
39
+ if transcript_text:
40
+ user_text = (user_text + " " + transcript_text).strip() if user_text else transcript_text
41
+
42
+ if not user_text:
43
+ return history, None, "Please speak or type something."
44
+
45
+ messages.append({"role": "user", "content": user_text})
46
+ chosen_model = model or os.getenv("OPENAI_MODEL", "gpt-4o-mini")
47
+
48
+ comp = client.chat.completions.create(
49
+ model=chosen_model,
50
+ messages=messages,
51
+ temperature=float(temperature)
52
+ )
53
+ reply = comp.choices[0].message.content.strip()
54
+
55
+ # TTS
56
+ speech = client.audio.speech.create(
57
+ model="gpt-4o-mini-tts",
58
+ voice=voice,
59
+ input=reply
60
+ )
61
+ # Save to a temp mp3
62
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp:
63
+ tmp.write(speech.read())
64
+ tts_path = tmp.name
65
+
66
+ new_hist = (history or []) + [[user_text, reply]]
67
+ return new_hist, tts_path, transcript_text or ""
68
+
69
+ with gr.Blocks(theme=gr.themes.Soft(), fill_height=True) as demo:
70
+ gr.Markdown("# 🎙️ Voice Chat (Hugging Face Space)
71
+ Talk to the AI and it talks back.")
72
+
73
+ with gr.Row():
74
+ chatbot = gr.Chatbot(height=340, type="messages")
75
+ with gr.Row():
76
+ audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Mic (press to record)")
77
+ with gr.Row():
78
+ text_in = gr.Textbox(placeholder="...or type here and press Enter", scale=2)
79
+ voice = gr.Dropdown(choices=["alloy","verse","amber","aria","bright","sage","sol","luna","coral","spark","horizon"], value="alloy", label="Voice", scale=1)
80
+ with gr.Row():
81
+ model = gr.Textbox(value="", placeholder="Model (leave blank for gpt-4o-mini)", label="Model override", scale=1)
82
+ temp = gr.Slider(0.0, 1.5, value=0.6, step=0.1, label="Creativity")
83
+ with gr.Row():
84
+ audio_out = gr.Audio(label="AI Voice Reply", autoplay=True)
85
+ transcript = gr.Textbox(label="Last transcription", interactive=False)
86
+
87
+ state = gr.State([])
88
+
89
+ def _chat(state_hist, audio, text, voice, model, temp):
90
+ return chat_fn(state_hist, audio, text, voice, model, temp)
91
+
92
+ go = gr.Button("Send / Speak")
93
+ clear = gr.Button("Clear")
94
+
95
+ go.click(_chat, inputs=[state, audio_in, text_in, voice, model, temp], outputs=[state, audio_out, transcript])
96
+ text_in.submit(_chat, inputs=[state, audio_in, text_in, voice, model, temp], outputs=[state, audio_out, transcript])
97
+ clear.click(fn=lambda: ([], None, ""), outputs=[state, audio_out, transcript])
98
+
99
+ if __name__ == "__main__":
100
+ demo.launch()
101
+