KrSharangrav commited on
Commit
8799fb1
Β·
1 Parent(s): b03e8ad

chatbot changes

Browse files
Files changed (3) hide show
  1. app.py +17 -38
  2. chatbot.py +20 -46
  3. 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
- #### **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 to Display Data**
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.")
 
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 streamlit as st
2
- import google.generativeai as genai
3
- from transformers import pipeline
4
- import os
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
- # Load Sentiment Analysis Model (RoBERTa)
15
- sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
16
-
17
- # Function to analyze sentiment
18
- def analyze_sentiment(text):
19
- sentiment_result = sentiment_pipeline(text)[0]
20
- label = sentiment_result['label'] # Extract sentiment label (POSITIVE, NEGATIVE, NEUTRAL)
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 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}")
 
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