File size: 12,784 Bytes
30ea74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f553b4
30ea74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44d5dcc
30ea74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#!/usr/bin/env python3
"""
Voice Development Assistant - Hugging Face Spaces
Optimized for ZeroGPU H200 cluster
Uses OpenRouter for LLM, HuggingFace for TTS
"""

import gradio as gr
import numpy as np
import os
import tempfile
import requests

print(f"πŸ“¦ Gradio version: {gr.__version__}")

# Check for ZeroGPU availability
try:
    import spaces
    ZERO_GPU_AVAILABLE = True
    print("πŸš€ ZeroGPU detected - GPU acceleration enabled!")
except ImportError:
    ZERO_GPU_AVAILABLE = False
    print("⚠️ ZeroGPU not available - running on CPU")

# Configuration from environment
CONFIG = {
    'openrouter_key': os.getenv('OPENROUTER_API_KEY', ''),
    'whisper_model': os.getenv('WHISPER_MODEL', 'base'),
    'language': os.getenv('LANGUAGE', 'en'),
    'llm_model': os.getenv('LLM_MODEL', 'cognitivecomputations/dolphin-mistral-24b-venice-edition:free'),
    'max_tokens': int(os.getenv('MAX_TOKENS', '4096')),
    'temperature': float(os.getenv('TEMPERATURE', '1.0'))
}

OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"

# Lazy-loaded models
whisper_model = None
tts_pipeline = None
conversation_history = []


def get_whisper_model():
    """Load Whisper model (uses GPU when available via ZeroGPU)"""
    global whisper_model
    if whisper_model is None:
        import whisper
        import torch
        
        device = "cuda" if torch.cuda.is_available() else "cpu"
        model_name = CONFIG['whisper_model']
        
        print(f"Loading Whisper model '{model_name}' on {device}...")
        whisper_model = whisper.load_model(model_name, device=device)
        print(f"βœ… Whisper model loaded on {device}")
    return whisper_model


def get_tts_pipeline():
    """Get HuggingFace TTS pipeline"""
    global tts_pipeline
    if tts_pipeline is None:
        try:
            import torch
            from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
            from datasets import load_dataset
            
            device = "cuda" if torch.cuda.is_available() else "cpu"
            print(f"Loading TTS models on {device}...")
            
            processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
            model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts").to(device)
            vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan").to(device)
            
            embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
            speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(device)
            
            tts_pipeline = {
                "processor": processor,
                "model": model,
                "vocoder": vocoder,
                "speaker_embeddings": speaker_embeddings,
                "device": device
            }
            print("βœ… HuggingFace TTS initialized (SpeechT5)")
        except Exception as e:
            print(f"⚠️ SpeechT5 failed, trying MMS-TTS: {e}")
            try:
                from transformers import pipeline
                tts_pipeline = pipeline("text-to-speech", model="facebook/mms-tts-eng")
                print("βœ… HuggingFace TTS initialized (MMS-TTS)")
            except Exception as e2:
                print(f"❌ TTS initialization failed: {e2}")
                tts_pipeline = None
    return tts_pipeline


def chat_with_openrouter(messages: list) -> str:
    """Send chat request to OpenRouter API"""
    api_key = CONFIG['openrouter_key']
    if not api_key:
        raise ValueError("OpenRouter API key not configured. Set OPENROUTER_API_KEY secret.")
    
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://huggingface.co/spaces",
        "X-Title": "Voice Development Assistant"
    }
    
    payload = {
        "model": CONFIG['llm_model'],
        "messages": messages,
        "max_tokens": CONFIG['max_tokens'],
        "temperature": CONFIG['temperature']
    }
    
    response = requests.post(
        f"{OPENROUTER_BASE_URL}/chat/completions",
        headers=headers,
        json=payload,
        timeout=120
    )
    
    if response.status_code != 200:
        raise Exception(f"OpenRouter API error: {response.status_code} - {response.text}")
    
    return response.json()['choices'][0]['message']['content']


def transcribe_audio_gpu(audio_data: np.ndarray) -> str:
    """Transcribe audio using Whisper"""
    model = get_whisper_model()
    
    if audio_data.dtype != np.float32:
        if audio_data.dtype == np.int16:
            audio_data = audio_data.astype(np.float32) / 32768.0
        else:
            audio_data = audio_data.astype(np.float32)
    
    if len(audio_data.shape) > 1:
        audio_data = audio_data[:, 0] if audio_data.shape[1] > 1 else audio_data.flatten()
    
    result = model.transcribe(audio_data, language=CONFIG['language'], fp16=False)
    return result["text"].strip()


# Wrap with ZeroGPU decorator if available
if ZERO_GPU_AVAILABLE:
    @spaces.GPU(duration=60)
    def transcribe_with_gpu(audio_data: np.ndarray) -> str:
        return transcribe_audio_gpu(audio_data)
else:
    transcribe_with_gpu = transcribe_audio_gpu


def transcribe_audio(audio):
    """Transcribe audio input from Gradio"""
    try:
        if audio is None:
            return "No audio provided. Please record or upload audio."
        
        sample_rate, audio_data = audio
        text = transcribe_with_gpu(audio_data)
        return text if text else "No speech detected."
    except Exception as e:
        return f"Error: {str(e)}"


def synthesize_text(text):
    """Synthesize text to speech"""
    try:
        if not text:
            return None, "No text provided"
        
        import torch
        import scipy.io.wavfile as wavfile
        
        tts = get_tts_pipeline()
        if tts is None:
            return None, "TTS not available"
        
        if isinstance(tts, dict):
            inputs = tts["processor"](text=text, return_tensors="pt").to(tts["device"])
            with torch.no_grad():
                speech = tts["model"].generate_speech(
                    inputs["input_ids"], 
                    tts["speaker_embeddings"], 
                    vocoder=tts["vocoder"]
                )
            audio_data = speech.cpu().numpy()
            sample_rate = 16000
        else:
            result = tts(text)
            audio_data = result["audio"][0]
            sample_rate = result["sampling_rate"]
        
        with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp:
            wavfile.write(tmp.name, sample_rate, audio_data)
            return tmp.name, f"βœ… Synthesized {len(text)} characters"
    except Exception as e:
        return None, f"Error: {str(e)}"


def chat_with_claude(message, history):
    """Chat with LLM via OpenRouter"""
    global conversation_history
    
    try:
        if not message.strip():
            return history
        
        conversation_history.append({"role": "user", "content": message})
        assistant_message = chat_with_openrouter(conversation_history)
        conversation_history.append({"role": "assistant", "content": assistant_message})
        
        history.append([message, assistant_message])
        return history
    except Exception as e:
        history.append([message, f"Error: {str(e)}"])
        return history


def voice_chat(audio):
    """Complete voice conversation"""
    global conversation_history
    
    try:
        if audio is None:
            return None, "No audio provided", ""
        
        sample_rate, audio_data = audio
        
        user_text = transcribe_with_gpu(audio_data)
        if not user_text:
            return None, "No speech detected", ""
        
        conversation_history.append({"role": "user", "content": user_text})
        response_text = chat_with_openrouter(conversation_history)
        conversation_history.append({"role": "assistant", "content": response_text})
        
        audio_path, _ = synthesize_text(response_text)
        conversation_log = f"**🎀 You:** {user_text}\n\n**πŸ€– Assistant:** {response_text}"
        
        return audio_path, conversation_log, response_text
    except Exception as e:
        return None, f"Error: {str(e)}", ""


def clear_history():
    """Clear conversation history"""
    global conversation_history
    conversation_history = []
    return []


def check_api_status():
    """Check system status"""
    status = []
    
    if CONFIG['openrouter_key']:
        status.append("βœ… OpenRouter API key configured")
    else:
        status.append("❌ OpenRouter API key missing (Set OPENROUTER_API_KEY secret)")
    
    status.append("βœ… HuggingFace TTS (free, no API key)")
    
    if ZERO_GPU_AVAILABLE:
        status.append("πŸš€ ZeroGPU enabled (H200 acceleration)")
    else:
        status.append("πŸ’» Running on CPU")
    
    return "\n".join(status)


# Build Gradio Interface
demo = gr.Blocks(title="Voice Development Assistant")

with demo:
    gr.Markdown("""
    # 🎀 Voice Development Assistant
    
    **Personal Voice Interface for Development Workflows**
    
    Speech-to-Text β€’ Text-to-Speech β€’ Claude AI Conversations
    """)
    
    with gr.Accordion("πŸ“Š System Status", open=False):
        status_display = gr.Markdown(check_api_status())
        refresh_btn = gr.Button("πŸ”„ Refresh Status")
        refresh_btn.click(check_api_status, outputs=[status_display])
    
    with gr.Tabs():
        # Voice Chat
        with gr.Tab("🎀 Voice Chat"):
            gr.Markdown("### Speak with Claude using your voice")
            with gr.Row():
                with gr.Column(scale=1):
                    voice_input = gr.Audio(label="πŸŽ™οΈ Click to Record", sources=["microphone"], type="numpy")
                    voice_submit = gr.Button("πŸš€ Send to Claude", variant="primary")
                with gr.Column(scale=1):
                    voice_output = gr.Audio(label="πŸ”Š Claude's Response", type="filepath")
                    voice_log = gr.Markdown(label="Conversation")
                    voice_text = gr.Textbox(label="Response Text", lines=3, interactive=False)
            voice_submit.click(voice_chat, inputs=[voice_input], outputs=[voice_output, voice_log, voice_text])
        
        # Transcribe
        with gr.Tab("πŸ“ Transcribe"):
            gr.Markdown("### Convert speech to text using Whisper")
            with gr.Row():
                with gr.Column():
                    stt_input = gr.Audio(label="πŸŽ™οΈ Audio Input", sources=["microphone", "upload"], type="numpy")
                    stt_btn = gr.Button("πŸ“ Transcribe", variant="primary")
                with gr.Column():
                    stt_output = gr.Textbox(label="Transcription", lines=8, placeholder="Transcribed text appears here...")
            stt_btn.click(transcribe_audio, inputs=[stt_input], outputs=[stt_output])
        
        # TTS
        with gr.Tab("πŸ”Š Speak"):
            gr.Markdown("### Convert text to natural speech (HuggingFace TTS)")
            with gr.Row():
                with gr.Column():
                    tts_input = gr.Textbox(label="Text to Speak", lines=5, placeholder="Enter text to synthesize...")
                    tts_btn = gr.Button("πŸ”Š Generate Speech", variant="primary")
                with gr.Column():
                    tts_output = gr.Audio(label="Generated Audio", type="filepath")
                    tts_status = gr.Textbox(label="Status", interactive=False)
            tts_btn.click(synthesize_text, inputs=[tts_input], outputs=[tts_output, tts_status])
        
        # Text Chat
        with gr.Tab("πŸ’¬ Text Chat"):
            gr.Markdown("### Chat with Claude via text")
            chatbot = gr.Chatbot(height=450)
            with gr.Row():
                chat_input = gr.Textbox(label="Message", placeholder="Type your message...", scale=4)
                chat_submit = gr.Button("Send", variant="primary", scale=1)
            clear_btn = gr.Button("πŸ—‘οΈ Clear History")
            
            chat_submit.click(chat_with_claude, inputs=[chat_input, chatbot], outputs=[chatbot]).then(lambda: "", outputs=[chat_input])
            chat_input.submit(chat_with_claude, inputs=[chat_input, chatbot], outputs=[chatbot]).then(lambda: "", outputs=[chat_input])
            clear_btn.click(clear_history, outputs=[chatbot])
    
    gr.Markdown("""
    ---
    **Voice Development Assistant** β€’ Built with Whisper, HuggingFace TTS, and OpenRouter
    
    πŸ” Configure OPENROUTER_API_KEY as a Hugging Face Space secret
    """)

if __name__ == "__main__":
    demo.launch()