File size: 1,919 Bytes
f25fa78
 
 
 
4b0f6e2
f25fa78
0d352fa
f25fa78
 
 
 
 
 
 
48e0702
f25fa78
 
4b0f6e2
 
61a5fad
 
 
 
 
 
 
 
4b0f6e2
4689429
 
61a5fad
4b0f6e2
 
 
61a5fad
 
4b0f6e2
61a5fad
4b0f6e2
 
4689429
 
4b0f6e2
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import matplotlib.pyplot as plt
import numpy as np

@st.cache_resource
def load_model():
    tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
    model = AutoModelForSequenceClassification.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
    return tokenizer, model

tokenizer, model = load_model()

st.title("Sentiment Analysis App")

text = st.text_input("Enter text to analyze:")
threshold = st.slider("Set sentiment strength threshold:", 0.0, 1.0, 0.5, 0.01)

if st.button("Analyze") and text:
    encoding = tokenizer.encode_plus(text, return_tensors="pt", padding=True, truncation=True)
    input_ids = encoding["input_ids"]
    attention_mask = encoding["attention_mask"]

    with torch.no_grad():
        output = model(input_ids, attention_mask)
    logits = output.logits.squeeze()

    num_classes = logits.shape[0]
    sentiments = ["Very Negative", "Negative", "Neutral", "Positive", "Very Positive"][:num_classes]

    softmax = torch.nn.Softmax(dim=0)
    probabilities = softmax(logits).numpy()

    prediction = int(torch.argmax(logits))
    sentiment = sentiments[prediction]
    st.write(f"Detected Sentiment: {sentiment}")

    # Normalize scores for display
    values = probabilities.tolist()

    fig, ax = plt.subplots()
    colors = plt.cm.coolwarm(np.linspace(0, 1, num_classes))
    bars = ax.bar(sentiments, values, color=colors)

    # Highlight bars that pass the threshold
    for bar, value in zip(bars, values):
        if value > threshold:
            bar.set_alpha(1.0)  # Solid color for high confidence
        else:
            bar.set_alpha(0.5)  # Faded color for low confidence

    ax.set_title("Sentiment Analysis Scores with Confidence Threshold")
    ax.set_ylabel("Confidence")
    st.pyplot(fig)