Spaces:
Build error
Build error
Cody Jiang commited on
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import transformers
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
st.title("Sentiment Analysis App")
|
| 6 |
+
|
| 7 |
+
# Set default text
|
| 8 |
+
default_text = "Cody Jiang is a fantastic student in CS-UY-4613!"
|
| 9 |
+
|
| 10 |
+
# Select pretrained model
|
| 11 |
+
model_names = ['distilbert-base-uncased-finetuned-sst-2-english', 'bert-base-uncased', 'roberta-base', ]
|
| 12 |
+
model_name = st.selectbox("Select a pretrained model", model_names)
|
| 13 |
+
|
| 14 |
+
# Load selected model
|
| 15 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
|
| 16 |
+
model = transformers.AutoModelForSequenceClassification.from_pretrained(model_name)
|
| 17 |
+
|
| 18 |
+
# Set device
|
| 19 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
+
|
| 21 |
+
# Define sentiment labels
|
| 22 |
+
sentiment_labels = ['Negative', 'Positive']
|
| 23 |
+
|
| 24 |
+
# Analyze sentiment
|
| 25 |
+
if st.button("Submit"):
|
| 26 |
+
with st.spinner("Analyzing..."):
|
| 27 |
+
text = st.text_input("Enter text to analyze", default_text)
|
| 28 |
+
inputs = tokenizer(text, padding=True, truncation=True, return_tensors='pt')
|
| 29 |
+
inputs = inputs.to(device)
|
| 30 |
+
outputs = model(**inputs)
|
| 31 |
+
logits = outputs.logits
|
| 32 |
+
predictions = torch.argmax(logits, dim=1).cpu().numpy()
|
| 33 |
+
sentiment = sentiment_labels[predictions[0]]
|
| 34 |
+
|
| 35 |
+
st.success(f"Sentiment: {sentiment}")
|