bharathmunakala commited on
Commit
40d9fe6
Β·
verified Β·
1 Parent(s): c808a89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +250 -64
app.py CHANGED
@@ -1,70 +1,256 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
 
 
 
 
 
 
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import io
3
+ import time
4
+ import re
5
+ from typing import Generator, Tuple, Union
6
+ import numpy as np
7
+ import soundfile as sf
8
+ from fastrtc import (
9
+ AlgoOptions,
10
+ ReplyOnPause,
11
+ Stream,
12
+ )
13
+ from cartesia import Cartesia
14
+ from loguru import logger
15
+ from dotenv import load_dotenv
16
+ import os
17
+ load_dotenv()
18
+ from websearch_agent import agent, agent_config
19
+
20
+ logger.remove()
21
+ logger.add(
22
+ lambda msg: print(msg),
23
+ colorize=True,
24
+ format="<green>{time:HH:mm:ss}</green> | <level>{level}</level> | <level>{message}</level>",
25
+ )
26
+
27
+ # Initialize Cartesia with API key
28
+ cartesia_client = Cartesia(api_key=os.getenv("CARTESIA_API_KEY"))
29
+
30
+ # Cartesia Sonic 3 TTS Configuration
31
+ logger.info("🎀 Initializing Cartesia Sonic 3 TTS...")
32
+ CARTESIA_TTS_CONFIG = {
33
+ "model_id": "sonic-3", # Latest streaming TTS model
34
+ "voice": {
35
+ "mode": "id",
36
+ "id": "f786b574-daa5-4673-aa0c-cbe3e8534c02", # Katie - stable, realistic voice for voice agents
37
+ },
38
+ "output_format": {
39
+ "container": "raw",
40
+ "sample_rate": 24000,
41
+ "encoding": "pcm_f32le",
42
+ },
43
+ }
44
+ logger.info("βœ… Cartesia Sonic 3 TTS configured successfully")
45
+
46
+
47
+ def response(
48
+ audio: tuple[int, np.ndarray],
49
+ ) -> Generator[Tuple[int, np.ndarray], None, None]:
50
  """
51
+ Process audio input, transcribe it, generate a response using LangGraph, and deliver TTS audio.
52
+ Optimized for ultra-low latency with Cartesia STT and Sonic 3 TTS.
53
+
54
+ Args:
55
+ audio: Tuple containing sample rate and audio data
56
+
57
+ Yields:
58
+ Tuples of (sample_rate, audio_array) for audio playback
59
  """
60
+ start_time = time.time()
61
+ logger.info("πŸŽ™οΈ Received audio input")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ # ============ STT (Speech-to-Text) with Cartesia ============
64
+ stt_start = time.time()
65
+ logger.debug("πŸ”„ Transcribing audio with Cartesia...")
66
+ sample_rate, audio_data = audio
67
+
68
+ # Convert audio to PCM format for Cartesia
69
+ # Cartesia expects 16kHz, 16-bit PCM
70
+ target_sample_rate = 16000
71
+
72
+ # Resample if needed
73
+ if sample_rate != target_sample_rate:
74
+ import librosa
75
+ # Convert to float32 for resampling
76
+ if audio_data.dtype != np.float32:
77
+ audio_float = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max
78
+ else:
79
+ audio_float = audio_data
80
+
81
+ # Resample
82
+ audio_resampled = librosa.resample(
83
+ audio_float.T.flatten() if audio_float.ndim > 1 else audio_float,
84
+ orig_sr=sample_rate,
85
+ target_sr=target_sample_rate
86
+ )
87
+ audio_data = audio_resampled
88
+ sample_rate = target_sample_rate
89
+
90
+ # Convert to 16-bit PCM bytes
91
+ if audio_data.dtype == np.float32:
92
+ audio_int16 = (audio_data * 32767).astype(np.int16)
93
+ else:
94
+ audio_int16 = audio_data.astype(np.int16)
95
+
96
+ audio_bytes = audio_int16.tobytes()
97
+
98
+ # Create websocket connection with optimized endpointing
99
+ ws = cartesia_client.stt.websocket(
100
+ model="ink-whisper",
101
+ language="en",
102
+ encoding="pcm_s16le",
103
+ sample_rate=target_sample_rate,
104
+ min_volume=0.1, # Low threshold for voice detection
105
+ max_silence_duration_secs=0.3, # Quick endpointing
106
+ )
107
+
108
+ # Send audio in chunks (20ms chunks for streaming)
109
+ chunk_size = int(target_sample_rate * 0.02 * 2) # 20ms chunks
110
+ for i in range(0, len(audio_bytes), chunk_size):
111
+ chunk = audio_bytes[i:i + chunk_size]
112
+ if chunk:
113
+ ws.send(chunk)
114
+
115
+ # Finalize transcription
116
+ ws.send("finalize")
117
+ ws.send("done")
118
+
119
+ # Receive transcription results
120
+ transcript = ""
121
+ for result in ws.receive():
122
+ if result['type'] == 'transcript':
123
+ if result['is_final']:
124
+ transcript = result['text']
125
+ break
126
+ elif result['type'] == 'done':
127
+ break
128
+
129
+ ws.close()
130
+
131
+ stt_time = time.time() - stt_start
132
+ logger.info(f'πŸ‘‚ Transcribed in {stt_time:.2f}s: "{transcript}"')
133
+
134
+ # ============ LLM (Language Model) ============
135
+ llm_start = time.time()
136
+ logger.debug("🧠 Running agent...")
137
+ agent_response = agent.invoke(
138
+ {"messages": [{"role": "user", "content": transcript}]}, config=agent_config
139
+ )
140
+ response_text = agent_response["messages"][-1].content
141
+ llm_time = time.time() - llm_start
142
+ logger.info(f'πŸ’¬ Response in {llm_time:.2f}s: "{response_text}"')
143
+
144
+ # ============ TTS (Text-to-Speech) with Cartesia Sonic 3 ============
145
+ tts_start = time.time()
146
+ logger.debug("πŸ”Š Generating speech with Cartesia Sonic 3...")
147
+
148
+ # Clean markdown formatting for better TTS output
149
+ clean_text = response_text
150
+ # Remove asterisks (bold/italic markdown)
151
+ clean_text = re.sub(r'\*+', '', clean_text)
152
+ # Remove other common markdown symbols (including table separators)
153
+ clean_text = re.sub(r'[#_`]', '', clean_text)
154
+ # Remove dashes/hyphens used in tables and horizontal rules
155
+ clean_text = re.sub(r'-{2,}', ' ', clean_text) # Replace multiple dashes with space
156
+ # Remove pipe symbols used in markdown tables
157
+ clean_text = re.sub(r'\|', ' ', clean_text)
158
+ # Remove extra whitespace
159
+ clean_text = re.sub(r'\s+', ' ', clean_text).strip()
160
+
161
+ if clean_text != response_text:
162
+ logger.debug(f"Cleaned text for TTS: {clean_text}")
163
+
164
+ try:
165
+ # Generate speech using Cartesia Sonic 3 TTS (streaming)
166
+ chunk_count = 0
167
+ chunk_iter = cartesia_client.tts.bytes(
168
+ model_id=CARTESIA_TTS_CONFIG["model_id"],
169
+ transcript=clean_text,
170
+ voice=CARTESIA_TTS_CONFIG["voice"],
171
+ output_format=CARTESIA_TTS_CONFIG["output_format"],
172
+ )
173
+
174
+ # Buffer to accumulate partial chunks
175
+ buffer = b""
176
+ element_size = 4 # float32 is 4 bytes
177
+
178
+ # Stream audio chunks and convert to FastRTC format
179
+ for chunk in chunk_iter:
180
+ # Accumulate chunks in buffer
181
+ buffer += chunk
182
+
183
+ # Process complete float32 samples
184
+ num_complete_samples = len(buffer) // element_size
185
+ if num_complete_samples > 0:
186
+ # Extract complete samples
187
+ complete_bytes = num_complete_samples * element_size
188
+ complete_buffer = buffer[:complete_bytes]
189
+ buffer = buffer[complete_bytes:] # Keep remainder for next iteration
190
+
191
+ # Convert to numpy array
192
+ audio_array = np.frombuffer(complete_buffer, dtype=np.float32)
193
+ chunk_count += 1
194
+
195
+ # Yield in FastRTC format: (sample_rate, audio_array)
196
+ yield (CARTESIA_TTS_CONFIG["output_format"]["sample_rate"], audio_array)
197
+
198
+ # Process any remaining bytes in buffer
199
+ if len(buffer) > 0:
200
+ # Pad to complete sample if needed
201
+ remainder = len(buffer) % element_size
202
+ if remainder != 0:
203
+ buffer += b'\x00' * (element_size - remainder)
204
+
205
+ if len(buffer) >= element_size:
206
+ audio_array = np.frombuffer(buffer, dtype=np.float32)
207
+ chunk_count += 1
208
+ yield (CARTESIA_TTS_CONFIG["output_format"]["sample_rate"], audio_array)
209
+
210
+ tts_time = time.time() - tts_start
211
+ total_time = time.time() - start_time
212
+ logger.info(f'⚑ Performance: STT={stt_time:.2f}s | LLM={llm_time:.2f}s | TTS={tts_time:.2f}s | Total={total_time:.2f}s | Chunks={chunk_count}')
213
+
214
+ except Exception as e:
215
+ logger.error(f"Error in Cartesia TTS generation: {str(e)}")
216
+ raise
217
+
218
+
219
+ def create_stream() -> Stream:
220
+ """
221
+ Create and configure a Stream instance with audio capabilities.
222
+ Optimized for low latency.
223
+
224
+ Returns:
225
+ Stream: Configured FastRTC Stream instance
226
+ """
227
+ return Stream(
228
+ modality="audio",
229
+ mode="send-receive",
230
+ handler=ReplyOnPause(
231
+ response,
232
+ algo_options=AlgoOptions(
233
+ speech_threshold=0.4, # Slightly lower for faster detection
234
+ ),
235
+ ),
236
+ )
237
 
238
 
239
  if __name__ == "__main__":
240
+ parser = argparse.ArgumentParser(description="FastRTC Cartesia Voice Agent (Ultra-Low Latency)")
241
+ parser.add_argument(
242
+ "--phone",
243
+ action="store_true",
244
+ help="Launch with FastRTC phone interface (get a temp phone number)",
245
+ )
246
+ args = parser.parse_args()
247
+
248
+ stream = create_stream()
249
+ logger.info("🎧 Stream handler configured")
250
+
251
+ if args.phone:
252
+ logger.info("🌈 Launching with FastRTC phone interface...")
253
+ stream.fastphone()
254
+ else:
255
+ logger.info("🌈 Launching with Gradio UI...")
256
+ stream.ui.launch()