AbidHasan95 commited on
Commit
f026936
·
verified ·
1 Parent(s): a6d54c2

uploaded files for tokenizer and handler

Browse files
Files changed (3) hide show
  1. handler.py +163 -0
  2. test_bert_config.json +21 -0
  3. vocab.txt +0 -0
handler.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ import torch
3
+ import torch.nn as nn
4
+ import json
5
+ from transformers import pipeline, BertModel, AutoTokenizer, PretrainedConfig
6
+ from huggingface_hub import PyTorchModelHubMixin
7
+
8
+ class EndpointHandler():
9
+ def __init__(self, path=""):
10
+ # self.pipeline = pipeline("text-classification",model=path)
11
+ # self.model = CustomModel("test_bert_config.json")
12
+ # self.model.load_state_dict(torch.load("model3.pth"))
13
+ config = {"bert_config": "test_bert_config.json"}
14
+ self.model = CustomModel.from_pretrained("AbidHasan95/smsner_model2",**config)
15
+
16
+ def __call__(self, data: Dict[str, Any])-> List[Dict[str, Any]]:
17
+ """
18
+ data args:
19
+ inputs (:obj: `str`)
20
+ date (:obj: `str`)
21
+ Return:
22
+ A :obj:`list` | `dict`: will be serialized and returned
23
+ """
24
+ # get inputs
25
+ inputs = data.pop("inputs",data)
26
+ # date = data.pop("date", None)
27
+
28
+ # check if date exists and if it is a holiday
29
+ # if date is not None and date in self.holidays:
30
+ # return [{"label": "happy", "score": 1}]
31
+
32
+
33
+ # run normal prediction
34
+ prediction = self.model(inputs)
35
+ # prediction = json.dumps(prediction)
36
+ return prediction
37
+
38
+ class CustomModelOld(nn.Module):
39
+ def __init__(self, bert_config):
40
+ super(CustomModel, self).__init__()
41
+ # self.bert = BertModel.from_pretrained(base_model_path)
42
+ self.bert = BertModel._from_config(PretrainedConfig.from_json_file(bert_config))
43
+ self.dropout = nn.Dropout(0.2)
44
+ self.token_classifier = nn.Linear(self.bert.config.hidden_size, 16)
45
+ self.sequence_classifier = nn.Linear(self.bert.config.hidden_size, 7)
46
+
47
+ # Initialize weights
48
+ nn.init.kaiming_normal_(self.token_classifier.weight, mode='fan_in', nonlinearity='linear')
49
+ nn.init.kaiming_normal_(self.sequence_classifier.weight, mode='fan_in', nonlinearity='linear')
50
+ self.seq_labels = [
51
+ "Transaction",
52
+ "Courier",
53
+ "OTP",
54
+ "Expiry",
55
+ "Misc",
56
+ "Tele Marketing",
57
+ "Spam",
58
+ ]
59
+
60
+ self.token_class_labels = [
61
+ 'O',
62
+ 'Courier Service',
63
+ 'Credit',
64
+ 'Date',
65
+ 'Debit',
66
+ 'Email',
67
+ 'Expiry',
68
+ 'Item',
69
+ 'Order ID',
70
+ 'Organization',
71
+ 'OTP',
72
+ 'Phone Number',
73
+ 'Refund',
74
+ 'Time',
75
+ 'Tracking ID',
76
+ 'URL',
77
+ ]
78
+ base_model_path = '.'
79
+ self.tokenizer = AutoTokenizer.from_pretrained(base_model_path)
80
+
81
+ def forward(self, input_ids : torch.Tensor, attention_mask: torch.Tensor, token_type_ids: torch.Tensor):
82
+ outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
83
+ sequence_output, pooled_output = outputs.last_hidden_state, outputs.pooler_output
84
+
85
+ token_logits = self.token_classifier(self.dropout(sequence_output))
86
+ sequence_logits = self.sequence_classifier(self.dropout(pooled_output))
87
+
88
+ return token_logits, sequence_logits
89
+ def classify(self, inputs):
90
+ out = self.tokenizer(inputs, return_tensors="pt")
91
+ token_classification_logits, sequence_logits = self.forward(**out)
92
+ token_classification_logits = token_classification_logits.argmax(2)[0]
93
+ sequence_logits = sequence_logits.argmax(1)[0]
94
+ token_classification_out = [self.token_class_labels[i] for i in token_classification_logits.tolist()]
95
+ seq_classification_out = self.seq_labels[sequence_logits]
96
+ # return token_classification_out, seq_classification_out
97
+ return {"token_classfier":token_classification_out, "sequence_classfier": seq_classification_out}
98
+
99
+ class CustomModel(nn.Module, PyTorchModelHubMixin):
100
+ def __init__(self, bert_config: str):
101
+ super().__init__()
102
+ # self.bert = BertModel.from_pretrained(base_model_path)
103
+ self.bert = BertModel._from_config(PretrainedConfig.from_json_file(bert_config))
104
+ self.dropout = nn.Dropout(0.2)
105
+ self.token_classifier = nn.Linear(self.bert.config.hidden_size, 16)
106
+ self.sequence_classifier = nn.Linear(self.bert.config.hidden_size, 7)
107
+
108
+ # Initialize weights
109
+ nn.init.kaiming_normal_(self.token_classifier.weight, mode='fan_in', nonlinearity='linear')
110
+ nn.init.kaiming_normal_(self.sequence_classifier.weight, mode='fan_in', nonlinearity='linear')
111
+ self.seq_labels = [
112
+ "Transaction",
113
+ "Courier",
114
+ "OTP",
115
+ "Expiry",
116
+ "Misc",
117
+ "Tele Marketing",
118
+ "Spam",
119
+ ]
120
+
121
+ self.token_class_labels = [
122
+ 'O',
123
+ 'Courier Service',
124
+ 'Credit',
125
+ 'Date',
126
+ 'Debit',
127
+ 'Email',
128
+ 'Expiry',
129
+ 'Item',
130
+ 'Order ID',
131
+ 'Organization',
132
+ 'OTP',
133
+ 'Phone Number',
134
+ 'Refund',
135
+ 'Time',
136
+ 'Tracking ID',
137
+ 'URL',
138
+ ]
139
+ base_model_path = '.'
140
+ self.tokenizer = AutoTokenizer.from_pretrained(base_model_path)
141
+
142
+ # def forward(self, input_ids : torch.Tensor, attention_mask: torch.Tensor, token_type_ids: torch.Tensor):
143
+ # outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
144
+ # sequence_output, pooled_output = outputs.last_hidden_state, outputs.pooler_output
145
+
146
+ # token_classification_logits = self.token_classifier(self.dropout(sequence_output))
147
+ # sequence_logits = self.sequence_classifier(self.dropout(pooled_output))
148
+
149
+ # return token_classification_logits, sequence_logits
150
+ def forward(self, inputs: str):
151
+ out = self.tokenizer(inputs, return_tensors="pt")
152
+ outputs = self.bert(**out)
153
+ sequence_output, pooled_output = outputs.last_hidden_state, outputs.pooler_output
154
+
155
+ token_classification_logits = self.token_classifier(self.dropout(sequence_output))
156
+ sequence_logits = self.sequence_classifier(self.dropout(pooled_output))
157
+
158
+ token_classification_logits = token_classification_logits.argmax(2)[0]
159
+ sequence_logits = sequence_logits.argmax(1)[0]
160
+ token_classification_out = [self.token_class_labels[i] for i in token_classification_logits.tolist()]
161
+ seq_classification_out = self.seq_labels[sequence_logits]
162
+ model_out = str({"token_classfier":token_classification_out, "sequence_classfier": seq_classification_out})
163
+ return model_out
test_bert_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "bert/bert_uncased_L-2_H-512_A-8/",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "classifier_dropout": null,
5
+ "hidden_act": "gelu",
6
+ "hidden_dropout_prob": 0.1,
7
+ "hidden_size": 512,
8
+ "initializer_range": 0.02,
9
+ "intermediate_size": 2048,
10
+ "layer_norm_eps": 1e-12,
11
+ "max_position_embeddings": 512,
12
+ "model_type": "bert",
13
+ "num_attention_heads": 8,
14
+ "num_hidden_layers": 2,
15
+ "pad_token_id": 0,
16
+ "position_embedding_type": "absolute",
17
+ "transformers_version": "4.38.2",
18
+ "type_vocab_size": 2,
19
+ "use_cache": true,
20
+ "vocab_size": 30522
21
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff