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

chatbot to changes

Browse files
Files changed (3) hide show
  1. app.py +38 -17
  2. chatbot.py +56 -20
  3. 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
- # 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.")
 
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
- 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})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}")