kawallm 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.
Files changed (50) hide show
  1. kawallm-0.1.0/.gitignore +16 -0
  2. kawallm-0.1.0/CHANGELOG.md +14 -0
  3. kawallm-0.1.0/CONTRIBUTING.md +88 -0
  4. kawallm-0.1.0/LICENSE +201 -0
  5. kawallm-0.1.0/NOTICE +39 -0
  6. kawallm-0.1.0/PKG-INFO +240 -0
  7. kawallm-0.1.0/README.md +200 -0
  8. kawallm-0.1.0/docs/usage.md +234 -0
  9. kawallm-0.1.0/pyproject.toml +67 -0
  10. kawallm-0.1.0/src/kawallm/__init__.py +26 -0
  11. kawallm-0.1.0/src/kawallm/__main__.py +44 -0
  12. kawallm-0.1.0/src/kawallm/core.py +280 -0
  13. kawallm-0.1.0/src/kawallm/data/__init__.py +0 -0
  14. kawallm-0.1.0/src/kawallm/data/wilayah_kemendagri.json +1 -0
  15. kawallm-0.1.0/src/kawallm/integrations/__init__.py +3 -0
  16. kawallm-0.1.0/src/kawallm/integrations/fastapi.py +116 -0
  17. kawallm-0.1.0/src/kawallm/integrations/litellm.py +221 -0
  18. kawallm-0.1.0/src/kawallm/integrations/presidio.py +93 -0
  19. kawallm-0.1.0/src/kawallm/pii/__init__.py +69 -0
  20. kawallm-0.1.0/src/kawallm/pii/bank.py +58 -0
  21. kawallm-0.1.0/src/kawallm/pii/base.py +67 -0
  22. kawallm-0.1.0/src/kawallm/pii/bpjs.py +32 -0
  23. kawallm-0.1.0/src/kawallm/pii/nik.py +84 -0
  24. kawallm-0.1.0/src/kawallm/pii/npwp.py +58 -0
  25. kawallm-0.1.0/src/kawallm/pii/phone.py +49 -0
  26. kawallm-0.1.0/src/kawallm/pii/plate.py +33 -0
  27. kawallm-0.1.0/src/kawallm/pii/wilayah.py +38 -0
  28. kawallm-0.1.0/src/kawallm/py.typed +0 -0
  29. kawallm-0.1.0/src/kawallm/safety/__init__.py +4 -0
  30. kawallm-0.1.0/src/kawallm/safety/incitement.py +60 -0
  31. kawallm-0.1.0/src/kawallm/safety/jailbreak.py +127 -0
  32. kawallm-0.1.0/src/kawallm/safety/normalize.py +49 -0
  33. kawallm-0.1.0/src/kawallm/safety/scanner.py +154 -0
  34. kawallm-0.1.0/src/kawallm/safety/words/judol_pinjol.json +495 -0
  35. kawallm-0.1.0/src/kawallm/safety/words/regional_batak.json +44 -0
  36. kawallm-0.1.0/src/kawallm/safety/words/regional_jawa.json +96 -0
  37. kawallm-0.1.0/src/kawallm/safety/words/regional_minang.json +41 -0
  38. kawallm-0.1.0/src/kawallm/safety/words/regional_sulawesi.json +35 -0
  39. kawallm-0.1.0/src/kawallm/safety/words/regional_sunda.json +53 -0
  40. kawallm-0.1.0/src/kawallm/safety/words/sara_id.json +133 -0
  41. kawallm-0.1.0/src/kawallm/safety/words/toxic_id.json +267 -0
  42. kawallm-0.1.0/src/kawallm/synthetic.py +59 -0
  43. kawallm-0.1.0/tests/test_api.py +81 -0
  44. kawallm-0.1.0/tests/test_core.py +172 -0
  45. kawallm-0.1.0/tests/test_integrations_presidio_fastapi.py +55 -0
  46. kawallm-0.1.0/tests/test_litellm_integration.py +147 -0
  47. kawallm-0.1.0/tests/test_nik.py +69 -0
  48. kawallm-0.1.0/tests/test_npwp.py +41 -0
  49. kawallm-0.1.0/tests/test_pii_others.py +87 -0
  50. kawallm-0.1.0/tests/test_safety.py +103 -0
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .coverage
8
+ coverage.xml
9
+ htmlcov/
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ # Local-only dictionaries (e.g. non-commercial imports) โ€” never commit
13
+ local_*.json
14
+
15
+ CLAUDE.md
16
+ PRD.md
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ Format mengikuti [Keep a Changelog](https://keepachangelog.com/); versi mengikuti [SemVer](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ### Changed
8
+ - Versi paket sekarang satu sumber (`src/kawallm/__init__.py`).
9
+ - Paket menyertakan `py.typed` (PEP 561).
10
+ - Workflow publish menjalankan test dan memastikan tag sama dengan versi sebelum rilis.
11
+
12
+ ## [0.1.0]
13
+
14
+ - Rilis awal: masking PII Indonesia (NIK, NPWP, HP, rekening, BPJS, plat, email), safety scanner (judol/pinjol, SARA, jailbreak), integrasi LiteLLM, Presidio, FastAPI.
@@ -0,0 +1,88 @@
1
+ # Panduan Kontribusi KawalLM
2
+
3
+ Terima kasih sudah mau berkontribusi! ๐Ÿ™ Panduan ini dalam Bahasa Indonesia; PR/issue dalam Bahasa Inggris juga diterima.
4
+
5
+ ## Aturan emas: jangan pernah pakai data pribadi asli
6
+
7
+ Semua test, issue, dan contoh **wajib** memakai data sintetis:
8
+
9
+ ```python
10
+ from kawallm import synthetic
11
+
12
+ synthetic.nik(seed=1) # NIK valid secara struktur, kode wilayah asli, orang fiktif
13
+ synthetic.npwp(seed=1) # NPWP dengan checksum valid
14
+ synthetic.phone(seed=1)
15
+ synthetic.bpjs_kesehatan(seed=1)
16
+ ```
17
+
18
+ PR yang berisi NIK/NPWP/no. HP milik orang sungguhan akan ditutup dan history-nya dibersihkan.
19
+
20
+ ## Setup
21
+
22
+ ```bash
23
+ git clone https://github.com/<you>/KawalLM && cd KawalLM
24
+ uv venv && uv pip install -e ".[dev,litellm,presidio]"
25
+ uv run pytest --cov
26
+ uvx ruff check . && uvx ruff format .
27
+ ```
28
+
29
+ ## 1. Menambah kamus (paling mudah โ€” `good first issue`)
30
+
31
+ File ada di `src/kawallm/safety/words/`. Format:
32
+
33
+ ```json
34
+ {
35
+ "category": "TOXIC_SLANG",
36
+ "language": "jv",
37
+ "description": "Umpatan Bahasa Jawa",
38
+ "default_weight": 1.0,
39
+ "contributors": ["github-username"],
40
+ "terms": [
41
+ {"term": "jancuk"},
42
+ {"term": "asem", "weight": 0.5},
43
+ {"term": "anjing", "prefix": true}
44
+ ]
45
+ }
46
+ ```
47
+
48
+ - **Kategori**: `TOXIC_SLANG`, `JUDOL_PINJOL`, `SARA_HATE_SPEECH`.
49
+ - **Bobot**: `1.0` bila istilah hampir selalu bermasalah. `0.5`/`0.3` bila punya arti netral (mis. *asu* = anjing, *asem* = buah, *zeus* = dewa Yunani). Kategori baru memblokir saat jumlah bobot โ‰ฅ 1.0.
50
+ - **`prefix: true`** agar juga cocok dengan bentuk berimbuhan (`anjingnya`). Gunakan hati-hati.
51
+ - Tidak perlu menulis varian leetspeak (`g4c0r`) atau spasi (`s l o t`) โ€” normalizer menanganinya.
52
+ - Bahasa daerah baru โ†’ buat file baru `regional_<bahasa>.json`; otomatis termuat.
53
+ - Tambahkan contoh positif & negatif ke `tests/test_safety.py`.
54
+
55
+ ## 2. Menambah / memperbaiki detektor PII
56
+
57
+ Detektor ada di `src/kawallm/pii/`. Prinsip:
58
+
59
+ 1. **Validasi, bukan regex mentah.** Nomor yang gagal validasi tidak boleh dimaskir (mencegah false positive resi/barcode).
60
+ 2. Bila format tidak punya checksum/struktur khas, **wajib keyword proximity** (lihat `bpjs.py`, `bank.py`).
61
+ 3. Kembalikan `PIIMatch` dan daftarkan di `DETECTORS` (`pii/__init__.py`) serta `PRIORITY` (`pii/base.py`).
62
+ 4. Sertakan sumber resmi format (peraturan, dokumentasi instansi) di docstring.
63
+
64
+ ## 3. Rule jailbreak / SARA
65
+
66
+ `safety/jailbreak.py` dan `safety/incitement.py`. Regex dijalankan pada teks yang sudah dinormalisasi (huruf kecil, tanpa tanda baca). Setiap rule baru wajib punya test **false positive** (kalimat wajar yang mirip tapi tidak boleh diblokir).
67
+
68
+ ## 4. Update kode wilayah Kemendagri
69
+
70
+ ```bash
71
+ git clone --depth 1 https://github.com/cahyadsn/wilayah /tmp/wilayah
72
+ python scripts/build_wilayah.py /tmp/wilayah/db
73
+ ```
74
+
75
+ ## Data pihak ketiga
76
+
77
+ Hanya data berlisensi kompatibel Apache-2.0 (MIT, BSD, Apache, CC0, CC-BY) yang boleh dibundel, dan wajib dicatat di `NOTICE`. Data non-komersial (CC BY-NC) **tidak boleh** masuk repo โ€” sediakan script import seperti `scripts/import_abusive_lexicon.py`.
78
+
79
+ ## Checklist PR
80
+
81
+ - [ ] Test hijau, coverage โ‰ฅ 90%
82
+ - [ ] Ruff bersih
83
+ - [ ] Data sintetis saja
84
+ - [ ] Benchmark tidak memburuk (bila menyentuh hot path)
85
+
86
+ ## Kode etik
87
+
88
+ Kamus berisi kata kasar dan ujaran kebencian **semata-mata untuk moderasi**. Diskusi di issue/PR tetap profesional dan saling menghormati.
kawallm-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
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 discussing and 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 grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and 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 Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
kawallm-0.1.0/NOTICE ADDED
@@ -0,0 +1,39 @@
1
+ KawalLM
2
+ Copyright 2026 KawalLM contributors
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+
6
+ This product bundles third-party data:
7
+
8
+ 1. src/kawallm/data/wilayah_kemendagri.json
9
+ Derived from "wilayah" by Cahya DSN โ€” https://github.com/cahyadsn/wilayah
10
+ Data source: Keputusan Menteri Dalam Negeri tentang Pemberian dan Pemutakhiran
11
+ Kode, Data Wilayah Administrasi Pemerintahan dan Pulau (2016โ€“2025 editions).
12
+ License: MIT License, Copyright (c) 2017-2025 Cahya DSN.
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27
+
28
+ 2. NPWP check-digit rule follows the algorithm documented in python-stdnum
29
+ (stdnum.id.npwp, LGPL-2.1+). Only the public algorithm is reimplemented;
30
+ no code is copied.
31
+
32
+ Optional, NOT bundled (fetched by scripts at the user's discretion):
33
+
34
+ - IndoSafety (Apache-2.0) โ€” https://github.com/falensiazmi/IndoSafety
35
+ Used by scripts/eval_indosafety.py as an external evaluation set.
36
+ - id-multi-label-hate-speech-and-abusive-language-detection by Okky Ibrohim
37
+ (CC BY-NC-SA 4.0) โ€” https://github.com/okkyibrohim/id-multi-label-hate-speech-and-abusive-language-detection
38
+ NON-COMMERCIAL licence: it is not redistributed here. scripts/import_abusive_lexicon.py
39
+ converts it into a local, user-side dictionary file that must not be committed.
kawallm-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,240 @@
1
+ Metadata-Version: 2.5
2
+ Name: kawallm
3
+ Version: 0.1.0
4
+ Summary: Low-latency guardrail engine for Indonesian PII (UU PDP) masking and content safety, drop-in for LiteLLM Proxy.
5
+ Project-URL: Homepage, https://github.com/susiloharjo/kawalLM
6
+ Project-URL: Issues, https://github.com/susiloharjo/kawalLM/issues
7
+ Author: KawalLM contributors
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: guardrail,indonesia,litellm,llm,nik,npwp,pii,presidio,uu-pdp
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Natural Language :: Indonesian
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Text Processing :: Linguistic
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: pyahocorasick>=2.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: fastapi>=0.100; extra == 'dev'
27
+ Requires-Dist: httpx>=0.27; extra == 'dev'
28
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
29
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
30
+ Requires-Dist: pytest>=8; extra == 'dev'
31
+ Requires-Dist: ruff>=0.6; extra == 'dev'
32
+ Provides-Extra: fastapi
33
+ Requires-Dist: fastapi>=0.100; extra == 'fastapi'
34
+ Provides-Extra: litellm
35
+ Requires-Dist: fastapi>=0.100; extra == 'litellm'
36
+ Requires-Dist: litellm>=1.60; extra == 'litellm'
37
+ Provides-Extra: presidio
38
+ Requires-Dist: presidio-analyzer>=2.2; extra == 'presidio'
39
+ Description-Content-Type: text/markdown
40
+
41
+ # KawalLM ๐Ÿ‡ฎ๐Ÿ‡ฉ
42
+
43
+ **Guardrail engine open-source, latensi rendah, untuk kepatuhan UU PDP (UU No. 27/2022) di infrastruktur AI Indonesia.**
44
+
45
+ KawalLM memaskir PII lokal (NIK, NPWP, No. HP, rekening bank, BPJS, plat nomor) dengan **validasi semantik deterministik**, dan memblokir promosi **judol/pinjol ilegal**, **ujaran kebencian SARA**, serta **prompt injection berbahasa Indonesia** โ€” tanpa GPU, tanpa network call, drop-in untuk **LiteLLM Proxy**, **Presidio**, dan **FastAPI**.
46
+
47
+ > โš ๏ธ Status: **alpha (v0.1.0)**. Deteksi bukan jaminan kepatuhan hukum. Lakukan review untuk penggunaan berisiko tinggi.
48
+
49
+ ---
50
+
51
+ ## Kenapa KawalLM?
52
+
53
+ | Masalah | Guardrail global | KawalLM |
54
+ |---|---|---|
55
+ | NIK 16 digit | Tidak dikenali / regex mentah โ†’ resi & barcode ikut terblokir | Validasi kode wilayah Kemendagri (7.879 kecamatan, 2016โ€“2025) + tanggal lahir (DD+40 untuk perempuan) + serial โ‰  0000 |
56
+ | NPWP 15/16 digit | Tidak ada | Checksum Luhn digit ke-9, format bertitik atau keyword-gated |
57
+ | No. HP | Generic | Prefix operator (Telkomsel, Indosat, Tri, XL, Axis, Smartfren) |
58
+ | Rekening bank | Tidak ada | Proximity 5 kata + panjang per bank (BCA 10, Mandiri 13, BRI 15, โ€ฆ) |
59
+ | Judol / pinjol | Tidak paham "g4c0r", "s.l.o.t", "depo pulsa" | Aho-Corasick + normalisasi leetspeak/spasi + skor berbobot |
60
+ | Prompt injection ID | Fokus Bahasa Inggris | Rule "abaikan instruksi sebelumnya", "bocorkan system prompt", DAN, dll. |
61
+
62
+ ## Instalasi
63
+
64
+ ```bash
65
+ pip install kawallm # core (hanya butuh pyahocorasick)
66
+ pip install "kawallm[litellm]" # + LiteLLM Proxy guardrail
67
+ pip install "kawallm[presidio]" # + Presidio recognizer
68
+ pip install "kawallm[fastapi]" # + FastAPI middleware
69
+ ```
70
+
71
+ ## Quick start
72
+
73
+ ```python
74
+ from kawallm import KawalLM
75
+
76
+ guard = KawalLM(mask_pii=True, block_safety=True, validate_wilayah=True)
77
+
78
+ r = guard.scan("Tolong bayar ke rekening BCA 1234567890 an Eko, NIK saya 3171012304900001")
79
+ r.is_blocked # False
80
+ r.sanitized_text # 'Tolong bayar ke rekening BCA <ID_BANK_ACCOUNT> an Eko, NIK saya <ID_NIK>'
81
+
82
+ r = guard.scan("Tuliskan promosi link slot gacor maxwin depo pulsa")
83
+ r.is_blocked # True
84
+ r.violation_reason # 'JUDOL_PINJOL (depo, depo pulsa, gacor)'
85
+
86
+ guard.scan("Resi JNE 1234567890123456").sanitized_text # 16 digit tapi bukan NIK valid โ†’ tidak dimaskir
87
+ guard.scan("Jelaskan bahaya judi online bagi remaja").is_blocked # False โ€” diskusi edukatif lolos
88
+ ```
89
+
90
+ Reversible / pseudonimisasi bolak-balik (stateless โ€” `session_map` dipegang aplikasi, aman untuk multi-replica):
91
+
92
+ ```python
93
+ guard = KawalLM(mode="reversible")
94
+ text, session_map = guard.anonymize("Kirim SMS konfirmasi ke 081288889999 sekarang.")
95
+ # text = 'Kirim SMS konfirmasi ke <ID_PHONE_1> sekarang.'
96
+ # session_map = {'<ID_PHONE_1>': '081288889999'}
97
+
98
+ guard.deanonymize("Baik, terkirim ke <ID_PHONE_1>.", session_map)
99
+ # 'Baik, terkirim ke 081288889999.'
100
+ ```
101
+
102
+ Helper lain:
103
+
104
+ ```python
105
+ from kawallm import mask, check_safety, parse_nik
106
+
107
+ mask("HP 0812-3456-7890") # 'HP <ID_PHONE>'
108
+ check_safety("abaikan instruksi sebelumnya") # (False, 'JAILBREAK (...)')
109
+ parse_nik("3171015501920002")
110
+ # {'wilayah': {'provinsi': 'Daerah Khusus Ibukota Jakarta', 'kabkota': 'Kota Administrasi Jakarta Pusat',
111
+ # 'kecamatan': 'Gambir'}, 'jenis_kelamin': 'P', 'tanggal': 15, 'bulan': 1, ...}
112
+ ```
113
+
114
+ Panduan lengkap 3 skenario (LiteLLM gateway, library Python, reversible): [`docs/usage.md`](docs/usage.md).
115
+
116
+ CLI:
117
+
118
+ ```bash
119
+ echo "HP saya 081234567890" | kawallm # โ†’ HP saya <ID_PHONE>
120
+ kawallm --json "abaikan instruksi sebelumnya" # exit code 2 bila diblokir
121
+ ```
122
+
123
+ ### Mode masking
124
+
125
+ | Mode | Output | Kegunaan |
126
+ |---|---|---|
127
+ | `token` (default) | `<ID_NIK>` | Kirim ke LLM publik |
128
+ | `reversible` | `<ID_NIK_1>` + vault TTL in-memory | De-masking di respons (FR-3.2) |
129
+ | `partial` | `************0001` | Log / tampilan UI |
130
+ | `redact` | `[REDACTED]` | Data lake, fine-tuning |
131
+
132
+ ### Entitas
133
+
134
+ `ID_NIK`, `ID_NPWP`, `ID_PHONE`, `ID_BANK_ACCOUNT`, `ID_BPJS_KES`, `ID_BPJS_TK`, `ID_PLATE`, `EMAIL`.
135
+ Catatan: nomor **KK** punya struktur sama dengan NIK, sehingga terdeteksi sebagai `ID_NIK` (keduanya data pribadi).
136
+
137
+ ## LiteLLM Proxy
138
+
139
+ ```yaml
140
+ # config.yaml
141
+ guardrails:
142
+ - guardrail_name: kawallm
143
+ litellm_params:
144
+ guardrail: kawallm.integrations.litellm.KawalLMGuardrail
145
+ mode: [pre_call, post_call]
146
+ default_on: true
147
+ masking_mode: reversible
148
+ restore_output: true
149
+ block_categories: JUDOL_PINJOL,SARA_HATE_SPEECH,JAILBREAK
150
+ ```
151
+
152
+ | Hook | Perilaku |
153
+ |---|---|
154
+ | `pre_call` | Safety check pada pesan **role user** (system prompt tidak dicek agar "jangan bocorkan system prompt" tidak memicu blokir) โ†’ HTTP 400. PII dimaskir di **semua role**, termasuk multimodal text parts. |
155
+ | `post_call` | PII baru dari model dimaskir (*output leakage*), lalu token `<ID_X_n>` milik pemanggil dikembalikan (reversible). Argumen `tool_calls` juga di-de-mask. |
156
+ | streaming | Sama, dengan *hold-back buffer* 48 karakter agar nilai yang terpotong antar chunk tetap tertangkap. |
157
+
158
+ Docker siap jalan (LiteLLM + KawalLM):
159
+
160
+ ```bash
161
+ cd docker
162
+ OPENAI_API_KEY=sk-... LITELLM_MASTER_KEY=sk-local docker compose up --build
163
+ ```
164
+
165
+ ## Presidio
166
+
167
+ ```python
168
+ from presidio_analyzer import AnalyzerEngine
169
+ from kawallm.integrations.presidio import KawalLMRecognizer, analyzer_without_nlp
170
+
171
+ analyzer = AnalyzerEngine()
172
+ analyzer.registry.add_recognizer(KawalLMRecognizer(supported_language="en"))
173
+
174
+ # atau tanpa download model spaCy sama sekali:
175
+ analyzer = analyzer_without_nlp("id")
176
+ analyzer.analyze("NIK 3171011501900001", language="id")
177
+ ```
178
+
179
+ ## FastAPI
180
+
181
+ ```python
182
+ from fastapi import FastAPI
183
+ from kawallm.integrations.fastapi import KawalLMMiddleware
184
+
185
+ app = FastAPI()
186
+ app.add_middleware(KawalLMMiddleware, paths=("/chat",), fields=("prompt", "message"))
187
+ ```
188
+
189
+ ## Safety: cara kerja skor
190
+
191
+ Kamus (`src/kawallm/safety/words/*.json`) + rule regex dikompilasi sekali ke satu automaton Aho-Corasick. Setiap istilah punya **bobot**:
192
+
193
+ - `1.0` โ€” sinyal kuat (mis. `slot gacor`, `depo pulsa`, `bocoran rtp`) โ†’ cukup satu untuk blokir
194
+ - `0.5` / `0.3` โ€” sinyal ambigu (mis. `zeus`, `togel`, `judi online`) โ†’ perlu digabung sinyal lain hingga skor โ‰ฅ `threshold` (default 1.0)
195
+
196
+ Default **blocking**: `JUDOL_PINJOL`, `SARA_HATE_SPEECH`, `JAILBREAK`. `TOXIC_SLANG` hanya di-*flag* (bisa dijadikan blocking via `block_categories`).
197
+
198
+ ## Benchmark
199
+
200
+ `python benchmarks/bench_latency.py` โ€” safety scan + PII mask per payload, 1 core, Intel Xeon @ 2.1 GHz, Python 3.13, payload sintetis (~1 PII per 50 kata):
201
+
202
+ | Kata / payload | p50 | p95 | p99 | Throughput / core | Peak RSS |
203
+ |---:|---:|---:|---:|---:|---:|
204
+ | 100 | 0.30 ms | 0.47 ms | 0.56 ms | ~2.970 req/s | 21 MB |
205
+ | 500 | 1.22 ms | 1.45 ms | 2.16 ms | ~780 req/s | 21 MB |
206
+ | 1.000 | 2.36 ms | 2.83 ms | 5.3 ms | ~400 req/s | 21 MB |
207
+
208
+ **vs NFR PRD:** p95 โ‰ค 5 ms @1.000 kata โœ… ยท RAM < 120 MB โœ… ยท zero telemetry โœ… ยท coverage โ‰ฅ 90% โœ… (97%).
209
+ Throughput โ‰ฅ 1.500 req/s pada 2 vCPU **tercapai untuk prompt pendek (โ‰ค ~200 kata)**, tidak untuk payload 1.000 kata (~800 req/s di 2 core). Dua target ini secara matematis tidak bisa sama-sama terpenuhi: p95 5 ms per request = maks ~200 req/s per core.
210
+
211
+ ## Keterbatasan (jujur)
212
+
213
+ - **Bukan classifier.** Dictionary + rule menangkap promosi spam, slur, dan pola injection yang eksplisit. Pada dataset [IndoSafety](https://github.com/falensiazmi/IndoSafety) (3.014 *pertanyaan berbahaya* โ€” kategori yang berbeda), hanya 0,3% diblokir. Pertanyaan berbahaya semantik butuh model (Sprint 4: ONNX classifier). Jalankan sendiri: `python scripts/eval_indosafety.py`.
214
+ - **Kamus bahasa daerah masih seed** dan perlu verifikasi penutur asli โ€” ini area kontribusi utama.
215
+ - Validasi NIK/NPWP memeriksa **format**, bukan keberadaan orangnya.
216
+ - Vault reversible bersifat in-memory per proses; untuk multi-replica gunakan sticky session.
217
+ - Argumen `tool_calls` di request tidak di-scan.
218
+
219
+ ## Sumber data & atribusi
220
+
221
+ | Data | Sumber | Lisensi | Status |
222
+ |---|---|---|---|
223
+ | Kode wilayah Kemendagri 2016โ€“2025 | [cahyadsn/wilayah](https://github.com/cahyadsn/wilayah) | MIT | **Dibundel** (`src/kawallm/data/`) |
224
+ | Algoritma checksum NPWP | python-stdnum (`stdnum.id.npwp`) | LGPL โ€” hanya algoritma, tanpa kode | Diimplementasi ulang |
225
+ | IndoSafety (eval) | [falensiazmi/IndoSafety](https://github.com/falensiazmi/IndoSafety) | Apache-2.0 | Script eval, tidak dibundel |
226
+ | Abusive lexicon (Ibrohim & Budi 2019) | [okkyibrohim/โ€ฆ](https://github.com/okkyibrohim/id-multi-label-hate-speech-and-abusive-language-detection) | CC BY-NC-SA 4.0 | **Tidak dibundel** (non-komersial). `scripts/import_abusive_lexicon.py` untuk pemakaian lokal |
227
+
228
+ Lihat [`NOTICE`](NOTICE).
229
+
230
+ ## Proyek terkait
231
+
232
+ [IndoPII Mini](https://huggingface.co/AIbnuHibban/indopii-mini) (NER model PII Indonesia), [NusaIndex](https://pkg.go.dev/github.com/haikalmumtaz233/nusaindex) (validator Go/TS), [SEALGuard](https://github.com/awsm-research/SEALGuard) (guardrail LLM Asia Tenggara). KawalLM fokus pada lapisan deterministik CPU-only yang bisa digabung dengan model-model tersebut.
233
+
234
+ ## Kontribusi
235
+
236
+ Lihat [CONTRIBUTING.md](CONTRIBUTING.md). Kontribusi paling dibutuhkan: kamus bahasa daerah, panjang rekening bank, identitas baru (NIP, NISN, paspor, SIM).
237
+
238
+ ## Lisensi
239
+
240
+ Apache License 2.0 โ€” lihat [LICENSE](LICENSE).