privacy-gateway-testgen 0.4.1__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 (85) hide show
  1. privacy_gateway_testgen-0.4.1/LICENSE +21 -0
  2. privacy_gateway_testgen-0.4.1/PKG-INFO +623 -0
  3. privacy_gateway_testgen-0.4.1/README.md +601 -0
  4. privacy_gateway_testgen-0.4.1/pyproject.toml +47 -0
  5. privacy_gateway_testgen-0.4.1/setup.cfg +4 -0
  6. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/__init__.py +3 -0
  7. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/__main__.py +4 -0
  8. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/annotations.py +91 -0
  9. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/assets/fonts/OFL.txt +93 -0
  10. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/assets/fonts/README.md +19 -0
  11. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/assets/fonts/Sarabun-Bold.ttf +0 -0
  12. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/assets/fonts/Sarabun-Regular.ttf +0 -0
  13. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/builder.py +43 -0
  14. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/cli.py +280 -0
  15. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/config.py +110 -0
  16. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/configs/default.json +42 -0
  17. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/configs/policy.default.json +45 -0
  18. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/configs/v2/default.json +100 -0
  19. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/configs/v2/profiles.json +159 -0
  20. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/__init__.py +58 -0
  21. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/common.py +231 -0
  22. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/infra.py +245 -0
  23. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/lookalike.py +134 -0
  24. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/payment.py +68 -0
  25. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/pii.py +122 -0
  26. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/entities/secrets.py +116 -0
  27. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/evaluation.py +271 -0
  28. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/generator.py +417 -0
  29. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/language.py +18 -0
  30. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/models.py +92 -0
  31. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/policies.py +108 -0
  32. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/templates.py +964 -0
  33. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/textsim.py +74 -0
  34. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/__init__.py +1 -0
  35. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/archetypes.py +1517 -0
  36. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/cli.py +223 -0
  37. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/config.py +172 -0
  38. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/docmodel.py +219 -0
  39. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/evaluate.py +696 -0
  40. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/extract.py +623 -0
  41. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/generate.py +1877 -0
  42. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/localization.py +789 -0
  43. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/org.py +138 -0
  44. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/realism.py +668 -0
  45. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/__init__.py +32 -0
  46. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/base.py +77 -0
  47. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/fonts.py +55 -0
  48. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/images.py +491 -0
  49. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/ooxml.py +661 -0
  50. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/pdf.py +370 -0
  51. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/textfmt.py +453 -0
  52. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/renderers/textlayout.py +127 -0
  53. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/scenario.py +388 -0
  54. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/validation.py +443 -0
  55. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/v2/verify.py +101 -0
  56. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen/validation.py +239 -0
  57. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen.egg-info/PKG-INFO +623 -0
  58. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen.egg-info/SOURCES.txt +83 -0
  59. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen.egg-info/dependency_links.txt +1 -0
  60. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen.egg-info/entry_points.txt +2 -0
  61. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen.egg-info/requires.txt +8 -0
  62. privacy_gateway_testgen-0.4.1/src/privacy_gateway_testgen.egg-info/top_level.txt +1 -0
  63. privacy_gateway_testgen-0.4.1/tests/test_annotations.py +62 -0
  64. privacy_gateway_testgen-0.4.1/tests/test_builder.py +46 -0
  65. privacy_gateway_testgen-0.4.1/tests/test_cli.py +108 -0
  66. privacy_gateway_testgen-0.4.1/tests/test_entities.py +100 -0
  67. privacy_gateway_testgen-0.4.1/tests/test_evaluation.py +53 -0
  68. privacy_gateway_testgen-0.4.1/tests/test_generator.py +134 -0
  69. privacy_gateway_testgen-0.4.1/tests/test_packaging.py +48 -0
  70. privacy_gateway_testgen-0.4.1/tests/test_policies.py +76 -0
  71. privacy_gateway_testgen-0.4.1/tests/test_schema.py +36 -0
  72. privacy_gateway_testgen-0.4.1/tests/test_security.py +98 -0
  73. privacy_gateway_testgen-0.4.1/tests/test_templates.py +79 -0
  74. privacy_gateway_testgen-0.4.1/tests/test_v2_cli.py +59 -0
  75. privacy_gateway_testgen-0.4.1/tests/test_v2_consistency.py +151 -0
  76. privacy_gateway_testgen-0.4.1/tests/test_v2_correctness.py +559 -0
  77. privacy_gateway_testgen-0.4.1/tests/test_v2_disclosure.py +134 -0
  78. privacy_gateway_testgen-0.4.1/tests/test_v2_generation.py +174 -0
  79. privacy_gateway_testgen-0.4.1/tests/test_v2_language.py +162 -0
  80. privacy_gateway_testgen-0.4.1/tests/test_v2_realism.py +125 -0
  81. privacy_gateway_testgen-0.4.1/tests/test_v2_renderers.py +107 -0
  82. privacy_gateway_testgen-0.4.1/tests/test_v2_schema.py +61 -0
  83. privacy_gateway_testgen-0.4.1/tests/test_v2_security.py +100 -0
  84. privacy_gateway_testgen-0.4.1/tests/test_v2_thai_rendering.py +455 -0
  85. privacy_gateway_testgen-0.4.1/tests/test_validation.py +74 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Privacy Gateway Testgen contributors
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,623 @@
1
+ Metadata-Version: 2.4
2
+ Name: privacy-gateway-testgen
3
+ Version: 0.4.1
4
+ Summary: Deterministic synthetic prompts, real attachment files and file-aware ground truth for privacy-aware data gateways
5
+ Author: Privacy Gateway Testgen contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/GuyThanakornKhuntamanee/privacy-gateway-testgen
8
+ Project-URL: Repository, https://github.com/GuyThanakornKhuntamanee/privacy-gateway-testgen.git
9
+ Project-URL: Issues, https://github.com/GuyThanakornKhuntamanee/privacy-gateway-testgen/issues
10
+ Keywords: privacy,synthetic-data,pii,dlp,testing,dataset
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Security
13
+ Classifier: Topic :: Software Development :: Testing
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: Pillow<14,>=10.0
18
+ Requires-Dist: reportlab<5,>=4.0; python_version < "3.10"
19
+ Requires-Dist: reportlab<6,>=4.0; python_version >= "3.10"
20
+ Requires-Dist: pypdf<8,>=4.0
21
+ Dynamic: license-file
22
+
23
+ # privacy-gateway-testgen
24
+
25
+ Deterministic synthetic test prompts and **exact ground-truth** datasets for
26
+ privacy-aware data gateways, PII detection, DLP, privacy filters, masking /
27
+ tokenization / redaction, and AI sovereignty routing.
28
+
29
+ This is an Agent Skill plus a Python package. It generates
30
+ short, medium and long prompts in Thai, English and mixed language across four
31
+ domains — PII, payment data, secrets/credentials, and infrastructure — with
32
+ multi-domain, contextual, adversarial and negative cases. Every sensitive value
33
+ is synthetic, every span is recorded during prompt construction, and every run
34
+ is reproducible from a seed.
35
+
36
+ > All examples are synthetic. Do not put real customer data, live credentials
37
+ > or production infrastructure into this tool.
38
+
39
+ ## Why span-first generation
40
+
41
+ Most synthetic test generators write a prompt first and then ask a model (or a
42
+ regex) where the sensitive values are. Offsets drift, Thai text breaks, and the
43
+ "ground truth" quietly becomes a guess. This project inverts the order:
44
+
45
+ 1. Generate a synthetic entity value.
46
+ 2. Append it to the prompt through a builder that records its exact character
47
+ span.
48
+ 3. Validate that `prompt[start:end] == exact_entity_value` for every case.
49
+
50
+ The result is a dataset whose annotations are correct by construction. Imported
51
+ or LLM-authored prompts go through a separate `verify` stage and stay marked
52
+ `unverified` until a human checks the semantics.
53
+
54
+ ## Quick start
55
+
56
+ Requires Python 3.9+. Three runtime packages (`Pillow`, `reportlab`, `pypdf`)
57
+ render Thai PDF/image attachments and verify them; there is no network access and
58
+ no paid API at generation time.
59
+
60
+ ```bash
61
+ python -m pip install privacy-gateway-testgen
62
+
63
+ privacy-gateway-testgen generate --out datasets/sample
64
+ privacy-gateway-testgen validate --input datasets/sample/all.jsonl
65
+ privacy-gateway-testgen evaluate --out reports --dataset-out datasets/sample
66
+ ```
67
+
68
+ The default configs ship inside the package, so `--config` is optional. From a
69
+ source checkout instead:
70
+
71
+ ```bash
72
+ python -m pip install -e .
73
+ privacy-gateway-testgen generate --config configs/default.json --out datasets/sample
74
+ ```
75
+
76
+ Windows PowerShell (running from source):
77
+
78
+ ```powershell
79
+ $env:PYTHONPATH = "src"
80
+ python -m privacy_gateway_testgen generate --config configs/default.json --out datasets/sample
81
+ ```
82
+
83
+ ## v2: requests with real attachments
84
+
85
+ Schema `2.1` adds real files, per-attachment language, a case-level scenario
86
+ plan, cross-file consistency checks, structure-aware prompts and a realism
87
+ engine. The v1 command surface remains supported and the v1 sample is still
88
+ generated by the same command; v2 has its own commands:
89
+
90
+ Schema `2.0` remains readable: `validate-v2` accepts 2.0 cases and skips the
91
+ 2.1-only fields, and `datasets/compat/v2.0-sample/` is an immutable one-case
92
+ regression fixture checked by `tests/test_v2_correctness.py`.
93
+
94
+ ```bash
95
+ PYTHONPATH=src python -m privacy_gateway_testgen generate-v2 \
96
+ --config configs/v2/default.json --profile benchmark-balanced \
97
+ --out datasets/v2-sample
98
+
99
+ PYTHONPATH=src python -m privacy_gateway_testgen validate-v2 \
100
+ --dataset datasets/v2-sample --json
101
+
102
+ PYTHONPATH=src python -m privacy_gateway_testgen verify-v2 --dataset datasets/v2-sample
103
+
104
+ PYTHONPATH=src python -m privacy_gateway_testgen report-v2 \
105
+ --dataset datasets/v2-sample --out reports/v2 --check-reproducible
106
+ ```
107
+
108
+ The checked-in sample uses the `benchmark-balanced` profile so it carries one
109
+ verified example of each major category: text, structured text, Office document,
110
+ spreadsheet, PDF, image, developer/config file and log.
111
+
112
+ `generate-v2` supports `--count`, `--seed`, `--profile`, `--file-types`,
113
+ `--domains`, `--files-only` and `--policy`. Profiles are
114
+ `benchmark-balanced`, `real-world-enterprise`, `thai-enterprise`,
115
+ `developer-security`, `office-documents`, `ocr` and `negative-hard`. A JSON file
116
+ path can also be passed to `--profile` for a custom profile.
117
+
118
+ ### What a v2 case contains
119
+
120
+ A realistic prompt, zero to three attachments, per-entity provenance, policy
121
+ expectations, a shared scenario plan, consistency checks and verification
122
+ evidence:
123
+
124
+ ```json
125
+ {
126
+ "schema_version": "2.1",
127
+ "test_id": "pgt2-example-00001",
128
+ "persona": "developer",
129
+ "intent": "inspect_config",
130
+ "prompt": "นี้ config ล่าสุด ช่วยดูให้ทีว่าทำไม prod ต่อ db ไม่ได้",
131
+ "prompt_language": "th",
132
+ "scenario_id": "SCN-00001",
133
+ "attachments": [{
134
+ "attachment_id": "ATT-001",
135
+ "filename": "prod.env",
136
+ "extension": "env",
137
+ "mime_type": "text/plain",
138
+ "archetype": "application_environment_config",
139
+ "expected_extraction_method": "direct_text",
140
+ "language": "th",
141
+ "language_mix": "Thai business prose with English technical terms",
142
+ "language_capability": ["th", "en", "mixed"],
143
+ "synthetic": true,
144
+ "verification": {"status": "verified"}
145
+ }],
146
+ "domains": ["secrets", "infrastructure"],
147
+ "entities": [{
148
+ "annotation_id": "ENT-00001",
149
+ "source": "attachment",
150
+ "source_attachment": "ATT-001",
151
+ "entity_type": "password",
152
+ "exact_entity_value": "Example-Fake-Passw0rd-4821!",
153
+ "detection_expected": true,
154
+ "location": {"kind": "key_path", "key": "DB_PASSWORD", "line": 5}
155
+ }],
156
+ "cross_file_links": [],
157
+ "structure_references": [],
158
+ "consistency_checks": [{"check": "cross_file_identifiers", "status": "not_applicable", "passed": false, "evaluated_items": 0}]
159
+ }
160
+ ```
161
+
162
+ The actual v2 schema uses lower-case domain names (`secrets`,
163
+ `infrastructure`) and the exact field set in
164
+ [`schemas/testcase.v2.schema.json`](schemas/testcase.v2.schema.json). The object
165
+ above is an illustrative excerpt, not a byte-for-byte sample case; read
166
+ `datasets/v2-sample/cases.jsonl` for real cases.
167
+
168
+ ### Supported files
169
+
170
+ Real, parseable files are emitted for: `txt`, `csv`, `json`, `yaml`, `yml`,
171
+ `xml`, `log`, `md`, `env`, `ini`, `conf`, `toml`, `sql`, `tf`, `py`, `js`, `ts`,
172
+ `java`, `go`, `docx`, `xlsx`, `pptx`, `pdf`, `png`, `jpg` and `jpeg`.
173
+
174
+ - DOCX/XLSX/PPTX are macro-free OOXML ZIP packages.
175
+ - PDF supports native Thai/English text with an embedded Sarabun font and a
176
+ ToUnicode map, multi-page tables, scanned image-only pages and hybrid pages
177
+ (native prose plus an embedded screenshot region).
178
+ - Images are synthetic screenshots/scans with configurable OCR difficulty and a
179
+ real Thai-capable font (Pillow + FreeType + libraqm shaping).
180
+ - Spreadsheets support multiple sheets, hidden sheets, Thai/English headers and
181
+ empty/mixed-type cells.
182
+ - Ground truth uses `xlsx_cell`, `docx_paragraph`, `docx_table_cell`,
183
+ `pptx_shape`, `pdf_text`, `pdf_image`, `image_ocr`, `json_path`, `yaml_path`,
184
+ `xml_path`, `key_path`, `csv_cell` and `text_span`.
185
+
186
+ The document archetype library has 69 entries across HR, finance, sales/CRM,
187
+ healthcare, IT/engineering, management and operations. One archetype can render
188
+ as several formats; an invoice can be PDF, DOCX or XLSX without changing the
189
+ business content. The tested format/language matrix is in
190
+ [`docs/capability-matrix.md`](docs/capability-matrix.md).
191
+
192
+ ### Language system (schema 2.1)
193
+
194
+ - **Central localization layer** (`v2/localization.py`) for titles, headings,
195
+ table headers, sheet names, status values, notes, footers and formatting.
196
+ - **Per-attachment language**: a Thai DOCX can sit next to an English XLSX in
197
+ one case. `prompt_language`, `content_languages`, `language_mode`,
198
+ `language_coverage` and per-attachment `language` / `language_mix` record it.
199
+ - **True mixed documents**: bilingual headers such as `ชื่อ / name`, Thai prose
200
+ with English technical terms, and English machine keys with Thai comments.
201
+ - **Measured language labels**: `language_check` records Thai/Latin/neutral
202
+ character counts and shares over authored (static) text. Numbers and symbols
203
+ are neutral, so a digit-heavy log is still an English log. Defaults live in
204
+ `language_thresholds`: `th` needs Thai share >= 0.30, `en` needs Latin share
205
+ >= 0.80, `mixed` needs both >= 0.10. A document that does not match its
206
+ requested language is relabelled from its measurement (`language_routing:
207
+ relabelled_from_*`) or rejected, never silently accepted.
208
+ - **Thai formatting**: Buddhist-era or Gregorian dates (`thai_date_mode`),
209
+ THB currency (`currency_mode`) and Thai labels. English documents stay
210
+ English.
211
+ - **PDF and images carry Thai, English and mixed content.** The PDF writer embeds
212
+ the bundled Sarabun TrueType font with a ToUnicode map, so Thai text is real
213
+ PDF text and extracts back exactly; raster renderers use Pillow with libraqm
214
+ shaping, so combining marks are placed correctly. `language_capability` for
215
+ `pdf`, `png`, `jpg` and `jpeg` is `["th", "en", "mixed"]`. Only `log` stays
216
+ English-only (`log_english_only`), and the routing mechanism is kept for any
217
+ future renderer with a narrower capability.
218
+ - **Script-aware wrapping.** Thai clusters (base + combining marks) and entity
219
+ values are never split across lines; the image canvas widens instead, and PDF
220
+ lines keep entities atomic.
221
+
222
+ Prompt/attachment language combinations are measured in
223
+ `reports/v2/evaluation.json` under `language_matrix` (for example
224
+ `th->mixed`), not assumed.
225
+
226
+ ### Scenario plan and cross-file consistency
227
+
228
+ Every case builds one `ScenarioPlan` before its attachments: organisation,
229
+ people, customers, hosts, database endpoint, internal URL, incident/request/
230
+ ticket/invoice IDs, transaction references, dates and amounts. Builders draw
231
+ shared values from it, so `app.log`, `prod.env` and `incident_report.docx` tell
232
+ the same story.
233
+
234
+ The case records:
235
+
236
+ - `cross_file_links`: shared entities that occur in two or more attachments,
237
+ with one canonical value and the recorded representation variants (a Thai
238
+ name and its Latin rendition are the same identity);
239
+ - `bundle`: `single_file`, `multi_file`, `same_archetype`, `old_new` or
240
+ `prompt_only`, with members, a `relationship` block (`related` with evidence,
241
+ or `intentionally_unrelated` for explicit negative/ambiguous cases) and
242
+ revision changes;
243
+ - `consistency_checks`: each check carries `status` (`passed`, `failed`,
244
+ `not_applicable`, `not_evaluated`) and `evaluated_items`. Invoice arithmetic
245
+ and due date, payroll gross - tax = net, statement running balance, real log
246
+ timestamp ordering, linked amount/currency/transaction-reference agreement,
247
+ structure reference resolution and cross-file identifiers are included. A
248
+ vacuous check is `not_applicable`, never `passed`;
249
+ - `structure_references`: prompts such as "ดู tab employee" or "หน้า 3" point at
250
+ a sheet/page/section that a reader can actually see. Rows and columns are only
251
+ cited for tabular files, never for a flattened screenshot;
252
+ - `document_profile`: per-file structure (sections, tables, rows, sheets,
253
+ slides, pages).
254
+
255
+ Invoices and their transaction exports draw subtotal, tax, total, transaction
256
+ reference, currency and payment schedule from the same `ScenarioPlan`. A single
257
+ payment means invoice total == transaction amount; installment plans would be
258
+ represented explicitly instead of by accident. Image ground truth keeps each
259
+ entity atomic on one line (`entity_strategy: atomic_line`); the canvas widens
260
+ rather than break a value, and the verifier rejects any fragment annotation.
261
+ Old/new revisions change a real value (status, due date, amount, phone, time or
262
+ endpoint) and record before/after values with a location in both documents.
263
+
264
+ ### v2 dataset layout
265
+
266
+ ```
267
+ datasets/v2-sample/
268
+ ├── manifest.json
269
+ ├── NOTICE.md
270
+ ├── cases.jsonl
271
+ ├── all.json
272
+ ├── stats.json
273
+ ├── benchmark_safe_cases.jsonl
274
+ ├── benchmark_safe_text_cases.jsonl
275
+ ├── benchmark_safe_ocr_cases.jsonl
276
+ ├── benchmark_excluded_cases.jsonl
277
+ ├── train.jsonl validation.jsonl test.jsonl
278
+ ├── ground_truth/entities.jsonl
279
+ └── attachments/TC-.../file.ext
280
+ ```
281
+
282
+ `manifest.json` records schema/generator versions, fixed dataset epoch, seed,
283
+ profile, file/domain/language/persona/difficulty distributions, verification
284
+ status, config/policy hashes and SHA-256 for every generated artifact and
285
+ attachment. There is no wall-clock timestamp, so the same config + seed
286
+ reproduces the case JSON and attachment bytes.
287
+
288
+ `NOTICE.md` is the out-of-band synthetic statement. By default
289
+ (`disclosure: metadata`) generated files contain **no** "synthetic" or
290
+ "fictional" text: a detector under test must not read a hint that could suppress
291
+ a detection. `disclosure: banner` restores visible notices in documents and
292
+ images for artifacts shared with people; the setting is recorded in the manifest.
293
+
294
+ ### v2 measured sample
295
+
296
+ The committed `datasets/v2-sample` uses the `benchmark-balanced` profile at seed
297
+ 21: 72 cases, 76 attachment files, 17 file types and 3 attachment languages.
298
+ `reports/v2/evaluation.json` records measured values: schema validity 1.0,
299
+ prompt span accuracy 1.0, file open rate 1.0, extraction accuracy 1.0, entity
300
+ location accuracy 1.0, exact/near/document duplicate rate 0.0, negative share
301
+ 0.2222, multi-domain share 0.1806 and attachment share 0.8056. Of 72 cases, 62
302
+ are fully verified and 10 are `verified_partial` (image/scanned cases whose
303
+ annotations are render-layout verified, not OCR-verified).
304
+
305
+ Language is measured, not assumed: prompt languages are Thai 23, English 34,
306
+ mixed 15; attachment languages are Thai 35, English 34, mixed 7; 11 distinct
307
+ prompt/attachment language pairs appear. Mean Thai script share is 0.7538 for
308
+ Thai prompts, 0.5527 for mixed prompts and 0.0139 for English prompts, with 0
309
+ attachments below their declared threshold and 0 residual English labels in
310
+ Thai documents. 26 cases carry a structure reference (all 27 references
311
+ resolve), 14 cases have cross-file links (62 links), 15 cases are multi-file
312
+ and 9 contain a same-archetype pair. 14 cases are prompt-only.
313
+
314
+ Consistency reporting is structured: of 351 checks in the sample, 73 are
315
+ `passed`, 278 are `not_applicable` (for example a structure-resolution check in
316
+ a case whose prompt cites no structure) and 0 are `failed` or `not_evaluated`.
317
+ `not_applicable` is never counted as a pass.
318
+
319
+ `datasets/v2-thai-sample` is a focused 16-case sample from the
320
+ `thai-rendering` profile (21 files: Thai native, scanned and hybrid PDFs; Thai
321
+ PNG/JPG/JPEG screenshots; mixed Thai-English images; cross-file Thai cases). It
322
+ exists so the Thai rendering path can be inspected without reading tests.
323
+
324
+ ### Benchmark readiness and safe subset
325
+
326
+ `report-v2` computes `benchmark_ready` from dataset-level evidence, not from
327
+ unit tests: verified ground truth, no failed or unevaluated consistency check,
328
+ no known high correctness issue, valid timeline and entity ground truth,
329
+ measured language metadata, no replacement glyphs, render-verified Thai
330
+ PDF/image attachments, safety checks, no schema errors and a reproducibility
331
+ check. It also writes `benchmark_safe_cases.jsonl`,
332
+ `benchmark_safe_text_cases.jsonl`, `benchmark_safe_ocr_cases.jsonl` and
333
+ `benchmark_excluded_cases.jsonl` into the dataset; excluded cases list their
334
+ reasons.
335
+
336
+ The split is by modality, not by quality: a raster case whose layout and
337
+ canonical text are verified is a trustworthy testcase — the gateway under test
338
+ performs the OCR — but it does not belong in the same subset as a
339
+ text-extraction case. The committed sample reports `benchmark_ready: true` with
340
+ 72 safe cases: 66 `direct_text_extraction` and 6 `ocr_required`, 0 excluded.
341
+
342
+ `benchmark_ready` is only `true` when the report was generated with
343
+ `--check-reproducible`, so the reproducibility claim is measured rather than
344
+ assumed.
345
+
346
+ ### v2 limitations
347
+
348
+ These are deliberate and documented rather than hidden:
349
+
350
+ - Native PDF text is embedded Sarabun TrueType with a ToUnicode map, so Thai and
351
+ mixed text extracts back exactly. Byte-identical PDF bytes are guaranteed for
352
+ one pinned ReportLab version on one platform; across versions only the content
353
+ (text, spans, boxes, case JSON) is reproducible.
354
+ - Raster assets (PNG/JPEG, scanned PDF pages and hybrid PDF image regions) are
355
+ verified at layout level. No OCR engine runs in the test suite, so OCR
356
+ accuracy is not claimed; canonical pre-render text stays the ground truth and
357
+ these cases are marked `verified_partial` at case level.
358
+ - Raster degradation (noise, blur, small rotation, brightness gradient) changes
359
+ pixels. Bounding boxes are transformed to the final image
360
+ (`bbox_space: final`), so a box can cover slightly more area than the ink.
361
+ - PPTX speaker notes and native PowerPoint tables are not emitted yet. No XLSX
362
+ formulas are emitted; cells contain values, and multi-sheet workbooks can mark
363
+ a sheet hidden.
364
+ - YAML/TOML/INI/ENV verification uses the generator's strict subset parser.
365
+ - Archives, password-protected files, audio, video and executables are out of
366
+ scope.
367
+ - `report-v2` reports what it measured; a `verified_partial` case must not be
368
+ treated as OCR accuracy evidence, and it belongs to the OCR-required subset
369
+ rather than the text subset.
370
+ - Cross-file consistency is checked against generated annotations and the
371
+ scenario plan; no downstream gateway is executed.
372
+ - `verification.json` records only the dataset folder name (no absolute path), so
373
+ committed reports carry no machine-specific path. Byte identity still holds
374
+ only for one pinned dependency set on one platform; across machines the
375
+ case JSON, spans and report numbers are the comparable artifacts.
376
+ - Synthetic phone numbers, national-ID-shaped values and bank account numbers
377
+ are shape/checksum valid so detectors can be tested against realistic input.
378
+ A random value can resemble a real identifier; treat published datasets as
379
+ test fixtures, not as collision-free PII. See
380
+ [`SECURITY.md`](SECURITY.md#collision-risk-of-synthetic-identifiers).
381
+
382
+ ## What it produces
383
+
384
+ | Domain | Example entity types |
385
+ |---|---|
386
+ | PII | Thai national ID (checksum-valid), Thai name, phone, email, address, postal code, date of birth, personal IP, GPS, vehicle registration, bank account, health data, patient ID, passport |
387
+ | Payment | Test-BIN card numbers (Luhn-valid), expiry, CVV, cardholder name, bank account, transaction reference, authorization code, payment token, gateway credential |
388
+ | Secrets | API keys, access/refresh tokens, OAuth secrets, JWTs, passwords, DB credentials, connection strings, SSH/TLS keys, cloud keys, service-account credentials, webhook secrets, encryption keys, env/config secrets |
389
+ | Infrastructure | Internal IPv4/IPv6, private networks, hostnames, DNS, URLs, topology, endpoints, firewall rules, routing, Kubernetes, Docker, cloud resource IDs, DB endpoints, Terraform, deployment configs, logs, inventories, blueprints, metadata |
390
+
391
+ Prompt coverage:
392
+
393
+ - **Short** — one-line requests such as checking a customer ID, sending an API
394
+ key to an external model, or summarizing a card payment.
395
+ - **Medium** — support emails, payment verification, debugging, sysadmin
396
+ questions, document summaries, tables and JSON payloads.
397
+ - **Long** — enterprise reports, chat transcripts, meeting notes, architecture
398
+ documents, log exports, SQL dumps and Kubernetes manifests.
399
+ - **Contextual** — values inside quoted text, signatures, code fences, logs,
400
+ JSON/YAML, tables and multi-step instructions.
401
+ - **Mixed-domain** — PII + payment, secrets + infrastructure, three domains, and
402
+ all four domains in one prompt.
403
+ - **Negative / ambiguous** — ordinary business IDs, invalid checksums, Luhn
404
+ failures, placeholders, public IPs and documentation ranges, annotated as
405
+ lookalikes so false positives can be measured.
406
+
407
+ Every case is classified by domain, entity type, language, prompt length,
408
+ prompt style, structure, context complexity, detection mode, difficulty (1–5),
409
+ polarity, single/multi-domain, edge-case and adversarial flags.
410
+
411
+ ## Dataset format
412
+
413
+ `generate` writes:
414
+
415
+ ```
416
+ datasets/sample/
417
+ ├── all.jsonl
418
+ ├── train.jsonl
419
+ ├── validation.jsonl
420
+ ├── test.jsonl
421
+ ├── all.json
422
+ ├── stats.json
423
+ └── manifest.json
424
+ ```
425
+
426
+ Each JSONL row is one case (illustrative excerpt, not a byte-for-byte row):
427
+
428
+ ```json
429
+ {
430
+ "test_id": "pgt-example-00001",
431
+ "prompt": "Summarize payment 4111112399105924 for the customer.",
432
+ "language": "en",
433
+ "domains": ["payment"],
434
+ "entities": [{
435
+ "domain": "payment",
436
+ "entity_type": "payment_card_number",
437
+ "character_start": 18,
438
+ "character_end": 34,
439
+ "exact_entity_value": "4111112399105924",
440
+ "detection_expected": true,
441
+ "classification_expected": "payment_card_number",
442
+ "valid": true
443
+ }],
444
+ "policy_decision_expected": "TOKENIZE",
445
+ "action_expected": {"payment_card_number": "TOKENIZE"},
446
+ "routing_expected": "external",
447
+ "transformation_expected": [{"entity_type": "payment_card_number", "action": "TOKENIZE"}],
448
+ "output_leakage_check_expected": true,
449
+ "token_restoration_expected": "authorized_context_only",
450
+ "audit_log_expected": {
451
+ "record_fields": ["test_id", "policy_scenario", "entity_types", "actions"],
452
+ "forbidden_fields": ["exact_entity_value"]
453
+ },
454
+ "difficulty": 1,
455
+ "prompt_length_class": "short",
456
+ "prompt_style": "short",
457
+ "polarity": "positive",
458
+ "split": "train",
459
+ "verification_status": "verified_spans",
460
+ "char_offset_convention": "unicode_codepoints_0_based_end_exclusive"
461
+ }
462
+ ```
463
+
464
+ The full schema is [`schemas/testcase.schema.json`](schemas/testcase.schema.json).
465
+ `manifest.json` records the seed, dataset/generator version, config and policy
466
+ hashes, per-file SHA-256, and the split-to-template map used to prove leakage
467
+ isolation. Artifacts contain no timestamps, so the same config and seed produce
468
+ byte-identical files.
469
+
470
+ ## Configuration
471
+
472
+ `configs/default.json` controls:
473
+
474
+ - seed, total sample count, train/validation/test ratios
475
+ - domain, language, length, difficulty and entity-density distributions
476
+ - negative and multi-domain ratios
477
+ - near-duplicate threshold
478
+ - quality-gate thresholds
479
+
480
+ `configs/policy.default.json` controls:
481
+
482
+ - action precedence (`ALLOW → MASK → TOKENIZE → REDACT → LOCAL_ONLY → BLOCK`)
483
+ - policy scenarios and their routing / minimum action
484
+ - per-domain and per-entity-type rules
485
+
486
+ The default policy is an **illustrative test configuration**, not legal advice.
487
+ Replace it with your organisation's policy before evaluating a real gateway.
488
+
489
+ ## Policy expectations
490
+
491
+ For every detected entity, all matching rules are evaluated and the strictest
492
+ action wins. Scenario floors (`min_action`) raise detected entities further.
493
+ The case-level `policy_decision_expected` is the strictest entity action; per
494
+ entity actions remain available in `action_expected` and
495
+ `transformation_expected`. Routing is `local` for `LOCAL_ONLY`, `blocked` for
496
+ `BLOCK`, otherwise the scenario routing. With no detected entities the result is
497
+ `ALLOW`.
498
+
499
+ The shipped policy deliberately exercises every action, including conflicting
500
+ rules where the strictest must prevail.
501
+
502
+ ## Quality gates and current results
503
+
504
+ `evaluate` checks: schema validity, span accuracy, reproducibility, exact and
505
+ near duplicate rates, domain/language/length/difficulty/entity coverage,
506
+ negative and multi-domain ratios, all-action coverage, and split integrity
507
+ (including cross-split near-duplicates). It writes `reports/evaluation.json`
508
+ and `reports/evaluation.md`.
509
+
510
+ Latest run on the committed sample (`seed 7`, 140 cases):
511
+
512
+ | Gate | Result |
513
+ |---|---|
514
+ | Schema validity / span accuracy / reproducibility | PASS (1.0 / 1.0 / byte-identical) |
515
+ | Exact / near duplicate rate | PASS (0.0 / 0.0 at 0.98 threshold) |
516
+ | Domain coverage | PASS (PII .46, payment .26, secrets .23, infrastructure .26) |
517
+ | Language coverage | PASS (Thai .50, English .26, mixed .24) |
518
+ | Length coverage | PASS (short .39, medium .39, long .22) |
519
+ | Difficulty 1–5 | PASS (.39 / .12 / .22 / .21 / .06) |
520
+ | Entity-type coverage | PASS (32 types) |
521
+ | Negative ratio | PASS (.19 vs .20 target) |
522
+ | Multi-domain share | PASS (.28) |
523
+ | All six actions present | PASS |
524
+ | Split integrity | PASS (no family or near-duplicate crosses splits) |
525
+
526
+ See [`docs/evaluation-report.md`](docs/evaluation-report.md) and
527
+ [`reports/evaluation.md`](reports/evaluation.md) for the generated report.
528
+
529
+ Automated suite: **167 tests pass** (`python -m unittest discover -s tests -t .`).
530
+ The suite covers entity validity and safety, exact spans, every template in all
531
+ three languages, policy precedence, validation failures, annotation repair,
532
+ generator reproducibility/dedup/splits, security scans, schema agreement, the
533
+ CLI, every v2 file renderer's round trip, v2 distribution/persona/OCR cases,
534
+ localization, measured language shares, per-attachment language and routing,
535
+ cross-file consistency, financial agreement, log timelines, image atomic ground
536
+ truth, old/new bundles, structure references, v2 schema agreement, the 2.0
537
+ compatibility fixture and v2 security scans.
538
+
539
+ CI (`.github/workflows/ci.yml`) runs the suite on Python 3.9, 3.12 and 3.13, then
540
+ runs the v1 gate, generates the representative v2 dataset, and runs
541
+ `validate-v2`, `verify-v2`, `report-v2 --check-reproducible`, the 2.0 fixture and
542
+ a report-hash comparison across `PYTHONHASHSEED` values. v2 failures therefore
543
+ cannot silently pass.
544
+
545
+ ## Safety
546
+
547
+ - Emails use `example.com/org/net`; hosts use `.internal` / `.example`.
548
+ - IPv4 uses RFC 1918 or RFC 5737 ranges; IPv6 uses ULA `fd00::/8`.
549
+ - Cards use documented test BINs and are Luhn-valid; invalid card lookalikes
550
+ fail Luhn.
551
+ - AWS-like keys contain `FAKE`/`EXAMPLE`; PEM blocks use
552
+ `EXAMPLE FAKE ... PRIVATE KEY`, which real parsers reject.
553
+ - JWTs are HS256-shaped but have `example-fake-signature`.
554
+ - No network calls, telemetry, or third-party dependencies.
555
+
556
+ Read [`SECURITY.md`](SECURITY.md) before generating data for a shared
557
+ environment. Generated datasets are synthetic but may still trip scanners;
558
+ label them clearly.
559
+
560
+ ## Project layout
561
+
562
+ ```
563
+ SKILL.md Agent Skill instructions
564
+ configs/ dataset + policy configuration
565
+ schemas/testcase.schema.json JSON Schema
566
+ src/privacy_gateway_testgen/ package
567
+ entities/ four-domain + lookalike factories
568
+ templates.py prompt library
569
+ builder.py span-recording builder
570
+ generator.py dataset engine, dedup, splits, export
571
+ policies.py precedence + scenario resolution
572
+ validation.py schema/span/policy validation
573
+ evaluation.py quality gates
574
+ annotations.py imported-annotation verification
575
+ textsim.py duplicate/leakage similarity
576
+ cli.py command line interface
577
+ v2/ file-aware schema 2.1 generator
578
+ localization.py Thai/English/mixed labels and formatting
579
+ scenario.py shared people, hosts, IDs, transactions
580
+ archetypes.py business documents independent of format
581
+ renderers/ real TXT/CSV/JSON/Office/PDF/image bytes
582
+ extract.py reopen/parse/locate verification
583
+ generate.py targets, bundles, splits, export
584
+ evaluate.py measured gates and language/consistency metrics
585
+ tests/ unittest suite
586
+ datasets/sample/ generated sample dataset
587
+ reports/ latest evaluation
588
+ docs/ architecture, acceptance criteria, evaluation
589
+ evals/ skill-behavior evaluation prompts
590
+ ```
591
+
592
+ ## Development
593
+
594
+ ```bash
595
+ PYTHONPATH=src python -m unittest discover -s tests -t . -v
596
+ PYTHONPATH=src python -m privacy_gateway_testgen evaluate --config configs/default.json --out reports
597
+ ```
598
+
599
+ Add a factory or template, run the tests, regenerate the sample, and re-run the
600
+ gates. See [`CONTRIBUTING.md`](CONTRIBUTING.md) and
601
+ [`docs/architecture.md`](docs/architecture.md).
602
+
603
+ ## Limitations
604
+
605
+ - Validation/test splits are template-family-disjoint, so a small dataset has
606
+ fewer families per split. Add templates when split diversity matters.
607
+ - Distribution weights are **preferences, not exact quotas**: length and
608
+ difficulty are coupled to the available template families, so a run can drift
609
+ from the configured weights. `evaluation.json` reports configured-vs-measured
610
+ deltas; the gates enforce coverage, not every weight.
611
+ - Negative lookalikes may still be flagged by pattern-only detectors; that is
612
+ the intended false-positive probe, not a label error.
613
+ - Thai names, addresses and organisations are synthetic combinations that may
614
+ coincidentally resemble real entities.
615
+ - Only documented test card BINs are used. **No PCI DSS compliance is claimed.**
616
+ - The default policy is illustrative, not legal advice.
617
+ - No performance or latency claims are made.
618
+ - LLM-authored prompts are not produced by this tool; imported cases need the
619
+ `verify` stage and human semantic review.
620
+
621
+ ## License
622
+
623
+ MIT — see [`LICENSE`](LICENSE).