FastRTC_Groq01 / src /app.py
bharathmunakala's picture
Upload 2 files
49056bd verified
Raw History Blame Contribute Delete
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()