gheim 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.
gheim-0.1.0/.gitignore ADDED
@@ -0,0 +1,35 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .python-version
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
11
+ node_modules/
12
+ *.tgz
13
+ packages/*/dist/
14
+ packages/*/bun.lockb
15
+ .DS_Store
16
+ .env
17
+ .env.local
18
+ .claude/
19
+ coverage/
20
+ .coverage
21
+ htmlcov/
22
+ .hf_cache/
23
+
24
+ # Training artifacts (large; regenerated by re-running pipelines).
25
+ # Anchored to repo root so they don't shadow training/src/gheim_training/data/.
26
+ # Use `/data/*` (not `/data/`) so the directory itself isn't excluded —
27
+ # git can't re-include files inside an excluded directory.
28
+ /data/*
29
+ /checkpoints/
30
+ /wandb/
31
+ /logs/
32
+
33
+ # Exceptions: data provenance / audit READMEs that explain what's in /data/.
34
+ !/data/*.md
35
+ packages/gheim-js/package-lock.json
gheim-0.1.0/LICENSE ADDED
@@ -0,0 +1,190 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of tracking or improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not restrict the use of the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Joel Barmettler
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
189
+ implied. See the License for the specific language governing permissions
190
+ and limitations under the License.
gheim-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,224 @@
1
+ Metadata-Version: 2.4
2
+ Name: gheim
3
+ Version: 0.1.0
4
+ Summary: PII round-trip for LLM APIs: anonymize before the request, de-anonymize the stream on the way back.
5
+ Project-URL: Homepage, https://github.com/joelbarmettlerUZH/gheim
6
+ Project-URL: Repository, https://github.com/joelbarmettlerUZH/gheim
7
+ Project-URL: Issues, https://github.com/joelbarmettlerUZH/gheim/issues
8
+ Project-URL: Model card, https://huggingface.co/joelbarmettler/gheim-ch-560m
9
+ Project-URL: Dataset card, https://huggingface.co/datasets/joelbarmettler/gheim-ch-pii-171k
10
+ Author-email: Joel Barmettler <joel.barmettler@gmail.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: anonymization,llm,ner,openai,pii,privacy,redaction,swiss
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Security
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: httpx>=0.27
26
+ Provides-Extra: dev
27
+ Requires-Dist: dateparser>=1.2; extra == 'dev'
28
+ Requires-Dist: openai>=1.50; extra == 'dev'
29
+ Requires-Dist: phonenumbers>=8; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
31
+ Requires-Dist: pytest>=8; extra == 'dev'
32
+ Requires-Dist: ruff>=0.6; extra == 'dev'
33
+ Provides-Extra: local
34
+ Requires-Dist: torch>=2.2; extra == 'local'
35
+ Requires-Dist: transformers>=4.45; extra == 'local'
36
+ Provides-Extra: normalizers
37
+ Requires-Dist: dateparser>=1.2; extra == 'normalizers'
38
+ Requires-Dist: phonenumbers>=8; extra == 'normalizers'
39
+ Provides-Extra: openai
40
+ Requires-Dist: openai>=1.50; extra == 'openai'
41
+ Description-Content-Type: text/markdown
42
+
43
+ <div align="center">
44
+
45
+ <p align="center">
46
+ <img src="https://raw.githubusercontent.com/joelbarmettlerUZH/gheim/main/assets/logo.png" alt="gheim" width="360">
47
+ </p>
48
+
49
+ <p align="center"><strong>gheim (Python). PII round-trip for LLM APIs.</strong></p>
50
+
51
+ <p align="center">
52
+ <a href="https://pypi.org/project/gheim/"><img src="https://img.shields.io/pypi/v/gheim?color=blue&label=PyPI" alt="PyPI"></a>
53
+ <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.11%2B-blue" alt="Python 3.11+"></a>
54
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache%202.0-green" alt="Apache 2.0"></a>
55
+ </p>
56
+
57
+ </div>
58
+
59
+ Detect PII in text, substitute it with stable sentinels (`<PERSON_1>`,
60
+ `<EMAIL_2>`, ...), send the redacted text to any LLM, and restore the
61
+ originals on the way back, including in streamed responses. The package
62
+ is framework-agnostic and ships a drop-in `openai` client wrapper for
63
+ zero-effort integration.
64
+
65
+ See the [monorepo README](https://github.com/joelbarmettlerUZH/gheim) for
66
+ the cross-language overview and architecture.
67
+
68
+ ## Install
69
+
70
+ ```bash
71
+ uv add gheim # core: pairs with a RemoteDetector or GHEIM_API_KEY
72
+ uv add "gheim[local]" # + torch and transformers for on-device detection
73
+ uv add "gheim[openai]" # + drop-in OpenAI client
74
+ uv add "gheim[local,openai]" # both
75
+ ```
76
+
77
+ ## Model choice
78
+
79
+ `LocalDetector` runs a token-classification model in process. Two models
80
+ are recommended depending on the deployment context. Both implement the
81
+ same 33-class BIOES output schema and are interchangeable in
82
+ `LocalDetector` and the rest of the API.
83
+
84
+ | Model | Best for | Parameters | Notes |
85
+ |---|---|---:|---|
86
+ | [`joelbarmettler/gheim-ch-560m`](https://huggingface.co/joelbarmettler/gheim-ch-560m) | Swiss-market text (de_CH, fr_CH, it_CH, rm, en) with CH-format account numbers (IBAN, AHV, VAT-CHE) | 560M | Apache 2.0. Test F1 = 0.916 on Swiss text. |
87
+ | [`openai/privacy-filter`](https://huggingface.co/openai/privacy-filter) | English-first or general use, long-context (up to 128k tokens) | 1.4B (50M active, MoE) | Apache 2.0. Wider language coverage, larger weights. |
88
+
89
+ ```python
90
+ from gheim import LocalDetector
91
+
92
+ # Recommended for Swiss-market text:
93
+ det = LocalDetector(model_id="joelbarmettler/gheim-ch-560m")
94
+
95
+ # Alternative for English or general use:
96
+ det = LocalDetector(model_id="openai/privacy-filter")
97
+ ```
98
+
99
+ The package default `model_id` is `openai/privacy-filter`. Set
100
+ `GHEIM_DEFAULT_MODEL=joelbarmettler/gheim-ch-560m` in the environment, or
101
+ pass `model_id` explicitly, to opt into the Swiss model.
102
+
103
+ ## Drop-in OpenAI client
104
+
105
+ ```python
106
+ from gheim.openai import OpenAI
107
+
108
+ client = OpenAI() # same constructor args as openai.OpenAI
109
+ r = client.chat.completions.create(
110
+ model="gpt-4o",
111
+ messages=[{"role": "user", "content": "Hi, my name is Joel"}],
112
+ )
113
+ # r.choices[0].message.content contains "Joel".
114
+ # OpenAI only ever saw "<PERSON_1>".
115
+ ```
116
+
117
+ Streaming:
118
+
119
+ ```python
120
+ stream = client.chat.completions.create(..., stream=True)
121
+ for chunk in stream:
122
+ print(chunk.choices[0].delta.content or "", end="", flush=True)
123
+ ```
124
+
125
+ Async:
126
+
127
+ ```python
128
+ from gheim.openai import AsyncOpenAI
129
+ client = AsyncOpenAI()
130
+ r = await client.chat.completions.create(...)
131
+ ```
132
+
133
+ Per-call overrides:
134
+
135
+ ```python
136
+ from gheim import Session
137
+ session = Session() # reuse across calls for multi-turn coherent sentinels
138
+ r = client.chat.completions.create(
139
+ model="gpt-4o",
140
+ messages=[...],
141
+ gheim_session=session, # or gheim_detector=...
142
+ )
143
+ ```
144
+
145
+ ## Framework-agnostic
146
+
147
+ ```python
148
+ from gheim import Session, LocalDetector, anonymize_text, deanonymize_text
149
+
150
+ session = Session(detector=LocalDetector(model_id="joelbarmettler/gheim-ch-560m"))
151
+ clean = anonymize_text("Hi, my name is Joel", session)
152
+ # ... call any LLM with clean ...
153
+ final = deanonymize_text(response_text, session)
154
+ ```
155
+
156
+ Streaming deanonymizer:
157
+
158
+ ```python
159
+ from gheim import deanonymize_stream
160
+ for chunk in deanonymize_stream(my_chunk_iterator, session):
161
+ print(chunk, end="", flush=True)
162
+ ```
163
+
164
+ Chat-message helpers:
165
+
166
+ ```python
167
+ from gheim import anonymize_messages
168
+
169
+ redacted = anonymize_messages(messages, session) # preserves role, name, tool_call_id
170
+ ```
171
+
172
+ ## Wrapped endpoints
173
+
174
+ The drop-in `OpenAI` / `AsyncOpenAI` clients automatically protect every
175
+ text-carrying endpoint: `chat.completions`, `responses`, `completions` (legacy),
176
+ `embeddings`, `moderations`, `audio.speech`, `audio.transcriptions`,
177
+ `audio.translations`, `images.generate`, `images.edit`. Tool-call arguments and
178
+ SSE delta chunks are restored on the way back. See the
179
+ [monorepo README](https://github.com/joelbarmettlerUZH/gheim) for the full
180
+ coverage matrix and the embeddings caveat.
181
+
182
+ ### Strict mode
183
+
184
+ `gheim_strict=True` (default) raises `RuntimeError` if you call an unwrapped
185
+ endpoint (`beta.assistants`, `batches`, `files`, `uploads`, `fine_tuning`,
186
+ `vector_stores`). The error message names `client.raw.<path>` as the documented
187
+ escape hatch.
188
+
189
+ ```python
190
+ client = OpenAI(gheim_strict=False) # downgrade to one-time warnings
191
+ client.raw.beta.assistants.create(...) # always works regardless of strict mode
192
+ ```
193
+
194
+ ## Detector backends
195
+
196
+ ```python
197
+ from gheim import LocalDetector, RemoteDetector, default_detector
198
+
199
+ # Local inference. Weights download to the HF cache on first use.
200
+ det = LocalDetector(model_id="joelbarmettler/gheim-ch-560m",
201
+ device="auto", dtype=torch.bfloat16)
202
+
203
+ # Remote inference against your own gheim-server or api.gheim.ch.
204
+ det = RemoteDetector(base_url="http://your-host:8080", api_key="...")
205
+
206
+ # default_detector() picks remote if GHEIM_API_KEY is set, else local.
207
+ det = default_detector()
208
+ ```
209
+
210
+ ## Composite detector (recommended for production)
211
+
212
+ For categories where structure is verifiable by checksum (CH-IBAN, AHV,
213
+ VAT-CHE, credit cards, common token formats) the package ships a regex
214
+ catalogue under `gheim.detectors.composite` that pairs with the model
215
+ detector. The composite detector applies regex first, masks matched
216
+ spans, then runs the model on the remainder. This pushes effective
217
+ recall on `account_number`, `private_phone`, and `private_url` close
218
+ to 1.0 with high precision; the underlying ML model handles person
219
+ names, addresses, and dates.
220
+
221
+ ## License
222
+
223
+ Apache 2.0. Bundled model weights are inherited from the upstream
224
+ license of the model you select.
gheim-0.1.0/README.md ADDED
@@ -0,0 +1,182 @@
1
+ <div align="center">
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/joelbarmettlerUZH/gheim/main/assets/logo.png" alt="gheim" width="360">
5
+ </p>
6
+
7
+ <p align="center"><strong>gheim (Python). PII round-trip for LLM APIs.</strong></p>
8
+
9
+ <p align="center">
10
+ <a href="https://pypi.org/project/gheim/"><img src="https://img.shields.io/pypi/v/gheim?color=blue&label=PyPI" alt="PyPI"></a>
11
+ <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.11%2B-blue" alt="Python 3.11+"></a>
12
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache%202.0-green" alt="Apache 2.0"></a>
13
+ </p>
14
+
15
+ </div>
16
+
17
+ Detect PII in text, substitute it with stable sentinels (`<PERSON_1>`,
18
+ `<EMAIL_2>`, ...), send the redacted text to any LLM, and restore the
19
+ originals on the way back, including in streamed responses. The package
20
+ is framework-agnostic and ships a drop-in `openai` client wrapper for
21
+ zero-effort integration.
22
+
23
+ See the [monorepo README](https://github.com/joelbarmettlerUZH/gheim) for
24
+ the cross-language overview and architecture.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ uv add gheim # core: pairs with a RemoteDetector or GHEIM_API_KEY
30
+ uv add "gheim[local]" # + torch and transformers for on-device detection
31
+ uv add "gheim[openai]" # + drop-in OpenAI client
32
+ uv add "gheim[local,openai]" # both
33
+ ```
34
+
35
+ ## Model choice
36
+
37
+ `LocalDetector` runs a token-classification model in process. Two models
38
+ are recommended depending on the deployment context. Both implement the
39
+ same 33-class BIOES output schema and are interchangeable in
40
+ `LocalDetector` and the rest of the API.
41
+
42
+ | Model | Best for | Parameters | Notes |
43
+ |---|---|---:|---|
44
+ | [`joelbarmettler/gheim-ch-560m`](https://huggingface.co/joelbarmettler/gheim-ch-560m) | Swiss-market text (de_CH, fr_CH, it_CH, rm, en) with CH-format account numbers (IBAN, AHV, VAT-CHE) | 560M | Apache 2.0. Test F1 = 0.916 on Swiss text. |
45
+ | [`openai/privacy-filter`](https://huggingface.co/openai/privacy-filter) | English-first or general use, long-context (up to 128k tokens) | 1.4B (50M active, MoE) | Apache 2.0. Wider language coverage, larger weights. |
46
+
47
+ ```python
48
+ from gheim import LocalDetector
49
+
50
+ # Recommended for Swiss-market text:
51
+ det = LocalDetector(model_id="joelbarmettler/gheim-ch-560m")
52
+
53
+ # Alternative for English or general use:
54
+ det = LocalDetector(model_id="openai/privacy-filter")
55
+ ```
56
+
57
+ The package default `model_id` is `openai/privacy-filter`. Set
58
+ `GHEIM_DEFAULT_MODEL=joelbarmettler/gheim-ch-560m` in the environment, or
59
+ pass `model_id` explicitly, to opt into the Swiss model.
60
+
61
+ ## Drop-in OpenAI client
62
+
63
+ ```python
64
+ from gheim.openai import OpenAI
65
+
66
+ client = OpenAI() # same constructor args as openai.OpenAI
67
+ r = client.chat.completions.create(
68
+ model="gpt-4o",
69
+ messages=[{"role": "user", "content": "Hi, my name is Joel"}],
70
+ )
71
+ # r.choices[0].message.content contains "Joel".
72
+ # OpenAI only ever saw "<PERSON_1>".
73
+ ```
74
+
75
+ Streaming:
76
+
77
+ ```python
78
+ stream = client.chat.completions.create(..., stream=True)
79
+ for chunk in stream:
80
+ print(chunk.choices[0].delta.content or "", end="", flush=True)
81
+ ```
82
+
83
+ Async:
84
+
85
+ ```python
86
+ from gheim.openai import AsyncOpenAI
87
+ client = AsyncOpenAI()
88
+ r = await client.chat.completions.create(...)
89
+ ```
90
+
91
+ Per-call overrides:
92
+
93
+ ```python
94
+ from gheim import Session
95
+ session = Session() # reuse across calls for multi-turn coherent sentinels
96
+ r = client.chat.completions.create(
97
+ model="gpt-4o",
98
+ messages=[...],
99
+ gheim_session=session, # or gheim_detector=...
100
+ )
101
+ ```
102
+
103
+ ## Framework-agnostic
104
+
105
+ ```python
106
+ from gheim import Session, LocalDetector, anonymize_text, deanonymize_text
107
+
108
+ session = Session(detector=LocalDetector(model_id="joelbarmettler/gheim-ch-560m"))
109
+ clean = anonymize_text("Hi, my name is Joel", session)
110
+ # ... call any LLM with clean ...
111
+ final = deanonymize_text(response_text, session)
112
+ ```
113
+
114
+ Streaming deanonymizer:
115
+
116
+ ```python
117
+ from gheim import deanonymize_stream
118
+ for chunk in deanonymize_stream(my_chunk_iterator, session):
119
+ print(chunk, end="", flush=True)
120
+ ```
121
+
122
+ Chat-message helpers:
123
+
124
+ ```python
125
+ from gheim import anonymize_messages
126
+
127
+ redacted = anonymize_messages(messages, session) # preserves role, name, tool_call_id
128
+ ```
129
+
130
+ ## Wrapped endpoints
131
+
132
+ The drop-in `OpenAI` / `AsyncOpenAI` clients automatically protect every
133
+ text-carrying endpoint: `chat.completions`, `responses`, `completions` (legacy),
134
+ `embeddings`, `moderations`, `audio.speech`, `audio.transcriptions`,
135
+ `audio.translations`, `images.generate`, `images.edit`. Tool-call arguments and
136
+ SSE delta chunks are restored on the way back. See the
137
+ [monorepo README](https://github.com/joelbarmettlerUZH/gheim) for the full
138
+ coverage matrix and the embeddings caveat.
139
+
140
+ ### Strict mode
141
+
142
+ `gheim_strict=True` (default) raises `RuntimeError` if you call an unwrapped
143
+ endpoint (`beta.assistants`, `batches`, `files`, `uploads`, `fine_tuning`,
144
+ `vector_stores`). The error message names `client.raw.<path>` as the documented
145
+ escape hatch.
146
+
147
+ ```python
148
+ client = OpenAI(gheim_strict=False) # downgrade to one-time warnings
149
+ client.raw.beta.assistants.create(...) # always works regardless of strict mode
150
+ ```
151
+
152
+ ## Detector backends
153
+
154
+ ```python
155
+ from gheim import LocalDetector, RemoteDetector, default_detector
156
+
157
+ # Local inference. Weights download to the HF cache on first use.
158
+ det = LocalDetector(model_id="joelbarmettler/gheim-ch-560m",
159
+ device="auto", dtype=torch.bfloat16)
160
+
161
+ # Remote inference against your own gheim-server or api.gheim.ch.
162
+ det = RemoteDetector(base_url="http://your-host:8080", api_key="...")
163
+
164
+ # default_detector() picks remote if GHEIM_API_KEY is set, else local.
165
+ det = default_detector()
166
+ ```
167
+
168
+ ## Composite detector (recommended for production)
169
+
170
+ For categories where structure is verifiable by checksum (CH-IBAN, AHV,
171
+ VAT-CHE, credit cards, common token formats) the package ships a regex
172
+ catalogue under `gheim.detectors.composite` that pairs with the model
173
+ detector. The composite detector applies regex first, masks matched
174
+ spans, then runs the model on the remainder. This pushes effective
175
+ recall on `account_number`, `private_phone`, and `private_url` close
176
+ to 1.0 with high precision; the underlying ML model handles person
177
+ names, addresses, and dates.
178
+
179
+ ## License
180
+
181
+ Apache 2.0. Bundled model weights are inherited from the upstream
182
+ license of the model you select.