AyusmanSamasi commited on
Commit
80b0c2a
·
verified ·
1 Parent(s): a60425a

Update modeling.py

Browse files
Files changed (1) hide show
  1. modeling.py +21 -63
modeling.py CHANGED
@@ -1,64 +1,22 @@
1
  import torch
2
- import gradio as gr
3
- from transformers import AutoTokenizer
4
-
5
- LABELS = ["anger", "fear", "joy", "sadness", "surprise"] # your 5 labels
6
-
7
- tokenizer = AutoTokenizer.from_pretrained("./")
8
-
9
- model = BERTMultiLabel(
10
- model_name="microsoft/deberta-v3-base",
11
- num_labels=len(LABELS)
12
- )
13
-
14
- state = torch.load("pytorch_model.bin", map_location="cpu")
15
- model.load_state_dict(state)
16
- model.eval()
17
-
18
- def predict(text):
19
- if not text.strip():
20
- return {"error": "Please enter text"}
21
-
22
- enc = tokenizer(
23
- text,
24
- truncation=True,
25
- padding="max_length",
26
- max_length=128,
27
- return_tensors="pt"
28
- )
29
-
30
- with torch.no_grad():
31
- logits = model(enc["input_ids"], enc["attention_mask"])
32
- probs = torch.sigmoid(logits)[0].tolist()
33
-
34
- # probability dictionary
35
- scores = {label: round(p, 4) for label, p in zip(LABELS, probs)}
36
-
37
- # main mood (highest probability)
38
- main_emotion = LABELS[int(torch.tensor(probs).argmax())]
39
-
40
- return {
41
- "Predicted Mood": main_emotion,
42
- "Scores": scores
43
- }
44
-
45
- with gr.Blocks() as app:
46
- gr.Markdown("# 🧠 Mood Detection using DeBERTa-v3")
47
-
48
- with gr.Row():
49
- with gr.Column(scale=1):
50
- gr.Markdown("""
51
- ## 📌 Model Info
52
- - **Model:** DeBERTa-v3 Base
53
- - **Task:** Multi-label Sentiment / Emotion
54
- - **Framework:** PyTorch + Transformers
55
- - **Labels:** anger, fear, joy, sadness, surprise
56
- """)
57
-
58
- with gr.Column(scale=2):
59
- user_input = gr.Textbox(label="Enter text here")
60
- btn = gr.Button("Analyze Mood")
61
- output = gr.JSON(label="Output")
62
- btn.click(fn=predict, inputs=user_input, outputs=output)
63
-
64
- app.launch()
 
1
  import torch
2
+ import torch.nn as nn
3
+ from transformers import AutoModel
4
+
5
+ class BERTMultiLabel(nn.Module):
6
+ def __init__(self, model_name="microsoft/deberta-v3-base", num_labels=5):
7
+ super().__init__()
8
+ self.bert = AutoModel.from_pretrained(model_name)
9
+ hidden = self.bert.config.hidden_size
10
+ self.dropout = nn.Dropout(0.2)
11
+ self.classifier = nn.Linear(hidden, num_labels)
12
+
13
+ def forward(self, input_ids, attention_mask):
14
+ outputs = self.bert(
15
+ input_ids=input_ids,
16
+ attention_mask=attention_mask
17
+ )
18
+
19
+ cls = outputs.last_hidden_state[:, 0] # CLS token
20
+ cls = self.dropout(cls)
21
+ logits = self.classifier(cls)
22
+ return logits