Add application file
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.special import softmax
|
| 5 |
+
|
| 6 |
+
def preprocess(text):
|
| 7 |
+
new_text = []
|
| 8 |
+
for t in text.split(" "):
|
| 9 |
+
t = '@user' if t.startswith('@') and len(t) > 1 else t
|
| 10 |
+
t = 'http' if t.startswith('http') else t
|
| 11 |
+
new_text.append(t)
|
| 12 |
+
return " ".join(new_text)
|
| 13 |
+
|
| 14 |
+
MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
|
| 15 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
| 16 |
+
config = AutoConfig.from_pretrained(MODEL)
|
| 17 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL, output_attentions=False, output_hidden_states=False)
|
| 18 |
+
|
| 19 |
+
def predict_sentiment(text):
|
| 20 |
+
text = preprocess(text)
|
| 21 |
+
encoded_input = tokenizer(text, return_tensors='pt')
|
| 22 |
+
output = model(**encoded_input)
|
| 23 |
+
scores = output.logits[0].detach().numpy()
|
| 24 |
+
scores = softmax(scores)
|
| 25 |
+
ranking = np.argsort(scores)[::-1]
|
| 26 |
+
results = []
|
| 27 |
+
for i in range(scores.shape[0]):
|
| 28 |
+
label = config.id2label[ranking[i]]
|
| 29 |
+
score = np.round(float(scores[ranking[i]]), 4)
|
| 30 |
+
results.append(f"{label}: {score}")
|
| 31 |
+
return "\n".join(results)
|
| 32 |
+
|
| 33 |
+
examples = [
|
| 34 |
+
["I feel happy!"],
|
| 35 |
+
["Had a lovely day at the park 🌳"],
|
| 36 |
+
["Feeling down after today's news 😞"],
|
| 37 |
+
["Just landed a new job, super excited!!"]
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
footer_text = """
|
| 41 |
+
<b>About the Model</b><br>
|
| 42 |
+
This sentiment analysis model is based on the roberta-base architecture and has been fine-tuned for sentiment analysis on tweets. For more information, check out the model's repository on Hugging Face:
|
| 43 |
+
<a href="https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest" target="_blank">cardiffnlp/twitter-roberta-base-sentiment-latest</a>.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
iface = gr.Interface(fn=predict_sentiment,
|
| 47 |
+
inputs=gr.components.Textbox(lines=2, placeholder="Enter Text Here..."),
|
| 48 |
+
outputs="text",
|
| 49 |
+
title="Sentiment Analysis",
|
| 50 |
+
description="This model predicts the sentiment of a given text. Enter text to see its sentiment.",
|
| 51 |
+
examples=examples,
|
| 52 |
+
article=footer_text)
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
iface.launch()
|