Spaces:
No application file
No application file
Download src/app.py from bharathmunakala/FastRTC_Groq: direct link, hf CLI and curl.
- Browser
- Download file 3.38 kB
-
https://huggingface.co/spaces/bharathmunakala/FastRTC_Groq/resolve/main/src/app.py
- Command line
-
hf download hf://spaces/bharathmunakala/FastRTC_Groq/src/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bharathmunakala/FastRTC_Groq/resolve/main/src/app.py
3.38 kB
| import argparse | |
| import io | |
| from typing import Generator, Tuple, Union | |
| import numpy as np | |
| import soundfile as sf | |
| from fastrtc import ( | |
| AlgoOptions, | |
| ReplyOnPause, | |
| Stream, | |
| get_tts_model, | |
| ) | |
| from groq import Groq | |
| from loguru import logger | |
| from dotenv import load_dotenv | |
| import os | |
| load_dotenv() | |
| from websearch_agent import agent, agent_config | |
| logger.remove() | |
| logger.add( | |
| lambda msg: print(msg), | |
| colorize=True, | |
| format="<green>{time:HH:mm:ss}</green> | <level>{level}</level> | <level>{message}</level>", | |
| ) | |
| groq_client = Groq() | |
| # Initialize FastRTC TTS model (Kokoro) | |
| logger.info("π€ Initializing FastRTC TTS model...") | |
| tts_model = get_tts_model() # Uses Kokoro TTS | |
| logger.info("β FastRTC TTS model initialized successfully") | |
| def response( | |
| audio: tuple[int, np.ndarray], | |
| ) -> Generator[Tuple[int, np.ndarray], None, None]: | |
| """ | |
| Process audio input, transcribe it, generate a response using LangGraph, and deliver TTS audio. | |
| Args: | |
| audio: Tuple containing sample rate and audio data | |
| Yields: | |
| Tuples of (sample_rate, audio_array) for audio playback | |
| """ | |
| logger.info("ποΈ Received audio input") | |
| logger.debug("π Transcribing audio...") | |
| # Convert numpy array to WAV bytes | |
| sample_rate, audio_data = audio | |
| buffer = io.BytesIO() | |
| sf.write(buffer, audio_data.T, sample_rate, format='WAV') | |
| buffer.seek(0) | |
| transcript = groq_client.audio.transcriptions.create( | |
| file=("audio-file.wav", buffer.read()), | |
| model="whisper-large-v3-turbo", | |
| response_format="text", | |
| ) | |
| logger.info(f'π Transcribed: "{transcript}"') | |
| logger.debug("π§ Running agent...") | |
| agent_response = agent.invoke( | |
| {"messages": [{"role": "user", "content": transcript}]}, config=agent_config | |
| ) | |
| response_text = agent_response["messages"][-1].content | |
| logger.info(f'π¬ Response: "{response_text}"') | |
| logger.debug("π Generating speech with FastRTC TTS...") | |
| try: | |
| # Generate speech using FastRTC TTS model (Kokoro) | |
| for audio_chunk in tts_model.stream_tts_sync(response_text): | |
| yield audio_chunk | |
| except Exception as e: | |
| logger.error(f"Error in TTS generation: {str(e)}") | |
| raise | |
| def create_stream() -> Stream: | |
| """ | |
| Create and configure a Stream instance with audio capabilities. | |
| Returns: | |
| Stream: Configured FastRTC Stream instance | |
| """ | |
| return Stream( | |
| modality="audio", | |
| mode="send-receive", | |
| handler=ReplyOnPause( | |
| response, | |
| algo_options=AlgoOptions( | |
| speech_threshold=0.5, | |
| ), | |
| ), | |
| ) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="FastRTC Groq Voice Agent") | |
| parser.add_argument( | |
| "--phone", | |
| action="store_true", | |
| help="Launch with FastRTC phone interface (get a temp phone number)", | |
| ) | |
| args = parser.parse_args() | |
| stream = create_stream() | |
| logger.info("π§ Stream handler configured") | |
| if args.phone: | |
| logger.info("π Launching with FastRTC phone interface...") | |
| stream.fastphone() | |
| else: | |
| logger.info("π Launching with Gradio UI...") | |
| stream.ui.launch() | |