File size: 2,163 Bytes
3b0cc06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f52392
3b0cc06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f52392
 
3b0cc06
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
import gradio as gr
from gtts import gTTS
import openai
import speech_recognition as sr
import os

# Set OpenAI API Key
openai.api_key = "YOUR_OPENAI_API_KEY"  # Replace with your OpenAI API Key

# Text-to-Speech Function
def text_to_speech(response_text):
    tts = gTTS(response_text, lang="en")
    audio_file = "response.mp3"
    tts.save(audio_file)
    return audio_file

# Speech Recognition Function
def speech_to_text(audio_file):
    recognizer = sr.Recognizer()
    with sr.AudioFile(audio_file) as source:
        audio_data = recognizer.record(source)
        try:
            return recognizer.recognize_google(audio_data)
        except sr.UnknownValueError:
            return "I'm sorry, I couldn't understand that. Could you repeat?"
        except sr.RequestError:
            return "There was an error with the speech recognition service."

# Chatbot Logic using OpenAI GPT
def chatbot_response(user_input):
    try:
        response = openai.Completion.create(
            engine="text-davinci-003",  # Use a powerful GPT model
            prompt=f"User: {user_input}\nChatbot:",
            max_tokens=150,
            temperature=0.7,
        )
        return response.choices[0].text.strip()
    except Exception as e:
        return f"Error generating response: {e}"

# Gradio Interface Logic
def process_interaction(audio_file):
    # Convert user speech to text
    user_text = speech_to_text(audio_file)
    if "Error" in user_text or "sorry" in user_text:
        return user_text, None

    # Get chatbot response
    chatbot_reply = chatbot_response(user_text)

    # Convert chatbot reply to speech
    chatbot_audio = text_to_speech(chatbot_reply)

    return chatbot_reply, chatbot_audio

# Gradio Interface
interface = gr.Interface(
    fn=process_interaction,
    inputs=gr.Audio(source="microphone", type="filepath"),
    outputs=[gr.Textbox(label="Chatbot Reply"), gr.Audio(label="Chatbot Voice Reply")],
    title="Face-to-Face Chatbot",
    description="Talk to this chatbot like you're having a real conversation! Speak into your microphone to start.",
    live=True,
)

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