File size: 1,746 Bytes
78aa4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f6eb6d
78aa4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import torch
from transformers import RobertaTokenizer, RobertaForSequenceClassification

# Load model
model_name = "syedkhalid076/RoBERTa-Sentimental-Analysis-Model"
tokenizer = RobertaTokenizer.from_pretrained(model_name)
model = RobertaForSequenceClassification.from_pretrained(model_name)
model.eval()

# Function to predict sentiment for a single sentence
def predict_sentiment(sentence):
    inputs = tokenizer(sentence, return_tensors="pt", max_length=512, truncation=True)
    outputs = model(**inputs)
    logits = outputs.logits.detach().cpu().numpy()
    sentiment = "positive" if logits[0][1] > logits[0][0] else "negative"
    return sentiment

# Function to process CSV file and predict sentiment for each row
def process_csv(file):
    df = pd.read_csv(file)
    df['Sentiment'] = df['Text'].apply(predict_sentiment)
    return df

# Streamlit app
def main():
    st.title("Sentiment Analysis App")
    st.write("Write a sentence or upload a CSV file to analyze sentiment.")
    st.write("NOTE: If uploading a CSV file, please rename your column's name with the text/sentence to 'Text', where 'T' is in upper-case and the rest in lower-case")

    option = st.radio("Choose input type:", ("Write a sentence", "Upload a CSV file"))

    if option == "Write a sentence":
        sentence = st.text_input("Enter a sentence:")
        if st.button("Analyze"):
            sentiment = predict_sentiment(sentence)
            st.write("Sentiment:", sentiment)

    elif option == "Upload a CSV file":
        file = st.file_uploader("Upload CSV file", type=['csv'])
        if file is not None:
            df = process_csv(file)
            st.write(df)

if __name__ == '__main__':
    main()