junaid17 commited on
Commit
eefad1b
·
verified ·
1 Parent(s): c73c156

Upload 6 files

Browse files
BERT_MODEL.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47318e40a47b689c5d0cc90d41b345a4e3b0f15a2a4a01fd7916763fc5873e52
3
+ size 266456825
TOKENIZER/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
TOKENIZER/tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": true,
48
+ "extra_special_tokens": {},
49
+ "mask_token": "[MASK]",
50
+ "model_max_length": 512,
51
+ "never_split": null,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "strip_accents": null,
55
+ "tokenize_chinese_chars": true,
56
+ "tokenizer_class": "DistilBertTokenizer",
57
+ "unk_token": "[UNK]"
58
+ }
TOKENIZER/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from typing import Literal
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from transformers import DistilBertTokenizer, DistilBertModel
7
+ import logging
8
+ import time
9
+
10
+ logging.getLogger("transformers").setLevel(logging.ERROR)
11
+
12
+ # ----------------------------
13
+ # Model Definition
14
+ # ----------------------------
15
+ class SentimentClassifier(torch.nn.Module):
16
+ def __init__(self):
17
+ super().__init__()
18
+ self.bert = DistilBertModel.from_pretrained("distilbert-base-uncased")
19
+ for param in self.bert.parameters():
20
+ param.requires_grad = False
21
+ self.classifier = torch.nn.Sequential(
22
+ torch.nn.Linear(768, 256),
23
+ torch.nn.BatchNorm1d(256),
24
+ torch.nn.ReLU(),
25
+ torch.nn.Dropout(0.3),
26
+ torch.nn.Linear(256, 128),
27
+ torch.nn.BatchNorm1d(128),
28
+ torch.nn.ReLU(),
29
+ torch.nn.Dropout(0.3),
30
+ torch.nn.Linear(128, 64),
31
+ torch.nn.BatchNorm1d(64),
32
+ torch.nn.ReLU(),
33
+ torch.nn.Dropout(0.3),
34
+ torch.nn.Linear(64, 3)
35
+ )
36
+
37
+ def forward(self, input_ids, attention_mask):
38
+ sentence_embeddings = self.bert(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state[:, 0, :]
39
+ return self.classifier(sentence_embeddings)
40
+
41
+
42
+ app = FastAPI(title="TwittoBERT API", version="1.0")
43
+
44
+ model = None
45
+ tokenizer = None
46
+
47
+
48
+
49
+ @app.on_event("startup")
50
+ def load_model_and_tokenizer():
51
+ global model, tokenizer
52
+ print("Loading model and tokenizer...")
53
+ start = time.time()
54
+ model = SentimentClassifier()
55
+ model.load_state_dict(torch.load("BERT_MODEL.pth", map_location=torch.device("cpu")))
56
+ model.eval()
57
+ tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
58
+ print(f"✅ Model loaded in {time.time() - start:.2f}s")
59
+
60
+
61
+ class PredictionRequest(BaseModel):
62
+ text: str
63
+
64
+ class PredictionResponse(BaseModel):
65
+ sentiment: Literal["Negative", "Neutral", "Positive"]
66
+ confidence: float # 0.0 to 100.0
67
+
68
+ class StatusResponse(BaseModel):
69
+ status: str
70
+ model_loaded: bool
71
+
72
+ # ----------------------------
73
+ # Endpoints
74
+ # ----------------------------
75
+ @app.get("/status", response_model=StatusResponse)
76
+ async def status():
77
+ return {
78
+ "status": "healthy",
79
+ "model_loaded": model is not None and tokenizer is not None
80
+ }
81
+
82
+ @app.post("/predict", response_model=PredictionResponse)
83
+ async def predict(request: PredictionRequest):
84
+ if not request.text.strip():
85
+ raise HTTPException(status_code=400, detail="Text cannot be empty")
86
+
87
+ try:
88
+ inputs = tokenizer(
89
+ request.text,
90
+ padding="max_length",
91
+ max_length=250,
92
+ truncation=True,
93
+ return_tensors="pt"
94
+ )
95
+
96
+ with torch.no_grad():
97
+ logits = model(**inputs)
98
+ probs = F.softmax(logits, dim=1)
99
+ confidence, pred_class = torch.max(probs, dim=1)
100
+
101
+ label = ["Negative", "Neutral", "Positive"][pred_class.item()]
102
+ confidence_score = round(confidence.item() * 100, 2)
103
+
104
+ return {"sentiment": label, "confidence": confidence_score}
105
+
106
+ except Exception as e:
107
+ raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ pillow
2
+ torch
3
+ torchvi
4
+ transformers
5
+ functools
6
+ huggingface_hub
7
+ fastapi
8
+ uvicorn