SentimentAnalysis / backup.py
KrSharangrav
chatbot.py push
b03e8ad
raw
history blame
2.9 kB
import streamlit as st
import pandas as pd
import google.generativeai as genai # Import Generative AI library
import os
from pymongo import MongoClient
from db import insert_data_if_empty, get_mongo_client # Import functions from db.py
from transformers import pipeline # Import Hugging Face transformers for sentiment analysis
# πŸ”‘ Fetch API key from Hugging Face Secrets
GEMINI_API_KEY = os.getenv("gemini_api")
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
else:
st.error("⚠️ Google API key is missing! Set it in Hugging Face Secrets.")
#### **1. Ensure Data is Inserted Before Display**
insert_data_if_empty()
#### **2. MongoDB Connection**
collection = get_mongo_client()
#### **3. Streamlit App to Display Data**
st.title("πŸ“Š MongoDB Data Viewer with AI Sentiment Chatbot")
# Show first 5 rows from MongoDB
#st.subheader("First 5 Rows from Database")
#data = list(collection.find({}, {"_id": 0}).limit(5))
#if data:
# st.write(pd.DataFrame(data))
#else:
# st.warning("⚠️ No data found. Try refreshing the app.")
# Button to show full MongoDB data
#if st.button("Show Complete Data"):
# all_data = list(collection.find({}, {"_id": 0}))
# st.write(pd.DataFrame(all_data))
#### **4. Load Sentiment Analysis Model (RoBERTa)**
sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
# Function to analyze sentiment
def analyze_sentiment(text):
sentiment_result = sentiment_pipeline(text)[0]
label = sentiment_result['label'] # Extract sentiment label (POSITIVE, NEGATIVE, NEUTRAL)
score = sentiment_result['score'] # Extract confidence score
# Convert labels to a readable format
sentiment_mapping = {
"LABEL_0": "Negative",
"LABEL_1": "Neutral",
"LABEL_2": "Positive"
}
return sentiment_mapping.get(label, "Unknown"), score
#### **5. AI Chatbot with Sentiment Analysis**
st.subheader("πŸ€– AI Chatbot with Sentiment Analysis")
# User input for chatbot
user_prompt = st.text_area("Ask AI something or paste text for sentiment analysis:")
if st.button("Analyze Sentiment & Get AI Response"):
if user_prompt:
try:
# AI Response from Gemini
model = genai.GenerativeModel("gemini-1.5-pro")
ai_response = model.generate_content(user_prompt)
# Sentiment Analysis
sentiment_label, confidence = analyze_sentiment(user_prompt)
# Display AI Response & Sentiment Analysis
st.write("### AI Response:")
st.write(ai_response.text)
st.write("### Sentiment Analysis:")
st.write(f"**Sentiment:** {sentiment_label} ({confidence:.2f} confidence)")
except Exception as e:
st.error(f"❌ Error: {e}")
else:
st.warning("⚠️ Please enter a question or text for sentiment analysis.")