Spaces:
Sleeping
Sleeping
KrSharangrav
commited on
Commit
Β·
7268351
1
Parent(s):
8799fb1
chatbot to changes
Browse files- app.py +38 -17
- chatbot.py +56 -20
- db.py +28 -19
app.py
CHANGED
@@ -1,24 +1,45 @@
|
|
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 |
-
|
7 |
-
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
mongo_data = get_mongo_data()
|
12 |
-
if mongo_data is not None:
|
13 |
-
st.dataframe(pd.DataFrame(mongo_data).head())
|
14 |
|
15 |
-
|
16 |
-
st.
|
17 |
-
user_input = st.text_input("Enter a tweet to analyze:")
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
else:
|
24 |
-
st.warning("Please enter a
|
|
|
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 functionality
|
5 |
|
6 |
+
#### **1. Ensure Data is Inserted Before Display**
|
7 |
+
insert_data_if_empty()
|
8 |
|
9 |
+
#### **2. MongoDB Connection**
|
10 |
+
collection = get_mongo_client()
|
|
|
|
|
|
|
11 |
|
12 |
+
#### **3. Streamlit App UI**
|
13 |
+
st.title("π MongoDB Data Viewer with AI Sentiment Chatbot")
|
|
|
14 |
|
15 |
+
# Show first 5 rows from MongoDB
|
16 |
+
st.subheader("First 5 Rows from Database")
|
17 |
+
data = list(collection.find({}, {"_id": 0}).limit(5))
|
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("β οΈ Please enter a question or text for sentiment analysis.")
|
chatbot.py
CHANGED
@@ -1,20 +1,56 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
"
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import streamlit as st
|
3 |
+
import google.generativeai as genai
|
4 |
+
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
|
5 |
+
|
6 |
+
# π Fetch API key from Hugging Face Secrets
|
7 |
+
GEMINI_API_KEY = os.getenv("gemini_api")
|
8 |
+
|
9 |
+
if GEMINI_API_KEY:
|
10 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
11 |
+
else:
|
12 |
+
st.error("β οΈ Google API key is missing! Set it in Hugging Face Secrets.")
|
13 |
+
|
14 |
+
# Correct Model Path
|
15 |
+
MODEL_NAME = "cardiffnlp/twitter-roberta-base-sentiment"
|
16 |
+
|
17 |
+
# Load Sentiment Analysis Model (Ensure the correct model is used)
|
18 |
+
try:
|
19 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
20 |
+
sentiment_pipeline = pipeline("sentiment-analysis", model=MODEL_NAME, tokenizer=tokenizer)
|
21 |
+
except Exception as e:
|
22 |
+
st.error(f"β Error loading sentiment model: {e}")
|
23 |
+
|
24 |
+
# Function to analyze sentiment
|
25 |
+
def analyze_sentiment(text):
|
26 |
+
try:
|
27 |
+
sentiment_result = sentiment_pipeline(text)[0]
|
28 |
+
label = sentiment_result['label'] # Extract sentiment label (POSITIVE, NEGATIVE, NEUTRAL)
|
29 |
+
score = sentiment_result['score'] # Extract confidence score
|
30 |
+
|
31 |
+
# Convert labels to readable format
|
32 |
+
sentiment_mapping = {
|
33 |
+
"LABEL_0": "Negative",
|
34 |
+
"LABEL_1": "Neutral",
|
35 |
+
"LABEL_2": "Positive"
|
36 |
+
}
|
37 |
+
return sentiment_mapping.get(label, "Unknown"), score
|
38 |
+
except Exception as e:
|
39 |
+
return f"Error analyzing sentiment: {e}", None
|
40 |
+
|
41 |
+
# Function to generate AI response & analyze sentiment
|
42 |
+
def chatbot_response(user_prompt):
|
43 |
+
if not user_prompt:
|
44 |
+
return None, None, None
|
45 |
+
|
46 |
+
try:
|
47 |
+
# AI Response from Gemini
|
48 |
+
model = genai.GenerativeModel("gemini-1.5-pro")
|
49 |
+
ai_response = model.generate_content(user_prompt)
|
50 |
+
|
51 |
+
# Sentiment Analysis
|
52 |
+
sentiment_label, confidence = analyze_sentiment(user_prompt)
|
53 |
+
|
54 |
+
return ai_response.text, sentiment_label, confidence
|
55 |
+
except Exception as e:
|
56 |
+
return f"β Error: {e}", None, None
|
db.py
CHANGED
@@ -1,21 +1,30 @@
|
|
1 |
-
import
|
2 |
-
import
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
def
|
6 |
-
|
7 |
-
|
8 |
-
|
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 |
-
|
17 |
-
|
18 |
-
collection =
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import requests
|
3 |
+
import io
|
4 |
+
from pymongo import MongoClient
|
5 |
|
6 |
+
#### **1. MongoDB Connection**
|
7 |
+
def get_mongo_client():
|
8 |
+
client = MongoClient("mongodb+srv://groupA:pythongroupA@sentimentcluster.4usfj.mongodb.net/?retryWrites=true&w=majority&appName=SentimentCluster")
|
9 |
+
db = client["sentiment_db"]
|
10 |
+
return db["tweets"]
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
#### **2. Insert Data If Collection is Empty**
|
13 |
+
def insert_data_if_empty():
|
14 |
+
collection = get_mongo_client()
|
15 |
+
|
16 |
+
if collection.count_documents({}) == 0:
|
17 |
+
print("π’ No data found. Inserting dataset...")
|
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}")
|