Spaces:
Sleeping
Sleeping
File size: 1,526 Bytes
b03e8ad |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
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
|