faysal725 commited on
Commit
5a863b3
Β·
verified Β·
1 Parent(s): e539205

folder is added

Browse files
calibration.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f217d6037eac4d7c33b1d72b09f52bfab416ea26a81d2a775d505d20a65ff512
3
+ size 884
category_model/1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 384,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
category_model/README.md ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: sentence-transformers/paraphrase-MiniLM-L3-v2
3
+ library_name: setfit
4
+ metrics:
5
+ - accuracy
6
+ pipeline_tag: text-classification
7
+ tags:
8
+ - setfit
9
+ - sentence-transformers
10
+ - text-classification
11
+ - generated_from_setfit_trainer
12
+ widget:
13
+ - text: need help seeing the fucking status of order
14
+ - text: i want to see how long the shipping takes, how can i do it?
15
+ - text: i dont know how i can find my damn invoices from
16
+ - text: where to sign up to the company nmewsletter
17
+ - text: i have to notify of a payment error
18
+ inference: true
19
+ ---
20
+
21
+ # SetFit with sentence-transformers/paraphrase-MiniLM-L3-v2
22
+
23
+ This is a [SetFit](https://github.com/huggingface/setfit) model that can be used for Text Classification. This SetFit model uses [sentence-transformers/paraphrase-MiniLM-L3-v2](https://huggingface.co/sentence-transformers/paraphrase-MiniLM-L3-v2) as the Sentence Transformer embedding model. A [LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) instance is used for classification.
24
+
25
+ The model has been trained using an efficient few-shot learning technique that involves:
26
+
27
+ 1. Fine-tuning a [Sentence Transformer](https://www.sbert.net) with contrastive learning.
28
+ 2. Training a classification head with features from the fine-tuned Sentence Transformer.
29
+
30
+ ## Model Details
31
+
32
+ ### Model Description
33
+ - **Model Type:** SetFit
34
+ - **Sentence Transformer body:** [sentence-transformers/paraphrase-MiniLM-L3-v2](https://huggingface.co/sentence-transformers/paraphrase-MiniLM-L3-v2)
35
+ - **Classification head:** a [LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) instance
36
+ - **Maximum Sequence Length:** 128 tokens
37
+ - **Number of Classes:** 4 classes
38
+ <!-- - **Training Dataset:** [Unknown](https://huggingface.co/datasets/unknown) -->
39
+ <!-- - **Language:** Unknown -->
40
+ <!-- - **License:** Unknown -->
41
+
42
+ ### Model Sources
43
+
44
+ - **Repository:** [SetFit on GitHub](https://github.com/huggingface/setfit)
45
+ - **Paper:** [Efficient Few-Shot Learning Without Prompts](https://arxiv.org/abs/2209.11055)
46
+ - **Blogpost:** [SetFit: Efficient Few-Shot Learning Without Prompts](https://huggingface.co/blog/setfit)
47
+
48
+ ### Model Labels
49
+ | Label | Examples |
50
+ |:------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
51
+ | 2 | <ul><li>"i'm having an issue with the . please assist. i was looking for to use for testing purposes, but it's not working, my mouse is too far from my keyboard and there's no way to turn i've tried clearing the cache and data for the app, but the issue persists."</li><li>"i'm having an issue with the . please assist. the is from an ad agency. we're not responsible for the item you bought without your consent, and we'll this problem started occurring after the recent software update. i haven't made any other changes to the device."</li><li>"i'm having an issue with the . please assist. i've performed a factory reset on my , hoping it would resolve the problem, but it didn't help."</li></ul> |
52
+ | 1 | <ul><li>'i have to check when my item is gonnaarrive help me'</li><li>'can iu talk to customer support'</li><li>'i want help to earn a produxt'</li></ul> |
53
+ | 0 | <ul><li>'how can i give a quick look at my bill 00108?'</li><li>'where can i give a quick look at invoice 37777'</li><li>'could you help me list the allowed payment modalities?'</li></ul> |
54
+ | 3 | <ul><li>'how could i inform of a sign-up issue?'</li><li>'i need information about a pwd recovery'</li><li>'need to change the info on my user account'</li></ul> |
55
+
56
+ ## Uses
57
+
58
+ ### Direct Use for Inference
59
+
60
+ First install the SetFit library:
61
+
62
+ ```bash
63
+ pip install setfit
64
+ ```
65
+
66
+ Then you can load this model and run inference.
67
+
68
+ ```python
69
+ from setfit import SetFitModel
70
+
71
+ # Download from the πŸ€— Hub
72
+ model = SetFitModel.from_pretrained("setfit_model_id")
73
+ # Run inference
74
+ preds = model("i have to notify of a payment error")
75
+ ```
76
+
77
+ <!--
78
+ ### Downstream Use
79
+
80
+ *List how someone could finetune this model on their own dataset.*
81
+ -->
82
+
83
+ <!--
84
+ ### Out-of-Scope Use
85
+
86
+ *List how the model may foreseeably be misused and address what users ought not to do with the model.*
87
+ -->
88
+
89
+ <!--
90
+ ## Bias, Risks and Limitations
91
+
92
+ *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
93
+ -->
94
+
95
+ <!--
96
+ ### Recommendations
97
+
98
+ *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
99
+ -->
100
+
101
+ ## Training Details
102
+
103
+ ### Training Set Metrics
104
+ | Training set | Min | Median | Max |
105
+ |:-------------|:----|:--------|:----|
106
+ | Word count | 2 | 19.2405 | 61 |
107
+
108
+ | Label | Training Sample Count |
109
+ |:------|:----------------------|
110
+ | 0 | 500 |
111
+ | 1 | 500 |
112
+ | 2 | 500 |
113
+ | 3 | 500 |
114
+
115
+ ### Training Hyperparameters
116
+ - batch_size: (16, 16)
117
+ - num_epochs: (1, 1)
118
+ - max_steps: -1
119
+ - sampling_strategy: oversampling
120
+ - num_iterations: 20
121
+ - body_learning_rate: (2e-05, 1e-05)
122
+ - head_learning_rate: 0.01
123
+ - loss: CosineSimilarityLoss
124
+ - distance_metric: cosine_distance
125
+ - margin: 0.25
126
+ - end_to_end: False
127
+ - use_amp: False
128
+ - warmup_proportion: 0.1
129
+ - seed: 42
130
+ - eval_max_steps: -1
131
+ - load_best_model_at_end: False
132
+
133
+ ### Training Results
134
+ | Epoch | Step | Training Loss | Validation Loss |
135
+ |:------:|:----:|:-------------:|:---------------:|
136
+ | 0.0002 | 1 | 0.3088 | - |
137
+ | 0.01 | 50 | 0.3099 | - |
138
+ | 0.02 | 100 | 0.2896 | - |
139
+ | 0.03 | 150 | 0.2212 | - |
140
+ | 0.04 | 200 | 0.2497 | - |
141
+ | 0.05 | 250 | 0.2114 | - |
142
+ | 0.06 | 300 | 0.2305 | - |
143
+ | 0.07 | 350 | 0.261 | - |
144
+ | 0.08 | 400 | 0.207 | - |
145
+ | 0.09 | 450 | 0.1719 | - |
146
+ | 0.1 | 500 | 0.1956 | - |
147
+ | 0.11 | 550 | 0.0833 | - |
148
+ | 0.12 | 600 | 0.2184 | - |
149
+ | 0.13 | 650 | 0.1225 | - |
150
+ | 0.14 | 700 | 0.136 | - |
151
+ | 0.15 | 750 | 0.1928 | - |
152
+ | 0.16 | 800 | 0.1396 | - |
153
+ | 0.17 | 850 | 0.0646 | - |
154
+ | 0.18 | 900 | 0.1592 | - |
155
+ | 0.19 | 950 | 0.0691 | - |
156
+ | 0.2 | 1000 | 0.1672 | - |
157
+ | 0.21 | 1050 | 0.0948 | - |
158
+ | 0.22 | 1100 | 0.0664 | - |
159
+ | 0.23 | 1150 | 0.1591 | - |
160
+ | 0.24 | 1200 | 0.0275 | - |
161
+ | 0.25 | 1250 | 0.0686 | - |
162
+ | 0.26 | 1300 | 0.2408 | - |
163
+ | 0.27 | 1350 | 0.1807 | - |
164
+ | 0.28 | 1400 | 0.0895 | - |
165
+ | 0.29 | 1450 | 0.0291 | - |
166
+ | 0.3 | 1500 | 0.0628 | - |
167
+ | 0.31 | 1550 | 0.0712 | - |
168
+ | 0.32 | 1600 | 0.0978 | - |
169
+ | 0.33 | 1650 | 0.0579 | - |
170
+ | 0.34 | 1700 | 0.0306 | - |
171
+ | 0.35 | 1750 | 0.0752 | - |
172
+ | 0.36 | 1800 | 0.12 | - |
173
+ | 0.37 | 1850 | 0.0958 | - |
174
+ | 0.38 | 1900 | 0.0436 | - |
175
+ | 0.39 | 1950 | 0.0735 | - |
176
+ | 0.4 | 2000 | 0.1054 | - |
177
+ | 0.41 | 2050 | 0.0921 | - |
178
+ | 0.42 | 2100 | 0.1 | - |
179
+ | 0.43 | 2150 | 0.075 | - |
180
+ | 0.44 | 2200 | 0.0374 | - |
181
+ | 0.45 | 2250 | 0.0739 | - |
182
+ | 0.46 | 2300 | 0.1083 | - |
183
+ | 0.47 | 2350 | 0.0388 | - |
184
+ | 0.48 | 2400 | 0.0492 | - |
185
+ | 0.49 | 2450 | 0.0524 | - |
186
+ | 0.5 | 2500 | 0.0367 | - |
187
+ | 0.51 | 2550 | 0.0653 | - |
188
+ | 0.52 | 2600 | 0.0967 | - |
189
+ | 0.53 | 2650 | 0.0872 | - |
190
+ | 0.54 | 2700 | 0.0664 | - |
191
+ | 0.55 | 2750 | 0.0403 | - |
192
+ | 0.56 | 2800 | 0.068 | - |
193
+ | 0.57 | 2850 | 0.0984 | - |
194
+ | 0.58 | 2900 | 0.0909 | - |
195
+ | 0.59 | 2950 | 0.086 | - |
196
+ | 0.6 | 3000 | 0.0158 | - |
197
+ | 0.61 | 3050 | 0.076 | - |
198
+ | 0.62 | 3100 | 0.0177 | - |
199
+ | 0.63 | 3150 | 0.0338 | - |
200
+ | 0.64 | 3200 | 0.0861 | - |
201
+ | 0.65 | 3250 | 0.0311 | - |
202
+ | 0.66 | 3300 | 0.0544 | - |
203
+ | 0.67 | 3350 | 0.0774 | - |
204
+ | 0.68 | 3400 | 0.0227 | - |
205
+ | 0.69 | 3450 | 0.0507 | - |
206
+ | 0.7 | 3500 | 0.0279 | - |
207
+ | 0.71 | 3550 | 0.0037 | - |
208
+ | 0.72 | 3600 | 0.0498 | - |
209
+ | 0.73 | 3650 | 0.0256 | - |
210
+ | 0.74 | 3700 | 0.0503 | - |
211
+ | 0.75 | 3750 | 0.0297 | - |
212
+ | 0.76 | 3800 | 0.0523 | - |
213
+ | 0.77 | 3850 | 0.019 | - |
214
+ | 0.78 | 3900 | 0.0733 | - |
215
+ | 0.79 | 3950 | 0.036 | - |
216
+ | 0.8 | 4000 | 0.024 | - |
217
+ | 0.81 | 4050 | 0.0808 | - |
218
+ | 0.82 | 4100 | 0.0838 | - |
219
+ | 0.83 | 4150 | 0.0362 | - |
220
+ | 0.84 | 4200 | 0.0796 | - |
221
+ | 0.85 | 4250 | 0.0664 | - |
222
+ | 0.86 | 4300 | 0.0229 | - |
223
+ | 0.87 | 4350 | 0.0461 | - |
224
+ | 0.88 | 4400 | 0.0125 | - |
225
+ | 0.89 | 4450 | 0.0153 | - |
226
+ | 0.9 | 4500 | 0.0483 | - |
227
+ | 0.91 | 4550 | 0.0371 | - |
228
+ | 0.92 | 4600 | 0.0305 | - |
229
+ | 0.93 | 4650 | 0.0481 | - |
230
+ | 0.94 | 4700 | 0.092 | - |
231
+ | 0.95 | 4750 | 0.0483 | - |
232
+ | 0.96 | 4800 | 0.0198 | - |
233
+ | 0.97 | 4850 | 0.0191 | - |
234
+ | 0.98 | 4900 | 0.0482 | - |
235
+ | 0.99 | 4950 | 0.0189 | - |
236
+ | 1.0 | 5000 | 0.0193 | - |
237
+
238
+ ### Framework Versions
239
+ - Python: 3.12.13
240
+ - SetFit: 1.0.3
241
+ - Sentence Transformers: 2.7.0
242
+ - Transformers: 4.40.2
243
+ - PyTorch: 2.11.0+cu128
244
+ - Datasets: 3.2.0
245
+ - Tokenizers: 0.19.1
246
+
247
+ ## Citation
248
+
249
+ ### BibTeX
250
+ ```bibtex
251
+ @article{https://doi.org/10.48550/arxiv.2209.11055,
252
+ doi = {10.48550/ARXIV.2209.11055},
253
+ url = {https://arxiv.org/abs/2209.11055},
254
+ author = {Tunstall, Lewis and Reimers, Nils and Jo, Unso Eun Seo and Bates, Luke and Korat, Daniel and Wasserblat, Moshe and Pereg, Oren},
255
+ keywords = {Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
256
+ title = {Efficient Few-Shot Learning Without Prompts},
257
+ publisher = {arXiv},
258
+ year = {2022},
259
+ copyright = {Creative Commons Attribution 4.0 International}
260
+ }
261
+ ```
262
+
263
+ <!--
264
+ ## Glossary
265
+
266
+ *Clearly define terms in order to be accessible across audiences.*
267
+ -->
268
+
269
+ <!--
270
+ ## Model Card Authors
271
+
272
+ *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
273
+ -->
274
+
275
+ <!--
276
+ ## Model Card Contact
277
+
278
+ *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
279
+ -->
category_model/config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "sentence-transformers/paraphrase-MiniLM-L3-v2",
3
+ "architectures": [
4
+ "BertModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "classifier_dropout": null,
8
+ "gradient_checkpointing": false,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 384,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 1536,
14
+ "layer_norm_eps": 1e-12,
15
+ "max_position_embeddings": 512,
16
+ "model_type": "bert",
17
+ "num_attention_heads": 12,
18
+ "num_hidden_layers": 3,
19
+ "pad_token_id": 0,
20
+ "position_embedding_type": "absolute",
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.40.2",
23
+ "type_vocab_size": 2,
24
+ "use_cache": true,
25
+ "vocab_size": 30522
26
+ }
category_model/config_sentence_transformers.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "2.0.0",
4
+ "transformers": "4.7.0",
5
+ "pytorch": "1.9.0+cu102"
6
+ },
7
+ "prompts": {},
8
+ "default_prompt_name": null
9
+ }
category_model/config_setfit.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "normalize_embeddings": false,
3
+ "labels": null
4
+ }
category_model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d47cb714e248b6092182b58af0aa38943ec53ab6d40aa4551af74ff305ea6d01
3
+ size 69565312
category_model/model_head.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e0d576e5792dcbbfaaf6011efb00f1d189590e39a03487b4d2c79693df4f571
3
+ size 13191
category_model/modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ }
14
+ ]
category_model/sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 128,
3
+ "do_lower_case": false
4
+ }
category_model/special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
category_model/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
category_model/tokenizer_config.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "mask_token": "[MASK]",
49
+ "max_length": 128,
50
+ "model_max_length": 512,
51
+ "never_split": null,
52
+ "pad_to_multiple_of": null,
53
+ "pad_token": "[PAD]",
54
+ "pad_token_type_id": 0,
55
+ "padding_side": "right",
56
+ "sep_token": "[SEP]",
57
+ "stride": 0,
58
+ "strip_accents": null,
59
+ "tokenize_chinese_chars": true,
60
+ "tokenizer_class": "BertTokenizer",
61
+ "truncation_side": "right",
62
+ "truncation_strategy": "longest_first",
63
+ "unk_token": "[UNK]"
64
+ }
category_model/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
label_mappings.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:862012dd3c4ee3360ad9f54c3b3731c5ef1c1b2b4967e8bd1012985144dfb2ab
3
+ size 380
predict.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Support Ticket Classifier β€” Prediction Module
3
+ Loads trained SetFit category model + calibration + keyword urgency rules.
4
+ """
5
+ import re
6
+ import pickle
7
+ import numpy as np
8
+ from setfit import SetFitModel
9
+
10
+
11
+ # ── Text cleaning (must match Phase 1 exactly) ────────────────────────
12
+ def clean_text(text: str) -> str:
13
+ if not isinstance(text, str):
14
+ return ""
15
+ text = text.lower()
16
+ text = re.sub(r"\{[^}]+\}", "", text)
17
+ text = re.sub(r"http\S+|www\.\S+", "", text)
18
+ text = re.sub(r"\S+@\S+", "", text)
19
+ text = re.sub(r"[^a-z0-9\s.,!?'\-]", " ", text)
20
+ text = re.sub(r"\s+", " ", text)
21
+ return text.strip()
22
+
23
+
24
+ # ── Keyword-based urgency rules ───────────────────────────────────────
25
+ HIGH_KEYWORDS = [
26
+ "urgent", "asap", "immediately", "emergency", "critical",
27
+ "can't access", "cannot access", "locked out", "account hacked",
28
+ "charged twice", "double charged", "unauthorized charge",
29
+ "service down", "not working", "completely broken", "data loss",
30
+ "refund immediately", "cancel immediately", "fraud", "security breach",
31
+ "down all day"
32
+ ]
33
+ LOW_KEYWORDS = [
34
+ "just wondering", "question about", "when will", "how do i",
35
+ "could you explain", "i would like to know", "curious about",
36
+ "general question", "update my", "change my"
37
+ ]
38
+
39
+
40
+ def get_urgency(text: str) -> str:
41
+ t = text.lower()
42
+ if any(kw in t for kw in HIGH_KEYWORDS):
43
+ return "high"
44
+ if any(kw in t for kw in LOW_KEYWORDS):
45
+ return "low"
46
+ return "medium"
47
+
48
+
49
+ # ── Classifier (lazy-loaded singleton) ────────────────────────────────
50
+ class TicketClassifier:
51
+ _instance = None
52
+
53
+ def __new__(cls):
54
+ if cls._instance is None:
55
+ cls._instance = super().__new__(cls)
56
+ cls._instance._loaded = False
57
+ return cls._instance
58
+
59
+ def load(self):
60
+ if self._loaded:
61
+ return
62
+ print("Loading category model...")
63
+ self.cat_model = SetFitModel.from_pretrained("category_model")
64
+
65
+ print("Loading calibration...")
66
+ with open("calibration.pkl", "rb") as f:
67
+ self.platt_scaler = pickle.load(f)
68
+
69
+ print("Loading label mappings...")
70
+ with open("label_mappings.pkl", "rb") as f:
71
+ mappings = pickle.load(f)
72
+ self.cat_encoder = mappings["category"]
73
+
74
+ self._loaded = True
75
+ print("βœ… Model ready.")
76
+
77
+ def predict(self, ticket_text: str) -> dict:
78
+ if not self._loaded:
79
+ self.load()
80
+
81
+ cleaned = clean_text(ticket_text)
82
+
83
+ # Category + calibrated confidence
84
+ raw_probs = np.array(self.cat_model.predict_proba([cleaned]))
85
+ cal_probs = self.platt_scaler.predict_proba(raw_probs)
86
+ cat_idx = int(np.argmax(cal_probs[0]))
87
+ category = self.cat_encoder.inverse_transform([cat_idx])[0]
88
+ confidence = round(float(cal_probs[0][cat_idx]), 4)
89
+
90
+ # Urgency from keyword rules
91
+ urgency = get_urgency(ticket_text)
92
+
93
+ return {
94
+ "category": category,
95
+ "confidence": confidence,
96
+ "urgency": urgency
97
+ }
98
+
99
+
100
+ # Convenience function
101
+ _classifier = TicketClassifier()
102
+
103
+ def predict_ticket(text: str) -> dict:
104
+ return _classifier.predict(text)
105
+
106
+
107
+ # Quick local test
108
+ if __name__ == "__main__":
109
+ samples = [
110
+ "I was charged twice and need a refund immediately",
111
+ "How do I update my billing address?",
112
+ "The app is completely broken, I cannot access my account",
113
+ "Just wondering when my subscription renews",
114
+ ]
115
+ for s in samples:
116
+ result = predict_ticket(s)
117
+ print(f"\nTicket : {s}")
118
+ print(f"Category : {result['category']} ({result['confidence']*100:.1f}%)")
119
+ print(f"Urgency : {result['urgency']}")
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ setfit==1.0.3
2
+ sentence-transformers==2.7.0
3
+ transformers==4.40.2
4
+ huggingface_hub==0.23.5
5
+ scikit-learn>=1.3.0
6
+ numpy>=1.24.0
7
+ fastapi>=0.110.0
8
+ uvicorn[standard]>=0.27.0
9
+ pydantic>=2.0.0