File size: 2,408 Bytes
51ee734
 
 
 
c9b77b5
51ee734
 
 
ee188e2
 
51ee734
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9b77b5
ef8449d
51ee734
 
 
 
 
 
 
 
ef8449d
51ee734
 
ef8449d
 
 
 
 
 
 
 
51ee734
ef8449d
51ee734
 
 
56e41c7
51ee734
 
 
 
 
 
 
ef8449d
f85ddaf
51ee734
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68

import torch
import gradio as gr
from model import SentimentAnalysisModel
from timeit import default_timer as timer

# Load the pre-trained sentiment analysis model
model = SentimentAnalysisModel(bert_model_name="SamLowe/roberta-base-go_emotions", num_labels=7)
model.load_state_dict(torch.load("best_model_75.pth", map_location=torch.device('cpu')), strict=False)

model.eval()

# Mapping from predicted class to emoji
emoji_to_emotion = {
    0: 'joy ๐Ÿ˜†',
    1: 'fear ๐Ÿ˜ฑ',
    2: 'anger ๐Ÿ˜ก',
    3: 'sadness ๐Ÿ˜ญ',
    4: 'disgust ๐Ÿคฎ',
    5: 'shame ๐Ÿ˜ณ',
    6: 'guilt ๐Ÿ˜ž'
}

# Function to make predictions
def predict_sentiment(text):
    start_time = timer()
    
    inputs = model.tokenizer(text, return_tensors="pt", truncation=True, padding=True)
    input_ids = inputs["input_ids"]
    attention_mask = inputs["attention_mask"]

    with torch.no_grad():
        outputs = model(input_ids=input_ids, attention_mask=attention_mask)

    logits = outputs.logits
    probabilities = torch.nn.functional.softmax(logits, dim=1)
    
    # Map predicted class to emoji
    predicted_class = torch.argmax(logits, dim=1).item()
    result = emoji_to_emotion[predicted_class]
    
    # Create a dictionary of class probabilities
    class_probabilities = {emoji_to_emotion[i]: float(probabilities[0, i]) for i in range(len(emoji_to_emotion))}
    
    # Calculate prediction time
    pred_time = round(timer() - start_time, 5)
    
    return class_probabilities, pred_time

# Create title, description and article strings
title = "Emoji-aware Sentiment Analysis using Roberta Model"
description = "Explore the power of sentiment analysis with our Emotion Detector! Simply input a sentence or text, and let our model predict the underlying emotion."
article = "Sentiment Analysis, also known as opinion mining, is a branch of Natural Language Processing (NLP) that involves determining the emotional tone behind a piece of text. This powerful tool allows us to uncover the underlying feelings, attitudes, and opinions expressed in written communication."


# Interface for Gradio
iface = gr.Interface(
    fn=predict_sentiment,
    inputs="text",
    outputs=[gr.Label(num_top_classes=7, label="Predictions"),
                             gr.Number(label="Prediction time (s)")],
    title=title,
    description=description,
    article=article)

# Launch the Gradio interface
iface.launch()