Spaces:
Runtime error

CHATBOT / app.py
mohsin06's picture
Update app.py
b709b7c verified
Raw History Blame Contribute Delete
2.78 kB
import os
import whisper
from groq import Groq
from gtts import gTTS
import gradio as gr
GROQ_API_KEY = "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"
client = Groq(api_key=GROQ_API_KEY)
# Step 1: Load Whisper Model
print("Loading Whisper model...")
model = whisper.load_model("base") # Use "small", "medium", or "large" for better accuracy
# Step 2: Initialize Groq Client
print("Initializing Groq API client...")
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
# Step 3: Define Functions
# Function to transcribe audio using Whisper
def transcribe_audio(audio_file):
print("Transcribing audio...")
result = model.transcribe(audio_file)
transcription = result["text"]
print(f"Transcription: {transcription}")
return transcription
# Function to get LLM response from Groq
def get_llm_response(transcription):
print("Getting response from Groq LLM...")
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": transcription,
}
],
model="llama3-8b-8192", # Specify the desired model
stream=False, # Set True if streaming responses
)
llm_response = chat_completion.choices[0].message.content
print(f"LLM Response: {llm_response}")
return llm_response
# Function to convert text to speech using GTTS
def text_to_speech(response_text):
print("Converting text to speech...")
tts = gTTS(response_text)
audio_file = "response.mp3"
tts.save(audio_file)
print(f"Audio response saved to {audio_file}")
return audio_file
# Main pipeline: Voice-to-voice chatbot
def voice_to_voice(audio):
try:
# Step 1: Transcribe Audio
transcription = transcribe_audio(audio)
# Step 2: Get Response from Groq API
llm_response = get_llm_response(transcription)
# Step 3: Convert LLM Response to Audio
response_audio = text_to_speech(llm_response)
return llm_response, response_audio
except Exception as e:
print(f"Error occurred: {e}")
return "An error occurred. Please try again.", None
# Step 4: Create Gradio Interface
print("Setting up Gradio interface...")
interface = gr.Interface(
fn=voice_to_voice, # Main function
inputs=gr.Audio(type="filepath", label="Speak Here"), # Input: Audio
outputs=[
gr.Textbox(label="LLM Response"), # Output: Transcribed text and LLM response
gr.Audio(label="Response Audio") # Output: Audio file
],
title="Real-Time Voice-to-Voice Chatbot",
description="Speak into the microphone, and the chatbot will respond with synthesized speech.",
)
# Step 5: Launch Interface
print("Launching Gradio app...")
interface.launch(share=True)