File size: 2,097 Bytes
78aa4a9 18fbfdd 78aa4a9 2628f29 78aa4a9 2628f29 78aa4a9 2628f29 78aa4a9 2628f29 78aa4a9 2628f29 78aa4a9 2628f29 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 49 50 51 52 53 54 55 56 57 58 59 |
import streamlit as st
import pandas as pd
import torch
from transformers import RobertaTokenizer, RobertaForSequenceClassification
# Load model
model_name = "syedkhalid076/RoBERTa-Sentimental-Analysis-v2"
tokenizer = RobertaTokenizer.from_pretrained(model_name)
model = RobertaForSequenceClassification.from_pretrained(model_name)
model.eval()
# Define sentiment labels
sentiment_labels = {0: "Negative", 1: "Neutral", 2: "Positive"}
# 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()
predicted_class = torch.argmax(logits, dim=-1).item()
sentiment = sentiment_labels[predicted_class]
return sentiment
# Function to process CSV file and predict sentiment for each row
def process_csv(file):
df = pd.read_csv(file)
if 'Text' not in df.columns:
st.error("CSV file must have a 'Text' column with sentences for analysis.")
return None
df['sentiment'] = df['text'].apply(predict_sentiment)
return df
# Streamlit app
def main():
st.title("Sentiment Analysis App")
st.write("Analyze text sentiment as Negative, Neutral, or Positive.")
st.write("NOTE: If uploading a CSV file, ensure the column containing text is named 'text' (case-sensitive).")
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"):
if sentence.strip():
sentiment = predict_sentiment(sentence)
st.write("Sentiment:", sentiment)
else:
st.warning("Please enter a valid sentence.")
elif option == "Upload a CSV file":
file = st.file_uploader("Upload CSV file", type=['csv'])
if file is not None:
df = process_csv(file)
if df is not None:
st.write(df)
if __name__ == '__main__':
main()
|