temsa commited on
Commit
d1ddb26
·
verified ·
1 Parent(s): 5caf0eb

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -1,35 +1,5 @@
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
  *.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
2
  *.onnx filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
3
  *.pt filter=lfs diff=lfs merge=lfs -text
4
  *.pth filter=lfs diff=lfs merge=lfs -text
 
5
  *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ .venv/
3
+ *.pyc
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,8 @@
 
 
 
 
 
 
 
 
 
1
+ This release is derived from OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1 (Apache-2.0).
2
+
3
+ Additional training data attribution:
4
+ - joelniklaus/mapa (CC-BY-4.0)
5
+ - gretelai/synthetic_pii_finance_multilingual (Apache-2.0)
6
+ - Synthetic Irish datasets created in this workspace and released under Apache-2.0
7
+
8
+ This repo distributes model artifacts and synthetic benchmark files. It does not redistribute third-party dataset rows.
README.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - de-identification
11
+ - token-classification
12
+ - ireland
13
+ - irish
14
+ - gaelic
15
+ - ppsn
16
+ - eircode
17
+ - passport
18
+ - phone-number
19
+ - iban
20
+ - onnx
21
+ - int8
22
+ base_model:
23
+ - OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1
24
+ datasets:
25
+ - temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1
26
+ - temsa/OpenMed-Irish-CorePII-TrainMix-v1
27
+ - joelniklaus/mapa
28
+ - gretelai/synthetic_pii_finance_multilingual
29
+ ---
30
+
31
+ # OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5
32
+
33
+ Token-classification checkpoint for Irish core PII in English and Irish Gaelic.
34
+
35
+ ## Included Variants
36
+
37
+ - Full `transformers` checkpoint in the repo root
38
+ - Unquantized ONNX export in `onnx/model.onnx`
39
+ - Dynamic q8 ONNX artifact in `onnx/model_quantized.onnx`
40
+ - `inference_mask.py` for the full checkpoint
41
+ - `inference_mask_onnx.py` for the ONNX q8 artifact
42
+ - benchmark files in `eval/`
43
+
44
+ ## Coverage
45
+
46
+ - `PPSN`
47
+ - `ACCOUNT_NUMBER`
48
+ - `BANK_ROUTING_NUMBER`
49
+ - `CREDIT_DEBIT_CARD`
50
+ - `PASSPORT_NUMBER`
51
+ - `POSTCODE`
52
+ - `PHONE_NUMBER`
53
+ - `EMAIL`
54
+ - `FIRST_NAME`
55
+ - `LAST_NAME`
56
+ - `SWIFT_BIC`
57
+
58
+ ## What Changed From rc4
59
+
60
+ `rc5` keeps the same fine-tuned checkpoint weights as `temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc4`, but changes the shipped inference stack:
61
+
62
+ - recommended `PPSN` threshold lowered from `0.71` to `0.55`
63
+ - recommended decoder is now the Irish core label-aware repair decoder for both full and q8 inference
64
+ - bundled q8 artifact is rebuilt from a preprocessed ONNX export before dynamic int8 quantization
65
+
66
+ This is the right change because the new QA misses in Gaelic weak-context PPSN text were calibration/inference failures, not weight-quality failures.
67
+
68
+ ## Recommended Inference
69
+
70
+ Full checkpoint:
71
+
72
+ ```bash
73
+ uv run python inference_mask.py \
74
+ --model temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5 \
75
+ --ppsn-min-score 0.55 \
76
+ --other-min-score 0.50 \
77
+ --text "Duradh liom mo uimhir 1234567T a sholatar agus me ag denamh iarratais." \
78
+ --json
79
+ ```
80
+
81
+ Dynamic q8 ONNX:
82
+
83
+ ```bash
84
+ uv run python inference_mask_onnx.py \
85
+ --model temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5 \
86
+ --onnx-file onnx/model_quantized.onnx \
87
+ --ppsn-min-score 0.55 \
88
+ --other-min-score 0.50 \
89
+ --text "Is e mo upsp na 1234567tw agus teastaionn uaim eolas faoi liuntas curamora." \
90
+ --json
91
+ ```
92
+
93
+ The bundled `pyproject.toml` is intended for `uv`. Use `uv run` so `onnxruntime` is available for the q8 script.
94
+
95
+ ## Key Benchmarks
96
+
97
+ ### Fix For The Reported Gaelic PPSN Regression
98
+
99
+ | Variant | QA Gaelic weak-context PPSN F1 |
100
+ |---|---:|
101
+ | `rc4` full published defaults | 0.0000 |
102
+ | `rc4` q8 published defaults | 0.6667 |
103
+ | `rc5` full | 1.0000 |
104
+ | `rc5` q8 | 1.0000 |
105
+
106
+ ### Base OpenMed vs rc5
107
+
108
+ | Suite | Base OpenMed | rc5 full | rc5 ONNX q8 |
109
+ |---|---:|---:|---:|
110
+ | Irish core manual | 0.6119 | 0.9737 | 0.9669 |
111
+ | Irish PPSN/phone edge | 0.0769 | 0.9744 | 0.9744 |
112
+ | Remaining gaps | n/a | 1.0000 | 0.8889 |
113
+ | Phone/passport/finance | n/a | 0.9600 | 0.9362 |
114
+ | Finance boundary repair | n/a | 0.9143 | 0.8750 |
115
+ | Multilingual PPSN | 0.0000 | 0.9333 | 0.9333 |
116
+ | User PPSN regressions | n/a | 1.0000 | 1.0000 |
117
+ | Irish PPSN overlap | n/a | 1.0000 | 1.0000 |
118
+
119
+ ### Core Label Breakdown
120
+
121
+ | Label | Base OpenMed | rc5 full | rc5 ONNX q8 |
122
+ |---|---:|---:|---:|
123
+ | PPSN | 0.0000 | 0.9231 | 0.9231 |
124
+ | PHONE_NUMBER | 0.0000 | 0.9565 | 0.9565 |
125
+ | POSTCODE | 0.0000 | 1.0000 | 0.8571 |
126
+ | PASSPORT_NUMBER | 0.0000 | 1.0000 | 1.0000 |
127
+ | ACCOUNT_NUMBER | 0.4000 | 0.8571 | 0.8571 |
128
+ | BANK_ROUTING_NUMBER | 0.0000 | 1.0000 | 1.0000 |
129
+ | EMAIL | 1.0000 | 1.0000 | 1.0000 |
130
+ | FIRST_NAME | 0.8947 | 1.0000 | 1.0000 |
131
+ | LAST_NAME | 0.8889 | 1.0000 | 1.0000 |
132
+
133
+ ## Dynamic q8 Artifact
134
+
135
+ Artifact paths:
136
+
137
+ - unquantized: `onnx/model.onnx`
138
+ - quantized: `onnx/model_quantized.onnx`
139
+
140
+ Quantization recipe used in this repo:
141
+
142
+ - ONNX pre-processing before quantization
143
+ - ONNX Runtime dynamic int8
144
+ - `qint8`
145
+ - `per_channel=true`
146
+ - `op_types=MatMul,Gemm,Attention`
147
+
148
+ This q8 path keeps the same F1 as the best prior q8 recipe on the sampled comparison suites while improving CPU throughput on the manual Irish-core suites.
149
+
150
+ ### CPU Throughput
151
+
152
+ | Suite | Base OpenMed | rc5 full | rc5 ONNX q8 |
153
+ |---|---:|---:|---:|
154
+ | Irish core manual | 15.79 | 6.70 | 34.43 |
155
+ | Irish PPSN/phone edge | 16.60 | 16.50 | 36.56 |
156
+ | Multilingual PPSN | 121.08 | 125.30 | 289.49 |
157
+
158
+ ## Limits
159
+
160
+ - The full checkpoint is still stronger than q8 on the finance-boundary suite.
161
+ - The q8 artifact is still weaker than the full checkpoint on the strict remaining-gap suite.
162
+ - Grouped credit/debit-card boundary cases remain the main shared weakness and should still be QA tested.
163
+
164
+ ## License And Attribution
165
+
166
+ - Release license: Apache-2.0
167
+ - Base model: `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1`
168
+ - See `NOTICE` and `training_sources.json` for attribution and release 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,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repo_id": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5",
3
+ "base_model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
4
+ "previous_public_candidate": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc4",
5
+ "stable_public_reference": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1",
6
+ "recommended_thresholds": {
7
+ "full_checkpoint": {
8
+ "ppsn_min_score": 0.55,
9
+ "other_min_score": 0.5
10
+ },
11
+ "onnx_q8": {
12
+ "ppsn_min_score": 0.55,
13
+ "other_min_score": 0.5
14
+ }
15
+ },
16
+ "inference_stack": {
17
+ "full_checkpoint": "transformers + word-aligned PPSN decoder + Irish core label-aware repair decoder",
18
+ "onnx_q8": "ONNX Runtime + word-aligned PPSN decoder + Irish core label-aware repair decoder",
19
+ "quantized_artifact": "preprocessed ONNX export + dynamic int8 qint8 per-channel quantization over MatMul,Gemm,Attention"
20
+ },
21
+ "rc4_default_fix": {
22
+ "full_rc4_gaelic_weak_ppsn_f1": 0.0,
23
+ "q8_rc4_gaelic_weak_ppsn_f1": 0.6666666666666666,
24
+ "full_rc5_gaelic_weak_ppsn_f1": 1.0,
25
+ "q8_rc5_gaelic_weak_ppsn_f1": 1.0
26
+ },
27
+ "comparison": {
28
+ "base": {
29
+ "core": 0.6119402985074627,
30
+ "edge": 0.07692307692307693,
31
+ "multilingual_ppsn": 0.0,
32
+ "gaelic_weak_ppsn": 0.0
33
+ },
34
+ "full_rc5": {
35
+ "core": 0.9736842105263158,
36
+ "edge": 0.9743589743589743,
37
+ "remaining_gaps": 1.0,
38
+ "finance": 0.96,
39
+ "finance_boundary": 0.9142857142857143,
40
+ "multilingual_ppsn": 0.9333333333333333,
41
+ "user_ppsn": 1.0,
42
+ "gaelic_weak_ppsn": 1.0,
43
+ "overlap_ppsn": 1.0
44
+ },
45
+ "onnx_q8_rc5": {
46
+ "core": 0.9668874172185431,
47
+ "edge": 0.9743589743589743,
48
+ "remaining_gaps": 0.888888888888889,
49
+ "finance": 0.9361702127659575,
50
+ "finance_boundary": 0.8750000000000001,
51
+ "multilingual_ppsn": 0.9333333333333333,
52
+ "user_ppsn": 1.0,
53
+ "gaelic_weak_ppsn": 1.0,
54
+ "overlap_ppsn": 1.0
55
+ }
56
+ },
57
+ "throughput_examples_per_second": {
58
+ "base": {
59
+ "core": 15.788589934237567,
60
+ "edge": 16.597286250507974,
61
+ "multilingual_ppsn": 121.08022850236169
62
+ },
63
+ "full_rc5": {
64
+ "core": 6.700125103140684,
65
+ "edge": 16.499042309254193,
66
+ "multilingual_ppsn": 125.29715423168584
67
+ },
68
+ "onnx_q8_rc5": {
69
+ "core": 34.43327146422294,
70
+ "edge": 36.5647497398089,
71
+ "multilingual_ppsn": 289.4883372843083
72
+ }
73
+ }
74
+ }
eval/benchmark_summary.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Benchmark Summary
2
+
3
+ Recommended thresholds:
4
+ - Full checkpoint: `ppsn_min_score=0.55`, `other_min_score=0.50`
5
+ - ONNX q8: `ppsn_min_score=0.55`, `other_min_score=0.50`
6
+
7
+ ## What Changed From rc4
8
+
9
+ - `rc5` keeps the same full checkpoint weights as `rc4`.
10
+ - The public inference defaults change from `ppsn_min_score=0.71` to `0.55`.
11
+ - The recommended inference path for both variants uses the Irish core label-aware decoder.
12
+ - The bundled ONNX q8 artifact is rebuilt from a preprocessed ONNX export before dynamic int8 quantization.
13
+
14
+ ## Fix For The New Gaelic PPSN Regression
15
+
16
+ | Variant | QA Gaelic weak-context PPSN F1 |
17
+ |---|---:|
18
+ | rc4 full defaults | 0.0000 |
19
+ | rc4 q8 defaults | 0.6667 |
20
+ | rc5 full | 1.0000 |
21
+ | rc5 q8 | 1.0000 |
22
+
23
+ ## Base vs rc5
24
+
25
+ | Suite | Base OpenMed | rc5 full | rc5 ONNX q8 |
26
+ |---|---:|---:|---:|
27
+ | Irish core manual | 0.6119 | 0.9737 | 0.9669 |
28
+ | Irish PPSN/phone edge | 0.0769 | 0.9744 | 0.9744 |
29
+ | Remaining gaps | n/a | 1.0000 | 0.8889 |
30
+ | Phone/passport/finance | n/a | 0.9600 | 0.9362 |
31
+ | Finance boundary repair | n/a | 0.9143 | 0.8750 |
32
+ | Multilingual PPSN | 0.0000 | 0.9333 | 0.9333 |
33
+ | User PPSN regressions | n/a | 1.0000 | 1.0000 |
34
+ | Irish PPSN overlap | n/a | 1.0000 | 1.0000 |
35
+
36
+ ## Core Label Breakdown
37
+
38
+ | Label | Base OpenMed | rc5 full | rc5 ONNX q8 |
39
+ |---|---:|---:|---:|
40
+ | PPSN | 0.0000 | 0.9231 | 0.9231 |
41
+ | PHONE_NUMBER | 0.0000 | 0.9565 | 0.9565 |
42
+ | POSTCODE | 0.0000 | 1.0000 | 0.8571 |
43
+ | PASSPORT_NUMBER | 0.0000 | 1.0000 | 1.0000 |
44
+ | ACCOUNT_NUMBER | 0.4000 | 0.8571 | 0.8571 |
45
+ | BANK_ROUTING_NUMBER | 0.0000 | 1.0000 | 1.0000 |
46
+ | EMAIL | 1.0000 | 1.0000 | 1.0000 |
47
+ | FIRST_NAME | 0.8947 | 1.0000 | 1.0000 |
48
+ | LAST_NAME | 0.8889 | 1.0000 | 1.0000 |
49
+
50
+ ## CPU Throughput
51
+
52
+ | Suite | Base OpenMed | rc5 full | rc5 ONNX q8 |
53
+ |---|---:|---:|---:|
54
+ | Irish core manual | 15.79 | 6.70 | 34.43 |
55
+ | Irish PPSN/phone edge | 16.60 | 16.50 | 36.56 |
56
+ | Multilingual PPSN | 121.08 | 125.30 | 289.49 |
57
+
58
+ ## Notes
59
+
60
+ - `rc5` fixes the two Gaelic weak-context PPSN misses reported on `rc4`.
61
+ - The q8 artifact keeps the same F1 as the best previous q8 recipe on the sampled comparison suites, but CPU throughput improves materially after ONNX pre-processing.
62
+ - The full checkpoint remains stronger than q8 on the finance-boundary and remaining-gap suites.
inference_mask.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import os
5
+ import shutil
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+ os.environ.setdefault("TRANSFORMERS_NO_TF", "1")
10
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
11
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
12
+ os.environ["USE_TF"] = "0"
13
+ os.environ["USE_FLAX"] = "0"
14
+ os.environ["USE_TORCH"] = "1"
15
+
16
+ import torch
17
+ from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline
18
+
19
+ from irish_core_decoder import repair_irish_core_spans
20
+
21
+
22
+ def load_tokenizer(model_ref: str):
23
+ tokenizer_ref = model_ref
24
+ tokenizer_path = Path(model_ref)
25
+ if tokenizer_path.exists():
26
+ tokenizer_cfg_path = tokenizer_path / "tokenizer_config.json"
27
+ if tokenizer_cfg_path.exists():
28
+ data = json.loads(tokenizer_cfg_path.read_text(encoding="utf-8"))
29
+ if "fix_mistral_regex" in data:
30
+ tmpdir = Path(tempfile.mkdtemp(prefix="openmed_tokenizer_"))
31
+ keep = {
32
+ "tokenizer_config.json",
33
+ "tokenizer.json",
34
+ "special_tokens_map.json",
35
+ "vocab.txt",
36
+ "vocab.json",
37
+ "merges.txt",
38
+ "added_tokens.json",
39
+ "sentencepiece.bpe.model",
40
+ "spiece.model",
41
+ }
42
+ for child in tokenizer_path.iterdir():
43
+ if child.is_file() and child.name in keep:
44
+ shutil.copy2(child, tmpdir / child.name)
45
+ data.pop("fix_mistral_regex", None)
46
+ (tmpdir / "tokenizer_config.json").write_text(
47
+ json.dumps(data, ensure_ascii=False, indent=2) + "\n",
48
+ encoding="utf-8",
49
+ )
50
+ tokenizer_ref = str(tmpdir)
51
+ try:
52
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=True)
53
+ except Exception:
54
+ pass
55
+ try:
56
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=False)
57
+ except TypeError:
58
+ pass
59
+ try:
60
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True)
61
+ except Exception:
62
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=False)
63
+
64
+
65
+ def mask_text(text: str, spans: list[dict]) -> str:
66
+ out = text
67
+ for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
68
+ out = out[:span["start"]] + f"[{span['label']}]" + out[span["end"]:]
69
+ return out
70
+
71
+
72
+ def main() -> None:
73
+ parser = argparse.ArgumentParser()
74
+ parser.add_argument("--model", default=".")
75
+ parser.add_argument("--text", required=True)
76
+ parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
77
+ parser.add_argument("--ppsn-min-score", type=float, default=0.55)
78
+ parser.add_argument("--other-min-score", type=float, default=0.50)
79
+ parser.add_argument("--json", action="store_true")
80
+ args = parser.parse_args()
81
+
82
+ tokenizer = load_tokenizer(args.model)
83
+ model = AutoModelForTokenClassification.from_pretrained(args.model)
84
+ if args.device == "auto":
85
+ device = "cuda" if torch.cuda.is_available() else "cpu"
86
+ else:
87
+ device = args.device
88
+ model.to(device)
89
+ model.eval()
90
+
91
+ nlp = pipeline(
92
+ "token-classification",
93
+ model=model,
94
+ tokenizer=tokenizer,
95
+ aggregation_strategy="simple",
96
+ device=0 if device == "cuda" else -1,
97
+ )
98
+ general = nlp(args.text)
99
+ spans = repair_irish_core_spans(
100
+ args.text,
101
+ model,
102
+ tokenizer,
103
+ general,
104
+ other_min_score=args.other_min_score,
105
+ ppsn_min_score=args.ppsn_min_score,
106
+ )
107
+ result = {
108
+ "model": args.model,
109
+ "masked_text": mask_text(args.text, spans),
110
+ "spans": spans,
111
+ "ppsn_decoder": "word_aligned",
112
+ "general_decoder": "irish_core_label_aware",
113
+ "ppsn_min_score": args.ppsn_min_score,
114
+ "other_min_score": args.other_min_score,
115
+ "backend": "transformers",
116
+ }
117
+ if args.json:
118
+ print(json.dumps(result, indent=2, ensure_ascii=False))
119
+ else:
120
+ print(result["masked_text"])
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
inference_mask_onnx.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+
5
+ from irish_core_decoder import repair_irish_core_spans_onnx
6
+ from onnx_token_classifier import load_onnx_token_classifier
7
+
8
+
9
+ def mask_text(text: str, spans: list[dict]) -> str:
10
+ out = text
11
+ for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
12
+ out = out[:span["start"]] + f"[{span['label']}]" + out[span["end"]:]
13
+ return out
14
+
15
+
16
+ def main() -> None:
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument("--model", default=".")
19
+ parser.add_argument("--onnx-file", default="onnx/model_quantized.onnx")
20
+ parser.add_argument("--text", required=True)
21
+ parser.add_argument("--ppsn-min-score", type=float, default=0.55)
22
+ parser.add_argument("--other-min-score", type=float, default=0.50)
23
+ parser.add_argument("--json", action="store_true")
24
+ args = parser.parse_args()
25
+
26
+ session, tokenizer, config, onnx_path = load_onnx_token_classifier(args.model, onnx_file=args.onnx_file)
27
+ spans = repair_irish_core_spans_onnx(
28
+ args.text,
29
+ session,
30
+ tokenizer,
31
+ config,
32
+ other_min_score=args.other_min_score,
33
+ ppsn_min_score=args.ppsn_min_score,
34
+ )
35
+ result = {
36
+ "model": args.model,
37
+ "onnx_file": str(onnx_path),
38
+ "masked_text": mask_text(args.text, spans),
39
+ "spans": spans,
40
+ "ppsn_decoder": "word_aligned",
41
+ "general_decoder": "irish_core_label_aware",
42
+ "ppsn_min_score": args.ppsn_min_score,
43
+ "other_min_score": args.other_min_score,
44
+ "backend": "onnx",
45
+ }
46
+ if args.json:
47
+ print(json.dumps(result, indent=2, ensure_ascii=False))
48
+ else:
49
+ print(result["masked_text"])
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
irish_core_decoder.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import regex as re
3
+ import torch
4
+
5
+ from raw_word_aligned import word_aligned_ppsn_spans
6
+
7
+
8
+ TOKEN_RE = re.compile(r"[A-Za-z0-9]+|[^\w\s]", re.UNICODE)
9
+ PHONE_RE = re.compile(r"^(?:\+353\s?(?:\(0\))?\s?\d(?:[\s-]?\d){7,8}|0\d(?:[\s-]?\d){7,8})$")
10
+ PASSPORT_RE = re.compile(r"^[A-Z]{2}\s?\d{7}$")
11
+ SORT_RE = re.compile(r"^(?:\d{6}|\d{2}[ -]\d{2}[ -]\d{2})$")
12
+ IBAN_IE_RE = re.compile(r"^IE\d{2}(?:\s?[A-Z]{4})(?:\s?\d{4}){3}\s?\d{2}$")
13
+ BIC_RE = re.compile(r"^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?$")
14
+ EIRCODE_RE = re.compile(r"^(?:[ACDEFHKNPRTVWXY]\d{2}|D6W)\s?[0-9ACDEFHKNPRTVWXY]{4}$", re.IGNORECASE)
15
+
16
+ DEFAULT_LABEL_THRESHOLDS = {
17
+ "PHONE_NUMBER": 0.35,
18
+ "PASSPORT_NUMBER": 0.11,
19
+ "BANK_ROUTING_NUMBER": 0.35,
20
+ "ACCOUNT_NUMBER": 0.40,
21
+ "CREDIT_DEBIT_CARD": 0.08,
22
+ "SWIFT_BIC": 0.50,
23
+ }
24
+
25
+ FORMAT_LABELS = set(DEFAULT_LABEL_THRESHOLDS)
26
+ OUTPUT_PRIORITY = {
27
+ "PPSN": 0,
28
+ "PASSPORT_NUMBER": 1,
29
+ "ACCOUNT_NUMBER": 2,
30
+ "BANK_ROUTING_NUMBER": 3,
31
+ "CREDIT_DEBIT_CARD": 4,
32
+ "PHONE_NUMBER": 5,
33
+ "SWIFT_BIC": 6,
34
+ "POSTCODE": 7,
35
+ "EMAIL": 8,
36
+ "FIRST_NAME": 9,
37
+ "LAST_NAME": 10,
38
+ }
39
+
40
+
41
+ def tokenize_with_spans(text: str):
42
+ return [(m.group(0), m.start(), m.end()) for m in TOKEN_RE.finditer(text)]
43
+
44
+
45
+ def normalize_label(label: str) -> str:
46
+ label = (label or "").strip()
47
+ if label.startswith("B-") or label.startswith("I-"):
48
+ label = label[2:]
49
+ return label.upper()
50
+
51
+
52
+ def luhn_ok(value: str) -> bool:
53
+ digits = "".join(ch for ch in value if ch.isdigit())
54
+ if not (13 <= len(digits) <= 19):
55
+ return False
56
+ total = 0
57
+ double = False
58
+ for ch in reversed(digits):
59
+ number = int(ch)
60
+ if double:
61
+ number *= 2
62
+ if number > 9:
63
+ number -= 9
64
+ total += number
65
+ double = not double
66
+ return total % 10 == 0
67
+
68
+
69
+ def plausible_label_text(label: str, value: str) -> bool:
70
+ value = value.strip()
71
+ if label == "PHONE_NUMBER":
72
+ return PHONE_RE.match(value) is not None
73
+ if label == "PASSPORT_NUMBER":
74
+ return PASSPORT_RE.match(value) is not None
75
+ if label == "BANK_ROUTING_NUMBER":
76
+ return SORT_RE.match(value) is not None
77
+ if label == "ACCOUNT_NUMBER":
78
+ compact = value.replace(" ", "")
79
+ return IBAN_IE_RE.match(value) is not None or (compact.isdigit() and len(compact) == 8)
80
+ if label == "CREDIT_DEBIT_CARD":
81
+ return luhn_ok(value)
82
+ if label == "SWIFT_BIC":
83
+ return BIC_RE.match(value) is not None
84
+ if label == "POSTCODE":
85
+ return EIRCODE_RE.match(value) is not None
86
+ return True
87
+
88
+
89
+ def label_ids_from_mapping(id2label, label: str):
90
+ target = label.upper()
91
+ ids = []
92
+ for raw_id, raw_label in id2label.items():
93
+ if normalize_label(str(raw_label)) == target:
94
+ ids.append(int(raw_id))
95
+ return ids
96
+
97
+
98
+ def label_ids(model, label: str):
99
+ return label_ids_from_mapping(model.config.id2label, label)
100
+
101
+
102
+ def word_scores_for_label(text: str, model, tokenizer, label: str):
103
+ pieces = tokenize_with_spans(text)
104
+ if not pieces:
105
+ return pieces, []
106
+ words = [word for word, _, _ in pieces]
107
+ encoded = tokenizer(words, is_split_into_words=True, return_tensors="pt", truncation=True)
108
+ word_ids = encoded.word_ids(batch_index=0)
109
+ device = next(model.parameters()).device
110
+ encoded = {key: value.to(device) for key, value in encoded.items()}
111
+ with torch.no_grad():
112
+ logits = model(**encoded).logits[0]
113
+ probs = torch.softmax(logits, dim=-1)
114
+ ids = label_ids(model, label)
115
+ scores = []
116
+ for word_index in range(len(pieces)):
117
+ score = 0.0
118
+ for token_index, wid in enumerate(word_ids):
119
+ if wid != word_index:
120
+ continue
121
+ for label_id in ids:
122
+ score = max(score, float(probs[token_index, label_id]))
123
+ scores.append(score)
124
+ return pieces, scores
125
+
126
+
127
+ def word_scores_for_label_onnx(text: str, session, tokenizer, config, label: str):
128
+ from onnx_token_classifier import _run_onnx, _softmax
129
+
130
+ pieces = tokenize_with_spans(text)
131
+ if not pieces:
132
+ return pieces, []
133
+ words = [word for word, _, _ in pieces]
134
+ encoded = tokenizer(words, is_split_into_words=True, return_tensors="np", truncation=True)
135
+ word_ids = encoded.word_ids(batch_index=0)
136
+ logits = _run_onnx(session, encoded)[0]
137
+ probs = _softmax(logits, axis=-1)
138
+ ids = label_ids_from_mapping(config.id2label, label)
139
+ scores = []
140
+ for word_index in range(len(pieces)):
141
+ score = 0.0
142
+ for token_index, wid in enumerate(word_ids):
143
+ if wid != word_index:
144
+ continue
145
+ for label_id in ids:
146
+ score = max(score, float(probs[token_index, label_id]))
147
+ scores.append(score)
148
+ return pieces, scores
149
+
150
+
151
+ def _word_aligned_label_spans_from_scores(text: str, label: str, threshold: float, pieces, scores):
152
+ spans = []
153
+ active = None
154
+ for (word, start, end), score in zip(pieces, scores):
155
+ keep = score >= threshold
156
+ if label in {"PHONE_NUMBER", "BANK_ROUTING_NUMBER", "CREDIT_DEBIT_CARD"} and word in {"-", "/"}:
157
+ keep = active is not None and score >= threshold / 2.0
158
+ if keep:
159
+ if active is None:
160
+ active = {"start": start, "end": end, "label": label}
161
+ else:
162
+ if start - active["end"] <= 1:
163
+ active["end"] = end
164
+ else:
165
+ spans.append(active)
166
+ active = {"start": start, "end": end, "label": label}
167
+ elif active is not None:
168
+ spans.append(active)
169
+ active = None
170
+ if active is not None:
171
+ spans.append(active)
172
+ out = []
173
+ for span in spans:
174
+ value = text[span["start"] : span["end"]]
175
+ if plausible_label_text(label, value):
176
+ out.append(
177
+ {
178
+ "label": label,
179
+ "start": span["start"],
180
+ "end": span["end"],
181
+ "text": value,
182
+ }
183
+ )
184
+ return out
185
+
186
+
187
+ def word_aligned_label_spans(
188
+ text: str,
189
+ model,
190
+ tokenizer,
191
+ label: str,
192
+ threshold: float,
193
+ ):
194
+ pieces, scores = word_scores_for_label(text, model, tokenizer, label)
195
+ return _word_aligned_label_spans_from_scores(text, label, threshold, pieces, scores)
196
+
197
+
198
+ def word_aligned_label_spans_onnx(
199
+ text: str,
200
+ session,
201
+ tokenizer,
202
+ config,
203
+ label: str,
204
+ threshold: float,
205
+ ):
206
+ pieces, scores = word_scores_for_label_onnx(text, session, tokenizer, config, label)
207
+ return _word_aligned_label_spans_from_scores(text, label, threshold, pieces, scores)
208
+
209
+
210
+ def pipeline_to_spans(text: str, outputs: list[dict], min_score: float):
211
+ spans = []
212
+ for output in outputs:
213
+ label = normalize_label(output.get("entity_group") or output.get("entity") or "")
214
+ if not label:
215
+ continue
216
+ score = float(output.get("score", 0.0))
217
+ if score < min_score:
218
+ continue
219
+ spans.append(
220
+ {
221
+ "label": label,
222
+ "start": int(output["start"]),
223
+ "end": int(output["end"]),
224
+ "score": score,
225
+ "text": text[int(output["start"]) : int(output["end"])],
226
+ }
227
+ )
228
+ return spans
229
+
230
+
231
+ def overlaps(a: dict, b: dict) -> bool:
232
+ return not (a["end"] <= b["start"] or b["end"] <= a["start"])
233
+
234
+
235
+ def span_length(span: dict) -> int:
236
+ return int(span["end"]) - int(span["start"])
237
+
238
+
239
+ def normalize_simple_span(span: dict):
240
+ label = normalize_label(span["label"])
241
+ value = span["text"]
242
+ if label == "PHONE_NUMBER" and plausible_label_text("CREDIT_DEBIT_CARD", value):
243
+ label = "CREDIT_DEBIT_CARD"
244
+ if label in FORMAT_LABELS or label == "POSTCODE":
245
+ if not plausible_label_text(label, value):
246
+ return None
247
+ return {
248
+ "label": label,
249
+ "start": int(span["start"]),
250
+ "end": int(span["end"]),
251
+ "score": float(span.get("score", 0.0)),
252
+ "text": value,
253
+ }
254
+
255
+
256
+ def dedupe_and_sort(spans: list[dict]):
257
+ ordered = sorted(
258
+ spans,
259
+ key=lambda span: (
260
+ int(span["start"]),
261
+ -span_length(span),
262
+ OUTPUT_PRIORITY.get(str(span["label"]).upper(), 99),
263
+ ),
264
+ )
265
+ kept = []
266
+ for span in ordered:
267
+ if any(overlaps(span, other) for other in kept):
268
+ continue
269
+ kept.append(span)
270
+ return kept
271
+
272
+
273
+ def repair_irish_core_spans(
274
+ text: str,
275
+ model,
276
+ tokenizer,
277
+ general_outputs: list[dict],
278
+ other_min_score: float,
279
+ ppsn_min_score: float,
280
+ label_thresholds: dict[str, float] | None = None,
281
+ ):
282
+ thresholds = dict(DEFAULT_LABEL_THRESHOLDS)
283
+ if label_thresholds:
284
+ thresholds.update({key.upper(): value for key, value in label_thresholds.items()})
285
+
286
+ spans = []
287
+ for span in pipeline_to_spans(text, general_outputs, min_score=other_min_score):
288
+ normalized = normalize_simple_span(span)
289
+ if normalized is not None and normalized["label"] != "PPSN":
290
+ spans.append(normalized)
291
+
292
+ ppsn_spans = word_aligned_ppsn_spans(text, model, tokenizer, threshold=ppsn_min_score)
293
+ for span in ppsn_spans:
294
+ spans.append(
295
+ {
296
+ "label": "PPSN",
297
+ "start": int(span["start"]),
298
+ "end": int(span["end"]),
299
+ "score": float(span.get("score", 0.0)),
300
+ "text": text[int(span["start"]) : int(span["end"])],
301
+ }
302
+ )
303
+
304
+ repairs = []
305
+ for label, threshold in thresholds.items():
306
+ repairs.extend(word_aligned_label_spans(text, model, tokenizer, label, threshold))
307
+
308
+ for candidate in repairs:
309
+ updated = []
310
+ replaced = False
311
+ for span in spans:
312
+ if not overlaps(candidate, span):
313
+ updated.append(span)
314
+ continue
315
+ if candidate["label"] == span["label"] and span_length(candidate) > span_length(span):
316
+ replaced = True
317
+ continue
318
+ if candidate["label"] in FORMAT_LABELS and span["label"] in FORMAT_LABELS and span_length(candidate) > span_length(span):
319
+ replaced = True
320
+ continue
321
+ updated.append(span)
322
+ spans = updated
323
+ if replaced or not any(overlaps(candidate, span) for span in spans):
324
+ spans.append(candidate)
325
+
326
+ return dedupe_and_sort(spans)
327
+
328
+
329
+ def repair_irish_core_spans_onnx(
330
+ text: str,
331
+ session,
332
+ tokenizer,
333
+ config,
334
+ other_min_score: float,
335
+ ppsn_min_score: float,
336
+ label_thresholds: dict[str, float] | None = None,
337
+ general_outputs: list[dict] | None = None,
338
+ ):
339
+ from onnx_token_classifier import simple_aggregate_spans_onnx, word_aligned_ppsn_spans_onnx
340
+
341
+ thresholds = dict(DEFAULT_LABEL_THRESHOLDS)
342
+ if label_thresholds:
343
+ thresholds.update({key.upper(): value for key, value in label_thresholds.items()})
344
+
345
+ spans = []
346
+ if general_outputs is None:
347
+ general_outputs = simple_aggregate_spans_onnx(
348
+ text,
349
+ session,
350
+ tokenizer,
351
+ config,
352
+ min_score=other_min_score,
353
+ )
354
+ for span in pipeline_to_spans(text, general_outputs, min_score=other_min_score):
355
+ normalized = normalize_simple_span(span)
356
+ if normalized is not None and normalized["label"] != "PPSN":
357
+ spans.append(normalized)
358
+
359
+ ppsn_spans = word_aligned_ppsn_spans_onnx(text, session, tokenizer, config, threshold=ppsn_min_score)
360
+ for span in ppsn_spans:
361
+ spans.append(
362
+ {
363
+ "label": "PPSN",
364
+ "start": int(span["start"]),
365
+ "end": int(span["end"]),
366
+ "score": float(span.get("score", 0.0)),
367
+ "text": text[int(span["start"]) : int(span["end"])],
368
+ }
369
+ )
370
+
371
+ repairs = []
372
+ for label, threshold in thresholds.items():
373
+ repairs.extend(word_aligned_label_spans_onnx(text, session, tokenizer, config, label, threshold))
374
+
375
+ for candidate in repairs:
376
+ updated = []
377
+ replaced = False
378
+ for span in spans:
379
+ if not overlaps(candidate, span):
380
+ updated.append(span)
381
+ continue
382
+ if candidate["label"] == span["label"] and span_length(candidate) > span_length(span):
383
+ replaced = True
384
+ continue
385
+ if candidate["label"] in FORMAT_LABELS and span["label"] in FORMAT_LABELS and span_length(candidate) > span_length(span):
386
+ replaced = True
387
+ continue
388
+ updated.append(span)
389
+ spans = updated
390
+ if replaced or not any(overlaps(candidate, span) for span in spans):
391
+ spans.append(candidate)
392
+
393
+ return dedupe_and_sort(spans)
label_meta.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "models/openmed-mliteclinical-irish-core-v21_overlaprepair_lite_full_s120",
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
+ "PASSPORT_NUMBER",
121
+ "PHONE_NUMBER",
122
+ "POSTCODE",
123
+ "BANK_ROUTING_NUMBER",
124
+ "ACCOUNT_NUMBER",
125
+ "CREDIT_DEBIT_CARD",
126
+ "EMAIL",
127
+ "FIRST_NAME",
128
+ "LAST_NAME",
129
+ "SWIFT_BIC"
130
+ ]
131
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28bf5137f337a8712d5208abb848706ef434bd9ba37e852d7d2153b415d9d1de
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,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "models/openmed-mliteclinical-irish-core-v21_overlaprepair_lite_full_s120",
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
+ "PASSPORT_NUMBER",
121
+ "PHONE_NUMBER",
122
+ "POSTCODE",
123
+ "BANK_ROUTING_NUMBER",
124
+ "ACCOUNT_NUMBER",
125
+ "CREDIT_DEBIT_CARD",
126
+ "EMAIL",
127
+ "FIRST_NAME",
128
+ "LAST_NAME",
129
+ "SWIFT_BIC"
130
+ ]
131
+ }
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fdb5aaf79c011096cbda3f322dcd54f089b79b1e818a54b2a7ed08f2a4d67bb
3
+ size 539431661
onnx/model_quantized.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfca716e6121e0fbcff98bc4236b306cd9dd02c0d4c9d2fa200ec45386602c0e
3
+ size 412032376
onnx/onnx_export.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_model": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5#onnx_full",
3
+ "onnx_path": "onnx/model.onnx",
4
+ "method": "exported_with_optimum",
5
+ "preferred_onnx_file": null,
6
+ "opset": 18,
7
+ "max_length": 256,
8
+ "copied_assets": [
9
+ "config.json",
10
+ "label_meta.json",
11
+ "special_tokens_map.json",
12
+ "tokenizer.json",
13
+ "tokenizer_config.json",
14
+ "vocab.txt"
15
+ ],
16
+ "external_data": false,
17
+ "task": "token-classification"
18
+ }
onnx/quantization.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_dir": "onnx/model.onnx",
3
+ "input_model": "models/openmed-mliteclinical-irish-core-v23_fprepair_full_s100_onnx_pp_q8_pc/model.onnx",
4
+ "output_model": "models/openmed-mliteclinical-irish-core-v23_fprepair_full_s100_onnx_pp_q8_pc/model_quantized.onnx",
5
+ "weight_type": "qint8",
6
+ "per_channel": true,
7
+ "reduce_range": false,
8
+ "op_types": [
9
+ "MatMul",
10
+ "Gemm",
11
+ "Attention"
12
+ ],
13
+ "copied_assets": [
14
+ "models/openmed-mliteclinical-irish-core-v23_fprepair_full_s100_onnx_pp/model.onnx",
15
+ "onnx_export.json",
16
+ "config.json",
17
+ "label_meta.json",
18
+ "special_tokens_map.json",
19
+ "tokenizer.json",
20
+ "tokenizer_config.json",
21
+ "vocab.txt"
22
+ ],
23
+ "format": "onnx_dynamic_quantized",
24
+ "task": "token-classification",
25
+ "source_model": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5#onnx_full"
26
+ }
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,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import json
3
+ import os
4
+ import tempfile
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ os.environ.setdefault("TRANSFORMERS_NO_TF", "1")
9
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
10
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
11
+ os.environ["USE_TF"] = "0"
12
+ os.environ["USE_FLAX"] = "0"
13
+ os.environ["USE_TORCH"] = "1"
14
+
15
+ import numpy as np
16
+ import regex as re
17
+ from huggingface_hub import HfApi, hf_hub_download
18
+ from transformers import AutoConfig, AutoTokenizer
19
+
20
+
21
+ TOKEN_RE = re.compile(r"[A-Za-z0-9]+|[^\w\s]", re.UNICODE)
22
+ DEFAULT_ONNX_FILES = [
23
+ "onnx/model_quantized.onnx",
24
+ "model_quantized.onnx",
25
+ "onnx/model.onnx",
26
+ "model.onnx",
27
+ ]
28
+ EIRCODE_RE = re.compile(r"^(?:[ACDEFHKNPRTVWXY]\d{2}|D6W)\s?[0-9ACDEFHKNPRTVWXY]{4}$", re.IGNORECASE)
29
+
30
+
31
+ def tokenize_with_spans(text: str):
32
+ return [(m.group(0), m.start(), m.end()) for m in TOKEN_RE.finditer(text)]
33
+
34
+
35
+ def normalize_label(label: str) -> str:
36
+ label = (label or "").strip()
37
+ if label.startswith("B-") or label.startswith("I-"):
38
+ label = label[2:]
39
+ return label.upper()
40
+
41
+
42
+ def looks_like_eircode(value: str) -> bool:
43
+ return EIRCODE_RE.match(value.strip()) is not None
44
+
45
+
46
+ def _load_tokenizer(tokenizer_ref: str):
47
+ tokenizer_path = Path(tokenizer_ref)
48
+ if tokenizer_path.exists():
49
+ tokenizer_cfg_path = tokenizer_path / "tokenizer_config.json"
50
+ if tokenizer_cfg_path.exists():
51
+ data = json.loads(tokenizer_cfg_path.read_text(encoding="utf-8"))
52
+ if "fix_mistral_regex" in data:
53
+ tmpdir = Path(tempfile.mkdtemp(prefix="openmed_onnx_tokenizer_"))
54
+ keep = {
55
+ "tokenizer_config.json",
56
+ "tokenizer.json",
57
+ "special_tokens_map.json",
58
+ "vocab.txt",
59
+ "vocab.json",
60
+ "merges.txt",
61
+ "added_tokens.json",
62
+ "sentencepiece.bpe.model",
63
+ "spiece.model",
64
+ }
65
+ for child in tokenizer_path.iterdir():
66
+ if child.is_file() and child.name in keep:
67
+ target = tmpdir / child.name
68
+ target.write_bytes(child.read_bytes())
69
+ data.pop("fix_mistral_regex", None)
70
+ (tmpdir / "tokenizer_config.json").write_text(
71
+ json.dumps(data, ensure_ascii=False, indent=2) + "\n",
72
+ encoding="utf-8",
73
+ )
74
+ tokenizer_ref = str(tmpdir)
75
+
76
+ try:
77
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=True)
78
+ except Exception:
79
+ pass
80
+ try:
81
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=False)
82
+ except TypeError:
83
+ pass
84
+ try:
85
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True)
86
+ except Exception:
87
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=False)
88
+
89
+
90
+ def _resolve_local_onnx(model_path: Path, preferred: str | None = None) -> Path:
91
+ candidates = ([preferred] if preferred else []) + DEFAULT_ONNX_FILES
92
+ for candidate in candidates:
93
+ if not candidate:
94
+ continue
95
+ path = model_path / candidate
96
+ if path.exists():
97
+ return path
98
+ raise FileNotFoundError(f"No ONNX file found under {model_path}")
99
+
100
+
101
+ def _resolve_remote_onnx(model_ref: str, preferred: str | None = None) -> Path:
102
+ api = HfApi()
103
+ files = set(api.list_repo_files(repo_id=model_ref, repo_type="model"))
104
+ candidates = ([preferred] if preferred else []) + DEFAULT_ONNX_FILES
105
+ for candidate in candidates:
106
+ if candidate and candidate in files:
107
+ return Path(hf_hub_download(repo_id=model_ref, filename=candidate, repo_type="model"))
108
+ raise FileNotFoundError(f"No ONNX file published for {model_ref}")
109
+
110
+
111
+ def load_onnx_token_classifier(
112
+ model_ref: str,
113
+ onnx_file: str | None = None,
114
+ providers: list[str] | None = None,
115
+ ):
116
+ import onnxruntime as ort
117
+
118
+ model_path = Path(model_ref)
119
+ if model_path.exists():
120
+ onnx_path = _resolve_local_onnx(model_path, preferred=onnx_file)
121
+ config = AutoConfig.from_pretrained(model_ref)
122
+ tokenizer = _load_tokenizer(model_ref)
123
+ else:
124
+ onnx_path = _resolve_remote_onnx(model_ref, preferred=onnx_file)
125
+ config = AutoConfig.from_pretrained(model_ref)
126
+ tokenizer = _load_tokenizer(model_ref)
127
+
128
+ session = ort.InferenceSession(str(onnx_path), providers=providers or ["CPUExecutionProvider"])
129
+ return session, tokenizer, config, onnx_path
130
+
131
+
132
+ def _run_onnx(session, encoded: dict[str, Any]) -> np.ndarray:
133
+ feed = {}
134
+ input_names = {item.name for item in session.get_inputs()}
135
+ for key, value in encoded.items():
136
+ if key == "offset_mapping":
137
+ continue
138
+ if key in input_names:
139
+ feed[key] = value
140
+ outputs = session.run(None, feed)
141
+ return outputs[0]
142
+
143
+
144
+ def _softmax(logits: np.ndarray, axis: int = -1) -> np.ndarray:
145
+ shifted = logits - np.max(logits, axis=axis, keepdims=True)
146
+ exp = np.exp(shifted)
147
+ return exp / np.clip(np.sum(exp, axis=axis, keepdims=True), 1e-12, None)
148
+
149
+
150
+ def _split_tag(label: str) -> tuple[str, str]:
151
+ if label.startswith("B-") or label.startswith("I-"):
152
+ return label[:1], label[2:]
153
+ return "B", label
154
+
155
+
156
+ def simple_aggregate_spans_onnx(
157
+ text: str,
158
+ session,
159
+ tokenizer,
160
+ config,
161
+ min_score: float = 0.5,
162
+ ) -> list[dict[str, Any]]:
163
+ encoded = tokenizer(text, return_offsets_mapping=True, return_tensors="np", truncation=True)
164
+ logits = _run_onnx(session, encoded)[0]
165
+ probs = _softmax(logits, axis=-1)
166
+ pred_ids = probs.argmax(axis=-1)
167
+ id2label = {int(k): v for k, v in config.id2label.items()}
168
+ offsets = encoded["offset_mapping"][0].tolist()
169
+ attention_mask = encoded.get("attention_mask")
170
+ if attention_mask is None:
171
+ attention = [1] * len(offsets)
172
+ else:
173
+ attention = attention_mask[0].tolist()
174
+
175
+ spans: list[dict[str, Any]] = []
176
+ active: dict[str, Any] | None = None
177
+ for idx, ((start, end), keep) in enumerate(zip(offsets, attention)):
178
+ if not keep or start == end:
179
+ if active is not None:
180
+ spans.append(active)
181
+ active = None
182
+ continue
183
+
184
+ label = id2label[int(pred_ids[idx])]
185
+ if label == "O":
186
+ if active is not None:
187
+ spans.append(active)
188
+ active = None
189
+ continue
190
+
191
+ score = float(probs[idx, int(pred_ids[idx])])
192
+ if score < min_score:
193
+ if active is not None:
194
+ spans.append(active)
195
+ active = None
196
+ continue
197
+
198
+ prefix, entity = _split_tag(label)
199
+ if (
200
+ active is None
201
+ or prefix == "B"
202
+ or entity != active["entity_group"]
203
+ or int(start) > int(active["end"]) + 1
204
+ ):
205
+ if active is not None:
206
+ spans.append(active)
207
+ active = {
208
+ "entity_group": entity,
209
+ "start": int(start),
210
+ "end": int(end),
211
+ "score": score,
212
+ }
213
+ else:
214
+ active["end"] = int(end)
215
+ active["score"] = max(float(active["score"]), score)
216
+
217
+ if active is not None:
218
+ spans.append(active)
219
+
220
+ for span in spans:
221
+ span["word"] = text[span["start"] : span["end"]]
222
+ return spans
223
+
224
+
225
+ def ppsn_label_ids_from_config(config) -> list[int]:
226
+ ids = []
227
+ for raw_id, raw_label in config.id2label.items():
228
+ label_id = int(raw_id)
229
+ label = str(raw_label or "").strip()
230
+ if label.endswith("PPSN"):
231
+ ids.append(label_id)
232
+ return sorted(ids)
233
+
234
+
235
+ def word_aligned_ppsn_spans_onnx(
236
+ text: str,
237
+ session,
238
+ tokenizer,
239
+ config,
240
+ threshold: float = 0.4,
241
+ ) -> list[dict[str, Any]]:
242
+ pieces = tokenize_with_spans(text)
243
+ if not pieces:
244
+ return []
245
+
246
+ words = [word for word, _, _ in pieces]
247
+ encoded = tokenizer(words, is_split_into_words=True, return_tensors="np", truncation=True)
248
+ word_ids = encoded.word_ids(batch_index=0)
249
+ logits = _run_onnx(session, encoded)[0]
250
+ probs = _softmax(logits, axis=-1)
251
+ label_ids = ppsn_label_ids_from_config(config)
252
+
253
+ word_scores: list[float] = []
254
+ for word_index in range(len(pieces)):
255
+ score = 0.0
256
+ for token_index, wid in enumerate(word_ids):
257
+ if wid != word_index:
258
+ continue
259
+ for label_id in label_ids:
260
+ score = max(score, float(probs[token_index, label_id]))
261
+ word_scores.append(score)
262
+
263
+ spans: list[dict[str, Any]] = []
264
+ active = None
265
+ for (_, start, end), score in zip(pieces, word_scores):
266
+ if score >= threshold:
267
+ if active is None:
268
+ active = {"start": start, "end": end, "score": score}
269
+ else:
270
+ active["end"] = end
271
+ active["score"] = max(active["score"], score)
272
+ elif active is not None:
273
+ spans.append(active)
274
+ active = None
275
+
276
+ if active is not None:
277
+ spans.append(active)
278
+
279
+ for span in spans:
280
+ span["text"] = text[span["start"] : span["end"]]
281
+ span["label"] = "PPSN"
282
+ span["source"] = "onnx"
283
+ return spans
pyproject.toml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "openmed-irish-core-pii"
3
+ version = "0.2.0rc5"
4
+ description = "OpenMed Irish core PII token-classification release"
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
qa_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repo_id": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5",
3
+ "recommended_inference": {
4
+ "full_checkpoint": {
5
+ "script": "inference_mask.py",
6
+ "ppsn_decoder": "word_aligned",
7
+ "general_decoder": "irish_core_label_aware",
8
+ "ppsn_min_score": 0.55,
9
+ "other_min_score": 0.5,
10
+ "device": "cpu"
11
+ },
12
+ "onnx_q8": {
13
+ "script": "inference_mask_onnx.py",
14
+ "onnx_artifact": "onnx/model_quantized.onnx",
15
+ "ppsn_decoder": "word_aligned",
16
+ "general_decoder": "irish_core_label_aware",
17
+ "ppsn_min_score": 0.55,
18
+ "other_min_score": 0.5,
19
+ "device": "cpu"
20
+ }
21
+ },
22
+ "smoke_texts": [
23
+ "Duradh liom mo uimhir 1234567T a sholatar agus me ag denamh iarratais.",
24
+ "Is e mo upsp na 1234567tw agus teastaionn uaim eolas faoi liuntas curamora.",
25
+ "My PPSN is 1234567T and my sort code is 90-00-17.",
26
+ "Please provide your passport: NN5123456 and call me on 0851234567.",
27
+ "My IBAN is IE29AIBK93115212345678 and my email is aidan.oiarraidh@example.ie."
28
+ ],
29
+ "known_limit_texts": [
30
+ "Passport PA 1234567 was used to board the flight.",
31
+ "Card 4242 4242 4242 4242 in very short contexts should still be QA tested.",
32
+ "Compact mobile numbers in very short mixed-numeric contexts should still be QA tested."
33
+ ]
34
+ }
raw_word_aligned.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import regex as re
3
+ import torch
4
+
5
+
6
+ TOKEN_RE = re.compile(r"[A-Za-z0-9]+|[^\w\s]", re.UNICODE)
7
+
8
+
9
+ def tokenize_with_spans(text: str):
10
+ return [(m.group(0), m.start(), m.end()) for m in TOKEN_RE.finditer(text)]
11
+
12
+
13
+ def ppsn_label_ids(model) -> list[int]:
14
+ ids = []
15
+ for raw_id, raw_label in model.config.id2label.items():
16
+ label_id = int(raw_id)
17
+ label = str(raw_label or "").strip()
18
+ if label.endswith("PPSN"):
19
+ ids.append(label_id)
20
+ return sorted(ids)
21
+
22
+
23
+ def word_aligned_ppsn_spans(text: str, model, tokenizer, threshold: float) -> list[dict]:
24
+ pieces = tokenize_with_spans(text)
25
+ if not pieces:
26
+ return []
27
+
28
+ words = [word for word, _, _ in pieces]
29
+ encoded = tokenizer(words, is_split_into_words=True, return_tensors="pt", truncation=True)
30
+ word_ids = encoded.word_ids(batch_index=0)
31
+
32
+ device = next(model.parameters()).device
33
+ encoded = {k: v.to(device) for k, v in encoded.items()}
34
+
35
+ with torch.no_grad():
36
+ logits = model(**encoded).logits[0]
37
+
38
+ probs = torch.softmax(logits, dim=-1)
39
+ label_ids = ppsn_label_ids(model)
40
+
41
+ word_scores: list[float] = []
42
+ for word_index in range(len(pieces)):
43
+ score = 0.0
44
+ for token_index, wid in enumerate(word_ids):
45
+ if wid != word_index:
46
+ continue
47
+ for label_id in label_ids:
48
+ score = max(score, float(probs[token_index, label_id]))
49
+ word_scores.append(score)
50
+
51
+ spans: list[dict] = []
52
+ active = None
53
+ for (word, start, end), score in zip(pieces, word_scores):
54
+ if score >= threshold:
55
+ if active is None:
56
+ active = {"start": start, "end": end, "score": score}
57
+ else:
58
+ active["end"] = end
59
+ active["score"] = max(active["score"], score)
60
+ elif active is not None:
61
+ spans.append(active)
62
+ active = None
63
+
64
+ if active is not None:
65
+ spans.append(active)
66
+
67
+ for span in spans:
68
+ span["text"] = text[span["start"] : span["end"]]
69
+ span["label"] = "PPSN"
70
+ span["source"] = "model"
71
+
72
+ return spans
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
+ }
training_sources.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
3
+ "previous_public_candidate": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc4",
4
+ "stable_public_reference": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v1",
5
+ "release_purpose": "Fifth v2 release candidate for the IrishCorePII line. rc5 keeps the rc4 checkpoint weights but changes the public inference defaults and bundled dynamic q8 artifact to recover Gaelic weak-context PPSN cases and improve CPU q8 throughput.",
6
+ "recommended_thresholds": {
7
+ "full_checkpoint": {
8
+ "ppsn_min_score": 0.55,
9
+ "other_min_score": 0.5
10
+ },
11
+ "onnx_q8": {
12
+ "ppsn_min_score": 0.55,
13
+ "other_min_score": 0.5
14
+ }
15
+ },
16
+ "inference_stack_notes": [
17
+ "PPSN extraction uses the word-aligned decoder.",
18
+ "General Irish core PII extraction uses the label-aware repair decoder for both full and ONNX q8 inference.",
19
+ "The ONNX q8 artifact is built from a preprocessed ONNX export and then dynamically quantized with qint8 per-channel quantization over MatMul,Gemm,Attention."
20
+ ],
21
+ "training_mix_summary": [
22
+ {
23
+ "component": "same fine-tuned full checkpoint weights as rc4",
24
+ "weight": 1.0
25
+ },
26
+ {
27
+ "component": "updated inference calibration for weak-context Gaelic PPSN recovery",
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "component": "preprocessed ONNX export before dynamic q8 quantization",
32
+ "weight": 1.0
33
+ }
34
+ ],
35
+ "upstream_attribution": [
36
+ {
37
+ "name": "temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1",
38
+ "license": "Apache-2.0"
39
+ },
40
+ {
41
+ "name": "temsa/OpenMed-Irish-CorePII-TrainMix-v1",
42
+ "license": "CC-BY-4.0 composite"
43
+ },
44
+ {
45
+ "name": "joelniklaus/mapa",
46
+ "license": "CC-BY-4.0"
47
+ },
48
+ {
49
+ "name": "gretelai/synthetic_pii_finance_multilingual",
50
+ "license": "Apache-2.0"
51
+ }
52
+ ],
53
+ "quantization_notes": {
54
+ "promoted_q8_recipe": "ONNX Runtime dynamic int8 qint8 per-channel quantization over MatMul,Gemm,Attention after ONNX pre-processing with symbolic shape inference disabled.",
55
+ "rejected_q8_recipes": [
56
+ "non-per-channel dynamic int8",
57
+ "MatMul,Gemm-only dynamic int8 without ONNX pre-processing"
58
+ ]
59
+ },
60
+ "known_limitations": [
61
+ "The full checkpoint still outperforms q8 on the finance-boundary suite.",
62
+ "The strict remaining-gap suite is still weaker on q8 than on the full checkpoint.",
63
+ "Grouped credit/debit card boundary cases remain the main shared weakness."
64
+ ]
65
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff