File size: 2,219 Bytes
46445fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import gradio as gr
from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
import numpy as np
from scipy.special import softmax

def preprocess(text):
    new_text = []
    for t in text.split(" "):
        t = '@user' if t.startswith('@') and len(t) > 1 else t
        t = 'http' if t.startswith('http') else t
        new_text.append(t)
    return " ".join(new_text)

MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
config = AutoConfig.from_pretrained(MODEL)
model = AutoModelForSequenceClassification.from_pretrained(MODEL, output_attentions=False, output_hidden_states=False)

def predict_sentiment(text):
    text = preprocess(text)
    encoded_input = tokenizer(text, return_tensors='pt')
    output = model(**encoded_input)
    scores = output.logits[0].detach().numpy()
    scores = softmax(scores)
    ranking = np.argsort(scores)[::-1]
    results = []
    for i in range(scores.shape[0]):
        label = config.id2label[ranking[i]]
        score = np.round(float(scores[ranking[i]]), 4)
        results.append(f"{label}: {score}")
    return "\n".join(results)

examples = [
    ["I feel happy!"],
    ["Had a lovely day at the park 🌳"],
    ["Feeling down after today's news 😞"],
    ["Just landed a new job, super excited!!"]
]

footer_text = """
<b>About the Model</b><br>
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:
<a href="https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest" target="_blank">cardiffnlp/twitter-roberta-base-sentiment-latest</a>.
"""

iface = gr.Interface(fn=predict_sentiment, 
                     inputs=gr.components.Textbox(lines=2, placeholder="Enter Text Here..."), 
                     outputs="text",
                     title="Sentiment Analysis",
                     description="This model predicts the sentiment of a given text. Enter text to see its sentiment.",
                     examples=examples,
                     article=footer_text)

if __name__ == "__main__":
    iface.launch()