bb-mask 0.3.0__py3-none-any.whl

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.
bb_mask/__init__.py ADDED
@@ -0,0 +1,51 @@
1
+ """Data Mask istemcisi. Müşteri LLM çağrısı bu pakette yoktur."""
2
+
3
+ from bb_mask.client import (
4
+ DEFAULT_BASE_URL,
5
+ DEFAULT_TIMEOUT,
6
+ VERSION,
7
+ BBAnonym,
8
+ BBError,
9
+ MaskSession,
10
+ PlaceholderStyle,
11
+ Tagged,
12
+ aanonymize,
13
+ aanonymize_documents,
14
+ aanonymize_file,
15
+ anonymize,
16
+ anonymize_bytes,
17
+ anonymize_documents,
18
+ anonymize_file,
19
+ arestore,
20
+ delete,
21
+ get_map,
22
+ init,
23
+ restore,
24
+ session,
25
+ )
26
+
27
+ __version__ = VERSION
28
+
29
+ __all__ = [
30
+ "DEFAULT_BASE_URL",
31
+ "DEFAULT_TIMEOUT",
32
+ "VERSION",
33
+ "BBAnonym",
34
+ "BBError",
35
+ "MaskSession",
36
+ "PlaceholderStyle",
37
+ "Tagged",
38
+ "aanonymize",
39
+ "aanonymize_documents",
40
+ "aanonymize_file",
41
+ "anonymize",
42
+ "anonymize_bytes",
43
+ "anonymize_documents",
44
+ "anonymize_file",
45
+ "arestore",
46
+ "delete",
47
+ "get_map",
48
+ "init",
49
+ "restore",
50
+ "session",
51
+ ]
bb_mask/client.py ADDED
@@ -0,0 +1,530 @@
1
+ """bb_mask HTTP istemcisi. Model çağrısı bu modülde yoktur.
2
+
3
+ doc_id serviste kalır. get_map sözlüğü verir. persist=False state döner.
4
+ session() doc_id veya state'i gizler.
5
+
6
+ anonymize_file(path) yolu okur; anonymize_bytes(filename, content) bayt alır.
7
+ İki ad hem modülde hem BBAnonym üzerinde aynı anlama gelir.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import threading
14
+ from contextlib import contextmanager
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Iterator, Literal
18
+ from urllib.parse import quote
19
+
20
+ import httpx
21
+
22
+ # Müşteri kodu sunucudaki Data Mask konteynerine gider (8081).
23
+ DEFAULT_BASE_URL = "https://app.bbmask.co"
24
+ # Motor 120 sn bekler; istemci motordan sonra pes etsin ki iade/502 kararı sunucudan gelsin.
25
+ DEFAULT_TIMEOUT = 150.0
26
+ VERSION = "0.3.0"
27
+
28
+ PlaceholderStyle = Literal["angle", "bracket_tr"]
29
+ PLACEHOLDER_STYLES = ("angle", "bracket_tr")
30
+
31
+
32
+ class BBError(RuntimeError):
33
+ def __init__(self, status_code: int, detail: str, request_id: str | None = None):
34
+ super().__init__(detail)
35
+ self.status_code = status_code
36
+ self.detail = detail
37
+ self.request_id = request_id
38
+
39
+
40
+ @dataclass
41
+ class Tagged:
42
+ text: str
43
+ doc_id: str | None = None
44
+ state: dict | None = None
45
+ entities_found: dict = field(default_factory=dict)
46
+ balance_credits: str | None = None
47
+ request_id: str | None = None
48
+ placeholder_style: str = "angle"
49
+ keep_legal_form: bool = False
50
+ health_data: bool = False
51
+ llm_review: dict | None = None
52
+
53
+
54
+ def _options(
55
+ placeholder_style: PlaceholderStyle,
56
+ keep_legal_form: bool,
57
+ health_data: bool,
58
+ llm_review: bool,
59
+ ) -> dict:
60
+ if placeholder_style not in PLACEHOLDER_STYLES:
61
+ raise BBError(400, "placeholder_style angle veya bracket_tr olmalı")
62
+ return {
63
+ "placeholder_style": placeholder_style,
64
+ "keep_legal_form": bool(keep_legal_form),
65
+ "health_data": bool(health_data),
66
+ "llm_review": bool(llm_review),
67
+ }
68
+
69
+
70
+ def _form(persist: bool, options: dict) -> dict:
71
+ data = {"persist": str(persist).lower()}
72
+ for key, value in options.items():
73
+ data[key] = str(value).lower() if isinstance(value, bool) else value
74
+ return data
75
+
76
+
77
+ def _mask(token: str) -> str:
78
+ return f"{token[:8]}…{token[-4:]}" if len(token) > 12 else "…"
79
+
80
+
81
+ class BBAnonym:
82
+ """Tek anahtarın istemcisi. Bağlantı havuzu nesneyle yaşar; with ile ya da close() ile kapanır."""
83
+
84
+ def __init__(self, base_url: str, token: str, timeout: float = DEFAULT_TIMEOUT):
85
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
86
+ self._token = token
87
+ self.timeout = timeout
88
+ self._http: httpx.Client | None = None
89
+ self._lock = threading.Lock()
90
+
91
+ def __repr__(self) -> str:
92
+ return f"BBAnonym(base_url={self.base_url!r}, token={_mask(self._token)!r}, timeout={self.timeout})"
93
+
94
+ def __enter__(self) -> BBAnonym:
95
+ return self
96
+
97
+ def __exit__(self, *_exc) -> None:
98
+ self.close()
99
+
100
+ def close(self) -> None:
101
+ with self._lock:
102
+ if self._http is not None:
103
+ self._http.close()
104
+ self._http = None
105
+
106
+ def _client(self) -> httpx.Client:
107
+ with self._lock:
108
+ if self._http is None:
109
+ self._http = httpx.Client(
110
+ base_url=self.base_url,
111
+ timeout=self.timeout,
112
+ headers={"Authorization": f"Bearer {self._token}", "User-Agent": f"bb-mask-python/{VERSION}"},
113
+ )
114
+ return self._http
115
+
116
+ def _send(self, method: str, path: str, **kwargs) -> httpx.Response:
117
+ try:
118
+ return self._client().request(method, path, **kwargs)
119
+ except httpx.TimeoutException as exc:
120
+ raise BBError(504, f"Zaman aşımı ({self.timeout:g} sn). Ücret düşmüş olabilir.") from exc
121
+ except httpx.HTTPError as exc:
122
+ raise BBError(503, f"Servise ulaşılamadı ({self.base_url})") from exc
123
+
124
+ def _parse(self, response: httpx.Response) -> dict:
125
+ request_id = response.headers.get("x-request-id")
126
+ if response.status_code >= 400:
127
+ detail = response.text
128
+ try:
129
+ body = response.json()
130
+ if isinstance(body, dict) and body.get("detail"):
131
+ detail = str(body["detail"])
132
+ except Exception:
133
+ pass
134
+ raise BBError(response.status_code, detail, request_id)
135
+ try:
136
+ body = response.json()
137
+ except ValueError as exc:
138
+ raise BBError(502, "Servis JSON dönmedi", request_id) from exc
139
+ if not isinstance(body, dict):
140
+ raise BBError(502, "Servis JSON dönmedi", request_id)
141
+ body["_request_id"] = request_id
142
+ return body
143
+
144
+ def _tagged(self, body: dict, persist: bool) -> Tagged:
145
+ doc_id = body.get("doc_id") or None
146
+ if not persist:
147
+ doc_id = None
148
+ return Tagged(
149
+ text=body.get("text") or "",
150
+ doc_id=doc_id,
151
+ state=body.get("state"),
152
+ entities_found=body.get("entities_found") or {},
153
+ balance_credits=body.get("balance_credits"),
154
+ request_id=body.get("_request_id"),
155
+ placeholder_style=body.get("placeholder_style") or "angle",
156
+ keep_legal_form=bool(body.get("keep_legal_form")),
157
+ health_data=bool(body.get("health_data")),
158
+ llm_review=body.get("llm_review"),
159
+ )
160
+
161
+ def anonymize(
162
+ self,
163
+ text: str,
164
+ persist: bool = True,
165
+ *,
166
+ placeholder_style: PlaceholderStyle = "angle",
167
+ keep_legal_form: bool = False,
168
+ health_data: bool = False,
169
+ llm_review: bool = False,
170
+ ) -> Tagged:
171
+ """Metni anonimleştirir. 1 kredi.
172
+
173
+ persist: True → harita serviste, Tagged.doc_id dolu. False → Tagged.state dolu.
174
+ placeholder_style: "angle" → <PERSON_0>. "bracket_tr" → [KİŞİ_1]. Başka değer BBError(400).
175
+ keep_legal_form: True → şirket türü eki etiketin dışında: [ŞİRKET_1] A.Ş.
176
+ health_data: True → tanı, ilaç, tahlil, kan grubu gibi sağlık verisi de etiketlenir.
177
+ llm_review: True → kuralların kaçırdıkları LLM ile ikinci kez aranır. Durum Tagged.llm_review.
178
+ """
179
+ options = _options(placeholder_style, keep_legal_form, health_data, llm_review)
180
+ response = self._send("POST", "/v1/anonymize", json={"text": text, "persist": persist, **options})
181
+ return self._tagged(self._parse(response), persist)
182
+
183
+ def anonymize_bytes(
184
+ self,
185
+ filename: str,
186
+ content: bytes,
187
+ persist: bool = True,
188
+ *,
189
+ placeholder_style: PlaceholderStyle = "angle",
190
+ keep_legal_form: bool = False,
191
+ health_data: bool = False,
192
+ llm_review: bool = False,
193
+ ) -> Tagged:
194
+ """Bayttan tek dosya (.txt, .pdf, .docx). 1 kredi. Seçenekler anonymize ile aynı."""
195
+ options = _options(placeholder_style, keep_legal_form, health_data, llm_review)
196
+ response = self._send(
197
+ "POST",
198
+ "/v1/anonymize/file",
199
+ data=_form(persist, options),
200
+ files={"file": (filename, content, "application/octet-stream")},
201
+ )
202
+ return self._tagged(self._parse(response), persist)
203
+
204
+ def anonymize_file(
205
+ self,
206
+ path: str | Path,
207
+ persist: bool = True,
208
+ *,
209
+ placeholder_style: PlaceholderStyle = "angle",
210
+ keep_legal_form: bool = False,
211
+ health_data: bool = False,
212
+ llm_review: bool = False,
213
+ ) -> Tagged:
214
+ """Yoldan tek dosya. 1 kredi. Seçenekler anonymize ile aynı."""
215
+ file_path = Path(path)
216
+ return self.anonymize_bytes(
217
+ file_path.name,
218
+ file_path.read_bytes(),
219
+ persist,
220
+ placeholder_style=placeholder_style,
221
+ keep_legal_form=keep_legal_form,
222
+ health_data=health_data,
223
+ llm_review=llm_review,
224
+ )
225
+
226
+ def anonymize_documents(
227
+ self,
228
+ paths: list[str | Path],
229
+ persist: bool = True,
230
+ *,
231
+ placeholder_style: PlaceholderStyle = "angle",
232
+ keep_legal_form: bool = False,
233
+ health_data: bool = False,
234
+ llm_review: bool = False,
235
+ ) -> Tagged:
236
+ """1–3 dosya, tek doc_id. 1 kredi. Seçenekler anonymize ile aynı."""
237
+ options = _options(placeholder_style, keep_legal_form, health_data, llm_review)
238
+ if not 1 <= len(paths) <= 3:
239
+ raise BBError(400, "Bir istekte 1–3 dosya")
240
+ files = []
241
+ for path in paths:
242
+ file_path = Path(path)
243
+ files.append(("files", (file_path.name, file_path.read_bytes(), "application/octet-stream")))
244
+ response = self._send("POST", "/v1/anonymize/documents", data=_form(persist, options), files=files)
245
+ return self._tagged(self._parse(response), persist)
246
+
247
+ def restore(self, doc_id_or_state: str | dict, model_text: str) -> str:
248
+ payload: dict = {"text": model_text}
249
+ if isinstance(doc_id_or_state, dict):
250
+ payload["state"] = doc_id_or_state
251
+ else:
252
+ payload["doc_id"] = doc_id_or_state
253
+ response = self._send("POST", "/v1/restore", json=payload)
254
+ return self._parse(response).get("text") or ""
255
+
256
+ def get_map(self, doc_id: str, once: bool = False) -> dict:
257
+ response = self._send("GET", f"/v1/mappings/{quote(doc_id, safe='')}", params={"once": str(once).lower()})
258
+ return self._parse(response).get("state") or {}
259
+
260
+ def delete(self, doc_id: str) -> bool:
261
+ response = self._send("DELETE", f"/v1/mappings/{quote(doc_id, safe='')}")
262
+ return bool(self._parse(response).get("deleted"))
263
+
264
+
265
+ class MaskSession:
266
+ """persist=True ise harita bizde kalır ve çıkışta silinir.
267
+ persist=False ise state oturum nesnesindedir. Seçenekler oturum boyunca sabittir."""
268
+
269
+ def __init__(
270
+ self,
271
+ client: BBAnonym,
272
+ persist: bool = True,
273
+ *,
274
+ placeholder_style: PlaceholderStyle = "angle",
275
+ keep_legal_form: bool = False,
276
+ health_data: bool = False,
277
+ llm_review: bool = False,
278
+ ):
279
+ self._client = client
280
+ self.persist = persist
281
+ self.options = _options(placeholder_style, keep_legal_form, health_data, llm_review)
282
+ self._ids: list[str] = []
283
+ self._doc_id: str | None = None
284
+ self._state: dict | None = None
285
+
286
+ def _remember(self, tagged: Tagged) -> Tagged:
287
+ self._doc_id = tagged.doc_id
288
+ self._state = tagged.state
289
+ if tagged.doc_id:
290
+ self._ids.append(tagged.doc_id)
291
+ return tagged
292
+
293
+ def anonymize(self, text: str) -> Tagged:
294
+ return self._remember(self._client.anonymize(text, self.persist, **self.options))
295
+
296
+ def anonymize_file(self, path: str | Path) -> Tagged:
297
+ return self._remember(self._client.anonymize_file(path, self.persist, **self.options))
298
+
299
+ def anonymize_documents(self, paths: list[str | Path]) -> Tagged:
300
+ return self._remember(self._client.anonymize_documents(paths, self.persist, **self.options))
301
+
302
+ def restore(self, model_text: str) -> str:
303
+ if self.persist:
304
+ if not self._doc_id:
305
+ raise BBError(400, "Oturumda anonymize yok")
306
+ return self._client.restore(self._doc_id, model_text)
307
+ if not self._state:
308
+ raise BBError(400, "Oturumda state yok")
309
+ return self._client.restore(self._state, model_text)
310
+
311
+ def close(self) -> None:
312
+ if not self.persist:
313
+ self._state = None
314
+ return
315
+ for doc_id in self._ids:
316
+ try:
317
+ self._client.delete(doc_id)
318
+ except BBError:
319
+ pass
320
+ self._ids.clear()
321
+
322
+
323
+ _current: BBAnonym | None = None
324
+
325
+
326
+ def init(api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = DEFAULT_TIMEOUT) -> BBAnonym:
327
+ """Süreçte bir kez. Model çağrısı değildir."""
328
+ global _current
329
+ if not api_key.strip():
330
+ raise BBError(401, "api_key boş")
331
+ _current = BBAnonym(base_url, api_key.strip(), timeout)
332
+ return _current
333
+
334
+
335
+ def _require() -> BBAnonym:
336
+ if _current is None:
337
+ raise BBError(401, "bb_mask.init çağrılmadı")
338
+ return _current
339
+
340
+
341
+ def anonymize(
342
+ text: str,
343
+ persist: bool = True,
344
+ *,
345
+ placeholder_style: PlaceholderStyle = "angle",
346
+ keep_legal_form: bool = False,
347
+ health_data: bool = False,
348
+ llm_review: bool = False,
349
+ ) -> Tagged:
350
+ """Metni anonimleştirir. 1 kredi. init gerekir.
351
+
352
+ persist: True → harita serviste, Tagged.doc_id dolu. False → Tagged.state dolu.
353
+ placeholder_style: "angle" → <PERSON_0>. "bracket_tr" → [KİŞİ_1]. Başka değer BBError(400).
354
+ keep_legal_form: True → şirket türü eki etiketin dışında: [ŞİRKET_1] A.Ş.
355
+ health_data: True → tanı, ilaç, tahlil, kan grubu gibi sağlık verisi de etiketlenir.
356
+ llm_review: True → kuralların kaçırdıkları LLM ile ikinci kez aranır. Durum Tagged.llm_review.
357
+ """
358
+ return _require().anonymize(
359
+ text,
360
+ persist,
361
+ placeholder_style=placeholder_style,
362
+ keep_legal_form=keep_legal_form,
363
+ health_data=health_data,
364
+ llm_review=llm_review,
365
+ )
366
+
367
+
368
+ def anonymize_file(
369
+ path: str | Path,
370
+ persist: bool = True,
371
+ *,
372
+ placeholder_style: PlaceholderStyle = "angle",
373
+ keep_legal_form: bool = False,
374
+ health_data: bool = False,
375
+ llm_review: bool = False,
376
+ ) -> Tagged:
377
+ """Yoldan tek dosya (.txt, .pdf, .docx). 1 kredi. Seçenekler anonymize ile aynı."""
378
+ return _require().anonymize_file(
379
+ path,
380
+ persist,
381
+ placeholder_style=placeholder_style,
382
+ keep_legal_form=keep_legal_form,
383
+ health_data=health_data,
384
+ llm_review=llm_review,
385
+ )
386
+
387
+
388
+ def anonymize_bytes(
389
+ filename: str,
390
+ content: bytes,
391
+ persist: bool = True,
392
+ *,
393
+ placeholder_style: PlaceholderStyle = "angle",
394
+ keep_legal_form: bool = False,
395
+ health_data: bool = False,
396
+ llm_review: bool = False,
397
+ ) -> Tagged:
398
+ """Bayttan tek dosya. 1 kredi. Seçenekler anonymize ile aynı."""
399
+ return _require().anonymize_bytes(
400
+ filename,
401
+ content,
402
+ persist,
403
+ placeholder_style=placeholder_style,
404
+ keep_legal_form=keep_legal_form,
405
+ health_data=health_data,
406
+ llm_review=llm_review,
407
+ )
408
+
409
+
410
+ def anonymize_documents(
411
+ paths: list[str | Path],
412
+ persist: bool = True,
413
+ *,
414
+ placeholder_style: PlaceholderStyle = "angle",
415
+ keep_legal_form: bool = False,
416
+ health_data: bool = False,
417
+ llm_review: bool = False,
418
+ ) -> Tagged:
419
+ """1–3 dosya, tek doc_id. 1 kredi. Seçenekler anonymize ile aynı."""
420
+ return _require().anonymize_documents(
421
+ paths,
422
+ persist,
423
+ placeholder_style=placeholder_style,
424
+ keep_legal_form=keep_legal_form,
425
+ health_data=health_data,
426
+ llm_review=llm_review,
427
+ )
428
+
429
+
430
+ def restore(doc_id_or_state: str | dict, model_text: str) -> str:
431
+ return _require().restore(doc_id_or_state, model_text)
432
+
433
+
434
+ def get_map(doc_id: str, once: bool = False) -> dict:
435
+ return _require().get_map(doc_id, once=once)
436
+
437
+
438
+ def delete(doc_id: str) -> bool:
439
+ return _require().delete(doc_id)
440
+
441
+
442
+ @contextmanager
443
+ def session(
444
+ persist: bool = True,
445
+ *,
446
+ placeholder_style: PlaceholderStyle = "angle",
447
+ keep_legal_form: bool = False,
448
+ health_data: bool = False,
449
+ llm_review: bool = False,
450
+ ) -> Iterator[MaskSession]:
451
+ """with ile MaskSession. Seçenekler anonymize ile aynı; oturumdaki her çağrıya gider."""
452
+ handle = MaskSession(
453
+ _require(),
454
+ persist,
455
+ placeholder_style=placeholder_style,
456
+ keep_legal_form=keep_legal_form,
457
+ health_data=health_data,
458
+ llm_review=llm_review,
459
+ )
460
+ try:
461
+ yield handle
462
+ finally:
463
+ handle.close()
464
+
465
+
466
+ async def aanonymize(
467
+ text: str,
468
+ persist: bool = True,
469
+ *,
470
+ placeholder_style: PlaceholderStyle = "angle",
471
+ keep_legal_form: bool = False,
472
+ health_data: bool = False,
473
+ llm_review: bool = False,
474
+ ) -> Tagged:
475
+ """anonymize'ın async karşılığı. Seçenekler aynı."""
476
+ return await asyncio.to_thread(
477
+ anonymize,
478
+ text,
479
+ persist,
480
+ placeholder_style=placeholder_style,
481
+ keep_legal_form=keep_legal_form,
482
+ health_data=health_data,
483
+ llm_review=llm_review,
484
+ )
485
+
486
+
487
+ async def aanonymize_file(
488
+ path: str | Path,
489
+ persist: bool = True,
490
+ *,
491
+ placeholder_style: PlaceholderStyle = "angle",
492
+ keep_legal_form: bool = False,
493
+ health_data: bool = False,
494
+ llm_review: bool = False,
495
+ ) -> Tagged:
496
+ """anonymize_file'ın async karşılığı. Seçenekler aynı."""
497
+ return await asyncio.to_thread(
498
+ anonymize_file,
499
+ path,
500
+ persist,
501
+ placeholder_style=placeholder_style,
502
+ keep_legal_form=keep_legal_form,
503
+ health_data=health_data,
504
+ llm_review=llm_review,
505
+ )
506
+
507
+
508
+ async def aanonymize_documents(
509
+ paths: list[str | Path],
510
+ persist: bool = True,
511
+ *,
512
+ placeholder_style: PlaceholderStyle = "angle",
513
+ keep_legal_form: bool = False,
514
+ health_data: bool = False,
515
+ llm_review: bool = False,
516
+ ) -> Tagged:
517
+ """anonymize_documents'ın async karşılığı. Seçenekler aynı."""
518
+ return await asyncio.to_thread(
519
+ anonymize_documents,
520
+ paths,
521
+ persist,
522
+ placeholder_style=placeholder_style,
523
+ keep_legal_form=keep_legal_form,
524
+ health_data=health_data,
525
+ llm_review=llm_review,
526
+ )
527
+
528
+
529
+ async def arestore(doc_id_or_state: str | dict, model_text: str) -> str:
530
+ return await asyncio.to_thread(restore, doc_id_or_state, model_text)
bb_mask/py.typed ADDED
File without changes
@@ -0,0 +1,373 @@
1
+ Metadata-Version: 2.4
2
+ Name: bb-mask
3
+ Version: 0.3.0
4
+ Summary: Data Mask istemcisi: metin ve dosya anonimleştirme, restore. Model çağrısı yok.
5
+ Author: BigBrains
6
+ License: MIT
7
+ Project-URL: Homepage, https://app.bbmask.co
8
+ Project-URL: Documentation, https://app.bbmask.co/#/sdk
9
+ Project-URL: Repository, https://github.com/bigbrains-company/bb-mask-sdk
10
+ Keywords: anonymization,kvkk,pii,data-mask,bigbrains
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Security
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: httpx>=0.27.0
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=8; extra == "test"
26
+ Dynamic: license-file
27
+
28
+ # bb-mask
29
+
30
+ Türkçe hukuki metindeki kişisel veriyi etiketler, model cevabındaki etiketleri geri açar. Paket ince bir HTTP istemcisidir. Model çağırmaz, metin yazdırmaz, bekletmez.
31
+
32
+ Müşteri Data Mask konsolundan `dm_test_` anahtarı alır. Kendi backend’i bu paketi kurar ve anahtarı `init`’e verir. LLM satırı müşterinindir; SDK’nın öncesine `anonymize`, sonrasına `restore` konur.
33
+
34
+ ```python
35
+ import os
36
+ import bb_mask
37
+
38
+ bb_mask.init(api_key=os.environ["BB_ANONYM_TOKEN"])
39
+
40
+
41
+ def ozetle(metin: str) -> str:
42
+ tagged = bb_mask.anonymize(metin)
43
+ cevap = kendi_llm(tagged.text) # bu satır sizde
44
+ return bb_mask.restore(tagged.doc_id, cevap)
45
+ ```
46
+
47
+ Python 3.11+. Tek bağımlılık `httpx`. Bu klasör Python paketidir. Node, Go, C# ve Java aynı deponun diğer klasörlerindedir.
48
+
49
+ ## Kurulum
50
+
51
+ Paket yayınlanınca:
52
+
53
+ ```bash
54
+ pip install bb-mask
55
+ ```
56
+
57
+ Yayın öncesi, depo kökünden:
58
+
59
+ ```bash
60
+ pip install -e python
61
+ ```
62
+
63
+ Anahtarı koda veya repoya yazmayın. Ortam değişkeni veya kendi ayar dosyanız yeter.
64
+
65
+ ```bash
66
+ export BB_ANONYM_TOKEN="dm_test_..."
67
+ ```
68
+
69
+ `init` süreçte bir kez çalışır. Model çağrısı değildir. Modül fonksiyonları (`bb_mask.anonymize` ve diğerleri) bundan önce çağrılırsa `BBError(401)` verir ve servise gitmez.
70
+
71
+ ```python
72
+ istemci = bb_mask.init(
73
+ api_key=os.environ["BB_ANONYM_TOKEN"],
74
+ base_url="https://app.bbmask.co", # varsayılan budur
75
+ timeout=150, # saniye
76
+ )
77
+ ```
78
+
79
+ | Argüman | Tip | Anlam |
80
+ |---|---|---|
81
+ | `api_key` | `str` | Konsoldaki `dm_test_` anahtarı. Boşsa `BBError(401)`. |
82
+ | `base_url` | `str` | Servis adresi. Varsayılan `https://app.bbmask.co`. |
83
+ | `timeout` | `float` | HTTP zaman aşımı, saniye. Varsayılan `150`; motor 120 sn bekler, istemci ondan sonra pes eder. |
84
+
85
+ Dönüş `BBAnonym`'dur. Modül fonksiyonları bu istemciyi kullanır. İkinci `init` öncekinin yerine geçer.
86
+
87
+ İkinci bir anahtar gerekiyorsa süreç globaline dokunmadan `BBAnonym` kurun. Kurucu `init` istemez.
88
+
89
+ ```python
90
+ diger = bb_mask.BBAnonym("https://app.bbmask.co", token, timeout=150)
91
+ ```
92
+
93
+ ## Nesneler
94
+
95
+ ### `Tagged`
96
+
97
+ `anonymize`, `anonymize_file` ve `anonymize_documents` bunu döner.
98
+
99
+ | Alan | Tip | Ne zaman dolu |
100
+ |---|---|---|
101
+ | `text` | `str` | Her zaman. Kişisel veri yerine etiket vardır: `<PERSON_0>`, `<TR_NATIONAL_ID_0>`. |
102
+ | `doc_id` | `str \| None` | `persist=True` (varsayılan). Haritanın servisteki anahtarı. Yalnız aynı çalışma alanının anahtarı açar. |
103
+ | `state` | `dict \| None` | `persist=False`. Haritanın kendisi. Servise yazılmaz. |
104
+ | `entities_found` | `dict[str, int]` | Her zaman. Tip başına sayı: `{"PERSON": 2}`. Düz isim taşımaz. |
105
+ | `balance_credits` | `str \| None` | Çağrıdan sonra kalan bakiye: `"9.00"`. |
106
+ | `request_id` | `str \| None` | Yanıtın `X-Request-Id` değeri. Konsoldaki Kullanım satırıyla eşleşir. |
107
+ | `placeholder_style` | `str` | Uygulanan etiket biçimi: `"angle"` veya `"bracket_tr"`. |
108
+ | `keep_legal_form` | `bool` | Uygulanan değer. |
109
+ | `health_data` | `bool` | Uygulanan değer. |
110
+ | `llm_review` | `dict \| None` | `llm_review=True` istendiyse durum özeti: `status`, `model`, `chunks`, `chunks_failed`, `elapsed_ms`, `added_spans`, `error`. Düz isim taşımaz. |
111
+
112
+ ```python
113
+ tagged = bb_mask.anonymize("Davacı Hasan Demirkol, TC 62601815964")
114
+ tagged.doc_id # "a1b2..."
115
+ tagged.text # "Davacı <PERSON_0>, TC <TR_NATIONAL_ID_0>"
116
+ tagged.state # None
117
+ ```
118
+
119
+ Etiket biçimi `<TIP_0>`. Aynı yüzey aynı numarayı alır. Model etiketi bozarsa (`<PERSON 0>`) onarım servistedir. Mahkeme ve kanun adları etiketlenmez.
120
+
121
+ ### Seçenekler
122
+
123
+ Dört anonymize çağrısı (`anonymize`, `anonymize_file`, `anonymize_bytes`, `anonymize_documents`), async kardeşleri ve `session()` aynı isimli parametreleri alır. Yalnız isimle verilir. Hepsi kapalı başlar; servis kendi varsayılanına düşmez.
124
+
125
+ | Parametre | Varsayılan | Etki |
126
+ |---|---|---|
127
+ | `placeholder_style` | `"angle"` | `"angle"` → `<PERSON_0>`. `"bracket_tr"` → `[KİŞİ_1]`, `[ŞİRKET_1]`; 1'den başlar. Başka değer istek gitmeden `BBError(400)`. |
128
+ | `keep_legal_form` | `False` | `True` → şirket türü eki etiketin dışında kalır: `[ŞİRKET_1] A.Ş.`, `<ORGANIZATION_0> Ltd. Şti.` |
129
+ | `health_data` | `False` | `True` → KVKK m.6 sağlık verisi de etiketlenir: tanı, ilaç, tahlil, kan grubu, hasta no, sağlık kurumu. |
130
+ | `llm_review` | `False` | `True` → kuralların kaçırdığı kişi, şirket, adres ve kimlikler bir LLM ile ikinci kez aranır. Model geçici anonim metni görür. Servis katmanı kapalıysa hata değildir; `Tagged.llm_review["status"]` bunu söyler. |
131
+
132
+ ```python
133
+ tagged = bb_mask.anonymize(
134
+ "Davalı Kaya İnşaat A.Ş. çalışanı Ali Kaya, tanı: diyabet",
135
+ placeholder_style="bracket_tr",
136
+ keep_legal_form=True,
137
+ health_data=True,
138
+ llm_review=True,
139
+ )
140
+ tagged.text # "Davalı [ŞİRKET_1] A.Ş. çalışanı [KİŞİ_1], tanı: [TANI_1]"
141
+ tagged.llm_review # {"status": "ok", "model": "qwen/qwen3.8-27b", "added_spans": 0, ...}
142
+ ```
143
+
144
+ `state` ve `get_map` sözlüğü biçimden bağımsız kanonik etiket taşır (`<PERSON_0>`). `restore` iki biçimi de açar.
145
+
146
+ ### `state` / `get_map` sözlüğü
147
+
148
+ Şekil: `dict[str, dict[str, str]]`. Dış anahtar varlık tipi, iç anahtar düz metin, değer etikettir.
149
+
150
+ ```python
151
+ {
152
+ "PERSON": {"Hasan Demirkol": "<PERSON_0>"},
153
+ "TR_NATIONAL_ID": {"62601815964": "<TR_NATIONAL_ID_0>"},
154
+ }
155
+ ```
156
+
157
+ Sözlük düz isim taşır. Loga, bilete veya modele koymayın. `restore` bu sözlüğü kendisi kullanır; modele yalnız `tagged.text` gider.
158
+
159
+ ### `BBError`
160
+
161
+ `RuntimeError` alt sınıfı. `status_code: int`, `detail: str`, `request_id: str | None`. `str(hata)` ayrıntı metnidir. `request_id` servisten yanıt geldiyse doludur; destek isterken bu değeri iletin.
162
+
163
+ Ağ hatası da `BBError` olur; `httpx` istisnası dışarı sızmaz.
164
+
165
+ | Kod | Anlam |
166
+ |---|---|
167
+ | 400 | Boş metin, 1–3 dışı dosya sayısı, geçersiz `placeholder_style`, oturumda anonymize yok, `doc_id` ve `state` ikisi de yok. |
168
+ | 401 | `init` çağrılmadı, anahtar boş veya tanınmıyor. |
169
+ | 402 | Bakiye yok. Anonimleştirme servise gitmez. |
170
+ | 404 | Harita yok. Silinmiş, `once=True` ile okunmuş, başka çalışma alanının veya servis tutmuyordur. |
171
+ | 413 | Dosya 20 MB üstü. |
172
+ | 502 | Motor hata verdi; anonymize ücreti iade edilir. Yanıt JSON değilse de 502 olur. |
173
+ | 503 | Servise ulaşılamadı. İstek gitmedi. |
174
+ | 504 | `timeout` doldu. İstek servise ulaşmış olabilir; ücret düşmüş olabilir. Konsoldaki Kullanım sayfasına bakın. |
175
+
176
+ Ücret başarılı anonymize çağrısında düşer. Servis hata verirse ücret geri yazılır. `restore`, `get_map` ve `delete` ücret yazmaz.
177
+
178
+ ### `MaskSession`
179
+
180
+ `with bb_mask.session()` bunu verir. `doc_id` ve `state` oturumun içindedir.
181
+
182
+ | Metod | Dönüş |
183
+ |---|---|
184
+ | `anonymize(text)` | `Tagged` |
185
+ | `anonymize_file(path)` | `Tagged`. Yolu okur. |
186
+ | `anonymize_documents(paths)` | `Tagged` |
187
+ | `restore(model_metni)` | `str` |
188
+ | `close()` | `None`. Blok bitince kendiliğinden çağrılır. |
189
+ | `persist` | `bool`. Kurgu 1 ise `True`. Oturumda sabittir. |
190
+ | `options` | `dict`. `session(...)` içine verilen seçenekler. Her anonymize çağrısına gider. |
191
+
192
+ `restore` burada yalnız model metnini alır. Anonymize olmadan çağrılırsa `BBError(400)`. Blok bitince `close` çalışır: `persist=True` ise tutulan her `doc_id` silinir, `persist=False` ise state düşer ve servise silme gitmez.
193
+
194
+ ## Çağrılar
195
+
196
+ Hepsi `init` sonrasında. Dosya uzantısı `.txt`, `.pdf` veya `.docx`. Dosya başına tavan 20 MB.
197
+
198
+ `anonymize_file(path)` bir yol alır ve dosyayı okur. Bayt sizdeyse `anonymize_bytes(filename, content)` kullanın. İki ad modülde ve `BBAnonym` üzerinde aynı anlama gelir. `MaskSession.anonymize_file(path)` de yolu okur.
199
+
200
+ ### Kurgu 1 — harita serviste, siz `doc_id` tutarsınız
201
+
202
+ ```python
203
+ tagged = bb_mask.anonymize(metin)
204
+ cevap = kendi_llm(tagged.text)
205
+ duz = bb_mask.restore(tagged.doc_id, cevap)
206
+ bb_mask.delete(tagged.doc_id) # iş bitince
207
+ ```
208
+
209
+ Tek dosya:
210
+
211
+ ```python
212
+ tagged = bb_mask.anonymize_file("dilekce.pdf")
213
+ duz = bb_mask.restore(tagged.doc_id, kendi_llm(tagged.text))
214
+ ```
215
+
216
+ Birden çok dosya tek `doc_id` paylaşır. Aynı kişi iki dosyada da `<PERSON_0>` olur. Üst sınır 3 dosyadır. Ücret tek anonymize’dir.
217
+
218
+ ```python
219
+ tagged = bb_mask.anonymize_documents(
220
+ ["dilekce.pdf", "cevap.docx", "ek.txt"]
221
+ )
222
+ duz = bb_mask.restore(tagged.doc_id, kendi_llm(tagged.text))
223
+ ```
224
+
225
+ `restore` orijinal dosyayı almaz. Modelin yazdığı metindeki etiketleri açar.
226
+
227
+ ### Kurgu 2 — aynı `doc_id`, üstüne sözlük
228
+
229
+ ```python
230
+ tagged = bb_mask.anonymize(metin)
231
+ sozluk = bb_mask.get_map(tagged.doc_id)
232
+ # sozluk["PERSON"]["Hasan Demirkol"] == "<PERSON_0>"
233
+
234
+ duz = bb_mask.restore(tagged.doc_id, kendi_llm(tagged.text))
235
+ ```
236
+
237
+ Okuyunca servisteki kopya da silinsin:
238
+
239
+ ```python
240
+ sozluk = bb_mask.get_map(tagged.doc_id, once=True)
241
+ # bundan sonra restore ve get_map 404 döner
242
+ ```
243
+
244
+ Sözlük gerekmiyorsa Kurgu 1 yeter.
245
+
246
+ ### Kurgu 3 — harita sizde, servis saklamaz
247
+
248
+ `doc_id` boştur. `state` sözlüktür. Onu modele koymayın. Süreç ölünce de `restore` çalışsın diye `state`’i kendi tarafta saklayabilirsiniz.
249
+
250
+ ```python
251
+ tagged = bb_mask.anonymize(metin, persist=False)
252
+ assert tagged.doc_id is None and tagged.state is not None
253
+
254
+ cevap = kendi_llm(tagged.text)
255
+ duz = bb_mask.restore(tagged.state, cevap)
256
+ ```
257
+
258
+ Dosyada da aynıdır: `anonymize_file(yol, persist=False)`, `anonymize_documents(yollar, persist=False)`.
259
+
260
+ ### Kurgu 4 — siz id veya json görmezsiniz
261
+
262
+ Kurgu 1. Çıkışta harita silinir.
263
+
264
+ ```python
265
+ with bb_mask.session() as s:
266
+ tagged = s.anonymize_documents(["dilekce.pdf", "ek.txt"])
267
+ cevap = kendi_llm(tagged.text)
268
+ duz = s.restore(cevap)
269
+ ```
270
+
271
+ Kurgu 3 yüzeyi. State oturum nesnesindedir, servise yazılmaz.
272
+
273
+ ```python
274
+ with bb_mask.session(persist=False) as s:
275
+ tagged = s.anonymize(metin)
276
+ duz = s.restore(kendi_llm(tagged.text))
277
+ ```
278
+
279
+ ### Async
280
+
281
+ Dört fonksiyon vardır. İmzalar senkron kardeşleriyle aynıdır. HTTP işi bir thread’de yürür. `init` bunlarda da gerekir.
282
+
283
+ ```python
284
+ aanonymize(text, persist=True, *, <seçenekler>) -> Tagged
285
+ aanonymize_file(path, persist=True, *, <seçenekler>) -> Tagged
286
+ aanonymize_documents(paths, persist=True, *, <seçenekler>) -> Tagged
287
+ arestore(doc_id_or_state, model_text) -> str
288
+ ```
289
+
290
+ ```python
291
+ tagged = await bb_mask.aanonymize(metin)
292
+ duz = await bb_mask.arestore(tagged.doc_id, cevap)
293
+ ```
294
+
295
+ `get_map`, `delete`, `session` ve `anonymize_bytes` için async karşılık yoktur.
296
+
297
+ ## Referans
298
+
299
+ Modül fonksiyonları `init` ister. `BBAnonym` metotları kurucudaki anahtarı kullanır.
300
+
301
+ ### Modül
302
+
303
+ ```python
304
+ init(api_key: str, base_url: str = "https://app.bbmask.co", timeout: float = 150) -> BBAnonym
305
+ anonymize(text: str, persist: bool = True, *, <seçenekler>) -> Tagged
306
+ anonymize_file(path: str | Path, persist: bool = True, *, <seçenekler>) -> Tagged
307
+ anonymize_bytes(filename: str, content: bytes, persist: bool = True, *, <seçenekler>) -> Tagged
308
+ anonymize_documents(paths: list[str | Path], persist: bool = True, *, <seçenekler>) -> Tagged
309
+ restore(doc_id_or_state: str | dict, model_text: str) -> str
310
+ get_map(doc_id: str, once: bool = False) -> dict
311
+ delete(doc_id: str) -> bool
312
+ session(persist: bool = True, *, <seçenekler>) # with ile MaskSession
313
+ aanonymize(text: str, persist: bool = True, *, <seçenekler>) -> Tagged
314
+ aanonymize_file(path: str | Path, persist: bool = True, *, <seçenekler>) -> Tagged
315
+ aanonymize_documents(paths: list[str | Path], persist: bool = True, *, <seçenekler>) -> Tagged
316
+ arestore(doc_id_or_state: str | dict, model_text: str) -> str
317
+ ```
318
+
319
+ `<seçenekler>` yalnız isimle verilen dört parametredir; imzada açıkça yazılıdır, editör tamamlar, `help(bb_mask.anonymize)` açıklar:
320
+
321
+ ```python
322
+ placeholder_style: Literal["angle", "bracket_tr"] = "angle",
323
+ keep_legal_form: bool = False,
324
+ health_data: bool = False,
325
+ llm_review: bool = False,
326
+ ```
327
+
328
+ `persist=True` haritayı serviste tutar, `Tagged.doc_id` dolar. `persist=False` haritayı yazmaz, `Tagged.state` dolar, `doc_id` `None` olur.
329
+
330
+ `restore` ilk argüman `doc_id` (`str`) veya `state` (`dict`). İkinci argüman modelin yazdığı metindir. Dönüş düz metindir.
331
+
332
+ `get_map` sözlüğü döner. `once=True` okuyunca servisteki kopyayı siler; bundan sonra `restore` ve `get_map` `404` verir.
333
+
334
+ `delete` servis `deleted` derse `True` döner.
335
+
336
+ `session` context manager'dır: `with bb_mask.session() as s`. Çıkışta `s.close()` çalışır.
337
+
338
+ ### `BBAnonym`
339
+
340
+ `init` gerekmez. Modülle aynı adları taşır. Tek bir `httpx.Client` paylaşır (bağlantı havuzu); `with` ile veya `close()` ile kapatılır. `repr()` anahtarı maskeler.
341
+
342
+ ```python
343
+ BBAnonym(base_url: str, token: str, timeout: float = 150)
344
+ anonymize(text: str, persist: bool = True, *, <seçenekler>) -> Tagged
345
+ anonymize_file(path: str | Path, persist: bool = True, *, <seçenekler>) -> Tagged
346
+ anonymize_bytes(filename: str, content: bytes, persist: bool = True, *, <seçenekler>) -> Tagged
347
+ anonymize_documents(paths: list[str | Path], persist: bool = True, *, <seçenekler>) -> Tagged
348
+ restore(doc_id_or_state: str | dict, model_text: str) -> str
349
+ get_map(doc_id: str, once: bool = False) -> dict
350
+ delete(doc_id: str) -> bool
351
+ close() -> None
352
+ ```
353
+
354
+ Paket `py.typed` taşır; tip denetleyiciler imzaları okur.
355
+
356
+ ### `MaskSession`
357
+
358
+ Kurucu dışarıdan çağrılmaz. `persist` ve seçenekler oturum açılırken verilir, metotlara tekrar geçilmez: `bb_mask.session(placeholder_style="bracket_tr", llm_review=True)`.
359
+
360
+ ```python
361
+ anonymize(text: str) -> Tagged
362
+ anonymize_file(path: str | Path) -> Tagged
363
+ anonymize_documents(paths: list[str | Path]) -> Tagged
364
+ restore(model_text: str) -> str
365
+ close() -> None
366
+ ```
367
+
368
+ ## Bu pakette olmayanlar
369
+
370
+ - Müşterinin LLM çağrısı ve `@ask`.
371
+ - FastAPI uygulaması, konsol çıktısı, `sleep`.
372
+ - Anahtar üretimi ve bakiye. Onlar panelde.
373
+ - Etiket onarımı. Bozuk etiketi servis düzeltir; sözlükteki anahtar düz metindir.
@@ -0,0 +1,8 @@
1
+ bb_mask/__init__.py,sha256=hWDpAxJqQYbohTbsn6vluONlqdiC-azYcmr4R_YAy_c,890
2
+ bb_mask/client.py,sha256=K_-ybVN5KqDsU7Eyw-lFRFt5dKlweOOvMlCMB-IPmO8,17781
3
+ bb_mask/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ bb_mask-0.3.0.dist-info/licenses/LICENSE,sha256=RHcVuJ2p_3PsOCHmfaMU-gQ_-cnp218vP6ntzkgGe_Q,1066
5
+ bb_mask-0.3.0.dist-info/METADATA,sha256=LHwZQJq9RgfRNgShw4BW3HGqHxk_49pdlrmSB9PyPck,15049
6
+ bb_mask-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ bb_mask-0.3.0.dist-info/top_level.txt,sha256=jgtV8XzImseHc0zB6KUkxo30OafqEpz-loyT_2FsYsw,8
8
+ bb_mask-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BigBrains
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ bb_mask