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 sentiment analysis model # 🔑 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. Sentiment Analysis Chatbot** st.subheader("🤖 AI Sentiment Analysis Chatbot") # Load Hugging Face sentiment analysis model (RoBERTa) sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment") # User input for chatbot user_prompt = st.text_input("Enter a text for sentiment analysis:") if st.button("Analyze Sentiment"): if user_prompt: try: # Perform sentiment analysis sentiment_result = sentiment_pipeline(user_prompt)[0] # Display sentiment results st.write("### Sentiment Analysis Result:") st.write(f"**Sentiment:** {sentiment_result['label']}") st.write(f"**Confidence Score:** {sentiment_result['score']:.4f}") # Fetch similar sentiment examples from MongoDB sentiment_label = sentiment_result["label"].lower() matching_texts = list(collection.find({"sentiment": sentiment_label}, {"_id": 0, "text": 1}).limit(3)) if matching_texts: st.write("### Similar Sentiment Examples from MongoDB:") for item in matching_texts: st.write(f"- {item['text']}") else: st.write("No similar sentiment examples found in MongoDB.") except Exception as e: st.error(f"❌ Error: {e}") else: st.warning("⚠️ Please enter some text.")