Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
|
| 6 |
+
# Initialize tokenizer and model once to avoid reloading them on every interaction
|
| 7 |
+
@st.cache(allow_output_mutation=True)
|
| 8 |
+
def load_model():
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
|
| 10 |
+
model = AutoModelForSequenceClassification.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
|
| 11 |
+
return tokenizer, model
|
| 12 |
+
|
| 13 |
+
tokenizer, model = load_model()
|
| 14 |
+
|
| 15 |
+
st.title("Sentiment Analysis App")
|
| 16 |
+
|
| 17 |
+
text = st.text_input("Enter text to analyze:")
|
| 18 |
+
if st.button("Analyze"):
|
| 19 |
+
encoding = tokenizer.encode_plus(text, return_tensors="pt", padding=True, truncation=True)
|
| 20 |
+
input_ids = encoding["input_ids"]
|
| 21 |
+
attention_mask = encoding["attention_mask"]
|
| 22 |
+
|
| 23 |
+
with torch.no_grad():
|
| 24 |
+
output = model(input_ids, attention_mask)
|
| 25 |
+
prediction = int(torch.argmax(output.logits))
|
| 26 |
+
|
| 27 |
+
# Detailed sentiment output
|
| 28 |
+
sentiment = ["Negative", "Neutral", "Positive"][prediction]
|
| 29 |
+
st.write(f"Sentiment: {sentiment}")
|
| 30 |
+
|
| 31 |
+
values = output.logits.squeeze().tolist() # Flatten the logits tensor to a list
|
| 32 |
+
labels = ["Negative", "Neutral", "Positive"]
|
| 33 |
+
|
| 34 |
+
# Plotting
|
| 35 |
+
fig, ax = plt.subplots()
|
| 36 |
+
ax.bar(labels, values, color=['red', 'blue', 'green'])
|
| 37 |
+
ax.set_title("Sentiment Analysis Scores")
|
| 38 |
+
ax.set_ylabel("Score")
|
| 39 |
+
st.pyplot(fig)
|