File size: 2,403 Bytes
ba9baca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1244e3
 
b8fc6b8
b1244e3
 
 
ba9baca
 
b1244e3
 
 
 
006e4b1
b1244e3
006e4b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1244e3
006e4b1
 
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
import streamlit as st
import pandas as pd
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import matplotlib.pyplot as plt

# Load model and tokenizer
model_name = "tabularisai/multilingual-sentiment-analysis"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

def predict_sentiment(texts):
    inputs = tokenizer(texts, return_tensors="pt", truncation=True, padding=True, max_length=512)
    with torch.no_grad():
        outputs = model(**inputs)
    probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
    sentiment_map = {0: "Very Negative", 1: "Negative", 2: "Neutral", 3: "Positive", 4: "Very Positive"}
    return [sentiment_map[p] for p in torch.argmax(probabilities, dim=-1).tolist()]

# Streamlit UI
st.title("Sentiment Analysis App")
st.write("Analyze sentiment from uploaded text data.")

# Sidebar for File Upload
st.sidebar.header("Upload File")
uploaded_file = st.sidebar.file_uploader("Choose an Excel File", type=["xlsx", "xls"])

if uploaded_file is not None:
    df = pd.read_excel(uploaded_file, engine="openpyxl")  # Ensure openpyxl is installed
    st.sidebar.write("✅ File Uploaded Successfully!")
    
    text_column = st.sidebar.selectbox("Select Text Column", df.columns)

    if st.sidebar.button("Analyze Sentiment"):
        st.session_state.df = df  # Store dataframe in session state
        st.session_state.df["Sentiment"] = predict_sentiment(df[text_column].astype(str).tolist())
        st.session_state.analysis_done = True  # Set flag to indicate analysis is done

# Check if analysis is done and persist results
if "analysis_done" in st.session_state and st.session_state.analysis_done:
    df = st.session_state.df  # Retrieve dataframe from session state
    st.write("### Sentiment Analysis Results:")
    st.dataframe(df[[text_column, "Sentiment"]])
    
    # Pie chart
    sentiment_counts = df["Sentiment"].value_counts()
    fig, ax = plt.subplots()
    ax.pie(sentiment_counts, labels=sentiment_counts.index, autopct='%1.1f%%', colors=["red", "orange", "gray", "lightgreen", "green"])
    ax.set_title("Sentiment Distribution")
    st.pyplot(fig)

    # Download button (chart remains visible)
    st.sidebar.download_button("Download Results", df.to_csv(index=False).encode('utf-8'), "sentiment_results.csv", "text/csv")