Spaces:
Runtime error
Runtime error
ivybm
commited on
Commit
·
9fefb12
1
Parent(s):
2b82f9a
Add streamlit app
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# Load the pretrained model and tokenizer
|
| 6 |
+
model_name = "distilbert-base-uncased-finetuned-sst-2-english" # Example model
|
| 7 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 9 |
+
|
| 10 |
+
# Set up the device (GPU or CPU)
|
| 11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
+
|
| 13 |
+
# Function to perform sentiment analysis
|
| 14 |
+
def perform_sentiment_analysis(text):
|
| 15 |
+
inputs = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
|
| 16 |
+
inputs = inputs.to(device)
|
| 17 |
+
outputs = model(**inputs)
|
| 18 |
+
logits = outputs.logits
|
| 19 |
+
probabilities = torch.softmax(logits, dim=1).detach().cpu().numpy()[0]
|
| 20 |
+
sentiment_label = "Positive" if probabilities[1] > probabilities[0] else "Negative"
|
| 21 |
+
return sentiment_label, probabilities
|
| 22 |
+
|
| 23 |
+
# Streamlit app
|
| 24 |
+
def main():
|
| 25 |
+
st.title("Sentiment Analysis App")
|
| 26 |
+
st.write("Enter a text and select a pretrained model to perform sentiment analysis.")
|
| 27 |
+
|
| 28 |
+
text = st.text_area("Enter text", value="")
|
| 29 |
+
|
| 30 |
+
model_options = {
|
| 31 |
+
"distilbert-base-uncased-finetuned-sst-2-english": "DistilBERT (SST-2)",
|
| 32 |
+
# Add more models here if desired
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
selected_model = st.selectbox("Select a pretrained model", list(model_options.keys()))
|
| 36 |
+
|
| 37 |
+
if st.button("Analyze"):
|
| 38 |
+
sentiment_label, probabilities = perform_sentiment_analysis(text)
|
| 39 |
+
st.write(f"Sentiment: {sentiment_label}")
|
| 40 |
+
st.write(f"Positive probability: {probabilities[1]}")
|
| 41 |
+
st.write(f"Negative probability: {probabilities[0]}")
|
| 42 |
+
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
main()
|