credgate 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ .Rproj.user/
2
+ .Rhistory
3
+ .RData
4
+ *.Rcheck/
5
+ credgate_*.tar.gz
6
+ result
7
+ result-*
8
+ .DS_Store
credgate-0.1.0/AUTHORS ADDED
@@ -0,0 +1,6 @@
1
+ # The CredGate Authors: people who hold copyright in CredGate.
2
+ # Contributors are added here with their first contribution.
3
+ # Format: Name <email> (GitHub handle)
4
+
5
+ Bharat Sikka <bharat8sikka@gmail.com> (@bharatsikka)
6
+ Aishwarya Bais <aishwarya.bais00@gmail.com> (@aishwaryabais)
credgate-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
credgate-0.1.0/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ CredGate
2
+ Copyright 2026 The CredGate Authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see
5
+ LICENSE). The CredGate Authors are listed in the AUTHORS file.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.5
2
+ Name: credgate
3
+ Version: 0.1.0
4
+ Summary: Governance layer for LLM requests with Indian PII detection
5
+ Project-URL: Homepage, https://github.com/dwarpal/credgate
6
+ Project-URL: Issues, https://github.com/dwarpal/credgate/issues
7
+ Author-email: Bharat Sikka <bharat8sikka@gmail.com>, Aishwarya Bais <aishwarya.bais00@gmail.com>
8
+ Maintainer-email: Bharat Sikka <bharat8sikka@gmail.com>, Aishwarya Bais <aishwarya.bais00@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: AUTHORS
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Keywords: aadhaar,compliance,dpdp,india,llm,pii,privacy
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Text Processing
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: regex>=2023.0
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=7; extra == 'test'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # credgate
29
+
30
+ Detects personal data before it leaves the machine, with Indian identifiers
31
+ built in: Aadhaar (with Verhoeff checksum), Aadhaar Virtual ID, PAN, GSTIN,
32
+ voter ID, passport, driving licence, UPI IDs, IFSC, bank accounts, payment
33
+ cards, +91 mobile numbers, ABHA, and names and addresses in Latin and Indic
34
+ scripts.
35
+
36
+ The detection rules live in a shared, language-neutral spec, so this package
37
+ and the R package `credgate` find exactly the same matches. Part of the
38
+ [CredGate](https://github.com/dwarpal/credgate) project; early development.
39
+
40
+ ## Installation
41
+
42
+ Python 3.11 or later; depends only on `regex` and `PyYAML`.
43
+
44
+ ```sh
45
+ pip install "git+https://github.com/dwarpal/credgate#subdirectory=pkg/python"
46
+ ```
47
+
48
+ With Nix: `nix build github:dwarpal/credgate#credgate`.
49
+
50
+ ## Usage
51
+
52
+ ```python
53
+ import credgate
54
+
55
+ spans = credgate.detect_pii("Name: Priya Nair; PAN: ABCPN1234K; UPI: priya.n@oksbi")
56
+ for s in spans:
57
+ print(s)
58
+ # Span(doc=0, start=6, end=16, type='person_name', value='XXXXX Nair', confidence=0.8)
59
+ # Span(doc=0, start=23, end=33, type='pan', value='XXXXXX234K', confidence=0.97)
60
+ # Span(doc=0, start=40, end=53, type='upi_id', value='XXXXX.X@Xksbi', confidence=0.99)
61
+
62
+ spans[1].value # 'ABCPN1234K' - printing masks values, the attribute does not
63
+ spans[1].reasons # "matched PAN pattern; context 'PAN'; holder type: individual"
64
+ ```
65
+
66
+ `detect_pii()` takes a string or a list of strings and returns `Span`
67
+ objects with the document index, 0-based end-exclusive positions, type, data
68
+ class, value, canonical form, confidence and reasons. `span.to_dict()` gives
69
+ a JSON-ready dict with the value masked (`reveal=True` to include it).
70
+
71
+ Context makes generic patterns trustworthy; pass a column name or similar:
72
+
73
+ ```python
74
+ credgate.detect_pii("ABC1234567") # [] - could be anything
75
+ credgate.detect_pii("ABC1234567", context="voter_id") # voter ID, confidence 0.97
76
+ ```
77
+
78
+ Checksums, synthetic test data and your own detectors:
79
+
80
+ ```python
81
+ credgate.verhoeff_valid("542229371182")
82
+ credgate.synth_indian_pii(5, seed=1) # synthetic records; never use as anonymised data
83
+
84
+ credgate.register_detector(credgate.Detector(
85
+ id="employee_id", data_class="internal", label="Employee ID",
86
+ patterns=credgate.bounded("EMP[0-9]{6}"),
87
+ ))
88
+ ```
89
+
90
+ ## Command line
91
+
92
+ ```sh
93
+ credgate detect notes.txt # masked report
94
+ credgate detect --lines --json customers.csv # one JSON object per match
95
+ git diff --cached | credgate detect --fail # non-zero exit if PII is found
96
+ credgate detectors # list detectors
97
+ ```
98
+
99
+ Values are masked unless you pass `--reveal`.
100
+
101
+ ## Limits
102
+
103
+ Names and addresses are found only next to a cue: an honorific (Shri, Smt,
104
+ श्रीमती), a relation (S/o, D/o), a field label (`Name:`, `पता:`) or a
105
+ house/village keyword followed by a PIN code. A bare 12-digit number may pass
106
+ the Aadhaar checksum by chance and is reported with lower confidence.
107
+
108
+ ## Licence
109
+
110
+ Apache License 2.0.
@@ -0,0 +1,83 @@
1
+ # credgate
2
+
3
+ Detects personal data before it leaves the machine, with Indian identifiers
4
+ built in: Aadhaar (with Verhoeff checksum), Aadhaar Virtual ID, PAN, GSTIN,
5
+ voter ID, passport, driving licence, UPI IDs, IFSC, bank accounts, payment
6
+ cards, +91 mobile numbers, ABHA, and names and addresses in Latin and Indic
7
+ scripts.
8
+
9
+ The detection rules live in a shared, language-neutral spec, so this package
10
+ and the R package `credgate` find exactly the same matches. Part of the
11
+ [CredGate](https://github.com/dwarpal/credgate) project; early development.
12
+
13
+ ## Installation
14
+
15
+ Python 3.11 or later; depends only on `regex` and `PyYAML`.
16
+
17
+ ```sh
18
+ pip install "git+https://github.com/dwarpal/credgate#subdirectory=pkg/python"
19
+ ```
20
+
21
+ With Nix: `nix build github:dwarpal/credgate#credgate`.
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+ import credgate
27
+
28
+ spans = credgate.detect_pii("Name: Priya Nair; PAN: ABCPN1234K; UPI: priya.n@oksbi")
29
+ for s in spans:
30
+ print(s)
31
+ # Span(doc=0, start=6, end=16, type='person_name', value='XXXXX Nair', confidence=0.8)
32
+ # Span(doc=0, start=23, end=33, type='pan', value='XXXXXX234K', confidence=0.97)
33
+ # Span(doc=0, start=40, end=53, type='upi_id', value='XXXXX.X@Xksbi', confidence=0.99)
34
+
35
+ spans[1].value # 'ABCPN1234K' - printing masks values, the attribute does not
36
+ spans[1].reasons # "matched PAN pattern; context 'PAN'; holder type: individual"
37
+ ```
38
+
39
+ `detect_pii()` takes a string or a list of strings and returns `Span`
40
+ objects with the document index, 0-based end-exclusive positions, type, data
41
+ class, value, canonical form, confidence and reasons. `span.to_dict()` gives
42
+ a JSON-ready dict with the value masked (`reveal=True` to include it).
43
+
44
+ Context makes generic patterns trustworthy; pass a column name or similar:
45
+
46
+ ```python
47
+ credgate.detect_pii("ABC1234567") # [] - could be anything
48
+ credgate.detect_pii("ABC1234567", context="voter_id") # voter ID, confidence 0.97
49
+ ```
50
+
51
+ Checksums, synthetic test data and your own detectors:
52
+
53
+ ```python
54
+ credgate.verhoeff_valid("542229371182")
55
+ credgate.synth_indian_pii(5, seed=1) # synthetic records; never use as anonymised data
56
+
57
+ credgate.register_detector(credgate.Detector(
58
+ id="employee_id", data_class="internal", label="Employee ID",
59
+ patterns=credgate.bounded("EMP[0-9]{6}"),
60
+ ))
61
+ ```
62
+
63
+ ## Command line
64
+
65
+ ```sh
66
+ credgate detect notes.txt # masked report
67
+ credgate detect --lines --json customers.csv # one JSON object per match
68
+ git diff --cached | credgate detect --fail # non-zero exit if PII is found
69
+ credgate detectors # list detectors
70
+ ```
71
+
72
+ Values are masked unless you pass `--reveal`.
73
+
74
+ ## Limits
75
+
76
+ Names and addresses are found only next to a cue: an honorific (Shri, Smt,
77
+ श्रीमती), a relation (S/o, D/o), a field label (`Name:`, `पता:`) or a
78
+ house/village keyword followed by a PIN code. A bare 12-digit number may pass
79
+ the Aadhaar checksum by chance and is reported with lower confidence.
80
+
81
+ ## Licence
82
+
83
+ Apache License 2.0.
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "credgate"
7
+ version = "0.1.0"
8
+ description = "Governance layer for LLM requests with Indian PII detection"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE", "AUTHORS"]
12
+ requires-python = ">=3.11"
13
+ authors = [
14
+ { name = "Bharat Sikka", email = "bharat8sikka@gmail.com" },
15
+ { name = "Aishwarya Bais", email = "aishwarya.bais00@gmail.com" },
16
+ ]
17
+ maintainers = [
18
+ { name = "Bharat Sikka", email = "bharat8sikka@gmail.com" },
19
+ { name = "Aishwarya Bais", email = "aishwarya.bais00@gmail.com" },
20
+ ]
21
+ keywords = ["pii", "privacy", "llm", "aadhaar", "dpdp", "compliance", "india"]
22
+ classifiers = [
23
+ "Development Status :: 2 - Pre-Alpha",
24
+ "Intended Audience :: Developers",
25
+ "Intended Audience :: Science/Research",
26
+ "Operating System :: OS Independent",
27
+ "Programming Language :: Python :: 3",
28
+ "Topic :: Security",
29
+ "Topic :: Text Processing",
30
+ ]
31
+ dependencies = ["regex>=2023.0", "PyYAML>=6.0"]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/dwarpal/credgate"
35
+ Issues = "https://github.com/dwarpal/credgate/issues"
36
+
37
+ [project.optional-dependencies]
38
+ test = ["pytest>=7"]
39
+
40
+ [project.scripts]
41
+ credgate = "credgate.cli:main"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/credgate"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
51
+ target-version = "py311"
52
+
53
+ [tool.ruff.lint]
54
+ select = [
55
+ "E", "W", # pycodestyle
56
+ "F", # pyflakes
57
+ "I", # isort
58
+ "B", # bugbear
59
+ "UP", # pyupgrade
60
+ "SIM", # simplify
61
+ "C4", # comprehensions
62
+ "PT", # pytest style
63
+ "RUF", # ruff-specific
64
+ ]
@@ -0,0 +1,47 @@
1
+ """CredGate: governance layer for LLM requests with Indian PII detection.
2
+
3
+ Detection rules come from the shared spec (see :func:`spec_path`), so this
4
+ package and the R package find exactly the same matches.
5
+ """
6
+
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ try:
10
+ __version__ = version("credgate")
11
+ except PackageNotFoundError: # running from a source checkout
12
+ __version__ = "0.1.0"
13
+
14
+ from ._spec import spec_path
15
+ from .checksums import (
16
+ gstin_check_char,
17
+ gstin_valid,
18
+ luhn_check_digit,
19
+ luhn_valid,
20
+ verhoeff_check_digit,
21
+ verhoeff_valid,
22
+ )
23
+ from .detect import Span, detect_pii, mask_value
24
+ from .detectors import Detector, bounded, detectors, register_detector, reset_detectors
25
+ from .normalise import Normalised, normalise
26
+ from .synth import synth_indian_pii
27
+
28
+ __all__ = [
29
+ "Detector",
30
+ "Normalised",
31
+ "Span",
32
+ "bounded",
33
+ "detect_pii",
34
+ "detectors",
35
+ "gstin_check_char",
36
+ "gstin_valid",
37
+ "luhn_check_digit",
38
+ "luhn_valid",
39
+ "mask_value",
40
+ "normalise",
41
+ "register_detector",
42
+ "reset_detectors",
43
+ "spec_path",
44
+ "synth_indian_pii",
45
+ "verhoeff_check_digit",
46
+ "verhoeff_valid",
47
+ ]
@@ -0,0 +1,64 @@
1
+ """Reading the shared detection spec shipped inside the package.
2
+
3
+ The spec (``spec/`` in the repository, copied here by ``tools/sync-spec.sh``)
4
+ is shared with the R package; see its README.md for the schema.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ from importlib import resources
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import regex
15
+ import yaml
16
+
17
+ SPEC_VERSION_SUPPORTED = 1
18
+
19
+
20
+ def spec_path() -> Path:
21
+ """Path of the ``spec`` directory shipped with the package."""
22
+ return Path(str(resources.files("credgate") / "spec"))
23
+
24
+
25
+ def read_spec_file(name: str, directory: Path | None = None) -> dict[str, Any]:
26
+ path = (directory or spec_path()) / name
27
+ with open(path, encoding="utf-8") as f:
28
+ data = yaml.safe_load(f)
29
+ if data.get("spec_version") != SPEC_VERSION_SUPPORTED:
30
+ raise ValueError(
31
+ f"Unsupported spec_version {data.get('spec_version')} in {name} "
32
+ f"(this credgate supports {SPEC_VERSION_SUPPORTED})."
33
+ )
34
+ return data
35
+
36
+
37
+ def _code_points(values: list[str]) -> frozenset[int]:
38
+ return frozenset(int(v.removeprefix("U+"), 16) for v in values)
39
+
40
+
41
+ @functools.cache
42
+ def engine() -> dict[str, Any]:
43
+ """Engine parameters from engine.yaml, with code points parsed."""
44
+ spec = read_spec_file("engine.yaml")
45
+ norm = spec["normalisation"]
46
+ return {
47
+ "digit_zeros": sorted(_code_points(norm["digit_zeros"])),
48
+ "remove": _code_points(norm["remove"]),
49
+ "dash": _code_points(norm["dash"]),
50
+ "boundary": spec["boundary"],
51
+ "separators": regex.compile(spec["separators"]),
52
+ "scoring": spec["scoring"],
53
+ }
54
+
55
+
56
+ @functools.cache
57
+ def detector_spec() -> dict[str, Any]:
58
+ """The parsed detectors.yaml."""
59
+ spec = read_spec_file("detectors.yaml")
60
+ spec["lists"] = {k: [str(x) for x in v] for k, v in spec.get("lists", {}).items()}
61
+ spec["tables"] = {
62
+ k: {str(key): str(val) for key, val in v.items()} for k, v in spec.get("tables", {}).items()
63
+ }
64
+ return spec