File size: 3,036 Bytes
5ceef28
bacd746
5ceef28
 
 
 
 
5687191
5ceef28
 
 
 
 
 
bacd746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
import streamlit as st
import pandas as pd
from transformers import pipeline

# Load the sentiment analysis pipeline
@st.cache_resource  # Cache the pipeline for faster loading
def load_pipeline():
    return pipeline("sentiment-analysis", model="distilbert-base-uncased", framework="pt")

sentiment_pipeline = load_pipeline()

# Streamlit app
st.title("Sentiment Analysis Tool")

# Input option: Text area or CSV file
input_option = st.radio("Choose input method:", ("Text Area", "CSV File"))

if input_option == "Text Area":
    # User input (Text Area)
    text = st.text_area("Enter text to analyze:", "This is a great movie!")

    # Analyze button
    if st.button("Analyze Text"):
        if text:
            with st.spinner("Analyzing..."):
                result = sentiment_pipeline(text)[0]  # Get the first (and only) result
            st.write("Sentiment:", result['label'])
            st.write("Confidence:", result['score'])
        else:
            st.warning("Please enter some text to analyze.")

elif input_option == "CSV File":
    # CSV File Upload
    uploaded_file = st.file_uploader("Upload a CSV file", type="csv")

    if uploaded_file is not None:
        try:
            df = pd.read_csv(uploaded_file)
            st.write("Preview of the CSV file:")
            st.dataframe(df.head())  # Display the first few rows

            # Column selection
            text_column = st.selectbox("Select the column containing the text:", df.columns)

            # Analyze button
            if st.button("Analyze CSV"):
                if text_column:
                    with st.spinner("Analyzing..."):
                        # Perform sentiment analysis on each row
                        results = []
                        for index, row in df.iterrows():
                            text = row[text_column]
                            try:
                                result = sentiment_pipeline(text)[0]
                                results.append({"text": text, "sentiment": result['label'], "confidence": result['score']})
                            except Exception as e:
                                results.append({"text": text, "sentiment": "Error", "confidence": 0.0, "error": str(e)}) #append error to text column
                        results_df = pd.DataFrame(results)
                        st.write("Sentiment Analysis Results:")
                        st.dataframe(results_df)

                        # Download the results as CSV
                        csv = results_df.to_csv(index=False).encode('utf-8')
                        st.download_button(
                            label="Download results as CSV",
                            data=csv,
                            file_name="sentiment_analysis_results.csv",
                            mime='text/csv',
                        )

                else:
                    st.warning("Please select the text column.")

        except Exception as e:
            st.error(f"Error reading the CSV file: {e}")