Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,128 +5,40 @@ import numpy as np
|
|
| 5 |
from gtts import gTTS
|
| 6 |
import os
|
| 7 |
import datetime
|
|
|
|
| 8 |
from sklearn.feature_extraction.text import CountVectorizer
|
| 9 |
from sklearn.preprocessing import LabelEncoder
|
| 10 |
from sklearn.naive_bayes import MultinomialNB
|
| 11 |
from nltk.stem import PorterStemmer
|
| 12 |
from textblob import TextBlob
|
| 13 |
import gradio as gr
|
| 14 |
-
from pydub import AudioSegment
|
| 15 |
import speech_recognition as sr
|
| 16 |
|
| 17 |
-
# Download
|
| 18 |
nltk.download('punkt')
|
| 19 |
|
| 20 |
-
# Load intents
|
| 21 |
with open('intents.json') as file:
|
| 22 |
intents = json.load(file)
|
| 23 |
|
|
|
|
| 24 |
stemmer = PorterStemmer()
|
| 25 |
all_words = []
|
| 26 |
tags = []
|
| 27 |
xy = []
|
| 28 |
|
| 29 |
-
#
|
| 30 |
for intent in intents["intents"]:
|
| 31 |
tag = intent["tag"]
|
| 32 |
tags.append(tag)
|
| 33 |
for pattern in intent["patterns"]:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
all_words.extend(
|
| 37 |
-
xy.append((" ".join(
|
| 38 |
|
|
|
|
| 39 |
vectorizer = CountVectorizer()
|
| 40 |
-
|
| 41 |
-
X = vectorizer.fit_transform(X_texts)
|
| 42 |
|
| 43 |
-
encoder = LabelEncoder()
|
| 44 |
-
y = encoder.fit_transform([x[1] for x in xy])
|
| 45 |
|
| 46 |
-
model = MultinomialNB()
|
| 47 |
-
model.fit(X, y)
|
| 48 |
-
|
| 49 |
-
# Memory for context (last 3 exchanges)
|
| 50 |
-
conversation_memory = []
|
| 51 |
-
|
| 52 |
-
def chatbot_response(user_input):
|
| 53 |
-
user_input_tokens = nltk.word_tokenize(user_input)
|
| 54 |
-
user_input_stemmed = [stemmer.stem(word.lower()) for word in user_input_tokens]
|
| 55 |
-
input_data = " ".join(user_input_stemmed)
|
| 56 |
-
input_vector = vectorizer.transform([input_data])
|
| 57 |
-
|
| 58 |
-
probs = model.predict_proba(input_vector)[0]
|
| 59 |
-
prediction = np.argmax(probs)
|
| 60 |
-
confidence = probs[prediction]
|
| 61 |
-
tag = encoder.inverse_transform([prediction])[0]
|
| 62 |
-
|
| 63 |
-
for intent in intents["intents"]:
|
| 64 |
-
if intent["tag"] == tag:
|
| 65 |
-
response = random.choice(intent["responses"])
|
| 66 |
-
|
| 67 |
-
# Sentiment analysis
|
| 68 |
-
sentiment = TextBlob(user_input).sentiment.polarity
|
| 69 |
-
if sentiment > 0.3:
|
| 70 |
-
response += " 😊"
|
| 71 |
-
elif sentiment < -0.3:
|
| 72 |
-
response += " I'm here for you. 😟"
|
| 73 |
-
|
| 74 |
-
# Store context memory
|
| 75 |
-
conversation_memory.append((user_input, response))
|
| 76 |
-
if len(conversation_memory) > 3:
|
| 77 |
-
conversation_memory.pop(0)
|
| 78 |
-
|
| 79 |
-
# Logging
|
| 80 |
-
with open("chat_log.txt", "a") as log:
|
| 81 |
-
log.write(f"{datetime.datetime.now()} - USER: {user_input}\nBOT: {response}\n")
|
| 82 |
-
|
| 83 |
-
return f"{response} (Confidence: {confidence:.2f})"
|
| 84 |
-
|
| 85 |
-
return "I'm not sure how to respond to that."
|
| 86 |
-
|
| 87 |
-
def gradio_chat(audio_input, text_input):
|
| 88 |
-
user_input = ""
|
| 89 |
-
|
| 90 |
-
# Convert audio to text
|
| 91 |
-
if audio_input is not None:
|
| 92 |
-
recognizer = sr.Recognizer()
|
| 93 |
-
try:
|
| 94 |
-
with sr.AudioFile(audio_input) as source:
|
| 95 |
-
audio_data = recognizer.record(source)
|
| 96 |
-
user_input = recognizer.recognize_google(audio_data)
|
| 97 |
-
except Exception as e:
|
| 98 |
-
return f"Audio error: {str(e)}", None
|
| 99 |
-
|
| 100 |
-
# Use typed text if available
|
| 101 |
-
if text_input:
|
| 102 |
-
user_input = text_input
|
| 103 |
-
|
| 104 |
-
if user_input.strip() == "":
|
| 105 |
-
return "Please say or type something meaningful.", None
|
| 106 |
-
|
| 107 |
-
response = chatbot_response(user_input)
|
| 108 |
-
|
| 109 |
-
# Text to speech
|
| 110 |
-
tts = gTTS(response)
|
| 111 |
-
response_audio_path = "response.mp3"
|
| 112 |
-
tts.save(response_audio_path)
|
| 113 |
-
|
| 114 |
-
return response, response_audio_path
|
| 115 |
-
|
| 116 |
-
# Gradio Interface
|
| 117 |
-
interface = gr.Interface(
|
| 118 |
-
fn=gradio_chat,
|
| 119 |
-
inputs=[
|
| 120 |
-
gr.Audio(type="filepath", label="Speak (Voice Input)"),
|
| 121 |
-
gr.Textbox(label="Or Type Your Message (Text Input)")
|
| 122 |
-
],
|
| 123 |
-
outputs=[
|
| 124 |
-
gr.Textbox(label="Bot Response"),
|
| 125 |
-
gr.Audio(label="Bot Voice Response")
|
| 126 |
-
],
|
| 127 |
-
title="ML Voice and Text Chatbot",
|
| 128 |
-
description="Talk to the chatbot using your voice or text. Now with memory, sentiment analysis, and better feedback!",
|
| 129 |
-
examples=[[None, "Hello"], [None, "I'm sad"], [None, "Thank you"]]
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
interface.launch(share=True)
|
|
|
|
| 5 |
from gtts import gTTS
|
| 6 |
import os
|
| 7 |
import datetime
|
| 8 |
+
import tempfile
|
| 9 |
from sklearn.feature_extraction.text import CountVectorizer
|
| 10 |
from sklearn.preprocessing import LabelEncoder
|
| 11 |
from sklearn.naive_bayes import MultinomialNB
|
| 12 |
from nltk.stem import PorterStemmer
|
| 13 |
from textblob import TextBlob
|
| 14 |
import gradio as gr
|
|
|
|
| 15 |
import speech_recognition as sr
|
| 16 |
|
| 17 |
+
# Download required NLTK data
|
| 18 |
nltk.download('punkt')
|
| 19 |
|
| 20 |
+
# Load intents JSON
|
| 21 |
with open('intents.json') as file:
|
| 22 |
intents = json.load(file)
|
| 23 |
|
| 24 |
+
# Preprocessing setup
|
| 25 |
stemmer = PorterStemmer()
|
| 26 |
all_words = []
|
| 27 |
tags = []
|
| 28 |
xy = []
|
| 29 |
|
| 30 |
+
# Extract and stem words from patterns
|
| 31 |
for intent in intents["intents"]:
|
| 32 |
tag = intent["tag"]
|
| 33 |
tags.append(tag)
|
| 34 |
for pattern in intent["patterns"]:
|
| 35 |
+
words = nltk.word_tokenize(pattern)
|
| 36 |
+
stemmed_words = [stemmer.stem(w.lower()) for w in words]
|
| 37 |
+
all_words.extend(stemmed_words)
|
| 38 |
+
xy.append((" ".join(stemmed_words), tag))
|
| 39 |
|
| 40 |
+
# Feature extraction
|
| 41 |
vectorizer = CountVectorizer()
|
| 42 |
+
X = vectorizer.fit_transform([x[0] for x in x]()_
|
|
|
|
| 43 |
|
|
|
|
|
|
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|