Spaces:
Sleeping
Sleeping
KrSharangrav
commited on
Commit
Β·
8799fb1
1
Parent(s):
b03e8ad
chatbot changes
Browse files- app.py +17 -38
- chatbot.py +20 -46
- db.py +19 -28
app.py
CHANGED
@@ -1,45 +1,24 @@
|
|
1 |
import streamlit as st
|
|
|
|
|
2 |
import pandas as pd
|
3 |
-
from db import insert_data_if_empty, get_mongo_client
|
4 |
-
from chatbot import chatbot_response # Import chatbot function
|
5 |
|
6 |
-
|
7 |
-
|
8 |
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
11 |
|
12 |
-
|
13 |
-
st.
|
|
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
if data:
|
20 |
-
st.write(pd.DataFrame(data))
|
21 |
-
else:
|
22 |
-
st.warning("β οΈ No data found. Try refreshing the app.")
|
23 |
-
|
24 |
-
# Button to show full MongoDB data
|
25 |
-
if st.button("Show Complete Data"):
|
26 |
-
all_data = list(collection.find({}, {"_id": 0}))
|
27 |
-
st.write(pd.DataFrame(all_data))
|
28 |
-
|
29 |
-
#### **4. AI Chatbot with Sentiment Analysis**
|
30 |
-
st.subheader("π€ AI Chatbot with Sentiment Analysis")
|
31 |
-
|
32 |
-
# User input for chatbot
|
33 |
-
user_prompt = st.text_area("Ask AI something or paste text for sentiment analysis:")
|
34 |
-
|
35 |
-
if st.button("Analyze Sentiment & Get AI Response"):
|
36 |
-
ai_response, sentiment_label, confidence = chatbot_response(user_prompt)
|
37 |
-
|
38 |
-
if ai_response:
|
39 |
-
st.write("### AI Response:")
|
40 |
-
st.write(ai_response)
|
41 |
-
|
42 |
-
st.write("### Sentiment Analysis:")
|
43 |
-
st.write(f"**Sentiment:** {sentiment_label} ({confidence:.2f} confidence)")
|
44 |
else:
|
45 |
-
st.warning("
|
|
|
1 |
import streamlit as st
|
2 |
+
from chatbot import chatbot_response
|
3 |
+
from db import get_mongo_data
|
4 |
import pandas as pd
|
|
|
|
|
5 |
|
6 |
+
# Streamlit UI
|
7 |
+
st.title("Twitter Sentiment Analysis Chatbot")
|
8 |
|
9 |
+
# Display MongoDB Data
|
10 |
+
st.subheader("MongoDB Data (First 5 Rows)")
|
11 |
+
mongo_data = get_mongo_data()
|
12 |
+
if mongo_data is not None:
|
13 |
+
st.dataframe(pd.DataFrame(mongo_data).head())
|
14 |
|
15 |
+
# Chatbot Input
|
16 |
+
st.subheader("Chat with the Sentiment Analysis Bot")
|
17 |
+
user_input = st.text_input("Enter a tweet to analyze:")
|
18 |
|
19 |
+
if st.button("Analyze"):
|
20 |
+
if user_input:
|
21 |
+
response = chatbot_response(user_input)
|
22 |
+
st.write("**Sentiment Analysis Result:**", response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
else:
|
24 |
+
st.warning("Please enter a tweet.")
|
chatbot.py
CHANGED
@@ -1,46 +1,20 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
score = sentiment_result['score'] # Extract confidence score
|
22 |
-
|
23 |
-
# Convert labels to a readable format
|
24 |
-
sentiment_mapping = {
|
25 |
-
"LABEL_0": "Negative",
|
26 |
-
"LABEL_1": "Neutral",
|
27 |
-
"LABEL_2": "Positive"
|
28 |
-
}
|
29 |
-
return sentiment_mapping.get(label, "Unknown"), score
|
30 |
-
|
31 |
-
# Function to generate AI response & analyze sentiment
|
32 |
-
def chatbot_response(user_prompt):
|
33 |
-
if not user_prompt:
|
34 |
-
return None, None, None
|
35 |
-
|
36 |
-
try:
|
37 |
-
# AI Response from Gemini
|
38 |
-
model = genai.GenerativeModel("gemini-1.5-pro")
|
39 |
-
ai_response = model.generate_content(user_prompt)
|
40 |
-
|
41 |
-
# Sentiment Analysis
|
42 |
-
sentiment_label, confidence = analyze_sentiment(user_prompt)
|
43 |
-
|
44 |
-
return ai_response.text, sentiment_label, confidence
|
45 |
-
except Exception as e:
|
46 |
-
return f"β Error: {e}", None, None
|
|
|
1 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
|
2 |
+
|
3 |
+
# Load model and tokenizer
|
4 |
+
model_path = "./model" # Load from local directory to avoid connection issues
|
5 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_path)
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
7 |
+
|
8 |
+
# Define sentiment analysis pipeline
|
9 |
+
sentiment_analyzer = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
|
10 |
+
|
11 |
+
def chatbot_response(text):
|
12 |
+
"""Analyze sentiment using RoBERTa model."""
|
13 |
+
if not text.strip():
|
14 |
+
return "Invalid input. Please enter text."
|
15 |
+
|
16 |
+
result = sentiment_analyzer(text)[0]
|
17 |
+
label = result["label"]
|
18 |
+
score = round(result["score"], 2)
|
19 |
+
|
20 |
+
return f"{label} (Confidence: {score})"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
db.py
CHANGED
@@ -1,30 +1,21 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import io
|
4 |
-
from pymongo import MongoClient
|
5 |
|
6 |
-
|
7 |
-
def
|
8 |
-
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
collection =
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
csv_url = "https://huggingface.co/spaces/sharangrav24/SentimentAnalysis/resolve/main/sentiment140.csv"
|
20 |
-
|
21 |
-
try:
|
22 |
-
response = requests.get(csv_url)
|
23 |
-
response.raise_for_status() # Ensure request was successful
|
24 |
-
df = pd.read_csv(io.StringIO(response.text), encoding="ISO-8859-1")
|
25 |
-
|
26 |
-
# Insert into MongoDB
|
27 |
-
collection.insert_many(df.to_dict("records"))
|
28 |
-
print("β
Data Inserted into MongoDB!")
|
29 |
-
except Exception as e:
|
30 |
-
print(f"β Error loading dataset: {e}")
|
|
|
1 |
+
import pymongo
|
2 |
+
import streamlit as st
|
|
|
|
|
3 |
|
4 |
+
# MongoDB Connection
|
5 |
+
def get_mongo_connection():
|
6 |
+
"""Establish connection to MongoDB."""
|
7 |
+
try:
|
8 |
+
client = pymongo.MongoClient(st.secrets["mongo_uri"])
|
9 |
+
db = client["twitter_db"]
|
10 |
+
collection = db["sentiments"]
|
11 |
+
return collection
|
12 |
+
except Exception as e:
|
13 |
+
st.error(f"MongoDB connection error: {e}")
|
14 |
+
return None
|
15 |
|
16 |
+
def get_mongo_data():
|
17 |
+
"""Fetch first 5 rows from MongoDB collection."""
|
18 |
+
collection = get_mongo_connection()
|
19 |
+
if collection:
|
20 |
+
return list(collection.find({}, {"_id": 0}).limit(5))
|
21 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|