File size: 2,463 Bytes
7268351
 
 
 
f763dd0
7268351
 
 
 
 
 
 
 
 
 
 
 
f763dd0
7268351
 
 
 
 
 
f763dd0
 
 
7268351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f763dd0
 
 
 
 
 
 
 
 
7268351
 
f763dd0
7268351
 
 
 
 
 
 
 
 
f763dd0
 
 
 
7268351
f763dd0
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import streamlit as st
import google.generativeai as genai
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
from keybert import KeyBERT  # Topic Extraction

# 🔑 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.")

# Correct Model Path
MODEL_NAME = "cardiffnlp/twitter-roberta-base-sentiment"

# Load Sentiment Analysis Model
try:
    tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
    sentiment_pipeline = pipeline("sentiment-analysis", model=MODEL_NAME, tokenizer=tokenizer)
except Exception as e:
    st.error(f"❌ Error loading sentiment model: {e}")

# Load KeyBERT for topic extraction
kw_model = KeyBERT()

# Function to analyze sentiment
def analyze_sentiment(text):
    try:
        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 readable format
        sentiment_mapping = {
            "LABEL_0": "Negative",
            "LABEL_1": "Neutral",
            "LABEL_2": "Positive"
        }
        return sentiment_mapping.get(label, "Unknown"), score
    except Exception as e:
        return f"Error analyzing sentiment: {e}", None

# Function to extract key topics
def extract_topics(text, num_keywords=3):
    try:
        keywords = kw_model.extract_keywords(text, keyphrase_ngram_range=(1, 2), top_n=num_keywords)
        return [word[0] for word in keywords]  # Return only the keywords
    except Exception as e:
        return [f"Error extracting topics: {e}"]

# Function to generate AI response, analyze sentiment, and extract topics
def chatbot_response(user_prompt):
    if not user_prompt:
        return None, 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)

        # Topic Extraction
        topics = extract_topics(user_prompt)

        return ai_response.text, sentiment_label, confidence, topics
    except Exception as e:
        return f"❌ Error: {e}", None, None, None