KrSharangrav commited on
Commit
bfd707a
Β·
1 Parent(s): b6af5ee

changed the sentiment logic

Browse files
Files changed (1) hide show
  1. app.py +32 -22
app.py CHANGED
@@ -4,7 +4,7 @@ import google.generativeai as genai # Import Generative AI library
4
  import os
5
  from pymongo import MongoClient
6
  from db import insert_data_if_empty, get_mongo_client # Import functions from db.py
7
- from transformers import pipeline # Import sentiment analysis pipeline
8
 
9
  # πŸ”‘ Fetch API key from Hugging Face Secrets
10
  GEMINI_API_KEY = os.getenv("gemini_api")
@@ -20,16 +20,8 @@ insert_data_if_empty()
20
  #### **2. MongoDB Connection**
21
  collection = get_mongo_client()
22
 
23
- #### **3. Load Sentiment Analysis Model**
24
- sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
25
-
26
- def analyze_sentiment(text):
27
- """Analyze sentiment using RoBERTa model."""
28
- sentiment_result = sentiment_pipeline(text)[0]['label']
29
- return sentiment_result # Returns "LABEL_0", "LABEL_1", or "LABEL_2"
30
-
31
- #### **4. Streamlit App to Display Data**
32
- st.title("πŸ“Š MongoDB Data Viewer with AI & Sentiment Analysis")
33
 
34
  # Show first 5 rows from MongoDB
35
  st.subheader("First 5 Rows from Database")
@@ -45,29 +37,47 @@ if st.button("Show Complete Data"):
45
  all_data = list(collection.find({}, {"_id": 0}))
46
  st.write(pd.DataFrame(all_data))
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  #### **5. AI Chatbot with Sentiment Analysis**
49
  st.subheader("πŸ€– AI Chatbot with Sentiment Analysis")
50
 
51
  # User input for chatbot
52
- user_prompt = st.text_input("Paste text here for AI sentiment analysis:")
53
 
54
- if st.button("Get AI Response & Sentiment"):
55
  if user_prompt:
56
  try:
57
- # Generate AI response
58
  model = genai.GenerativeModel("gemini-1.5-pro")
59
- response = model.generate_content(user_prompt)
60
- ai_response = response.text
61
 
62
- # Analyze sentiment
63
- sentiment = analyze_sentiment(ai_response)
64
 
65
- # Display results
66
  st.write("### AI Response:")
67
- st.write(ai_response)
68
- st.write(f"**Sentiment Analysis:** {sentiment}")
 
 
69
 
70
  except Exception as e:
71
  st.error(f"❌ Error: {e}")
72
  else:
73
- st.warning("⚠️ Please enter a text input.")
 
4
  import os
5
  from pymongo import MongoClient
6
  from db import insert_data_if_empty, get_mongo_client # Import functions from db.py
7
+ from transformers import pipeline # Import Hugging Face transformers for sentiment analysis
8
 
9
  # πŸ”‘ Fetch API key from Hugging Face Secrets
10
  GEMINI_API_KEY = os.getenv("gemini_api")
 
20
  #### **2. MongoDB Connection**
21
  collection = get_mongo_client()
22
 
23
+ #### **3. Streamlit App to Display Data**
24
+ st.title("πŸ“Š MongoDB Data Viewer with AI Sentiment Chatbot")
 
 
 
 
 
 
 
 
25
 
26
  # Show first 5 rows from MongoDB
27
  st.subheader("First 5 Rows from Database")
 
37
  all_data = list(collection.find({}, {"_id": 0}))
38
  st.write(pd.DataFrame(all_data))
39
 
40
+ #### **4. Load Sentiment Analysis Model (RoBERTa)**
41
+ sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
42
+
43
+ # Function to analyze sentiment
44
+ def analyze_sentiment(text):
45
+ sentiment_result = sentiment_pipeline(text)[0]
46
+ label = sentiment_result['label'] # Extract sentiment label (POSITIVE, NEGATIVE, NEUTRAL)
47
+ score = sentiment_result['score'] # Extract confidence score
48
+
49
+ # Convert labels to a readable format
50
+ sentiment_mapping = {
51
+ "LABEL_0": "Negative",
52
+ "LABEL_1": "Neutral",
53
+ "LABEL_2": "Positive"
54
+ }
55
+ return sentiment_mapping.get(label, "Unknown"), score
56
+
57
  #### **5. AI Chatbot with Sentiment Analysis**
58
  st.subheader("πŸ€– AI Chatbot with Sentiment Analysis")
59
 
60
  # User input for chatbot
61
+ user_prompt = st.text_area("Ask AI something or paste text for sentiment analysis:")
62
 
63
+ if st.button("Analyze Sentiment & Get AI Response"):
64
  if user_prompt:
65
  try:
66
+ # AI Response from Gemini
67
  model = genai.GenerativeModel("gemini-1.5-pro")
68
+ ai_response = model.generate_content(user_prompt)
 
69
 
70
+ # Sentiment Analysis
71
+ sentiment_label, confidence = analyze_sentiment(user_prompt)
72
 
73
+ # Display AI Response & Sentiment Analysis
74
  st.write("### AI Response:")
75
+ st.write(ai_response.text)
76
+
77
+ st.write("### Sentiment Analysis:")
78
+ st.write(f"**Sentiment:** {sentiment_label} ({confidence:.2f} confidence)")
79
 
80
  except Exception as e:
81
  st.error(f"❌ Error: {e}")
82
  else:
83
+ st.warning("⚠️ Please enter a question or text for sentiment analysis.")