AyusmanSamasi commited on
Commit
f7930d0
Β·
verified Β·
1 Parent(s): 360b167

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -40
app.py CHANGED
@@ -1,64 +1,68 @@
1
  import gradio as gr
2
  import torch
3
- import torch.nn as nn
4
- from transformers import AutoTokenizer, AutoModel
5
 
6
- LABELS = ["anger", "fear", "joy", "sadness", "surprise"]
7
 
 
8
 
9
- class BERTMultiLabel(nn.Module):
10
- def __init__(self, model_name="microsoft/deberta-v3-base", num_labels=5):
11
- super().__init__()
12
- self.bert = AutoModel.from_pretrained(model_name)
13
- hidden = self.bert.config.hidden_size
14
- self.dropout = nn.Dropout(0.2)
15
- self.classifier = nn.Linear(hidden, num_labels)
16
 
17
- def forward(self, input_ids, attention_mask):
18
- outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
19
- cls = outputs.last_hidden_state[:, 0]
20
- cls = self.dropout(cls)
21
- return self.classifier(cls)
22
 
23
- MODEL_PATH = "./"
24
-
25
- tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
 
26
 
27
- model = BERTMultiLabel(
28
- model_name="microsoft/deberta-v3-base",
29
- num_labels=len(LABELS)
30
- )
31
 
32
- state_dict = torch.load("pytorch_model.bin", map_location="cpu")
33
- model.load_state_dict(state_dict)
34
- model.eval()
 
 
 
 
35
 
36
- def predict_mood(text):
37
- enc = tokenizer(text, truncation=True, padding="max_length", max_length=128, return_tensors="pt")
38
  with torch.no_grad():
39
  logits = model(enc["input_ids"], enc["attention_mask"])
40
  probs = torch.sigmoid(logits).flatten().tolist()
41
 
42
  result = {label: float(f"{p:.4f}") for label, p in zip(LABELS, probs)}
43
- return result
 
 
 
 
 
 
 
 
 
 
44
 
45
- with gr.Blocks() as app:
46
- gr.Markdown("# 🧠 Mood Detector – DeBERTa-V3")
47
-
48
  with gr.Row():
 
49
  with gr.Column(scale=1):
50
  gr.Markdown("""
51
- ### πŸ“Œ Model Details
52
- - **Architecture:** DeBERTa-V3 Base
53
- - **Task:** Multi-label emotional mood detection
54
- - **Labels:** anger, fear, joy, sadness, surprise
55
- - **Framework:** PyTorch + Transformers
 
56
  """)
57
 
 
58
  with gr.Column(scale=2):
59
- text = gr.Textbox(label="Enter your text")
60
- output = gr.Label(label="Predicted Mood Probabilities")
61
- btn = gr.Button("Analyze Mood")
62
- btn.click(fn=predict_mood, inputs=text, outputs=output)
 
63
 
64
  app.launch()
 
1
  import gradio as gr
2
  import torch
3
+ from modeling import BERTMultiLabel
4
+ from transformers import AutoTokenizer
5
 
 
6
 
7
+ LABELS = ["anger", "fear", "joy", "sadness", "surprise"]
8
 
9
+ # ---- Load tokenizer ----
10
+ tokenizer = AutoTokenizer.from_pretrained("./")
 
 
 
 
 
11
 
 
 
 
 
 
12
 
13
+ model = BERTMultiLabel(model_name="microsoft/deberta-v3-base", num_labels=len(LABELS))
14
+ state = torch.load("pytorch_model.bin", map_location="cpu")
15
+ model.load_state_dict(state)
16
+ model.eval()
17
 
18
+ -
19
+ def predict(text):
20
+ if text.strip() == "":
21
+ return {"error": "Please enter text"}
22
 
23
+ enc = tokenizer(
24
+ text,
25
+ truncation=True,
26
+ padding="max_length",
27
+ max_length=128,
28
+ return_tensors="pt"
29
+ )
30
 
 
 
31
  with torch.no_grad():
32
  logits = model(enc["input_ids"], enc["attention_mask"])
33
  probs = torch.sigmoid(logits).flatten().tolist()
34
 
35
  result = {label: float(f"{p:.4f}") for label, p in zip(LABELS, probs)}
36
+ top_label = LABELS[int(torch.argmax(torch.tensor(probs)))]
37
+
38
+ return {
39
+ "Predicted Mood": top_label,
40
+ "Scores": result
41
+ }
42
+
43
+
44
+ with gr.Blocks(title="Mood Detector") as app:
45
+ gr.Markdown("# 🧠 DeBERTa Mood Detector")
46
+ gr.Markdown("Enter any text to analyze the emotional tone.")
47
 
 
 
 
48
  with gr.Row():
49
+ # LEFT PANEL
50
  with gr.Column(scale=1):
51
  gr.Markdown("""
52
+ ## πŸ“Œ Model Info
53
+ - **Architecture:** DeBERTa-v3 Base
54
+ - **Task:** Multi-label emotion classification
55
+ - **Trained by:** You
56
+ - **Dataset:** Custom text emotion dataset
57
+ - **Output:** anger, fear, joy, sadness, surprise
58
  """)
59
 
60
+ # RIGHT PANEL
61
  with gr.Column(scale=2):
62
+ user_input = gr.Textbox(label="Enter text here", placeholder="Type something like: 'I feel so happy today!'")
63
+ analyze_button = gr.Button("Analyze Mood")
64
+ output = gr.JSON(label="Result")
65
+
66
+ analyze_button.click(predict, inputs=user_input, outputs=output)
67
 
68
  app.launch()