Spaces:
Sleeping
Sleeping
File size: 2,575 Bytes
0f054ff | 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | import random
import json
import re
import numpy as np
from gtts import gTTS
import tempfile
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import MultinomialNB
from nltk.stem import PorterStemmer
import gradio as gr
# Load intents
with open('intents.json') as file:
intents = json.load(file)
# Initialize tools
stemmer = PorterStemmer()
all_words = []
tags = []
xy = []
# Custom tokenizer using regex
def simple_tokenize(text):
return re.findall(r'\b\w+\b', text.lower())
# Preprocessing
for intent in intents["intents"]:
tag = intent["tag"]
if tag not in tags:
tags.append(tag)
for pattern in intent["patterns"]:
words = simple_tokenize(pattern)
stemmed_words = [stemmer.stem(w) for w in words]
all_words.extend(stemmed_words)
xy.append((" ".join(stemmed_words), tag))
# Feature extraction
vectorizer = CountVectorizer()
X = vectorizer.fit_transform([item[0] for item in xy])
# Label encoding
label_encoder = LabelEncoder()
y = label_encoder.fit_transform([item[1] for item in xy])
# Model training
model = MultinomialNB()
model.fit(X, y)
# Chatbot response function
def chatbot_response(user_input):
if not user_input.strip():
return "Please type something...", None
words = simple_tokenize(user_input)
stemmed_input = " ".join([stemmer.stem(w) for w in words])
input_vec = vectorizer.transform([stemmed_input])
predicted_label = model.predict(input_vec)[0]
tag = label_encoder.inverse_transform([predicted_label])[0]
response = "I'm sorry, I didn't understand that."
for intent in intents["intents"]:
if intent["tag"] == tag:
response = random.choice(intent["responses"])
break
try:
tts = gTTS(text=response, lang='en')
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
tts.save(fp.name)
audio_path = fp.name
except Exception as e:
print("TTS error:", e)
audio_path = None
return response, audio_path
# Gradio interface
chat_interface = gr.Interface(
fn=chatbot_response,
inputs=gr.Textbox(lines=2, placeholder="Type your message..."),
outputs=[
gr.Textbox(label="Chatbot Response"),
gr.Audio(label="Voice Reply", type="filepath")
],
title="🤖 Chatbot with Voice Output",
description="Type a message and hear the chatbot's reply as audio."
)
# Launch app
if __name__ == "__main__":
chat_interface.launch()
|