Spaces:
Sleeping
Sleeping
Commit
•
3598b04
1
Parent(s):
7da5f3f
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
|
5 |
+
# Load model and tokenizer
|
6 |
+
model_name = "cardiffnlp/twitter-roberta-base-sentiment-latest"
|
7 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
9 |
+
|
10 |
+
def predict_sentiment(text):
|
11 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
|
12 |
+
with torch.no_grad():
|
13 |
+
outputs = model(**inputs)
|
14 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
15 |
+
sentiments = ['Negative', 'Neutral', 'Positive']
|
16 |
+
result = {sentiments[i]: float(predictions[0][i]) for i in range(len(sentiments))}
|
17 |
+
return result
|
18 |
+
|
19 |
+
def custom_theme():
|
20 |
+
"""Define a custom theme for the Gradio app."""
|
21 |
+
return gr.Theme(
|
22 |
+
# Define your color scheme
|
23 |
+
primary='#FF6347',
|
24 |
+
text_on_primary='#FFFFFF',
|
25 |
+
background='#F0F8FF',
|
26 |
+
card_background='#FAEBD7',
|
27 |
+
text='#2F4F4F',
|
28 |
+
icon='light',
|
29 |
+
)
|
30 |
+
|
31 |
+
# Create Gradio interface
|
32 |
+
iface = gr.Interface(fn=predict_sentiment,
|
33 |
+
inputs=gr.inputs.Textbox(lines=2, placeholder="Type your sentence here..."),
|
34 |
+
outputs=gr.outputs.Label(num_top_classes=3),
|
35 |
+
theme=custom_theme(),
|
36 |
+
title="Sentiment Analysis",
|
37 |
+
description="Analyze the sentiment of your text.",
|
38 |
+
article="<p style='text-align: center'>Enter a sentence to get its sentiment. The model categorizes sentiments into Negative, Neutral, and Positive.</p>")
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
iface.launch()
|