AliHamza852 commited on
Commit
f3d6de9
·
verified ·
1 Parent(s): 7df9ae0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -71
app.py CHANGED
@@ -2,92 +2,37 @@ import torch
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import gradio as gr
4
 
5
- # ============================================================
6
- # CONFIG
7
- # ============================================================
8
  MODEL_NAME = "bert-base-uncased"
9
- WEIGHTS_PATH = "bert_sentiment_model.pt" # Upload this file to your Space
10
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
11
 
12
- # Define label mappings (same as your training code)
13
- id2label = {
14
- 0: "Positive",
15
- 1: "Negative",
16
- 2: "Neutral"
17
- }
18
- label2id = {v: k for k, v in id2label.items()}
19
-
20
- # ============================================================
21
- # LOAD MODEL AND TOKENIZER
22
- # ============================================================
23
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
24
 
25
- model = AutoModelForSequenceClassification.from_pretrained(
26
- MODEL_NAME,
27
- num_labels=len(id2label),
28
- id2label=id2label,
29
- label2id=label2id
30
- )
31
-
32
- # Load fine-tuned weights
33
  model.load_state_dict(torch.load(WEIGHTS_PATH, map_location=DEVICE))
34
  model.to(DEVICE)
35
  model.eval()
36
 
37
- # ============================================================
38
- # INFERENCE FUNCTION
39
- # ============================================================
40
- def predict_sentiment(text):
41
- if not text.strip():
42
- return {"Sentiment": "⚠️ Please enter some text.", "Confidence": 0.0}
43
-
44
- encoding = tokenizer(
45
- text,
46
- add_special_tokens=True,
47
- max_length=256,
48
- padding="max_length",
49
- truncation=True,
50
- return_attention_mask=True,
51
- return_tensors="pt"
52
- )
53
-
54
- input_ids = encoding["input_ids"].to(DEVICE)
55
- attention_mask = encoding["attention_mask"].to(DEVICE)
56
 
 
 
57
  with torch.no_grad():
58
- outputs = model(input_ids=input_ids, attention_mask=attention_mask)
59
- logits = outputs.logits
60
- probabilities = torch.softmax(logits, dim=1)
61
- predicted_class = torch.argmax(probabilities, dim=1).item()
62
- confidence = probabilities[0][predicted_class].item()
63
-
64
- sentiment = id2label[predicted_class]
65
- return {"Sentiment": sentiment, "Confidence": round(confidence, 4)}
66
 
67
- # ============================================================
68
- # GRADIO INTERFACE
69
- # ============================================================
70
  demo = gr.Interface(
71
  fn=predict_sentiment,
72
- inputs=gr.Textbox(lines=4, placeholder="Type your review or feedback here...", label="💬 Enter Text"),
73
- outputs=[
74
- gr.Label(label="Predicted Sentiment"),
75
- gr.Number(label="Confidence", precision=4)
76
- ],
77
- title="BERT Sentiment Analyzer",
78
- description="Fine-tuned BERT model for classifying text into Positive, Negative, or Neutral sentiments.",
79
- examples=[
80
- ["I love this product! It's fantastic!"],
81
- ["This is terrible, worst experience ever."],
82
- ["It's okay, nothing special."],
83
- ["Amazing quality and great service!"],
84
- ["Very disappointed with this product."]
85
- ],
86
- theme="gradio/soft"
87
  )
88
 
89
- # ============================================================
90
- # LAUNCH
91
- # ============================================================
92
  if __name__ == "__main__":
93
  demo.launch()
 
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import gradio as gr
4
 
 
 
 
5
  MODEL_NAME = "bert-base-uncased"
6
+ WEIGHTS_PATH = "bert_sentiment_model.pt"
7
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
+ # Load tokenizer
 
 
 
 
 
 
 
 
 
 
10
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
 
12
+ # ⚠️ Make sure num_labels matches your training setup (2 if you trained with Positive/Negative)
13
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=2)
 
 
 
 
 
 
14
  model.load_state_dict(torch.load(WEIGHTS_PATH, map_location=DEVICE))
15
  model.to(DEVICE)
16
  model.eval()
17
 
18
+ id2label = {0: "Positive", 1: "Negative"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ def predict_sentiment(text):
21
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=256).to(DEVICE)
22
  with torch.no_grad():
23
+ outputs = model(**inputs)
24
+ probs = torch.softmax(outputs.logits, dim=1)
25
+ pred = torch.argmax(probs, dim=1).item()
26
+ confidence = probs[0][pred].item()
27
+ return f"{id2label[pred]} ({confidence:.2f} confidence)"
 
 
 
28
 
 
 
 
29
  demo = gr.Interface(
30
  fn=predict_sentiment,
31
+ inputs=gr.Textbox(lines=3, placeholder="Type your review here..."),
32
+ outputs="text",
33
+ title="Sentiment Analyzer (BERT)",
34
+ description="Predicts whether text sentiment is Positive or Negative."
 
 
 
 
 
 
 
 
 
 
 
35
  )
36
 
 
 
 
37
  if __name__ == "__main__":
38
  demo.launch()