aaronayitey's picture
Update app.py
48db237
import streamlit as st
import pandas as pd
from scipy.special import softmax
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
# Define the model path where the pre-trained model is saved on the Hugging Face model hub
model_path = "aaronayitey/Sentiment-classfication-ROBERTA-model"
# Initialize the tokenizer for the pre-trained model
tokenizer = AutoTokenizer.from_pretrained('roberta-base')
# Load the configuration for the pre-trained model
config = AutoConfig.from_pretrained(model_path)
# Load the pre-trained model
model = AutoModelForSequenceClassification.from_pretrained(model_path)
# Define a function to preprocess the text data
def preprocess(text):
new_text = []
# Replace user mentions with '@user'
for t in text.split(" "):
t = '@user' if t.startswith('@') and len(t) > 1 else t
# Replace links with 'http'
t = 'http' if t.startswith('http') else t
new_text.append(t)
# Join the preprocessed text
return " ".join(new_text)
# Define a function to perform sentiment analysis on the input text
def sentiment_analysis(text):
# Preprocess the input text
text = preprocess(text)
# Tokenize the input text using the pre-trained tokenizer
encoded_input = tokenizer(text, return_tensors='pt')
# Feed the tokenized input to the pre-trained model and obtain output
output = model(**encoded_input)
# Compute the softmax using torch
scores = torch.softmax(output.logits, dim=1)[0].tolist()
# Format the output dictionary with the predicted scores
labels = ['Negative', 'Neutral', 'Positive']
scores = {l: float(s) for (l, s) in zip(labels, scores)}
# Get the label with the highest score
max_score_label = max(scores, key=scores.get)
# Return the label with the highest score
return max_score_label
# Streamlit app title and description
st.title("Sentiment Analysis")
st.write("Enter a text, and we'll determine its sentiment!")
# Input text box for user input
user_input = st.text_area("Enter text here:")
# Button to analyze sentiment
if st.button("Analyze Sentiment"):
if user_input:
# Perform sentiment analysis on the user's input
sentiment_label = sentiment_analysis(user_input)
st.write(f"Sentiment: {sentiment_label}")
else:
st.warning("Please enter some text for sentiment analysis.")