temsa commited on
Commit
d49b0d0
·
verified ·
1 Parent(s): a73157c

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -1,35 +1,12 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
  *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
4
  *.ckpt filter=lfs diff=lfs merge=lfs -text
5
  *.ftz filter=lfs diff=lfs merge=lfs -text
6
  *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.jsonl filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
8
  *.onnx filter=lfs diff=lfs merge=lfs -text
 
9
  *.parquet filter=lfs diff=lfs merge=lfs -text
 
 
 
10
  *.pt filter=lfs diff=lfs merge=lfs -text
11
  *.pth filter=lfs diff=lfs merge=lfs -text
 
12
  *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
LICENSE ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ OpenMed-mLiteClinical-IrishCorePII-135M-v1
2
+
3
+ This release is derived from:
4
+ - OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1 (Apache-2.0)
5
+
6
+ Training/evaluation data used for this derivative included:
7
+ - temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1 (Apache-2.0 synthetic dataset)
8
+ - temsa/OpenMed-Irish-CorePII-TrainMix-v1 (composite training mix)
9
+ - joelniklaus/mapa (CC-BY-4.0)
10
+ - gretelai/synthetic_pii_finance_multilingual (Apache-2.0)
11
+
12
+ Please review the dataset cards and upstream licenses before redistributing derivative datasets.
README.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - ga
5
+ license: apache-2.0
6
+ library_name: transformers
7
+ pipeline_tag: token-classification
8
+ tags:
9
+ - pii
10
+ - token-classification
11
+ - de-identification
12
+ - ireland
13
+ - ppsn
14
+ - eircode
15
+ - finance
16
+ - passport
17
+ - phone-number
18
+ - multilingual
19
+ base_model:
20
+ - OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1
21
+ datasets:
22
+ - temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1
23
+ - temsa/OpenMed-Irish-CorePII-TrainMix-v1
24
+ - joelniklaus/mapa
25
+ - gretelai/synthetic_pii_finance_multilingual
26
+ model-index:
27
+ - name: temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1
28
+ results:
29
+ - task:
30
+ type: token-classification
31
+ name: Irish core PII detection
32
+ dataset:
33
+ type: custom
34
+ name: irish_core_pii_v1
35
+ metrics:
36
+ - type: f1
37
+ name: PPSN F1
38
+ value: 0.8000
39
+ - type: f1
40
+ name: phone_number F1
41
+ value: 0.8571
42
+ - type: f1
43
+ name: postcode F1
44
+ value: 1.0000
45
+ - task:
46
+ type: token-classification
47
+ name: Multilingual PPSN detection
48
+ dataset:
49
+ type: custom
50
+ name: multilingual_ppsn_v1_all
51
+ metrics:
52
+ - type: f1
53
+ name: PPSN F1
54
+ value: 0.9940
55
+ ---
56
+
57
+ # temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1
58
+
59
+ Full `transformers` checkpoint derived from `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1` and tuned for Irish core PII:
60
+
61
+ - `PPSN`
62
+ - `account_number`
63
+ - `bank_routing_number`
64
+ - `credit_debit_card`
65
+ - `PASSPORT_NUMBER`
66
+ - `postcode`
67
+ - `phone_number`
68
+ - `email`
69
+ - `first_name`
70
+ - `last_name`
71
+ - `swift_bic`
72
+
73
+ The main focus is English + Irish Gaelic (`ga`) handling for Irish administrative, citizen-support, and HSE-style text.
74
+
75
+ ## Included Artifacts
76
+
77
+ - Full `transformers` model files in the repo root
78
+ - Dynamic int8 ONNX export in `onnx/model_quantized.onnx`
79
+ - `inference_mask.py` for the full model
80
+ - `inference_mask_onnx.py` for the ONNX int8 artifact
81
+ - clean benchmark summaries in `eval/`
82
+
83
+ ## Recommended Inference
84
+
85
+ Highest accuracy:
86
+
87
+ ```bash
88
+ python3 inference_mask.py \
89
+ --text "My PPSN is 1234567TW and call me on 087 123 4567." \
90
+ --json
91
+ ```
92
+
93
+ Fast CPU path:
94
+
95
+ ```bash
96
+ python3 inference_mask_onnx.py \
97
+ --text "My PPSN is 1234567TW and call me on 087 123 4567." \
98
+ --json
99
+ ```
100
+
101
+ Dedicated Eircode example:
102
+
103
+ ```bash
104
+ python3 inference_mask.py \
105
+ --text "My Eircode is D02 X285." \
106
+ --json
107
+ ```
108
+
109
+ ## Benchmarks
110
+
111
+ Reference comparison on the manual Irish core suite and PPSN regression suites:
112
+
113
+ | Label | Base OpenMed | Previous Public Model | This Release | ONNX Q8 |
114
+ |---|---:|---:|---:|---:|
115
+ | `PPSN` | 0.0000 | 0.0800 | 0.8000 | 0.7273 |
116
+ | `account_number` | 0.3333 | 0.3333 | 1.0000 | 1.0000 |
117
+ | `bank_routing_number` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
118
+ | `credit_debit_card` | 0.1538 | 0.1818 | 1.0000 | 0.3333 |
119
+ | `PASSPORT_NUMBER` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
120
+ | `postcode` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
121
+ | `phone_number` | 0.0000 | 0.0000 | 0.8571 | 0.8571 |
122
+ | `email` | 0.7059 | 1.0000 | 1.0000 | 1.0000 |
123
+ | `first_name` | 0.8947 | 0.8947 | 1.0000 | 1.0000 |
124
+ | `last_name` | 0.8889 | 0.8889 | 1.0000 | 1.0000 |
125
+ | `swift_bic` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
126
+
127
+ Edge and multilingual PPSN checks:
128
+
129
+ | Suite | Base OpenMed | Previous Public Model | This Release | ONNX Q8 |
130
+ |---|---:|---:|---:|---:|
131
+ | `edge_ppsn` | 0.0000 | 0.4211 | 0.5000 | 0.4000 |
132
+ | `edge_phone_number` | 0.1429 | 0.1429 | 0.6316 | 0.5000 |
133
+ | `multilingual_ppsn` | 0.0000 | 0.9704 | 0.9940 | 0.9882 |
134
+
135
+ Multilingual PPSN throughput on CPU (`eval/multilingual_ppsn_v1_all.jsonl`):
136
+
137
+ - Base OpenMed: `42.30` examples/s
138
+ - Previous public PPSN model: `42.63` examples/s
139
+ - This release: `41.18` examples/s
140
+ - ONNX Q8: `81.99` examples/s
141
+
142
+ ## Practical Reading Of The Benchmarks
143
+
144
+ - This release is materially better than the previous public PPSN-only model on Irish phones, Eircodes, account details, passport numbers, and names.
145
+ - The bundled ONNX int8 export is useful for CPU speed, but it is not accuracy-identical to the full checkpoint.
146
+ - The largest ONNX drops are on `credit_debit_card` and some PPSN edge cases. Use the full model when those matter.
147
+
148
+ ## License And Attribution
149
+
150
+ - Model weights in this repo are distributed under Apache-2.0.
151
+ - Base model: `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1`
152
+ - Training data included synthetic Irish data plus attributed upstream data from:
153
+ - `joelniklaus/mapa` (`cc-by-4.0`)
154
+ - `gretelai/synthetic_pii_finance_multilingual` (`apache-2.0`)
155
+ - See `NOTICE` for attribution details.
config.json ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "gelu",
3
+ "architectures": [
4
+ "DistilBertForTokenClassification"
5
+ ],
6
+ "attention_dropout": 0.1,
7
+ "dim": 768,
8
+ "dropout": 0.1,
9
+ "dtype": "float32",
10
+ "hidden_dim": 3072,
11
+ "id2label": {
12
+ "0": "O",
13
+ "1": "B-account_number",
14
+ "2": "B-age",
15
+ "3": "B-api_key",
16
+ "4": "B-bank_routing_number",
17
+ "5": "B-biometric_identifier",
18
+ "6": "B-blood_type",
19
+ "7": "B-certificate_license_number",
20
+ "8": "B-city",
21
+ "9": "B-company_name",
22
+ "10": "B-coordinate",
23
+ "11": "B-country",
24
+ "12": "B-county",
25
+ "13": "B-credit_debit_card",
26
+ "14": "B-customer_id",
27
+ "15": "B-cvv",
28
+ "16": "B-date",
29
+ "17": "B-date_of_birth",
30
+ "18": "B-date_time",
31
+ "19": "B-device_identifier",
32
+ "20": "B-education_level",
33
+ "21": "B-email",
34
+ "22": "B-employee_id",
35
+ "23": "B-employment_status",
36
+ "24": "B-fax_number",
37
+ "25": "B-first_name",
38
+ "26": "B-gender",
39
+ "27": "B-health_plan_beneficiary_number",
40
+ "28": "B-http_cookie",
41
+ "29": "B-ipv4",
42
+ "30": "B-ipv6",
43
+ "31": "B-language",
44
+ "32": "B-last_name",
45
+ "33": "B-license_plate",
46
+ "34": "B-mac_address",
47
+ "35": "B-medical_record_number",
48
+ "36": "B-occupation",
49
+ "37": "B-password",
50
+ "38": "B-phone_number",
51
+ "39": "B-pin",
52
+ "40": "B-political_view",
53
+ "41": "B-postcode",
54
+ "42": "B-race_ethnicity",
55
+ "43": "B-religious_belief",
56
+ "44": "B-sexuality",
57
+ "45": "B-ssn",
58
+ "46": "B-state",
59
+ "47": "B-street_address",
60
+ "48": "B-swift_bic",
61
+ "49": "B-tax_id",
62
+ "50": "B-time",
63
+ "51": "B-unique_id",
64
+ "52": "B-url",
65
+ "53": "B-user_name",
66
+ "54": "B-vehicle_identifier",
67
+ "55": "I-account_number",
68
+ "56": "I-api_key",
69
+ "57": "I-biometric_identifier",
70
+ "58": "I-blood_type",
71
+ "59": "I-certificate_license_number",
72
+ "60": "I-city",
73
+ "61": "I-company_name",
74
+ "62": "I-coordinate",
75
+ "63": "I-country",
76
+ "64": "I-county",
77
+ "65": "I-credit_debit_card",
78
+ "66": "I-customer_id",
79
+ "67": "I-date",
80
+ "68": "I-date_of_birth",
81
+ "69": "I-date_time",
82
+ "70": "I-device_identifier",
83
+ "71": "I-education_level",
84
+ "72": "I-email",
85
+ "73": "I-employee_id",
86
+ "74": "I-employment_status",
87
+ "75": "I-fax_number",
88
+ "76": "I-first_name",
89
+ "77": "I-gender",
90
+ "78": "I-health_plan_beneficiary_number",
91
+ "79": "I-http_cookie",
92
+ "80": "I-ipv4",
93
+ "81": "I-ipv6",
94
+ "82": "I-language",
95
+ "83": "I-last_name",
96
+ "84": "I-license_plate",
97
+ "85": "I-mac_address",
98
+ "86": "I-medical_record_number",
99
+ "87": "I-occupation",
100
+ "88": "I-password",
101
+ "89": "I-phone_number",
102
+ "90": "I-pin",
103
+ "91": "I-political_view",
104
+ "92": "I-postcode",
105
+ "93": "I-race_ethnicity",
106
+ "94": "I-religious_belief",
107
+ "95": "I-sexuality",
108
+ "96": "I-ssn",
109
+ "97": "I-state",
110
+ "98": "I-street_address",
111
+ "99": "I-swift_bic",
112
+ "100": "I-tax_id",
113
+ "101": "I-time",
114
+ "102": "I-unique_id",
115
+ "103": "I-url",
116
+ "104": "I-user_name",
117
+ "105": "I-vehicle_identifier",
118
+ "106": "B-PPSN",
119
+ "107": "I-PPSN",
120
+ "108": "B-PASSPORT_NUMBER",
121
+ "109": "I-PASSPORT_NUMBER",
122
+ "110": "I-bank_routing_number"
123
+ },
124
+ "initializer_range": 0.02,
125
+ "label2id": {
126
+ "B-PASSPORT_NUMBER": 108,
127
+ "B-PPSN": 106,
128
+ "B-account_number": 1,
129
+ "B-age": 2,
130
+ "B-api_key": 3,
131
+ "B-bank_routing_number": 4,
132
+ "B-biometric_identifier": 5,
133
+ "B-blood_type": 6,
134
+ "B-certificate_license_number": 7,
135
+ "B-city": 8,
136
+ "B-company_name": 9,
137
+ "B-coordinate": 10,
138
+ "B-country": 11,
139
+ "B-county": 12,
140
+ "B-credit_debit_card": 13,
141
+ "B-customer_id": 14,
142
+ "B-cvv": 15,
143
+ "B-date": 16,
144
+ "B-date_of_birth": 17,
145
+ "B-date_time": 18,
146
+ "B-device_identifier": 19,
147
+ "B-education_level": 20,
148
+ "B-email": 21,
149
+ "B-employee_id": 22,
150
+ "B-employment_status": 23,
151
+ "B-fax_number": 24,
152
+ "B-first_name": 25,
153
+ "B-gender": 26,
154
+ "B-health_plan_beneficiary_number": 27,
155
+ "B-http_cookie": 28,
156
+ "B-ipv4": 29,
157
+ "B-ipv6": 30,
158
+ "B-language": 31,
159
+ "B-last_name": 32,
160
+ "B-license_plate": 33,
161
+ "B-mac_address": 34,
162
+ "B-medical_record_number": 35,
163
+ "B-occupation": 36,
164
+ "B-password": 37,
165
+ "B-phone_number": 38,
166
+ "B-pin": 39,
167
+ "B-political_view": 40,
168
+ "B-postcode": 41,
169
+ "B-race_ethnicity": 42,
170
+ "B-religious_belief": 43,
171
+ "B-sexuality": 44,
172
+ "B-ssn": 45,
173
+ "B-state": 46,
174
+ "B-street_address": 47,
175
+ "B-swift_bic": 48,
176
+ "B-tax_id": 49,
177
+ "B-time": 50,
178
+ "B-unique_id": 51,
179
+ "B-url": 52,
180
+ "B-user_name": 53,
181
+ "B-vehicle_identifier": 54,
182
+ "I-PASSPORT_NUMBER": 109,
183
+ "I-PPSN": 107,
184
+ "I-account_number": 55,
185
+ "I-api_key": 56,
186
+ "I-bank_routing_number": 110,
187
+ "I-biometric_identifier": 57,
188
+ "I-blood_type": 58,
189
+ "I-certificate_license_number": 59,
190
+ "I-city": 60,
191
+ "I-company_name": 61,
192
+ "I-coordinate": 62,
193
+ "I-country": 63,
194
+ "I-county": 64,
195
+ "I-credit_debit_card": 65,
196
+ "I-customer_id": 66,
197
+ "I-date": 67,
198
+ "I-date_of_birth": 68,
199
+ "I-date_time": 69,
200
+ "I-device_identifier": 70,
201
+ "I-education_level": 71,
202
+ "I-email": 72,
203
+ "I-employee_id": 73,
204
+ "I-employment_status": 74,
205
+ "I-fax_number": 75,
206
+ "I-first_name": 76,
207
+ "I-gender": 77,
208
+ "I-health_plan_beneficiary_number": 78,
209
+ "I-http_cookie": 79,
210
+ "I-ipv4": 80,
211
+ "I-ipv6": 81,
212
+ "I-language": 82,
213
+ "I-last_name": 83,
214
+ "I-license_plate": 84,
215
+ "I-mac_address": 85,
216
+ "I-medical_record_number": 86,
217
+ "I-occupation": 87,
218
+ "I-password": 88,
219
+ "I-phone_number": 89,
220
+ "I-pin": 90,
221
+ "I-political_view": 91,
222
+ "I-postcode": 92,
223
+ "I-race_ethnicity": 93,
224
+ "I-religious_belief": 94,
225
+ "I-sexuality": 95,
226
+ "I-ssn": 96,
227
+ "I-state": 97,
228
+ "I-street_address": 98,
229
+ "I-swift_bic": 99,
230
+ "I-tax_id": 100,
231
+ "I-time": 101,
232
+ "I-unique_id": 102,
233
+ "I-url": 103,
234
+ "I-user_name": 104,
235
+ "I-vehicle_identifier": 105,
236
+ "O": 0
237
+ },
238
+ "max_position_embeddings": 512,
239
+ "model_type": "distilbert",
240
+ "n_heads": 12,
241
+ "n_layers": 6,
242
+ "output_past": true,
243
+ "pad_token_id": 0,
244
+ "qa_dropout": 0.1,
245
+ "seq_classif_dropout": 0.2,
246
+ "sinusoidal_pos_embds": false,
247
+ "tie_weights_": true,
248
+ "transformers_version": "4.57.6",
249
+ "vocab_size": 119547
250
+ }
eval/benchmark_summary.json ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "models": {
3
+ "base": {
4
+ "model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
5
+ "backend": "transformers"
6
+ },
7
+ "current": {
8
+ "model": "temsa/OpenMed-mLiteClinical-IrishPPSN-135M-v1",
9
+ "backend": "transformers"
10
+ },
11
+ "candidate": {
12
+ "model": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1",
13
+ "backend": "transformers"
14
+ },
15
+ "onnx_q8": {
16
+ "model": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1#onnx_q8",
17
+ "backend": "onnx"
18
+ }
19
+ },
20
+ "core_suite": {
21
+ "input": "eval/irish_core_pii_v1.jsonl",
22
+ "labels": {
23
+ "PPSN": {
24
+ "base": 0.0,
25
+ "current": 0.08,
26
+ "candidate": 0.8,
27
+ "onnx_q8": 0.7272727272727272
28
+ },
29
+ "account_number": {
30
+ "base": 0.3333333333333333,
31
+ "current": 0.3333333333333333,
32
+ "candidate": 1.0,
33
+ "onnx_q8": 1.0
34
+ },
35
+ "bank_routing_number": {
36
+ "base": 0.0,
37
+ "current": 0.0,
38
+ "candidate": 1.0,
39
+ "onnx_q8": 1.0
40
+ },
41
+ "credit_debit_card": {
42
+ "base": 0.15384615384615385,
43
+ "current": 0.1818181818181818,
44
+ "candidate": 1.0,
45
+ "onnx_q8": 0.3333333333333333
46
+ },
47
+ "PASSPORT_NUMBER": {
48
+ "base": 0.0,
49
+ "current": 0.0,
50
+ "candidate": 1.0,
51
+ "onnx_q8": 1.0
52
+ },
53
+ "postcode": {
54
+ "base": 0.0,
55
+ "current": 0.0,
56
+ "candidate": 1.0,
57
+ "onnx_q8": 1.0
58
+ },
59
+ "phone_number": {
60
+ "base": 0.0,
61
+ "current": 0.0,
62
+ "candidate": 0.8571428571428571,
63
+ "onnx_q8": 0.8571428571428571
64
+ },
65
+ "email": {
66
+ "base": 0.7058823529411764,
67
+ "current": 1.0,
68
+ "candidate": 1.0,
69
+ "onnx_q8": 1.0
70
+ },
71
+ "first_name": {
72
+ "base": 0.8947368421052632,
73
+ "current": 0.8947368421052632,
74
+ "candidate": 1.0,
75
+ "onnx_q8": 1.0
76
+ },
77
+ "last_name": {
78
+ "base": 0.8888888888888888,
79
+ "current": 0.8888888888888888,
80
+ "candidate": 1.0,
81
+ "onnx_q8": 1.0
82
+ },
83
+ "swift_bic": {
84
+ "base": 0.0,
85
+ "current": 0.0,
86
+ "candidate": 1.0,
87
+ "onnx_q8": 1.0
88
+ }
89
+ }
90
+ },
91
+ "edge_suites": {
92
+ "edge_ppsn": {
93
+ "input": "eval/irish_ppsn_phone_edge_v1.jsonl",
94
+ "label": "PPSN",
95
+ "scores": {
96
+ "base": 0.0,
97
+ "current": 0.42105263157894735,
98
+ "candidate": 0.5,
99
+ "onnx_q8": 0.4
100
+ }
101
+ },
102
+ "edge_phone_number": {
103
+ "input": "eval/irish_ppsn_phone_edge_v1.jsonl",
104
+ "label": "phone_number",
105
+ "scores": {
106
+ "base": 0.14285714285714288,
107
+ "current": 0.14285714285714288,
108
+ "candidate": 0.631578947368421,
109
+ "onnx_q8": 0.5
110
+ }
111
+ },
112
+ "multilingual_ppsn": {
113
+ "input": "eval/multilingual_ppsn_v1_all.jsonl",
114
+ "label": "PPSN",
115
+ "scores": {
116
+ "base": 0.0,
117
+ "current": 0.9704142011834319,
118
+ "candidate": 0.9940119760479043,
119
+ "onnx_q8": 0.988235294117647
120
+ }
121
+ }
122
+ },
123
+ "thresholds": {
124
+ "ppsn_min_score": 0.4,
125
+ "other_min_score": 0.5
126
+ }
127
+ }
eval/benchmark_summary.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Irish Core Release Benchmark
2
+
3
+ ## Models
4
+ - `base`: `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1` (transformers)
5
+ - `current`: `temsa/OpenMed-mLiteClinical-IrishPPSN-135M-v1` (transformers)
6
+ - `candidate`: `temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1` (transformers)
7
+ - `onnx_q8`: `temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1#onnx_q8` (onnx dynamic int8, per-channel)
8
+
9
+ ## Core Suite F1
10
+
11
+ | Label | base | current | candidate | onnx_q8 |
12
+ |---|---:|---:|---:|---:|
13
+ | `PPSN` | 0.0000 | 0.0800 | 0.8000 | 0.7273 |
14
+ | `account_number` | 0.3333 | 0.3333 | 1.0000 | 1.0000 |
15
+ | `bank_routing_number` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
16
+ | `credit_debit_card` | 0.1538 | 0.1818 | 1.0000 | 0.3333 |
17
+ | `PASSPORT_NUMBER` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
18
+ | `postcode` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
19
+ | `phone_number` | 0.0000 | 0.0000 | 0.8571 | 0.8571 |
20
+ | `email` | 0.7059 | 1.0000 | 1.0000 | 1.0000 |
21
+ | `first_name` | 0.8947 | 0.8947 | 1.0000 | 1.0000 |
22
+ | `last_name` | 0.8889 | 0.8889 | 1.0000 | 1.0000 |
23
+ | `swift_bic` | 0.0000 | 0.0000 | 1.0000 | 1.0000 |
24
+
25
+ ## Edge And Multilingual F1
26
+
27
+ | Suite | base | current | candidate | onnx_q8 |
28
+ |---|---:|---:|---:|---:|
29
+ | `edge_ppsn` | 0.0000 | 0.4211 | 0.5000 | 0.4000 |
30
+ | `edge_phone_number` | 0.1429 | 0.1429 | 0.6316 | 0.5000 |
31
+ | `multilingual_ppsn` | 0.0000 | 0.9704 | 0.9940 | 0.9882 |
inference_mask.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import os
5
+
6
+ os.environ.setdefault("TRANSFORMERS_NO_TF", "1")
7
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
8
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
9
+ os.environ["USE_TF"] = "0"
10
+ os.environ["USE_FLAX"] = "0"
11
+ os.environ["USE_TORCH"] = "1"
12
+
13
+ import torch
14
+ from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline
15
+
16
+ import regex as re
17
+
18
+
19
+ TOKEN_RE = re.compile(r"[A-Za-z0-9]+|[^\w\s]", re.UNICODE)
20
+ EIRCODE_RE = re.compile(r"^(?:[ACDEFHKNPRTVWXY]\d{2}|D6W)\s?[0-9ACDEFHKNPRTVWXY]{4}$", re.IGNORECASE)
21
+ ALLOWED = {
22
+ "PPSN",
23
+ "ACCOUNT_NUMBER",
24
+ "BANK_ROUTING_NUMBER",
25
+ "CREDIT_DEBIT_CARD",
26
+ "PASSPORT_NUMBER",
27
+ "POSTCODE",
28
+ "PHONE_NUMBER",
29
+ "EMAIL",
30
+ "FIRST_NAME",
31
+ "LAST_NAME",
32
+ "SWIFT_BIC",
33
+ }
34
+
35
+
36
+ def tokenize_with_spans(text: str):
37
+ return [(m.group(0), m.start(), m.end()) for m in TOKEN_RE.finditer(text)]
38
+
39
+
40
+ def normalize_label(label: str) -> str:
41
+ label = (label or "").strip()
42
+ if label.startswith("B-") or label.startswith("I-"):
43
+ label = label[2:]
44
+ return label.upper()
45
+
46
+
47
+ def looks_like_eircode(value: str) -> bool:
48
+ return EIRCODE_RE.match(value.strip()) is not None
49
+
50
+
51
+ def ppsn_label_ids(model):
52
+ ids = []
53
+ for raw_id, raw_label in model.config.id2label.items():
54
+ label_id = int(raw_id)
55
+ label = str(raw_label or "").strip()
56
+ if label.endswith("PPSN"):
57
+ ids.append(label_id)
58
+ return sorted(ids)
59
+
60
+
61
+ def word_aligned_ppsn_spans(text: str, model, tokenizer, threshold: float):
62
+ pieces = tokenize_with_spans(text)
63
+ if not pieces:
64
+ return []
65
+ words = [word for word, _, _ in pieces]
66
+ encoded = tokenizer(words, is_split_into_words=True, return_tensors="pt", truncation=True)
67
+ word_ids = encoded.word_ids(batch_index=0)
68
+ device = next(model.parameters()).device
69
+ encoded = {k: v.to(device) for k, v in encoded.items()}
70
+ with torch.no_grad():
71
+ logits = model(**encoded).logits[0]
72
+ probs = torch.softmax(logits, dim=-1)
73
+ label_ids = ppsn_label_ids(model)
74
+ word_scores = []
75
+ for word_index in range(len(pieces)):
76
+ score = 0.0
77
+ for token_index, wid in enumerate(word_ids):
78
+ if wid != word_index:
79
+ continue
80
+ for label_id in label_ids:
81
+ score = max(score, float(probs[token_index, label_id]))
82
+ word_scores.append(score)
83
+ spans = []
84
+ active = None
85
+ for (_, start, end), score in zip(pieces, word_scores):
86
+ if score >= threshold:
87
+ if active is None:
88
+ active = {"start": start, "end": end, "score": score}
89
+ else:
90
+ active["end"] = end
91
+ active["score"] = max(active["score"], score)
92
+ elif active is not None:
93
+ spans.append(active)
94
+ active = None
95
+ if active is not None:
96
+ spans.append(active)
97
+ for span in spans:
98
+ span["label"] = "PPSN"
99
+ span["text"] = text[span["start"]:span["end"]]
100
+ return spans
101
+
102
+
103
+ def merge_spans(text: str, general_spans: list[dict], ppsn_spans: list[dict], other_min_score: float):
104
+ out = []
105
+ for span in general_spans:
106
+ label = normalize_label(span.get("entity_group") or span.get("entity") or "")
107
+ if label not in ALLOWED or label == "PPSN":
108
+ continue
109
+ if float(span.get("score", 0.0)) < other_min_score:
110
+ continue
111
+ out.append({
112
+ "label": label,
113
+ "start": int(span["start"]),
114
+ "end": int(span["end"]),
115
+ "score": float(span["score"]),
116
+ "text": text[int(span["start"]):int(span["end"])],
117
+ })
118
+ def overlaps(a, b):
119
+ return not (a["end"] <= b["start"] or b["end"] <= a["start"])
120
+ for span in ppsn_spans:
121
+ if looks_like_eircode(span["text"]):
122
+ continue
123
+ if any(overlaps(span, existing) for existing in out):
124
+ continue
125
+ out.append(span)
126
+ out.sort(key=lambda item: (item["start"], item["end"]))
127
+ return out
128
+
129
+
130
+ def mask_text(text: str, spans: list[dict]) -> str:
131
+ out = text
132
+ for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
133
+ out = out[:span["start"]] + f"[{span['label']}]" + out[span["end"]:]
134
+ return out
135
+
136
+
137
+ def main():
138
+ parser = argparse.ArgumentParser()
139
+ parser.add_argument("--model", default=".")
140
+ parser.add_argument("--text", required=True)
141
+ parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
142
+ parser.add_argument("--ppsn-min-score", type=float, default=0.4)
143
+ parser.add_argument("--other-min-score", type=float, default=0.5)
144
+ parser.add_argument("--json", action="store_true")
145
+ args = parser.parse_args()
146
+
147
+ try:
148
+ tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=True, fix_mistral_regex=True)
149
+ except Exception:
150
+ try:
151
+ tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=True, fix_mistral_regex=False)
152
+ except TypeError:
153
+ tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=True)
154
+ model = AutoModelForTokenClassification.from_pretrained(args.model)
155
+ if args.device == "auto":
156
+ device = "cuda" if torch.cuda.is_available() else "cpu"
157
+ else:
158
+ device = args.device
159
+ model.to(device)
160
+ model.eval()
161
+
162
+ nlp = pipeline("token-classification", model=model, tokenizer=tokenizer, aggregation_strategy="simple", device=0 if device == "cuda" else -1)
163
+ general = nlp(args.text)
164
+ ppsn = word_aligned_ppsn_spans(args.text, model, tokenizer, threshold=args.ppsn_min_score)
165
+ spans = merge_spans(args.text, general, ppsn, other_min_score=args.other_min_score)
166
+ result = {
167
+ "model": args.model,
168
+ "masked_text": mask_text(args.text, spans),
169
+ "spans": spans,
170
+ "ppsn_decoder": "word_aligned",
171
+ "ppsn_min_score": args.ppsn_min_score,
172
+ "other_min_score": args.other_min_score,
173
+ }
174
+ if args.json:
175
+ print(json.dumps(result, indent=2, ensure_ascii=False))
176
+ else:
177
+ print(result["masked_text"])
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
inference_mask_onnx.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+
5
+ from onnx_token_classifier import (
6
+ load_onnx_token_classifier,
7
+ looks_like_eircode,
8
+ normalize_label,
9
+ simple_aggregate_spans_onnx,
10
+ word_aligned_ppsn_spans_onnx,
11
+ )
12
+
13
+
14
+ ALLOWED = {
15
+ "PPSN",
16
+ "ACCOUNT_NUMBER",
17
+ "BANK_ROUTING_NUMBER",
18
+ "CREDIT_DEBIT_CARD",
19
+ "PASSPORT_NUMBER",
20
+ "POSTCODE",
21
+ "PHONE_NUMBER",
22
+ "EMAIL",
23
+ "FIRST_NAME",
24
+ "LAST_NAME",
25
+ "SWIFT_BIC",
26
+ }
27
+
28
+
29
+ def mask_text(text: str, spans: list[dict]) -> str:
30
+ out = text
31
+ for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
32
+ out = out[:span["start"]] + f"[{span['label']}]" + out[span["end"]:]
33
+ return out
34
+
35
+
36
+ def main():
37
+ parser = argparse.ArgumentParser()
38
+ parser.add_argument("--model", default=".")
39
+ parser.add_argument("--text", required=True)
40
+ parser.add_argument("--ppsn-min-score", type=float, default=0.4)
41
+ parser.add_argument("--other-min-score", type=float, default=0.5)
42
+ parser.add_argument("--json", action="store_true")
43
+ args = parser.parse_args()
44
+
45
+ session, tokenizer, config = load_onnx_token_classifier(args.model)
46
+ general = simple_aggregate_spans_onnx(args.text, session, tokenizer, config, min_score=args.other_min_score)
47
+ ppsn = word_aligned_ppsn_spans_onnx(args.text, session, tokenizer, config, threshold=args.ppsn_min_score)
48
+ spans = []
49
+ for span in general:
50
+ label = normalize_label(span["label"])
51
+ if label in ALLOWED and label != "PPSN":
52
+ spans.append(span)
53
+ def overlaps(a, b):
54
+ return not (a["end"] <= b["start"] or b["end"] <= a["start"])
55
+ for span in ppsn:
56
+ if looks_like_eircode(span["text"]):
57
+ continue
58
+ if any(overlaps(span, existing) for existing in spans):
59
+ continue
60
+ spans.append(span)
61
+ spans.sort(key=lambda item: (item["start"], item["end"]))
62
+ result = {
63
+ "model": args.model,
64
+ "masked_text": mask_text(args.text, spans),
65
+ "spans": spans,
66
+ "ppsn_decoder": "word_aligned",
67
+ "ppsn_min_score": args.ppsn_min_score,
68
+ "other_min_score": args.other_min_score,
69
+ "backend": "onnx",
70
+ }
71
+ if args.json:
72
+ print(json.dumps(result, indent=2, ensure_ascii=False))
73
+ else:
74
+ print(result["masked_text"])
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
label_meta.json ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
3
+ "label_list": [
4
+ "O",
5
+ "B-account_number",
6
+ "B-age",
7
+ "B-api_key",
8
+ "B-bank_routing_number",
9
+ "B-biometric_identifier",
10
+ "B-blood_type",
11
+ "B-certificate_license_number",
12
+ "B-city",
13
+ "B-company_name",
14
+ "B-coordinate",
15
+ "B-country",
16
+ "B-county",
17
+ "B-credit_debit_card",
18
+ "B-customer_id",
19
+ "B-cvv",
20
+ "B-date",
21
+ "B-date_of_birth",
22
+ "B-date_time",
23
+ "B-device_identifier",
24
+ "B-education_level",
25
+ "B-email",
26
+ "B-employee_id",
27
+ "B-employment_status",
28
+ "B-fax_number",
29
+ "B-first_name",
30
+ "B-gender",
31
+ "B-health_plan_beneficiary_number",
32
+ "B-http_cookie",
33
+ "B-ipv4",
34
+ "B-ipv6",
35
+ "B-language",
36
+ "B-last_name",
37
+ "B-license_plate",
38
+ "B-mac_address",
39
+ "B-medical_record_number",
40
+ "B-occupation",
41
+ "B-password",
42
+ "B-phone_number",
43
+ "B-pin",
44
+ "B-political_view",
45
+ "B-postcode",
46
+ "B-race_ethnicity",
47
+ "B-religious_belief",
48
+ "B-sexuality",
49
+ "B-ssn",
50
+ "B-state",
51
+ "B-street_address",
52
+ "B-swift_bic",
53
+ "B-tax_id",
54
+ "B-time",
55
+ "B-unique_id",
56
+ "B-url",
57
+ "B-user_name",
58
+ "B-vehicle_identifier",
59
+ "I-account_number",
60
+ "I-api_key",
61
+ "I-biometric_identifier",
62
+ "I-blood_type",
63
+ "I-certificate_license_number",
64
+ "I-city",
65
+ "I-company_name",
66
+ "I-coordinate",
67
+ "I-country",
68
+ "I-county",
69
+ "I-credit_debit_card",
70
+ "I-customer_id",
71
+ "I-date",
72
+ "I-date_of_birth",
73
+ "I-date_time",
74
+ "I-device_identifier",
75
+ "I-education_level",
76
+ "I-email",
77
+ "I-employee_id",
78
+ "I-employment_status",
79
+ "I-fax_number",
80
+ "I-first_name",
81
+ "I-gender",
82
+ "I-health_plan_beneficiary_number",
83
+ "I-http_cookie",
84
+ "I-ipv4",
85
+ "I-ipv6",
86
+ "I-language",
87
+ "I-last_name",
88
+ "I-license_plate",
89
+ "I-mac_address",
90
+ "I-medical_record_number",
91
+ "I-occupation",
92
+ "I-password",
93
+ "I-phone_number",
94
+ "I-pin",
95
+ "I-political_view",
96
+ "I-postcode",
97
+ "I-race_ethnicity",
98
+ "I-religious_belief",
99
+ "I-sexuality",
100
+ "I-ssn",
101
+ "I-state",
102
+ "I-street_address",
103
+ "I-swift_bic",
104
+ "I-tax_id",
105
+ "I-time",
106
+ "I-unique_id",
107
+ "I-url",
108
+ "I-user_name",
109
+ "I-vehicle_identifier",
110
+ "B-PPSN",
111
+ "I-PPSN",
112
+ "B-PASSPORT_NUMBER",
113
+ "I-PASSPORT_NUMBER",
114
+ "I-bank_routing_number"
115
+ ],
116
+ "num_labels": 111,
117
+ "target_label": "PPSN",
118
+ "extra_labels": [
119
+ "PPSN"
120
+ ]
121
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb4aa93befac4a1af03477314330f099ba9409dafbe0467c377988dfb91c4270
3
+ size 539290124
onnx/config.json ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "gelu",
3
+ "architectures": [
4
+ "DistilBertForTokenClassification"
5
+ ],
6
+ "attention_dropout": 0.1,
7
+ "dim": 768,
8
+ "dropout": 0.1,
9
+ "dtype": "float32",
10
+ "hidden_dim": 3072,
11
+ "id2label": {
12
+ "0": "O",
13
+ "1": "B-account_number",
14
+ "2": "B-age",
15
+ "3": "B-api_key",
16
+ "4": "B-bank_routing_number",
17
+ "5": "B-biometric_identifier",
18
+ "6": "B-blood_type",
19
+ "7": "B-certificate_license_number",
20
+ "8": "B-city",
21
+ "9": "B-company_name",
22
+ "10": "B-coordinate",
23
+ "11": "B-country",
24
+ "12": "B-county",
25
+ "13": "B-credit_debit_card",
26
+ "14": "B-customer_id",
27
+ "15": "B-cvv",
28
+ "16": "B-date",
29
+ "17": "B-date_of_birth",
30
+ "18": "B-date_time",
31
+ "19": "B-device_identifier",
32
+ "20": "B-education_level",
33
+ "21": "B-email",
34
+ "22": "B-employee_id",
35
+ "23": "B-employment_status",
36
+ "24": "B-fax_number",
37
+ "25": "B-first_name",
38
+ "26": "B-gender",
39
+ "27": "B-health_plan_beneficiary_number",
40
+ "28": "B-http_cookie",
41
+ "29": "B-ipv4",
42
+ "30": "B-ipv6",
43
+ "31": "B-language",
44
+ "32": "B-last_name",
45
+ "33": "B-license_plate",
46
+ "34": "B-mac_address",
47
+ "35": "B-medical_record_number",
48
+ "36": "B-occupation",
49
+ "37": "B-password",
50
+ "38": "B-phone_number",
51
+ "39": "B-pin",
52
+ "40": "B-political_view",
53
+ "41": "B-postcode",
54
+ "42": "B-race_ethnicity",
55
+ "43": "B-religious_belief",
56
+ "44": "B-sexuality",
57
+ "45": "B-ssn",
58
+ "46": "B-state",
59
+ "47": "B-street_address",
60
+ "48": "B-swift_bic",
61
+ "49": "B-tax_id",
62
+ "50": "B-time",
63
+ "51": "B-unique_id",
64
+ "52": "B-url",
65
+ "53": "B-user_name",
66
+ "54": "B-vehicle_identifier",
67
+ "55": "I-account_number",
68
+ "56": "I-api_key",
69
+ "57": "I-biometric_identifier",
70
+ "58": "I-blood_type",
71
+ "59": "I-certificate_license_number",
72
+ "60": "I-city",
73
+ "61": "I-company_name",
74
+ "62": "I-coordinate",
75
+ "63": "I-country",
76
+ "64": "I-county",
77
+ "65": "I-credit_debit_card",
78
+ "66": "I-customer_id",
79
+ "67": "I-date",
80
+ "68": "I-date_of_birth",
81
+ "69": "I-date_time",
82
+ "70": "I-device_identifier",
83
+ "71": "I-education_level",
84
+ "72": "I-email",
85
+ "73": "I-employee_id",
86
+ "74": "I-employment_status",
87
+ "75": "I-fax_number",
88
+ "76": "I-first_name",
89
+ "77": "I-gender",
90
+ "78": "I-health_plan_beneficiary_number",
91
+ "79": "I-http_cookie",
92
+ "80": "I-ipv4",
93
+ "81": "I-ipv6",
94
+ "82": "I-language",
95
+ "83": "I-last_name",
96
+ "84": "I-license_plate",
97
+ "85": "I-mac_address",
98
+ "86": "I-medical_record_number",
99
+ "87": "I-occupation",
100
+ "88": "I-password",
101
+ "89": "I-phone_number",
102
+ "90": "I-pin",
103
+ "91": "I-political_view",
104
+ "92": "I-postcode",
105
+ "93": "I-race_ethnicity",
106
+ "94": "I-religious_belief",
107
+ "95": "I-sexuality",
108
+ "96": "I-ssn",
109
+ "97": "I-state",
110
+ "98": "I-street_address",
111
+ "99": "I-swift_bic",
112
+ "100": "I-tax_id",
113
+ "101": "I-time",
114
+ "102": "I-unique_id",
115
+ "103": "I-url",
116
+ "104": "I-user_name",
117
+ "105": "I-vehicle_identifier",
118
+ "106": "B-PPSN",
119
+ "107": "I-PPSN",
120
+ "108": "B-PASSPORT_NUMBER",
121
+ "109": "I-PASSPORT_NUMBER",
122
+ "110": "I-bank_routing_number"
123
+ },
124
+ "initializer_range": 0.02,
125
+ "label2id": {
126
+ "B-PASSPORT_NUMBER": 108,
127
+ "B-PPSN": 106,
128
+ "B-account_number": 1,
129
+ "B-age": 2,
130
+ "B-api_key": 3,
131
+ "B-bank_routing_number": 4,
132
+ "B-biometric_identifier": 5,
133
+ "B-blood_type": 6,
134
+ "B-certificate_license_number": 7,
135
+ "B-city": 8,
136
+ "B-company_name": 9,
137
+ "B-coordinate": 10,
138
+ "B-country": 11,
139
+ "B-county": 12,
140
+ "B-credit_debit_card": 13,
141
+ "B-customer_id": 14,
142
+ "B-cvv": 15,
143
+ "B-date": 16,
144
+ "B-date_of_birth": 17,
145
+ "B-date_time": 18,
146
+ "B-device_identifier": 19,
147
+ "B-education_level": 20,
148
+ "B-email": 21,
149
+ "B-employee_id": 22,
150
+ "B-employment_status": 23,
151
+ "B-fax_number": 24,
152
+ "B-first_name": 25,
153
+ "B-gender": 26,
154
+ "B-health_plan_beneficiary_number": 27,
155
+ "B-http_cookie": 28,
156
+ "B-ipv4": 29,
157
+ "B-ipv6": 30,
158
+ "B-language": 31,
159
+ "B-last_name": 32,
160
+ "B-license_plate": 33,
161
+ "B-mac_address": 34,
162
+ "B-medical_record_number": 35,
163
+ "B-occupation": 36,
164
+ "B-password": 37,
165
+ "B-phone_number": 38,
166
+ "B-pin": 39,
167
+ "B-political_view": 40,
168
+ "B-postcode": 41,
169
+ "B-race_ethnicity": 42,
170
+ "B-religious_belief": 43,
171
+ "B-sexuality": 44,
172
+ "B-ssn": 45,
173
+ "B-state": 46,
174
+ "B-street_address": 47,
175
+ "B-swift_bic": 48,
176
+ "B-tax_id": 49,
177
+ "B-time": 50,
178
+ "B-unique_id": 51,
179
+ "B-url": 52,
180
+ "B-user_name": 53,
181
+ "B-vehicle_identifier": 54,
182
+ "I-PASSPORT_NUMBER": 109,
183
+ "I-PPSN": 107,
184
+ "I-account_number": 55,
185
+ "I-api_key": 56,
186
+ "I-bank_routing_number": 110,
187
+ "I-biometric_identifier": 57,
188
+ "I-blood_type": 58,
189
+ "I-certificate_license_number": 59,
190
+ "I-city": 60,
191
+ "I-company_name": 61,
192
+ "I-coordinate": 62,
193
+ "I-country": 63,
194
+ "I-county": 64,
195
+ "I-credit_debit_card": 65,
196
+ "I-customer_id": 66,
197
+ "I-date": 67,
198
+ "I-date_of_birth": 68,
199
+ "I-date_time": 69,
200
+ "I-device_identifier": 70,
201
+ "I-education_level": 71,
202
+ "I-email": 72,
203
+ "I-employee_id": 73,
204
+ "I-employment_status": 74,
205
+ "I-fax_number": 75,
206
+ "I-first_name": 76,
207
+ "I-gender": 77,
208
+ "I-health_plan_beneficiary_number": 78,
209
+ "I-http_cookie": 79,
210
+ "I-ipv4": 80,
211
+ "I-ipv6": 81,
212
+ "I-language": 82,
213
+ "I-last_name": 83,
214
+ "I-license_plate": 84,
215
+ "I-mac_address": 85,
216
+ "I-medical_record_number": 86,
217
+ "I-occupation": 87,
218
+ "I-password": 88,
219
+ "I-phone_number": 89,
220
+ "I-pin": 90,
221
+ "I-political_view": 91,
222
+ "I-postcode": 92,
223
+ "I-race_ethnicity": 93,
224
+ "I-religious_belief": 94,
225
+ "I-sexuality": 95,
226
+ "I-ssn": 96,
227
+ "I-state": 97,
228
+ "I-street_address": 98,
229
+ "I-swift_bic": 99,
230
+ "I-tax_id": 100,
231
+ "I-time": 101,
232
+ "I-unique_id": 102,
233
+ "I-url": 103,
234
+ "I-user_name": 104,
235
+ "I-vehicle_identifier": 105,
236
+ "O": 0
237
+ },
238
+ "max_position_embeddings": 512,
239
+ "model_type": "distilbert",
240
+ "n_heads": 12,
241
+ "n_layers": 6,
242
+ "output_past": true,
243
+ "pad_token_id": 0,
244
+ "qa_dropout": 0.1,
245
+ "seq_classif_dropout": 0.2,
246
+ "sinusoidal_pos_embds": false,
247
+ "tie_weights_": true,
248
+ "transformers_version": "4.57.6",
249
+ "vocab_size": 119547
250
+ }
onnx/label_meta.json ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
3
+ "label_list": [
4
+ "O",
5
+ "B-account_number",
6
+ "B-age",
7
+ "B-api_key",
8
+ "B-bank_routing_number",
9
+ "B-biometric_identifier",
10
+ "B-blood_type",
11
+ "B-certificate_license_number",
12
+ "B-city",
13
+ "B-company_name",
14
+ "B-coordinate",
15
+ "B-country",
16
+ "B-county",
17
+ "B-credit_debit_card",
18
+ "B-customer_id",
19
+ "B-cvv",
20
+ "B-date",
21
+ "B-date_of_birth",
22
+ "B-date_time",
23
+ "B-device_identifier",
24
+ "B-education_level",
25
+ "B-email",
26
+ "B-employee_id",
27
+ "B-employment_status",
28
+ "B-fax_number",
29
+ "B-first_name",
30
+ "B-gender",
31
+ "B-health_plan_beneficiary_number",
32
+ "B-http_cookie",
33
+ "B-ipv4",
34
+ "B-ipv6",
35
+ "B-language",
36
+ "B-last_name",
37
+ "B-license_plate",
38
+ "B-mac_address",
39
+ "B-medical_record_number",
40
+ "B-occupation",
41
+ "B-password",
42
+ "B-phone_number",
43
+ "B-pin",
44
+ "B-political_view",
45
+ "B-postcode",
46
+ "B-race_ethnicity",
47
+ "B-religious_belief",
48
+ "B-sexuality",
49
+ "B-ssn",
50
+ "B-state",
51
+ "B-street_address",
52
+ "B-swift_bic",
53
+ "B-tax_id",
54
+ "B-time",
55
+ "B-unique_id",
56
+ "B-url",
57
+ "B-user_name",
58
+ "B-vehicle_identifier",
59
+ "I-account_number",
60
+ "I-api_key",
61
+ "I-biometric_identifier",
62
+ "I-blood_type",
63
+ "I-certificate_license_number",
64
+ "I-city",
65
+ "I-company_name",
66
+ "I-coordinate",
67
+ "I-country",
68
+ "I-county",
69
+ "I-credit_debit_card",
70
+ "I-customer_id",
71
+ "I-date",
72
+ "I-date_of_birth",
73
+ "I-date_time",
74
+ "I-device_identifier",
75
+ "I-education_level",
76
+ "I-email",
77
+ "I-employee_id",
78
+ "I-employment_status",
79
+ "I-fax_number",
80
+ "I-first_name",
81
+ "I-gender",
82
+ "I-health_plan_beneficiary_number",
83
+ "I-http_cookie",
84
+ "I-ipv4",
85
+ "I-ipv6",
86
+ "I-language",
87
+ "I-last_name",
88
+ "I-license_plate",
89
+ "I-mac_address",
90
+ "I-medical_record_number",
91
+ "I-occupation",
92
+ "I-password",
93
+ "I-phone_number",
94
+ "I-pin",
95
+ "I-political_view",
96
+ "I-postcode",
97
+ "I-race_ethnicity",
98
+ "I-religious_belief",
99
+ "I-sexuality",
100
+ "I-ssn",
101
+ "I-state",
102
+ "I-street_address",
103
+ "I-swift_bic",
104
+ "I-tax_id",
105
+ "I-time",
106
+ "I-unique_id",
107
+ "I-url",
108
+ "I-user_name",
109
+ "I-vehicle_identifier",
110
+ "B-PPSN",
111
+ "I-PPSN",
112
+ "B-PASSPORT_NUMBER",
113
+ "I-PASSPORT_NUMBER",
114
+ "I-bank_routing_number"
115
+ ],
116
+ "num_labels": 111,
117
+ "target_label": "PPSN",
118
+ "extra_labels": [
119
+ "PPSN"
120
+ ]
121
+ }
onnx/model_quantized.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59db69ccb9165fa16ca9bf855b6c0e8b12a3f0152a6260e546a606cd30521b09
3
+ size 135293905
onnx/onnx_export.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_model": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1",
3
+ "format": "onnx",
4
+ "task": "token-classification",
5
+ "opset": 17,
6
+ "artifact": "model.onnx",
7
+ "exporter": "torch.onnx.export"
8
+ }
onnx/quantization.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_dir": "onnx/model.onnx",
3
+ "format": "onnx_dynamic_quantized",
4
+ "artifact": "model_quantized.onnx",
5
+ "weight_type": "QInt8",
6
+ "per_channel": true
7
+ }
onnx/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
+ }
onnx/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
onnx/tokenizer_config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": false,
47
+ "extra_special_tokens": {},
48
+ "fix_mistral_regex": true,
49
+ "mask_token": "[MASK]",
50
+ "max_length": 512,
51
+ "model_max_length": 512,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "stride": 0,
55
+ "strip_accents": null,
56
+ "tokenize_chinese_chars": true,
57
+ "tokenizer_class": "DistilBertTokenizer",
58
+ "truncation_side": "right",
59
+ "truncation_strategy": "longest_first",
60
+ "unk_token": "[UNK]"
61
+ }
onnx/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
onnx_token_classifier.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import json
3
+ import os
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+ os.environ.setdefault("TRANSFORMERS_NO_TF", "1")
8
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
9
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
10
+ os.environ["USE_TF"] = "0"
11
+ os.environ["USE_FLAX"] = "0"
12
+ os.environ["USE_TORCH"] = "1"
13
+
14
+ import numpy as np
15
+ import regex as re
16
+ from huggingface_hub import HfApi, hf_hub_download
17
+ from transformers import AutoConfig, AutoTokenizer
18
+
19
+
20
+ TOKEN_RE = re.compile(r"[A-Za-z0-9]+|[^\w\s]", re.UNICODE)
21
+ DEFAULT_ONNX_FILES = ["onnx/model_quantized.onnx", "model_quantized.onnx"]
22
+ EIRCODE_RE = re.compile(r"^(?:[ACDEFHKNPRTVWXY]\d{2}|D6W)\s?[0-9ACDEFHKNPRTVWXY]{4}$", re.IGNORECASE)
23
+
24
+
25
+ def tokenize_with_spans(text: str):
26
+ return [(m.group(0), m.start(), m.end()) for m in TOKEN_RE.finditer(text)]
27
+
28
+
29
+ def _load_tokenizer(tokenizer_ref: str):
30
+ tokenizer_path = Path(tokenizer_ref)
31
+ if tokenizer_path.exists():
32
+ tokenizer_cfg_path = tokenizer_path / "tokenizer_config.json"
33
+ if tokenizer_cfg_path.exists():
34
+ data = json.loads(tokenizer_cfg_path.read_text(encoding="utf-8"))
35
+ if "fix_mistral_regex" in data:
36
+ tmpdir = Path(tempfile.mkdtemp(prefix="openmed_onnx_tokenizer_"))
37
+ keep = {"tokenizer_config.json", "tokenizer.json", "special_tokens_map.json", "vocab.txt"}
38
+ for child in tokenizer_path.iterdir():
39
+ if child.is_file() and child.name in keep:
40
+ (tmpdir / child.name).write_bytes(child.read_bytes())
41
+ data.pop("fix_mistral_regex", None)
42
+ (tmpdir / "tokenizer_config.json").write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
43
+ tokenizer_ref = str(tmpdir)
44
+ try:
45
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=True)
46
+ except Exception:
47
+ try:
48
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=False)
49
+ except TypeError:
50
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True)
51
+
52
+
53
+ def load_onnx_token_classifier(model_ref: str, onnx_file: str | None = None):
54
+ import onnxruntime as ort
55
+ model_path = Path(model_ref)
56
+ if model_path.exists():
57
+ candidates = [onnx_file] if onnx_file else []
58
+ candidates += DEFAULT_ONNX_FILES
59
+ onnx_path = None
60
+ for candidate in candidates:
61
+ if not candidate:
62
+ continue
63
+ path = model_path / candidate
64
+ if path.exists():
65
+ onnx_path = path
66
+ break
67
+ if onnx_path is None:
68
+ raise FileNotFoundError("Missing ONNX artifact")
69
+ config = AutoConfig.from_pretrained(model_ref)
70
+ tokenizer = _load_tokenizer(model_ref)
71
+ else:
72
+ api = HfApi()
73
+ files = set(api.list_repo_files(repo_id=model_ref, repo_type="model"))
74
+ chosen = None
75
+ candidates = [onnx_file] if onnx_file else []
76
+ candidates += DEFAULT_ONNX_FILES
77
+ for candidate in candidates:
78
+ if candidate and candidate in files:
79
+ chosen = candidate
80
+ break
81
+ if chosen is None:
82
+ raise FileNotFoundError("No ONNX artifact published")
83
+ onnx_path = Path(hf_hub_download(repo_id=model_ref, filename=chosen, repo_type="model"))
84
+ config = AutoConfig.from_pretrained(model_ref)
85
+ tokenizer = _load_tokenizer(model_ref)
86
+ session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
87
+ return session, tokenizer, config
88
+
89
+
90
+ def _softmax(logits):
91
+ shifted = logits - np.max(logits, axis=-1, keepdims=True)
92
+ exp = np.exp(shifted)
93
+ return exp / np.clip(np.sum(exp, axis=-1, keepdims=True), 1e-12, None)
94
+
95
+
96
+ def _run(session, encoded):
97
+ input_names = {item.name for item in session.get_inputs()}
98
+ feed = {}
99
+ for key, value in encoded.items():
100
+ if key == "offset_mapping":
101
+ continue
102
+ if key in input_names:
103
+ feed[key] = value
104
+ return session.run(None, feed)[0]
105
+
106
+
107
+ def normalize_label(label: str) -> str:
108
+ label = (label or "").strip()
109
+ if label.startswith("B-") or label.startswith("I-"):
110
+ label = label[2:]
111
+ return label.upper()
112
+
113
+
114
+ def looks_like_eircode(value: str) -> bool:
115
+ return EIRCODE_RE.match(value.strip()) is not None
116
+
117
+
118
+ def ppsn_label_ids_from_config(config):
119
+ ids = []
120
+ for raw_id, raw_label in config.id2label.items():
121
+ label_id = int(raw_id)
122
+ label = str(raw_label or "").strip()
123
+ if label.endswith("PPSN"):
124
+ ids.append(label_id)
125
+ return sorted(ids)
126
+
127
+
128
+ def simple_aggregate_spans_onnx(text, session, tokenizer, config, min_score=0.5):
129
+ encoded = tokenizer(text, return_offsets_mapping=True, return_tensors="np", truncation=True)
130
+ logits = _run(session, encoded)[0]
131
+ probs = _softmax(logits)
132
+ pred_ids = probs.argmax(axis=-1)
133
+ id2label = {int(k): v for k, v in config.id2label.items()}
134
+ offsets = encoded["offset_mapping"][0].tolist()
135
+ attention = encoded["attention_mask"][0].tolist()
136
+ spans = []
137
+ active = None
138
+ for idx, ((start, end), keep) in enumerate(zip(offsets, attention)):
139
+ if not keep or start == end:
140
+ if active is not None:
141
+ spans.append(active)
142
+ active = None
143
+ continue
144
+ label = id2label[int(pred_ids[idx])]
145
+ if label == "O":
146
+ if active is not None:
147
+ spans.append(active)
148
+ active = None
149
+ continue
150
+ score = float(probs[idx, int(pred_ids[idx])])
151
+ if score < min_score:
152
+ if active is not None:
153
+ spans.append(active)
154
+ active = None
155
+ continue
156
+ prefix = label[:1] if label.startswith(("B-", "I-")) else "B"
157
+ entity = normalize_label(label)
158
+ if active is None or prefix == "B" or entity != active["label"] or int(start) > int(active["end"]) + 1:
159
+ if active is not None:
160
+ spans.append(active)
161
+ active = {"label": entity, "start": int(start), "end": int(end), "score": score}
162
+ else:
163
+ active["end"] = int(end)
164
+ active["score"] = max(float(active["score"]), score)
165
+ if active is not None:
166
+ spans.append(active)
167
+ for span in spans:
168
+ span["text"] = text[span["start"]:span["end"]]
169
+ return spans
170
+
171
+
172
+ def word_aligned_ppsn_spans_onnx(text, session, tokenizer, config, threshold=0.4):
173
+ pieces = tokenize_with_spans(text)
174
+ if not pieces:
175
+ return []
176
+ words = [word for word, _, _ in pieces]
177
+ encoded = tokenizer(words, is_split_into_words=True, return_tensors="np", truncation=True)
178
+ word_ids = encoded.word_ids(batch_index=0)
179
+ logits = _run(session, encoded)[0]
180
+ probs = _softmax(logits)
181
+ label_ids = ppsn_label_ids_from_config(config)
182
+ word_scores = []
183
+ for word_index in range(len(pieces)):
184
+ score = 0.0
185
+ for token_index, wid in enumerate(word_ids):
186
+ if wid != word_index:
187
+ continue
188
+ for label_id in label_ids:
189
+ score = max(score, float(probs[token_index, label_id]))
190
+ word_scores.append(score)
191
+ spans = []
192
+ active = None
193
+ for (_, start, end), score in zip(pieces, word_scores):
194
+ if score >= threshold:
195
+ if active is None:
196
+ active = {"label": "PPSN", "start": start, "end": end, "score": score}
197
+ else:
198
+ active["end"] = end
199
+ active["score"] = max(float(active["score"]), score)
200
+ elif active is not None:
201
+ spans.append(active)
202
+ active = None
203
+ if active is not None:
204
+ spans.append(active)
205
+ for span in spans:
206
+ span["text"] = text[span["start"]:span["end"]]
207
+ return spans
pyproject.toml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "openmed-mliteclinical-irish-core-pii"
3
+ version = "0.1.0"
4
+ description = "Irish core PII token-classification release for OpenMed mLiteClinical"
5
+ requires-python = ">=3.10"
6
+ readme = "README.md"
7
+ license = { text = "Apache-2.0" }
8
+ dependencies = [
9
+ "transformers>=4.41.0",
10
+ "torch",
11
+ "numpy>=1.26.0",
12
+ "regex>=2024.5.15",
13
+ "onnxruntime>=1.20.0",
14
+ "huggingface_hub>=0.36.0",
15
+ ]
16
+
17
+ [tool.uv]
18
+ package = false
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
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": false,
47
+ "extra_special_tokens": {},
48
+ "fix_mistral_regex": true,
49
+ "mask_token": "[MASK]",
50
+ "max_length": 512,
51
+ "model_max_length": 512,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "stride": 0,
55
+ "strip_accents": null,
56
+ "tokenize_chinese_chars": true,
57
+ "tokenizer_class": "DistilBertTokenizer",
58
+ "truncation_side": "right",
59
+ "truncation_strategy": "longest_first",
60
+ "unk_token": "[UNK]"
61
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff