File size: 2,209 Bytes
50fccd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6999c9a
50fccd1
 
 
 
 
 
 
3452fb6
6999c9a
50fccd1
6999c9a
 
 
 
 
 
 
3452fb6
6999c9a
 
 
 
 
 
3452fb6
6999c9a
 
 
 
3452fb6
 
50fccd1
6999c9a
 
50fccd1
 
 
 
 
 
 
 
 
 
 
 
 
 
e32207e
 
50fccd1
 
 
 
1b2fd97
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
69
70
71
72
73
74
75
76
77
import gradio as gr
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline

MODEL_ID = "tharakap/deberta-sentiment-analyser" 

CUSTOM_ID_TO_LABEL = {
    0: "anger",
    1: "fear",
    2: "joy",
    3: "sadness",
    4: "surprise"
}

def load_model_and_pipeline():
    tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
    
    model = AutoModelForSequenceClassification.from_pretrained(
        MODEL_ID, 
        id2label=CUSTOM_ID_TO_LABEL
    )
    
    return pipeline("text-classification", model=model, tokenizer=tokenizer, return_all_scores = True) 
try:
    classifier = load_model_and_pipeline()
except Exception as e:
    print(f"Error loading model: {e}")
    classifier = pipeline("sentiment-analysis") 


def predict_sentiment(text, threshold=0.2): # You set the threshold here
    results = classifier(text)[0]
    
    formatted = []
    active_labels = []

    for res in results:
        label = res["label"].upper()
        score = res["score"]
        
        # Check if the score is above the custom threshold
        if score >= threshold:
            active_labels.append(label)
            formatted.append(f"- **{label}** (ACTIVE): {round(score, 4)}")
        else:
            formatted.append(f"- {label}: {round(score, 4)}")
            
    output = "### Active Emotions (Threshold > " + str(threshold) + "):\n"
    if active_labels:
        output += ", ".join(active_labels) + "\n\n"
    else:
        output += "None detected above threshold.\n\n"
        
    output += "### All Emotion Scores:\n" + "\n".join(formatted)
    
    return output



iface = gr.Interface(
    fn=predict_sentiment,
    inputs=gr.Textbox(
        lines=5, 
        placeholder="Enter text for emotion analysis...",
        label="Input Text"
    ),
    outputs="markdown",
    title="DeBERTa Emotion Analysis Demo",
    description=f"An emotion classification demo using the DeBERTa model: {MODEL_ID}.",
    examples=[
        ["I am thrilled to hear the good news!"],
        ["I am terrified; the sight of the spider filled me with pure dread."],
        ["He is absolutely furious and enraged right now."] 
    ]
)

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