SentimentAnalysis / chatbot.py
KrSharangrav
chatbot.py push
b03e8ad
raw
history blame
1.53 kB
import streamlit as st
import google.generativeai as genai
from transformers import pipeline
import os
# πŸ”‘ 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.")
# 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
# Function to generate AI response & analyze sentiment
def chatbot_response(user_prompt):
if not user_prompt:
return None, None, None
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)
return ai_response.text, sentiment_label, confidence
except Exception as e:
return f"❌ Error: {e}", None, None