Spaces:
Runtime error
Runtime error
File size: 1,686 Bytes
9fefb12 |
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 |
import streamlit as st
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
# Load the pretrained model and tokenizer
model_name = "distilbert-base-uncased-finetuned-sst-2-english" # Example model
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Set up the device (GPU or CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Function to perform sentiment analysis
def perform_sentiment_analysis(text):
inputs = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
inputs = inputs.to(device)
outputs = model(**inputs)
logits = outputs.logits
probabilities = torch.softmax(logits, dim=1).detach().cpu().numpy()[0]
sentiment_label = "Positive" if probabilities[1] > probabilities[0] else "Negative"
return sentiment_label, probabilities
# Streamlit app
def main():
st.title("Sentiment Analysis App")
st.write("Enter a text and select a pretrained model to perform sentiment analysis.")
text = st.text_area("Enter text", value="")
model_options = {
"distilbert-base-uncased-finetuned-sst-2-english": "DistilBERT (SST-2)",
# Add more models here if desired
}
selected_model = st.selectbox("Select a pretrained model", list(model_options.keys()))
if st.button("Analyze"):
sentiment_label, probabilities = perform_sentiment_analysis(text)
st.write(f"Sentiment: {sentiment_label}")
st.write(f"Positive probability: {probabilities[1]}")
st.write(f"Negative probability: {probabilities[0]}")
if __name__ == "__main__":
main()
|