Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(examples): rebuild redact on the pre-registered PII coverage run (#452)

svonavaf99850a7b669
diff --git a/examples/README.md b/examples/README.md
index 81eea2f35..fadf971c8 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -31,7 +31,7 @@ to a separately maintained repository (clone and run there).
| [Answer several triage questions about one record, each with a probability](./typed-decisions) | Asking CVE descriptions typed pick-one and yes-or-no questions against NVD analyst gold, with a fast, a smart and an LLM lane, and the questions no model passed reported rather than shown | `extract`, `chat/completions` | Self-hosted SIE with GLiFormer, GLiClass, Laya, GLiNER2, GLiNER2.5-Decide and Qwen3 4B; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example |
| [Screen harmful prompts before your model sees them](./guardrails) | Scoring SIE's Qwen3Guard 4B and GLiGuard against three LLM judges and OpenAI Moderation on 4,768 human-labelled ToxicChat and Aegis 2.0 prompts, with a paired bootstrap and the pre-registered bars | `chat/completions`, `extract` | SIE Cloud with GLiGuard, an SIE server for Qwen3Guard; `fetch.py` pulls the recorded run and both sets, `score.py` reproduces every figure with no key | Runnable recorded example |
| [Expand a query into matchable terms](./sparse) | Comparing SPLADE, which adds terms the text never used, with bge-m3 sparse, which does not | `encode` | SIE Cloud with SPLADE++ and bge-m3; `fetch.py` pulls the recorded vectors, `score.py` reproduces the figures with no key | Runnable recorded example |
-| [Get the exact character offsets to mask](./redact) | Naming your own ID types, measuring against published gold PII spans, and showing what a 384-word window costs | `extract` | SIE Cloud with GLiNER multi PII; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example |
+| [Mask personal data before it reaches a log, a prompt or a vendor](./redact) | Composing two PII models and scoring coverage recall on 660 documents against Presidio, OpenAI Privacy Filter and two LLM prompts, with the price of each | `extract` | SIE Cloud with GLiNER PII and NuNER Zero; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example |
| [Read the numbers off a dashboard that has no API](./screenshot-mining) | Reading twelve Superset, Argo CD, Airflow, Kubernetes, GitLab and Jaeger screens into schema-valid JSON | `generate` | SIE Cloud with Qwen3.8 27B; `fetch.py` pulls the recorded run and the screenshots, `score.py` reproduces 328 of 335 with no key | Runnable recorded example |
| [Read a scanned form into typed fields, then check the answer](./doc-field-extraction) | Extracting typed fields from FAA, OSHA, NIST, USPS and invoice pages under a strict JSON schema, then measuring whether a second call that never sees the page is worth making | `generate`, `chat/completions` | SIE Cloud with Qwen3.8 27B; `fetch.py` pulls the recorded run and the page images, `score.py` reproduces 180 of 223 and 204 after the second call with no key | Runnable recorded example |
| [Ask a question about an image](./caption-vqa) | Putting one specific question to equipment photographs, hazmat placards, wiring drawings and analogue dials | `generate` | SIE Cloud with Qwen3.8 27B; `fetch.py` pulls the recorded run and the images, `score.py` reproduces 10 of 12 with no key | Runnable recorded example |
diff --git a/examples/redact/.gitignore b/examples/redact/.gitignore
index 3162f927f..4d80fd7c2 100644
--- a/examples/redact/.gitignore
+++ b/examples/redact/.gitignore
@@ -1,4 +1,4 @@
-data/
+evidence/
run-output/
__pycache__/
*.pyc
diff --git a/examples/redact/README.md b/examples/redact/README.md
index 3bb08c44e..95cd34b50 100644
--- a/examples/redact/README.md
+++ b/examples/redact/README.md
@@ -1,183 +1,192 @@
-# Get the exact character offsets to mask
-
-The runnable example behind [superlinked.com/redact](https://superlinked.com/redact).
-That page's sources are in its [SOURCES.md](https://superlinked.com/reference/redact/SOURCES.md).
+# Mask personal data before it reaches a log, a prompt or a vendor
## What this shows
-Twelve documents sent to `urchade/gliner_multi_pii-v1` and to
-`numind/NuNER_Zero` on `https://api.superlinked.com`, each request naming the
-ID types that document uses as plain strings. No training set and no model per
-type. The response gives back exact character offsets, so the surrounding text
-stays readable.
-
-The documents are CFPB and CMS published sample forms and synthetic records
-from NVIDIA's Nemotron-PII and Gretel's synthetic PII finance dataset, the
-latter two carrying their publishers' own gold PII annotations.
-
-The page masks personal data in four steps, and `score.py` re-derives each one
-from the recorded responses, offline:
-
-| step | published PII spans masked |
-|---|---|
-| One call to `gliner_multi_pii-v1`, whole document | 26 of 45 |
-| Split what runs past the model's input window | 33 of 45 |
-| Union a second call to `NuNER_Zero` | 41 of 45 |
-| Mask every later mention of a name already found | 45 of 45 |
-
-Both models are in the same task's catalog, so the second call is one more
-model id on the same endpoint. Both were recorded on all twelve documents in
-the same run, and the dataset has held all 24 calls since the page was first
-published.
-
-Two more figures it reproduces: 42 of the 49 masks land on a published gold
-span, and 0 of the 29 currency amounts across the ten recorded documents are
-masked.
-
-The second step is why the window matters. The model reads 384 words and
-punctuation marks at a time. The server this run was recorded against read
-only the first 384 and gave no truncation signal, so a longer document had to
-be split by the caller, with each part's starting offset added back to the
-spans it returns; the recorded inputs carry that split. Servers that include
-the fix for [#446](https://github.com/superlinked/sie/issues/446) read a longer
-document whole, in overlapping windows.
+This example holds the recorded run behind
+[superlinked.com/redact](https://superlinked.com/redact). Its sources are in
+that page's [SOURCES.md](https://superlinked.com/reference/redact/SOURCES.md).
+
+The study asks one question of each redaction option: how much of the personal
+data in a document does it leave readable? It sends 660 synthetic financial
+documents through five arms and counts, for each, the in-scope personal-data
+spans it masks completely. The metric was fixed before the first request on
+30 September 2026.
+
+- **Documents.** 660 rows of the English test split of
+ [`gretelai/synthetic_pii_finance_multilingual`](https://huggingface.co/datasets/gretelai/synthetic_pii_finance_multilingual)
+ (Apache 2.0, revision `7b844d16`), drawn with `random.Random(20260930)`:
+ support logs, IT tickets, emails, loan, card and insurance forms, SWIFT and
+ EDI messages. The personal data in them is synthetic, and every row carries
+ Gretel's own gold spans.
+- **Which spans count: 1,792.** The HIPAA Safe Harbor identifiers the set
+ labels (45 CFR 164.514(b)(2)), plus credentials: names, street addresses,
+ coordinates, dates of birth, phone numbers, emails, SSNs, bank and card
+ numbers, driver's licence and passport numbers, employee and customer IDs,
+ user names, IP addresses, passwords, PINs, card security codes and API keys.
+ Company names, dates, times, routing numbers and SWIFT codes are out of
+ scope.
+- **The figure: coverage recall.** A span counts as masked only when every
+ non-space character of it sits under a mask, whatever label the detector gave
+ it. A redactor fails when personal data stays readable, and a mask does not
+ care about labels; exact-span F1 would punish a detector for calling an
+ account number a card number while it hides it perfectly. F1 and overlap
+ precision are printed too.
+- **A second figure, fixed before the results were read.** The same, except a
+ span also counts when the only characters left readable are a U.S. state,
+ a Canadian province, a country or punctuation. Gretel's address spans run
+ through the state, and an arm that masks the street, city and postcode but
+ not `MI` fails the first figure without leaking anything that identifies a
+ person.
+- **Intervals.** 95% paired document-cluster bootstrap, 2,000 resamples, seed
+ 20260930.
+
+## Results
+
+| Arm | Masked (of 1,792) | Coverage recall | 95% interval | States and countries excused | $ a month, 1M documents |
+| --- | --- | --- | --- | --- | --- |
+| SIE, two models composed | 1,591 | 88.8% | 86.7% to 90.9% | 90.5% | $32 |
+| Claude Haiku 4.5 | 1,490 | 83.1% | 80.8% to 85.2% | 92.6% | $1,450 |
+| GPT-6 Luna | 1,448 | 80.8% | 78.2% to 83.1% | 93.2% | $113 |
+| OpenAI Privacy Filter | 1,214 | 67.7% | 64.3% to 71.0% | 69.8% | $23 (self-hosted, L4) |
+| Microsoft Presidio | 859 | 47.9% | 45.0% to 50.8% | 49.6% | $3 (self-hosted, CPU) |
+| AWS Comprehend | not measured | | | | $351 |
+
+SIE minus each arm, paired: Presidio +37.5 to +44.3 points, Privacy Filter
++17.8 to +24.5, Claude Haiku 4.5 +2.8 to +8.6, GPT-6 Luna +5.3 to +11.0. With
+states and countries excused SIE stays well ahead of Presidio (+37.6 to +44.3)
+and Privacy Filter (+17.4 to +24.1), is level with Claude Haiku 4.5 (-4.5 to
++0.3) and behind GPT-6 Luna (-4.9 to -0.4). SIE's lead over the two LLM prompts
+on the first figure is addresses whose state they left readable; the label list
+has no `state`. So this study makes no detection claim against an LLM prompt.
+It does say what they cost, and that redacting with an LLM API sends the
+unredacted text to that API.
+
+**AWS Comprehend, Azure AI Language and Google Cloud DLP were not measured.**
+The study had no access to them. Comprehend documents an entity type for 96.2%
+of the in-scope spans here (all but coordinates, employee IDs and customer
+IDs), so nothing here places it above or below SIE. Its row is price only.
+
+Overlap precision is low for every arm (0.35 to 0.60) because Gretel annotates
+a subset of each document's personal data: a mask on an unannotated name or
+email counts against it.
+
+## The arms
+
+| Arm | How it ran |
+| --- | --- |
+| SIE | `urchade/gliner_multi_pii-v1` and `numind/NuNER_Zero` on `https://api.superlinked.com`, the same 36 labels, each span kept at score 0.6 or above, the two unioned. Then every other whole-word, case-sensitive mention of a three-letter or longer token from a returned `person` span is masked, in the caller's code. A document over 300 words is sent as 300-word windows with a 50-word overlap, each window's offset added back to its spans. |
+| OpenAI Privacy Filter | the `opf` package from [openai/privacy-filter](https://github.com/openai/privacy-filter) at `f7f00ca`, default checkpoint and decoding, every span masked, on one NVIDIA L4 |
+| Microsoft Presidio | `presidio-analyzer` 2.2.364 `AnalyzerEngine()` defaults with spaCy `en_core_web_lg` 3.8.0, every entity masked |
+| GPT-6 Luna | `reasoning_effort: "none"`, `temperature: 0`, strict JSON schema, the 36 labels in the prompt |
+| Claude Haiku 4.5 | no extended thinking, `temperature: 0`, JSON schema, the same prompt |
+
+The LLM prompt: "Find every piece of personally identifiable information in the
+text. Use these types: {labels}. Copy each mention exactly as it appears in the
+text. Return an empty list if there is none." An LLM returns strings, not
+offsets, so every occurrence of a returned string is masked. Three of GPT-6
+Luna's 660 replies did not parse and count as no masks.
+
+The windows are there because each GLiNER-family model reads about 384 words
+per request, and the server this run was recorded against read only the first
+384 and said nothing when it stopped
+([#446](https://github.com/superlinked/sie/issues/446)). So the study split
+documents over 300 words in the client. A server with the fix for #446 reads a
+long document whole, in overlapping windows of its own; `run.py` still sends
+the client-side windows, so it reproduces the recorded requests. Each SIE
+model alone, one request per document with no floor: GLiNER PII 82.1%, NuNER
+Zero 62.7%.
+
+### Price inputs
+
+For 1,000,000 documents a month like these, list prices read on 30 September
+2026. `score.py` holds each input as a named constant.
+
+- **SIE:** $0.04 per million input tokens for GLiNER PII and $0.05 for NuNER
+ Zero, on the 238,605 and 227,727 tokens their tokenizers count in the 660
+ documents.
+- **AWS Comprehend `DetectPiiEntities`:** $0.000025 per 100-character unit,
+ its cheapest tier, 3-unit minimum per request, units counted as characters
+ over 100 with no rounding up.
+- **LLMs:** the tokens each provider reported for the run, at $0.10 and $0.50
+ (GPT-6 Luna) and $1 and $5 (Claude Haiku 4.5) per million input and output
+ tokens.
+- **Presidio and Privacy Filter** are free to download, so their price is the
+ compute: Modal list price per second (L4 $0.000222, a core $0.0000131, a GiB
+ $0.00000222), divided by 75% utilisation and times 1.75 for region, at the
+ throughput measured with the best worker count. Presidio: 8 cores and 16 GiB,
+ 98.5 documents a second. Privacy Filter: one L4, 8 cores and 32 GiB, 39.7
+ documents a second.
## Run it
-The code is in this repository. The inputs and the recorded responses are in
-the public Hugging Face dataset
-[`superlinked/sie-task-evidence`](https://huggingface.co/datasets/superlinked/sie-task-evidence),
-so a clone alone is not enough. Fetch, then score:
-
-```sh
-python3 fetch.py # downloads the pinned revision into data/
-python3 score.py # reproduces every published figure offline
-python3 run.py --check # rebuilds all 24 recorded requests from the inputs
-python3 score.py --floor-0 # the same figures with the confidence floor removed
-```
-
-The last one is why the 0.6 floor is not doing the work. Five of the run's 168
-spans fall below it: `ID #`, `File #` and `MIC #`, each covering a field's
-printed label and no value, and the given name `Annibale` twice, which the
-first model also returned at the same offsets inside `Annibale Caboto`. Every
-figure above is unchanged with the floor removed, the 42 of 49 included: the
-three field-label spans are on the Closing Disclosure, which carries no gold
-spans and so is not one of the six documents the precision figure is measured
-over, and the two `Annibale` spans merge into masks the first model already
-produced.
-
-These three need nothing installed: they are standard library only, and none
-of them needs an API key, a Hugging Face token or any inference spend.
-`fetch.py` pins a commit SHA, not `main`, and checks every downloaded file
-against a digest. It replaces `--dest` wholesale, so it refuses to touch
-anything without the `.sie-evidence` marker it writes, and it swaps the new
-directory in by rename rather than deleting the old one first.
-
-To call the API yourself. This is the only part that needs the SDK, and the
-only command here that spends anything:
+Download the recorded run, then score it. Neither step needs a key, and both
+are standard library only:
```sh
-uv sync
-SIE_API_KEY=... uv run python run.py --record --out run-output/calls.json
+python3 fetch.py
+python3 score.py
```
-`run.py` sends through `sie_sdk.SIEClient`. The import is deferred into
-`main()`, so `--check` and `--show` keep working on a bare `python3` with
-nothing installed. `python3 run.py --show <id>` prints a request without
-sending it.
-
-## What to expect
+`fetch.py` pulls the `redact/` folder of the public Hugging Face dataset
+[superlinked/sie-task-evidence](https://huggingface.co/datasets/superlinked/sie-task-evidence),
+pinned to one revision, about 4.4 MB. It checks every file against the id the
+dataset lists and against the SHA-256 in `manifest.json`, whose own digest is
+pinned in `fetch.py`. It holds:
+
+- `inputs/gretel-main.jsonl`: the 660 documents and their gold spans (start
+ and end in Unicode code points);
+- `rows/`: one recorded row per document per arm. The SIE rows hold the API
+ responses (`whole`, and `windows` for documents over 300 words); the LLM rows
+ the raw JSON reply and token counts; Presidio and Privacy Filter their spans;
+- `results/`: the study's own results file, token counts, and the throughput
+ and price per arm;
+- `manifest.json`: run date, endpoint, models, labels, prompt and arm settings.
+
+`score.py` composes SIE's two recorded responses, turns each arm's output into
+masks, and prints every figure above plus overlap precision, exact-span F1,
+each SIE model alone, and how many currency amounts SIE's masks touch. It
+exits nonzero unless every figure matches both the recorded results file and
+the page. It takes about two seconds; `--no-bootstrap` skips the intervals.
```
-benchmark documents scored: 6
- nemotron_insurance_claims_log 6 of 6 in one call, 6 composed
- nemotron_insurance_application 7 of 7 in one call, 7 composed
- gretel_customer_support_log 2 of 11 in one call, 11 composed
- gretel_it_support_ticket 3 of 11 in one call, 11 composed
- gretel_policyholder_report 4 of 5 in one call, 5 composed
- gretel_german_health_claim 4 of 5 in one call, 5 composed
-
-published PII spans masked, by step:
- 26 of 45 one call to urchade/gliner_multi_pii-v1, whole document
- 33 of 45 splitting what runs past the model's input window
- 41 of 45 unioning a second call to numind/NuNER_Zero
- 45 of 45 masking every later mention of a name already found
-
-42 of 49 masks land on a published gold span
-7 fall outside them, so neither benchmark can confirm or refute those
-
-the propagation step added 6 masks: Annibale, Paul
-
-0 of 29 currency amounts masked across the 10 recorded documents
-
-564-word chat, 11 published spans: 2 masked by one call, 11 by the composition
- the model reads the first 384 words, up to character 813
- 7 of those spans sit past that point, and the second request starts at character 812
-
-Reproduced: 26, 33, 41 and 45 of 45, 42 of 49 on gold, and 0 of 29 amounts masked.
+660 documents, 1,792 in-scope personal-data spans
+
+Arm Masked Coverage State excused Precision Exact F1
+SIE (GLiNER PII + NuNER Zero, composed) 1,591 of 1,792 88.8% 90.5% 0.346 0.396
+Claude Haiku 4.5 1,490 of 1,792 83.1% 92.6% 0.595 0.484
+GPT-6 Luna 1,448 of 1,792 80.8% 93.2% 0.590 0.474
+OpenAI Privacy Filter 1,214 of 1,792 67.7% 69.8% 0.590 0.504
+Microsoft Presidio 859 of 1,792 47.9% 49.6% 0.346 0.167
+...
+Every figure matches the recorded results and the published page.
```
-`score.py` exits nonzero if any figure fails to reproduce. `run.py --check`
-prints `24 of 24 recorded requests rebuilt from the inputs and matched`, and
-fails if a call is missing, recorded twice or implied by no case.
-
-## How the figures are derived
-
-The two sides of every comparison come from different places. The gold spans
-are the benchmark publishers' own annotations, carried in `inputs/cases.json`.
-The masks are read out of the recorded API responses in `calls.json`. Neither
-is derived from the other.
+Run SIE's composition yourself, with your own key:
-- **covered**: a gold span counts as masked only when the union of returned
- spans covers every one of its characters, so two overlapping returned spans
- are never counted twice.
-- **in the gold schema**: a returned span counts toward the 25 only when its
- label is one the gold annotation can express.
-- **on gold**: such a span counts toward the 23 when it overlaps any gold span.
-- **564 and 384**: counted with GLiNER's own word rule, against the recorded
- window boundary character offset, rather than taken from the page.
-
-## What is in the dataset
-
-```
-redact/
- inputs/cases.json 12 documents: text, requested labels, word counts, sources,
- and for the 6 benchmark documents the published gold PII spans
- calls.json 24 calls: request, response, status, timing, one file
- manifest.json endpoint, models, served revision, run window, digests
+```sh
+uv sync
+python3 run.py --show # the requests for one document, not sent
+SIE_API_KEY=... uv run python run.py # one document, masked and scored against its gold
+SIE_API_KEY=... uv run python run.py --doc 851 # another, by index or uid
+SIE_API_KEY=... uv run python run.py --all # all 660 into run-output/, about 470,000 tokens per model
+python3 score.py --sie-rows run-output # your run beside the recorded arms
```
-The 24 calls were 48 separate JSON files in sie-web. Merging them changed no
-byte of any request or response.
-
-## What this does NOT establish
-
-- **The 42 of 49 is agreement, not correctness.** Both benchmarks annotate
- only a subset of each document, so a mask outside their gold spans is
- unjudged rather than wrong. The seven unjudged masks are two claim numbers, a
- payment card's last four digits, a doctor's practice address, a medical
- condition, and two further mentions of a name a model had already returned.
-- **Nothing about recall on your documents.** Twelve documents from four
- publishers is a demonstration.
-- **Nothing about the 384-word window being a fixed property.** It is what
- these recordings show for these models. Measure it for the model you deploy.
-- **Nothing about either model alone being enough.** Chunked, on its own,
- `gliner_multi_pii-v1` reaches 33 of 45 and `NuNER_Zero` 37 of 45. The 41 is
- the union of the two, and the 45 needs the propagation step as well.
-- **Nothing about which documents the page shows.** Every figure here is over
- the recorded set: the four steps and the 42 of 49 over the six documents
- carrying gold spans, and the 0 of 29 amounts over all ten recorded documents
- that are not a second chunk. Which of them a page renders is the page's
- decision and nothing here can read it.
-- **A fresh `--record` run records less than the archive.** `client.extract`
- returns the per-item result rather than the server's envelope, and surfaces
- no response headers, so `--record` rebuilds the envelope around that item and
- each entry carries a `shape` field saying so. `score.py` reads the published
- `calls.json`.
-- **No tamper resistance.** The digests catch a truncated or corrupted
- download. They are not a provenance chain.
-
-sie-web keeps its own copy of these recordings under
-`apps/site/tests/fixtures/reference/redact/`, which is what its CI tests read.
-The two copies hold the same recorded responses. Nothing binds them together,
-so they can drift.
+`run.py` sends through `sie_sdk.SIEClient`, with the same labels and windows as
+the recorded run, and for one document prints the masked text, the gold spans
+it left readable, and whether its spans match the recording.
+
+## What this does not establish
+
+- **Nothing about your documents.** Gretel's documents are synthetic and
+ financial. Measure on your own data before relying on any of these figures.
+- **Nothing about AWS Comprehend, Azure or Google Cloud DLP.** They were not
+ run.
+- **No lead over an LLM prompt.** It depends on whether a readable state counts
+ as a leak.
+- **Nothing about what stays readable.** Overlap precision is bounded by what
+ Gretel chose to annotate, and SIE's name step masks every later mention of a
+ word a model called a person, including `Insured` in some insurance forms.
+- **Latency is not compared.** The recorded latency is in
+ `results/e2_results.json`; the self-hosted arms run in-process and SIE over
+ the network, so the numbers are not like for like.
diff --git a/examples/redact/fetch.py b/examples/redact/fetch.py
index f742a6698..142df453f 100755
--- a/examples/redact/fetch.py
+++ b/examples/redact/fetch.py
@@ -1,203 +1,165 @@
#!/usr/bin/env python3
-"""Download the recorded redact evidence from a pinned dataset revision.
+"""Download this task's recorded evidence from the pinned dataset revision.
- python3 fetch.py [--dest data]
+ python3 fetch.py
-Standard library only. No API key, no Hugging Face token, no inference spend.
-The dataset is public and anonymous-readable.
+Standard library only. No token, no account, no API key. The dataset is public
+and this pulls it anonymously.
-REVISION is a commit SHA, never a branch. `main` moves; a SHA does not.
+Everything lands in evidence/: the 660 documents with their gold spans, every
+arm's recorded response for every document, and the study's results files.
+score.py reads from there and never touches the network.
-Every downloaded file is checked against a digest before the scorer sees it.
-The chain is anchored in this file: MANIFEST_SHA256 pins manifest.json,
-manifest.json pins calls.json and every input file. A file that is missing or
-that fails its digest is a FAILURE, never a skip, and the script exits
-nonzero without writing a partial tree the scorer could mistake for complete.
+REVISION is a dataset commit, deliberately not `main`, so a later upload cannot
+change what this example scores.
-This script replaces `--dest` wholesale, so it refuses to touch anything it did
-not write. A directory qualifies only when it holds a `.sie-evidence` marker naming
-this dataset and task, and never when it is the working directory, an ancestor
-of it, your home directory or the filesystem root. Anything else stops the run
-with an explanation rather than being deleted.
-
-The replacement itself is two renames, not a delete and a copy: the old
-directory is renamed aside, the verified download is renamed into place, and
-only then is the old one removed. If the second rename fails the first is
-undone, so a reader is never left with neither.
+Every file is checked twice. First against the id the dataset lists for it at
+that revision (the git object id, or the SHA-256 of a Git LFS file). Then
+against the SHA-256 in manifest.json, whose own SHA-256 is pinned below. A file
+that is missing, extra or fails either check stops the run, and evidence/ is
+left as it was.
"""
from __future__ import annotations
-import argparse
import hashlib
import json
-import os
import shutil
import sys
import tempfile
-import urllib.error
import urllib.request
from pathlib import Path
+HERE = Path(__file__).resolve().parent
+EVIDENCE = HERE / "evidence"
+
DATASET = "superlinked/sie-task-evidence"
+REVISION = "4999a499aed5ea77181973070fa435a616552d80"
TASK = "redact"
-REVISION = "f2a5ffc8f157696f5dadd04dfbdf38d0bc991854"
-MANIFEST_SHA256 = "a1473db90bc914526bc0f84681e497840a4c33998b0f73f7d7a0ab51e4339d3f"
-
-BASE = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}/{TASK}"
-HTTP_OK = 200
-MARKER_NAME = ".sie-evidence"
-
-
-def download(relative_path: str) -> bytes:
- url = f"{BASE}/{relative_path}"
- request = urllib.request.Request(url, headers={"Accept": "*/*"}) # noqa: S310
- try:
- with urllib.request.urlopen(request, timeout=120) as response: # noqa: S310
- if response.status != HTTP_OK:
- raise RuntimeError(f"{url} returned HTTP {response.status}")
- return response.read()
- except urllib.error.HTTPError as error:
- raise RuntimeError(f"{url} returned HTTP {error.code}") from error
- except urllib.error.URLError as error:
- raise RuntimeError(f"{url} could not be reached: {error.reason}") from error
-
-
-def digest(payload: bytes) -> str:
- return hashlib.sha256(payload).hexdigest()
-
-
-def marker_bytes() -> bytes:
- """What marks a directory as this script's to replace."""
- return (
- json.dumps(
- {"written_by": "fetch.py", "dataset": DATASET, "task": TASK, "revision": REVISION},
- indent=2,
- )
- + "\n"
- ).encode("utf-8")
-
-
-def refuse_reason(dest: Path) -> str | None:
- """Why `dest` must not be replaced, or None when replacing it is safe.
-
- Checked before anything is downloaded and again before the swap.
+MANIFEST_SHA256 = "a3a7b8b6c73f20e4bcf99b5adec37ada0ff67f7a57d8b91cf8fac9e0406a6961"
+
+API = f"https://huggingface.co/api/datasets/{DATASET}/tree/{REVISION}"
+FILES = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}"
+
+# Every file score.py reads. A listing missing one of these is a failure, not a
+# short download: score.py would otherwise report on whatever happened to arrive.
+REQUIRED = (
+ "manifest.json",
+ "inputs/gretel-main.jsonl",
+ "rows/sie__urchade__gliner_multi_pii-v1.jsonl",
+ "rows/sie__numind__NuNER_Zero.jsonl",
+ "rows/presidio.jsonl",
+ "rows/privacy-filter.jsonl",
+ "rows/llm__gpt-6-luna.jsonl",
+ "rows/llm__claude-haiku-4-5.jsonl",
+ "results/gretel-main_results.json",
+ "results/gretel-main_tokens.json",
+ "results/e2_results.json",
+)
+
+
+def git_blob_oid(data: bytes) -> str:
+ """The object id git gives these bytes, which is what the dataset publishes.
+
+ SHA-1 is not chosen here for its strength; it is the identifier the dataset
+ already exposes, so the value can be checked against Hugging Face by hand.
"""
- resolved = dest.resolve()
- cwd = Path.cwd().resolve()
- # These hold whatever the marker says. A marker can be planted; the
- # working tree still must not be removable by a --dest typo.
- if resolved == resolved.parent:
- return f"{resolved} is the filesystem root"
- if resolved == cwd:
- return f"{resolved} is the current working directory"
- if resolved in cwd.parents:
- return f"{resolved} contains the current working directory"
- if resolved == Path.home().resolve():
- return f"{resolved} is your home directory"
-
- if dest.is_symlink():
- return f"{dest} is a symlink"
- if not dest.exists():
- return None
- if not dest.is_dir():
- return f"{dest} exists and is not a directory"
-
- marker = dest / MARKER_NAME
- if not marker.is_file():
- return (
- f"{dest} exists but holds no {MARKER_NAME}, so this script did not write it. "
- f"Move it aside, or pass --dest somewhere else."
- )
- try:
- recorded = json.loads(marker.read_text(encoding="utf-8"))
- except (OSError, ValueError) as error:
- return f"{dest}/{MARKER_NAME} could not be read: {error}"
- if recorded.get("dataset") != DATASET or recorded.get("task") != TASK:
- return f"{dest}/{MARKER_NAME} names {recorded.get('dataset')}/{recorded.get('task')}, not {DATASET}/{TASK}"
- return None
-
-
-def swap_into_place(staging: Path, dest: Path) -> None:
- """Put `staging` at `dest` without deleting anything first.
-
- Both live in the same parent, so each rename is atomic and cannot half
- happen. The previous directory is only removed once the new one is in
- place; if that fails, the previous one goes back.
- """
- previous = None
- if dest.exists():
- previous = dest.with_name(f"{dest.name}.previous-{os.getpid()}")
- if previous.exists():
- shutil.rmtree(previous)
- dest.replace(previous)
- try:
- staging.replace(dest)
- except OSError:
- if previous is not None:
- previous.replace(dest)
- raise
- if previous is not None:
- shutil.rmtree(previous, ignore_errors=True)
+ return hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest()
+
+
+def get(url: str) -> bytes:
+ # No Authorization header: the dataset is public and this must work for a
+ # reader who has never signed in to Hugging Face.
+ request = urllib.request.Request(url, headers={"User-Agent": f"sie-examples/{TASK}"})
+ with urllib.request.urlopen(request, timeout=300) as response:
+ return response.read()
+
+
+def listing() -> list[dict]:
+ entries = json.loads(get(f"{API}/{TASK}?recursive=true"))
+ files = [entry for entry in entries if entry.get("type") == "file"]
+ if not files:
+ raise SystemExit(f"{DATASET} revision {REVISION} has no files under {TASK}/")
+ return files
+
+
+def check_listed_id(remote: str, body: bytes, entry: dict) -> None:
+ if entry.get("size") is not None and len(body) != entry["size"]:
+ raise SystemExit(f"{remote}: downloaded {len(body)} bytes, the dataset lists {entry['size']}")
+ lfs_oid = (entry.get("lfs") or {}).get("oid")
+ blob_oid = entry.get("oid")
+ if lfs_oid:
+ if hashlib.sha256(body).hexdigest() != lfs_oid:
+ raise SystemExit(f"{remote}: the bytes do not hash to the LFS digest the dataset lists")
+ elif blob_oid:
+ if git_blob_oid(body) != blob_oid:
+ raise SystemExit(f"{remote}: the bytes do not match the object id the dataset lists")
+ else:
+ raise SystemExit(f"{remote}: the dataset lists no id for this file, so it cannot be checked")
+
+
+def check_manifest(staging: Path, written: set[str]) -> None:
+ manifest_bytes = (staging / "manifest.json").read_bytes()
+ if hashlib.sha256(manifest_bytes).hexdigest() != MANIFEST_SHA256:
+ raise SystemExit("manifest.json does not match the digest this script pins")
+ listed = {f["path"]: f for f in json.loads(manifest_bytes)["files"]}
+ extra = written - set(listed) - {"manifest.json"}
+ if extra:
+ raise SystemExit(f"files the manifest does not list: {', '.join(sorted(extra))}")
+ for path, entry in sorted(listed.items()):
+ if path not in written:
+ raise SystemExit(f"{path}: listed in manifest.json but not downloaded")
+ body = (staging / path).read_bytes()
+ if len(body) != entry["bytes"] or hashlib.sha256(body).hexdigest() != entry["sha256"]:
+ raise SystemExit(f"{path}: does not match the SHA-256 in manifest.json")
def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--dest", default="data", help="output directory (default: data)")
- args = parser.parse_args()
-
- dest = Path(args.dest)
- reason = refuse_reason(dest)
- if reason is not None:
- print(f"refusing to replace {dest}: {reason}", file=sys.stderr)
- return 1
-
- dest.parent.mkdir(parents=True, exist_ok=True)
-
- manifest_bytes = download("manifest.json")
- if digest(manifest_bytes) != MANIFEST_SHA256:
- print(
- f"manifest.json digest is {digest(manifest_bytes)}, expected {MANIFEST_SHA256}",
- file=sys.stderr,
- )
- return 1
- manifest = json.loads(manifest_bytes)
-
- files = manifest["files_sha256"]
- # Staged beside the destination, so the swap below is a rename on one
- # filesystem rather than a copy that can fail half way.
- staging = Path(tempfile.mkdtemp(prefix=f".{TASK}-evidence-", dir=dest.parent))
+ print(f"{DATASET} at {REVISION}")
+ # Download into a staging directory and swap it in only once every file has
+ # arrived and checked, so a failure never leaves a mixed set behind.
+ staging = Path(tempfile.mkdtemp(prefix="sie-evidence-", dir=HERE))
try:
- (staging / "manifest.json").write_bytes(manifest_bytes)
- for relative_path, expected in sorted(files.items()):
- payload = download(relative_path)
- actual = digest(payload)
- if actual != expected:
- print(f"{relative_path} digest is {actual}, expected {expected}", file=sys.stderr)
- return 1
- target = staging / relative_path
+ total = 0
+ written: set[str] = set()
+ for entry in sorted(listing(), key=lambda item: item["path"]):
+ remote = entry["path"]
+ relative = remote[len(TASK) + 1 :]
+ body = get(f"{FILES}/{remote}")
+ check_listed_id(remote, body, entry)
+ target = staging / relative
target.parent.mkdir(parents=True, exist_ok=True)
- target.write_bytes(payload)
-
- calls_sha = digest((staging / "calls.json").read_bytes())
- if calls_sha != manifest["calls_sha256"]:
- print("calls.json does not match the digest in manifest.json", file=sys.stderr)
- return 1
-
- (staging / MARKER_NAME).write_bytes(marker_bytes())
-
- # Re-checked here: the first check ran before the download, and the
- # destination could have changed since.
- reason = refuse_reason(dest)
- if reason is not None:
- print(f"refusing to replace {dest}: {reason}", file=sys.stderr)
+ target.write_bytes(body)
+ written.add(relative)
+ total += len(body)
+ print(f" {relative} ({len(body):,} bytes)")
+
+ missing = [name for name in REQUIRED if name not in written]
+ if missing:
+ print("The download is incomplete; score.py would not be scoring the recorded run:", file=sys.stderr)
+ for name in missing:
+ print(f" missing {name}", file=sys.stderr)
return 1
- swap_into_place(staging, dest)
+ check_manifest(staging, written)
+
+ # Move the old evidence aside and delete it only once the new set is in
+ # place, so a failed rename never leaves no evidence at all.
+ backup = EVIDENCE.with_name(EVIDENCE.name + ".old")
+ shutil.rmtree(backup, ignore_errors=True)
+ if EVIDENCE.exists():
+ EVIDENCE.rename(backup)
+ try:
+ staging.rename(EVIDENCE)
+ except OSError:
+ if backup.exists():
+ backup.rename(EVIDENCE)
+ raise
+ shutil.rmtree(backup, ignore_errors=True)
finally:
shutil.rmtree(staging, ignore_errors=True)
- print(f"{TASK}: {len(files) + 1} files verified into {args.dest}/ at revision {REVISION}")
- print(f"{manifest['call_count']} recorded calls in {args.dest}/calls.json")
+ print(f"Wrote {total:,} bytes to {EVIDENCE}, every file checked against the dataset and manifest.json")
+ print("Now run: python3 score.py")
return 0
diff --git a/examples/redact/pyproject.toml b/examples/redact/pyproject.toml
index 1dff8a71d..5308d0f23 100644
--- a/examples/redact/pyproject.toml
+++ b/examples/redact/pyproject.toml
@@ -1,7 +1,7 @@
[project]
name = "superlinked-sie-redact-example"
version = "0.1.0"
-description = "Get the exact character offsets to mask with SIE Cloud"
+description = "Mask personal data with two SIE PII models, scored against Presidio, OpenAI Privacy Filter and two LLM prompts on 660 documents"
requires-python = ">=3.12,<3.13"
dependencies = [
"sie-sdk>=0.6.23,<0.8.0",
diff --git a/examples/redact/run.py b/examples/redact/run.py
index 71baece4d..32634bcee 100755
--- a/examples/redact/run.py
+++ b/examples/redact/run.py
@@ -1,40 +1,26 @@
#!/usr/bin/env python3
-"""Send the /redact calls to SIE Cloud, or check the recorded ones.
+"""Run SIE's PII composition yourself, on one recorded document or all 660.
python3 fetch.py
- python3 run.py --check # offline, no key, nothing installed
- python3 run.py --show <case-id> # offline, prints one request
- uv sync && uv run python run.py --record # live, needs SIE_API_KEY
-
-Endpoint https://api.superlinked.com
-Path /v1/extract/<model>
-Models urchade/gliner_multi_pii-v1 (the model the page shows)
- numind/NuNER_Zero (recorded over the same documents)
-Revision every response carried x-sie-model-revision
- 10333b84de80b402376b626eb25366fb081d3faeb893eb4b01cf32e8c27e4aff
-
-Calls go through `sie_sdk.SIEClient`, per AGENTS.md. The import is deferred into
-main() so `--check` and `--show` run on a bare `python3` with nothing installed.
-
-Twelve documents go to both models, so 24 calls. Each request names the ID
-types that document uses, as plain strings, and the response gives back exact
-character offsets.
-
-Two of the twelve documents are tails: the part of a long document past word
-384, sent as a second request. `parent_case` and `parent_offset` in
-inputs/cases.json say which document they came from and where they start.
-
-`--check` rebuilds all 24 recorded request bodies from `data/inputs/cases.json`
-and compares each with the recorded request. Those bodies were confirmed against
-the SDK by intercepting the client transport: `client.extract` puts exactly these
-24 bodies on the wire, at exactly these paths.
-
-It is a bijection, not a walk over what is there: the expected call ids come
-from the inputs, one per model per document, so a call that is missing,
-recorded twice, or implied by no case fails the check.
-
-Migrated from apps/site/tests/fixtures/reference/redact/run.py in
-superlinked/sie-web@b07b6d73.
+ python3 run.py --show # offline: the requests for one document, not sent
+ SIE_API_KEY=... uv run python run.py # one document, masked and scored against its gold
+ SIE_API_KEY=... uv run python run.py --doc 851 # another document, by index or uid
+ SIE_API_KEY=... uv run python run.py --all # all 660, into run-output/
+ python3 score.py --sie-rows run-output # score your run beside the recorded arms
+
+Endpoint https://api.superlinked.com (set SIE_BASE_URL to use your own server)
+Models urchade/gliner_multi_pii-v1 and numind/NuNER_Zero, through sie_sdk.SIEClient
+Labels the 36 in score.py, the same for every request
+
+A document over 300 words is also sent as 300-word windows with a 50-word
+overlap, and each window's offset is added back to its spans; the composition
+uses the windows when there are any. That is what the recorded run did. `--all`
+also sends every document whole, as the run did, so score.py can report each
+model alone.
+
+The SDK import is deferred into the functions that send, so `--show` works on
+a bare `python3` with nothing installed. One document costs a fraction of a
+cent; `--all` sends about 470,000 tokens per model.
"""
from __future__ import annotations
@@ -43,269 +29,184 @@ import argparse
import json
import os
import sys
-import time
-from datetime import UTC, datetime
+import threading
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from score import (
+ EVIDENCE,
+ FIRST_MODEL,
+ REQUEST_LABELS,
+ SECOND_MODEL,
+ compose,
+ covered,
+ load_documents,
+ merge,
+ read_jsonl,
+ windows,
+)
+
if TYPE_CHECKING:
from sie_sdk import SIEClient
+HERE = Path(__file__).resolve().parent
ENDPOINT = "https://api.superlinked.com"
-MODELS = ["urchade/gliner_multi_pii-v1", "numind/NuNER_Zero"]
-
-
-def load(path: Path) -> Any:
- if not path.exists():
- raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
- return json.loads(path.read_text(encoding="utf-8"))
-
-
-class CallFailedError(Exception):
- """A call that did not produce a usable result.
-
- The SDK raises for a transport or HTTP failure. This covers the other
- half: a 200 whose item carries an `error`, which must never be recorded
- as though it were a result.
- """
-
-
-def failure_entry(
- call_id: str,
- set_name: str,
- case_id: str,
- model: str,
- path: str,
- body: dict[str, Any],
- error: BaseException,
- call_name: str | None = None,
-) -> dict[str, Any]:
- """What a failed call records.
-
- Every field the success path writes, so that `check` and `score.py` can
- read a calls.json holding failures instead of raising KeyError on it. Only
- the values differ: the status never reads as success, the response is null
- and `error` says what went wrong. A recorder and a reader that disagree
- about shape is how a failed run gets mistaken for a missing one.
- """
- entry: dict[str, Any] = {
- "id": call_id,
- "set": set_name,
- "case": case_id,
- }
- if call_name is not None:
- entry["call"] = call_name
- entry.update(
- {
- "model": model,
- "endpoint": ENDPOINT,
- "path": path,
- "status": "error",
- "error": {"type": type(error).__name__, "message": str(error)},
- "timing": {"at": datetime.now(UTC).isoformat(timespec="seconds"), "latency_ms": None, "attempts": 1},
- "request": {"method": "POST", "endpoint": ENDPOINT, "path": path, "model": model, "body": body},
- "response": None,
- "recorded": {},
- }
- )
- return entry
+MODELS = (FIRST_MODEL, SECOND_MODEL)
+ROWS = {
+ FIRST_MODEL: "sie__urchade__gliner_multi_pii-v1.jsonl",
+ SECOND_MODEL: "sie__numind__NuNER_Zero.jsonl",
+}
+DEFAULT_DOCUMENT = "1628" # a health insurance claim form, the document the page opens with
-def build_body(case: dict[str, Any]) -> dict[str, Any]:
- return {
- "items": [{"id": case["id"], "text": case["text"]}],
- "params": {"labels": case["labels"]},
- }
+def pick(documents: list[dict[str, Any]], key: str) -> dict[str, Any]:
+ for d in documents:
+ if key in (str(d["index"]), d["uid"]):
+ return d
+ raise SystemExit(f"no document with index or uid {key!r}; indexes run {documents[0]['index']} upward")
-def check(data_dir: Path) -> int:
- """Compare the recorded calls with the ones the inputs imply.
+def requests_for(doc: dict[str, Any], *, whole: bool) -> list[tuple[int, str]]:
+ """(offset, text) for every request one model gets for this document."""
+ spans = windows(doc["text"])
+ parts = [(start, doc["text"][start:end]) for start, end in spans] if len(spans) > 1 else []
+ return [(0, doc["text"]), *parts] if whole or not parts else parts
- A bijection, not a walk over what happens to be there: the expected call
- ids come from inputs/cases.json, one per model per document, so a call that
- is missing, recorded twice or not derivable from any case all fail.
- Checking only the calls present would pass a calls.json with one of them
- deleted.
- """
- cases = load(data_dir / "inputs/cases.json")["cases"]
- calls = load(data_dir / "calls.json")["calls"]
- expected: dict[str, tuple[str, dict[str, Any]]] = {}
+def show(doc: dict[str, Any]) -> None:
+ parts = requests_for(doc, whole=False)
+ print(f"document {doc['index']} ({doc['uid']}, {doc['domain']}): {len(doc['text']):,} characters")
+ print(f"{len(parts)} request(s) per model, {len(parts) * len(MODELS)} in all, to {ENDPOINT}")
for model in MODELS:
- for case in cases:
- expected[f"{model.replace('/', '__')}/{case['id']}"] = (model, case)
-
- recorded: dict[str, dict[str, Any]] = {}
- duplicates: list[str] = []
- for call in calls:
- if call["id"] in recorded:
- duplicates.append(call["id"])
- continue
- recorded[call["id"]] = call
-
- missing = sorted(set(expected) - set(recorded))
- unexpected = sorted(set(recorded) - set(expected))
-
- rebuilt = 0
- mismatched: list[str] = []
- for call_id in sorted(set(expected) & set(recorded)):
- call = recorded[call_id]
- model, case = expected[call_id]
- if call["case"] != case["id"]:
- mismatched.append(f"{call_id}: case {call['case']} differs from {case['id']}")
- elif call["model"] != model:
- mismatched.append(f"{call_id}: model {call['model']} differs from {model}")
- elif build_body(case) != call["request"]["body"]:
- mismatched.append(f"{call_id}: rebuilt body differs from the recorded body")
- elif call["path"] != f"/v1/extract/{model}":
- mismatched.append(f"{call_id}: path {call['path']} differs from /v1/extract/{model}")
- else:
- rebuilt += 1
-
- print(f"{rebuilt} of {len(calls)} recorded requests rebuilt from the inputs and matched")
- print(
- f"{len(expected)} calls expected from {len(cases)} documents across {len(MODELS)} models, {len(recorded)} recorded"
- )
- for call_id in missing:
- print(f"MISSING {call_id}: expected from the inputs, absent from calls.json", file=sys.stderr)
- for call_id in duplicates:
- print(f"DUPLICATE {call_id}: recorded more than once", file=sys.stderr)
- for call_id in unexpected:
- print(f"UNEXPECTED {call_id}: recorded but no case in inputs/cases.json implies it", file=sys.stderr)
- for line in mismatched:
- print(f"MISMATCH {line}", file=sys.stderr)
- if missing or duplicates or unexpected or mismatched:
- return 1
- return 0
+ for offset, text in parts:
+ body = {"items": [{"text": text}], "params": {"labels": REQUEST_LABELS}}
+ print()
+ print(f"POST /v1/extract/{model} (window at character {offset})")
+ print(json.dumps(body, ensure_ascii=False))
-def record(client: SIEClient, model: str, case: dict[str, Any]) -> dict[str, Any]:
- """Send one document through the SDK and return its calls.json entry."""
- body = build_body(case)
- path = f"/v1/extract/{model}"
- requested_at = datetime.now(UTC).isoformat(timespec="seconds")
- started = time.monotonic()
- result = client.extract(model, body["items"][0], labels=body["params"]["labels"])
- latency_ms = round((time.monotonic() - started) * 1000, 1)
- # A 200 can still carry a per-item failure. Never record one as a result.
- if result.get("error"):
- raise CallFailedError(f"{case['id']}: item error {result['error']}")
- if "entities" not in result:
- raise CallFailedError(f"{case['id']}: response carried no entities field")
- # Rebuild the envelope the archived run recorded, so score.py reads a fresh
- # run the same way. The SDK returns the per-item result, not the server's
- # envelope, and surfaces no response headers; both are said so below.
- item = {key: value for key, value in result.items() if key not in ("model", "request")}
- return {
- "id": f"{model.replace('/', '__')}/{case['id']}",
- "set": model.replace("/", "__"),
- "case": case["id"],
- "model": model,
- "endpoint": ENDPOINT,
- "path": path,
- "status": 200,
- "timing": {"at": requested_at, "latency_ms": latency_ms, "attempts": 1},
- "request": {"method": "POST", "endpoint": ENDPOINT, "path": path, "model": model, "body": body},
- "response": {
- "status": 200,
- "body": {"items": [item], "model": result.get("model", model)},
- "shape": "rebuilt from the sie_sdk per-item result; the SDK returns no server envelope and no headers",
- },
- "recorded": {
- "model_revision": client.last_model_revision,
- "retry_count": client.last_retry_count,
- },
- }
+def client() -> SIEClient:
+ api_key = os.environ.get("SIE_API_KEY", "").strip()
+ if not api_key:
+ raise SystemExit("Set SIE_API_KEY. python3 run.py --show needs no key.")
+ from sie_sdk import SIEClient
+ return SIEClient(os.environ.get("SIE_BASE_URL", ENDPOINT), api_key=api_key, timeout_s=300)
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--data", default="data", help="fetched evidence directory")
- parser.add_argument("--check", action="store_true", help="offline check, the default")
- parser.add_argument("--show", metavar="CASE", help="print one request and exit, sending nothing")
- parser.add_argument("--record", action="store_true", help="make live calls (needs SIE_API_KEY)")
- parser.add_argument("--out", default="run-output/calls.json", help="where --record writes")
- args = parser.parse_args()
- data_dir = Path(args.data)
- cases = load(data_dir / "inputs/cases.json")["cases"]
- by_id = {case["id"]: case for case in cases}
+def extract(sie: SIEClient, model: str, offset: int, text: str) -> list[dict[str, Any]]:
+ from sie_sdk.types import Item
- if args.show:
- case = by_id.get(args.show)
- if case is None:
- raise SystemExit(f"Unknown case: {args.show}")
- body = build_body(case)
- shown = [{"model": model, "method": "POST", "path": f"/v1/extract/{model}", "body": body} for model in MODELS]
- print(json.dumps(shown, indent=2, ensure_ascii=False))
- return 0
+ result = sie.extract(model, Item(text=text), labels=REQUEST_LABELS)
+ # Some SDK versions return a per-item failure in result["error"] instead of
+ # raising; an empty entity list there is a failure, not a clean document.
+ if result.get("error"):
+ raise RuntimeError(f"{model}: {result['error']}")
+ return [
+ {
+ "start": e["start"] + offset,
+ "end": e["end"] + offset,
+ "label": e["label"],
+ "score": e.get("score"),
+ "text": e.get("text"),
+ }
+ for e in result.get("entities") or []
+ ]
+
+
+def record(sie: SIEClient, model: str, doc: dict[str, Any], *, whole: bool) -> dict[str, Any]:
+ """One model's output for one document, in the recorded rows' shape."""
+ out: dict[str, Any] = {"whole": [], "windows": []}
+ spans = windows(doc["text"])
+ if whole or len(spans) == 1:
+ out["whole"] = extract(sie, model, 0, doc["text"])
+ if len(spans) > 1:
+ for start, end in spans:
+ out["windows"].append({"offset": start, "entities": extract(sie, model, start, doc["text"][start:end])})
+ return out
+
+
+def masked(text: str, spans: list[dict[str, Any]]) -> str:
+ labels = {}
+ for s in spans:
+ labels.setdefault((s["start"], s["end"]), s["label"])
+ out, at = [], 0
+ for a, b in merge(spans):
+ label = next((lab for (s, e), lab in labels.items() if s == a), "pii")
+ out += [text[at:a], f"[{label.upper()}]"]
+ at = b
+ return "".join([*out, text[at:]])
+
+
+def one(doc: dict[str, Any], evidence: Path) -> int:
+ sie = client()
+ outputs = {model: record(sie, model, doc, whole=False) for model in MODELS}
+ spans = compose(doc["text"], outputs[FIRST_MODEL], outputs[SECOND_MODEL])
+ masks = merge(spans)
+ hits = [covered(doc["text"], masks, g) for g in doc["scoped"]]
+ print(masked(doc["text"], spans))
+ print()
+ print(f"document {doc['index']} ({doc['domain']}): {sum(hits)} of {len(hits)} in-scope gold spans masked")
+ for g, hit in zip(doc["scoped"], hits, strict=True):
+ if not hit:
+ print(f" left readable: {g['label']} {doc['text'][g['start'] : g['end']]!r}")
+ recorded = {m: read_jsonl(evidence / "rows" / ROWS[m]) for m in MODELS}
+ then = compose(
+ doc["text"],
+ *(next(r["output"] for r in recorded[m] if r["index"] == doc["index"]) for m in MODELS),
+ )
+ then_hits = sum(covered(doc["text"], merge(then), g) for g in doc["scoped"])
+ same = {(s["start"], s["end"]) for s in spans} == {(s["start"], s["end"]) for s in then}
+ print(f"recorded run on 2026-09-30: {then_hits} of {len(hits)}; spans {'identical' if same else 'differ'}")
+ return 0
- if not args.record:
- return check(data_dir)
- api_key = os.environ.get("SIE_API_KEY", "").strip()
- if not api_key:
- raise SystemExit("Set SIE_API_KEY to send these calls, or run score.py on the recorded ones instead")
- base_url = os.environ.get("SIE_CLUSTER_URL") or os.environ.get("SIE_BASE_URL") or ENDPOINT
- # Deferred so --check and --show run on a bare `python3` with nothing installed.
- from sie_sdk import SIEClient # noqa: PLC0415
+def run_all(documents: list[dict[str, Any]], out: Path, workers: int) -> int:
+ local = threading.local()
- client = SIEClient(base_url, api_key=api_key, timeout_s=900)
+ def job(model: str, doc: dict[str, Any]) -> dict[str, Any]:
+ if not hasattr(local, "sie"):
+ local.sie = client()
+ try:
+ return {"index": doc["index"], "output": record(local.sie, model, doc, whole=True), "error": None}
+ except Exception as error: # noqa: BLE001 - recorded per row, as the study did
+ return {"index": doc["index"], "output": None, "error": f"{type(error).__name__}: {error}"[:300]}
- calls = []
- failed: list[str] = []
+ client() # fail on a missing key before starting threads
+ out.mkdir(parents=True, exist_ok=True)
+ failed = 0
for model in MODELS:
- for case in cases:
- call_id = f"{model.replace('/', '__')}/{case['id']}"
- try:
- entry = record(client, model, case)
- except Exception as error: # noqa: BLE001
- failed.append(f"{call_id}: {type(error).__name__}: {error}")
- calls.append(
- failure_entry(
- call_id,
- model.replace("/", "__"),
- case["id"],
- model,
- f"/v1/extract/{model}",
- build_body(case),
- error,
- )
- )
- print(f"{model} {case['id']}: FAILED {type(error).__name__}", file=sys.stderr)
- continue
- calls.append(entry)
- print(f"{model} {case['id']}: {entry['timing']['latency_ms']:.0f}ms", file=sys.stderr)
-
- ids = [entry["id"] for entry in calls]
- if len(ids) != len(set(ids)):
- raise SystemExit("duplicate call ids; refusing to write a calls.json two checks could read differently")
-
- out_path = Path(args.out)
- out_path.parent.mkdir(parents=True, exist_ok=True)
- out_path.write_text(
- json.dumps(
- {
- "task": "redact",
- "call_count": len(calls),
- "failed_calls": len(failed),
- "complete": not failed,
- "calls": calls,
- },
- indent=2,
- )
- + "\n",
- encoding="utf-8",
- )
- print(f"wrote {out_path}")
+ with ThreadPoolExecutor(max_workers=workers) as pool:
+ rows = list(pool.map(lambda d, m=model: job(m, d), documents))
+ failed += sum(r["error"] is not None for r in rows)
+ path = out / ROWS[model]
+ path.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8")
+ print(f"{model}: {len(rows)} documents -> {path}")
if failed:
- # A run that failed must not look like a run that succeeded.
- print(f"{len(failed)} of {len(calls)} calls FAILED:", file=sys.stderr)
- for line in failed:
- print(f" {line}", file=sys.stderr)
- print(f'{out_path} records them with status "error" and is not a complete run', file=sys.stderr)
- return 1
- return 0
+ print(f"{failed} document(s) failed; they score as no masks", file=sys.stderr)
+ print(f"Now run: python3 score.py --sie-rows {out}")
+ return 1 if failed else 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--doc", default=DEFAULT_DOCUMENT, help="document index or uid (default %(default)s)")
+ parser.add_argument("--show", action="store_true", help="print the requests for --doc without sending them")
+ parser.add_argument("--all", action="store_true", help="send all 660 documents and write rows files")
+ parser.add_argument("--out", type=Path, default=HERE / "run-output", help="where --all writes")
+ parser.add_argument("--workers", type=int, default=8, help="requests in flight for --all")
+ parser.add_argument("--evidence", type=Path, default=EVIDENCE, help="the directory fetch.py wrote")
+ args = parser.parse_args()
+
+ documents = load_documents(args.evidence)
+ if args.all:
+ return run_all(documents, args.out, args.workers)
+ doc = pick(documents, args.doc)
+ if args.show:
+ show(doc)
+ return 0
+ return one(doc, args.evidence)
if __name__ == "__main__":
diff --git a/examples/redact/score.py b/examples/redact/score.py
index ba20a4861..fffdaf295 100755
--- a/examples/redact/score.py
+++ b/examples/redact/score.py
@@ -1,432 +1,592 @@
#!/usr/bin/env python3
-"""Reproduce the /redact composition from the recorded calls.
+"""Re-derive every figure the /redact page publishes from the recorded run.
python3 fetch.py
- python3 score.py
-
-The page masks personal data with four steps, and this script re-derives each
-one offline from the recorded responses, with no API key and no inference
-spend, exiting nonzero if any figure fails.
-
- 26 of 45 one call to urchade/gliner_multi_pii-v1, whole document
- 33 of 45 splitting what runs past the model's input window
- 41 of 45 unioning a second call to numind/NuNER_Zero
- 45 of 45 masking every later mention of a name already found
-
- 42 of 49 masks that land on a published gold span
- 0 of 29 currency amounts masked, so the figures stay readable
-
-Both models are in the same task's catalog and both were recorded on all twelve
-documents in the same run; the dataset has held all 24 calls since the page was
-first published.
-
-The two sides of every comparison come from different places. The gold spans
-are the benchmark publishers' own annotations, carried in inputs/cases.json.
-The masks are read out of the recorded API responses in calls.json. Neither is
-derived from the other.
-
-Rules, exactly as sie-web's CI applies them:
-
- floor a returned span counts only at score >= 0.6, a threshold the
- caller sets. Five of the run's 168 spans fall below it: `ID #`,
- `File #` and `MIC #`, each covering a field's printed label and
- no value, and the given name `Annibale` twice, which the first
- model also returned at the same offsets inside `Annibale Caboto`.
- --floor-0 re-runs every step with the floor removed; all four
- reach the same figure, so it costs no coverage in this run
- covered a gold span counts as masked only when the UNION of returned
- spans covers every one of its characters, so two overlapping
- returned spans are never counted twice
- merged overlapping spans become one mask covering all of them, which is
- what the caller removes and what the precision figures count
- propagate every other whole-word, case-sensitive occurrence of a token of
- three letters or more from a returned `person` span is masked too
- in schema a mask counts toward the 49 only when its label is one the gold
- schema can express, through GOLD_TO_REQUESTED below
- on gold such a mask counts toward the 42 when it overlaps any gold span
-
-What this script does NOT check: which of the recorded documents the page
-displays, or in what order. That is the page's decision, it changes without the
-run changing, and an example has no way to read the page.
+ python3 score.py # every figure, checked against the recording
+ python3 score.py --no-bootstrap # skip the 95% intervals
+ python3 score.py --sie-rows run-output # score your own SIE run from run.py --all
+
+Standard library only. No API key, no network, no inference spend.
+
+The run: 660 documents from the English test split of
+gretelai/synthetic_pii_finance_multilingual, 1,792 in-scope personal-data
+spans, five arms. The figure is coverage recall: the share of in-scope gold
+spans whose every non-space character sits under the union of an arm's masks,
+whatever label the arm gave it.
+
+SIE's arm is a composition of two models on https://api.superlinked.com:
+
+1. `urchade/gliner_multi_pii-v1` and `numind/NuNER_Zero`, the same 36 labels,
+ each span kept at score >= 0.6. A document over 300 words is sent as
+ 300-word windows with a 50-word overlap, and each window's offset is added
+ back to its spans.
+2. The two models' spans unioned.
+3. Every other whole-word, case-sensitive occurrence of any three-letter or
+ longer token of a returned `person` span masked, in the caller's code.
+
+An LLM returns strings, not offsets, so every occurrence of a returned string
+is masked. Presidio and OpenAI Privacy Filter return offsets; every span is
+masked.
+
+Every figure is compared with the recorded results file and with the value the
+page publishes. A mismatch is a failure and the script exits nonzero.
"""
from __future__ import annotations
import argparse
import json
+import random
import re
import sys
-from collections.abc import Callable
from pathlib import Path
from typing import Any
-HTTP_OK = 200
+HERE = Path(__file__).resolve().parent
+EVIDENCE = HERE / "evidence"
+SEED = 20260930
+RESAMPLES = 2000
FIRST_MODEL = "urchade/gliner_multi_pii-v1"
SECOND_MODEL = "numind/NuNER_Zero"
-FIRST_SET = "urchade__gliner_multi_pii-v1"
-SECOND_SET = "numind__NuNER_Zero"
-MODEL_SETS = (FIRST_SET, SECOND_SET)
-
-# The confidence floor, and the person label the propagation step reads.
SCORE_FLOOR = 0.6
+WINDOW_WORDS = 300
+WINDOW_OVERLAP = 50
+# GLiNER's WhitespaceTokenSplitter: a run of word characters, or one other
+# character. This is the unit its 384-word input window counts.
+GLINER_WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")
+
+# The 36 labels every request named, SIE and LLM alike: 34 for HIPAA Safe
+# Harbor identifiers and credentials, plus two for Gretel types the 34 have no
+# word for.
+REQUEST_LABELS = [
+ "person", "street address", "city", "county", "postal code", "gps coordinates", "date of birth",
+ "phone number", "fax number", "email address", "url", "ip address", "mac address", "social security number",
+ "national id number", "tax id number", "medical record number", "health plan beneficiary number",
+ "account number", "credit card number", "cvv", "pin", "password", "api key", "http cookie", "username",
+ "customer id", "employee id", "certificate or license number", "license plate",
+ "vehicle identification number", "device identifier", "biometric identifier", "unique identifier",
+ "passport number", "driver's license number",
+] # fmt: skip
PERSON_LABEL = "person"
+LLM_PROMPT = (
+ "Find every piece of personally identifiable information in the text. Use these types: {labels}. "
+ "Copy each mention exactly as it appears in the text. Return an empty list if there is none."
+)
+
+# Gretel labels that count: the HIPAA Safe Harbor identifiers the set labels,
+# plus credentials. Company names, dates, times, routing numbers and SWIFT
+# codes do not.
+IN_SCOPE = frozenset(
+ {
+ "name", "first_name", "last_name", "street_address", "local_latlng", "date_of_birth", "phone_number",
+ "email", "ssn", "bban", "iban", "credit_card_number", "driver_license_number", "passport_number",
+ "employee_id", "customer_id", "user_name", "ipv4", "ipv6", "password", "account_pin",
+ "credit_card_security_code", "api_key",
+ }
+) # fmt: skip
+# In-scope Gretel labels with no AWS Comprehend DetectPiiEntities type in AWS's
+# documentation (read 2026-09-30).
+NO_COMPREHEND_TYPE = frozenset({"local_latlng", "employee_id", "customer_id"})
+
+# A name token is three letters or more, matched whole-word and case-sensitively.
NAME_TOKEN = re.compile(r"[^\W\d_]{3,}")
+# Currency amounts, for the "what stays readable" figure. It also matches some IP addresses.
+AMOUNT = re.compile(r"\$\s?\d[\d,]*(?:\.\d+)?|\d[\d.,]*\s?EUR|(?<![\w-])\d+\.\d{2}(?![\d-])")
-# Benchmark gold labels mapped to the label names the requests used.
-GOLD_TO_REQUESTED = {
- "first_name": "person",
- "last_name": "person",
- "name": "person",
- "email": "email",
- "ssn": "social security number",
- "phone_number": "phone number",
- "street_address": "address",
- "date_of_birth": "date of birth",
- "medical_record_number": "medical record number",
- "driver_license_number": "driver's license number",
- "password": "password",
- "bban": "account number",
- "iban": "iban",
- "swift_bic_code": "bank identifier code",
- "employee_id": "employee id",
- "credit_debit_card": "credit card number",
+COMPOSITION = "sie"
+# (arm id, display name, rows file). The arm id is the key in results/gretel-main_results.json.
+ARMS = [
+ (COMPOSITION, "SIE (GLiNER PII + NuNER Zero, composed)", None),
+ ("llm:claude-haiku-4-5", "Claude Haiku 4.5", "llm__claude-haiku-4-5.jsonl"),
+ ("llm:gpt-6-luna", "GPT-6 Luna", "llm__gpt-6-luna.jsonl"),
+ ("privacy-filter", "OpenAI Privacy Filter", "privacy-filter.jsonl"),
+ ("presidio", "Microsoft Presidio", "presidio.jsonl"),
+ (f"sie:{FIRST_MODEL}", "SIE GLiNER PII alone, one request", "sie__urchade__gliner_multi_pii-v1.jsonl"),
+ (f"sie:{SECOND_MODEL}", "SIE NuNER Zero alone, one request", "sie__numind__NuNER_Zero.jsonl"),
+]
+RECORDED_KEY = {COMPOSITION: "sie-composition"}
+
+# What the page publishes: spans masked, of 1,792, per arm.
+PUBLISHED_MASKED = {
+ COMPOSITION: 1591,
+ "llm:claude-haiku-4-5": 1490,
+ "llm:gpt-6-luna": 1448,
+ "privacy-filter": 1214,
+ "presidio": 859,
+}
+PUBLISHED_GOLD = 1792
+PUBLISHED_DOCUMENTS = 660
+
+# --- price inputs, list prices read on 2026-09-30 ------------------------------------------------------------------
+MONTHLY_DOCUMENTS = 1_000_000
+# SIE: $ per 1M input tokens, and the tokens each model's tokenizer counts in the 660 documents.
+SIE_PRICE_PER_1M_TOKENS = {FIRST_MODEL: 0.04, SECOND_MODEL: 0.05}
+SIE_TOKENS = {FIRST_MODEL: 238_605, SECOND_MODEL: 227_727}
+# AWS Comprehend DetectPiiEntities: cheapest tier, per 100-character unit, 3-unit minimum per request,
+# units counted as characters over 100 with no rounding up.
+COMPREHEND_PER_UNIT = 0.000025
+COMPREHEND_MIN_UNITS = 3
+COMPREHEND_CHARS_PER_UNIT = 100
+# LLMs: $ per 1M input and output tokens, times the tokens each provider reported for the run.
+LLM_PRICES = {"llm:gpt-6-luna": (0.10, 0.50), "llm:claude-haiku-4-5": (1.00, 5.00)}
+# Self-hosted arms: Modal list price per second of the container, at the throughput measured in
+# results/e2_results.json, divided by 75% utilisation and times 1.75 for region.
+L4_PER_S = 0.000222
+CORE_PER_S = 0.0000131
+GIB_PER_S = 0.00000222
+UTILISATION = 0.75
+REGION_MULTIPLIER = 1.75
+CONTAINERS = {
+ "presidio": {"gpus": 0, "cores": 8, "gib": 16},
+ "privacy-filter": {"gpus": 1, "cores": 8, "gib": 32},
+}
+COMPREHEND = "aws-comprehend"
+PUBLISHED_MONTHLY_USD = {
+ COMPOSITION: 32,
+ "presidio": 3,
+ "privacy-filter": 23,
+ "llm:gpt-6-luna": 113,
+ "llm:claude-haiku-4-5": 1450,
+ COMPREHEND: 351,
}
-AMOUNT = re.compile(r"\$\s?\d[\d,]*(?:\.\d+)?|\d[\d.,]*\s?EUR|(?<![\w-])\d+\.\d{2}(?![\d-])")
+# --- the composition -----------------------------------------------------------------------------------------------
+
+
+def windows(text: str) -> list[tuple[int, int]]:
+ """300-word windows with a 50-word overlap as (start, end) character ranges; one range for a short text."""
+ words = [m.span() for m in GLINER_WORD.finditer(text)]
+ if len(words) <= WINDOW_WORDS:
+ return [(0, len(text))]
+ out = []
+ step = WINDOW_WORDS - WINDOW_OVERLAP
+ for first in range(0, len(words), step):
+ last = min(first + WINDOW_WORDS, len(words)) - 1
+ out.append((words[first][0], words[last][1]))
+ if last == len(words) - 1:
+ break
+ return out
+
+
+def sie_spans(output: dict[str, Any] | None, *, windowed: bool, floor: float | None) -> list[dict[str, Any]]:
+ """One SIE model's spans for a document: the whole-document request, or its windows when it has them."""
+ output = output or {}
+ if windowed and output.get("windows"):
+ entities = [e for w in output["windows"] for e in w["entities"]]
+ else:
+ entities = output.get("whole") or []
+ if floor is not None:
+ entities = [e for e in entities if (e.get("score") or 0) >= floor]
+ return entities
+
+
+def propagated(text: str, spans: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Every other whole-word, case-sensitive occurrence of a name token not already inside a span."""
+ tokens = sorted(
+ {t for s in spans if s["label"] == PERSON_LABEL for t in NAME_TOKEN.findall(text[s["start"] : s["end"]])}
+ )
+ added = []
+ for token in tokens:
+ pattern = re.compile(r"(?<![^\W\d_])" + re.escape(token) + r"(?![^\W\d_])")
+ for m in pattern.finditer(text):
+ if any(s["start"] <= m.start() and s["end"] >= m.end() for s in spans):
+ continue
+ added.append({"start": m.start(), "end": m.end(), "label": PERSON_LABEL, "derived": True})
+ return added
-# GLiNER counts words with this rule, so the page's "564-word chat" and its
-# "384 words or fewer" window are both derived here rather than taken on trust.
-GLINER_WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")
-WINDOW_CASE = "gretel_customer_support_log"
-WINDOW_TAIL = "gretel_customer_support_log_tail"
-
-EXPECTED = {
- "gold_spans": 45,
- "step_one_call": 26,
- "step_chunked": 33,
- "step_two_models": 41,
- "step_propagated": 45,
- "masks_in_gold_schema": 49,
- "masks_on_gold": 42,
- "propagated_masks": 6,
- "amounts_masked": 0,
- "amounts_found": 29,
- "window_total": 11,
- "window_one_request": 2,
- "window_composed": 11,
- "window_past": 7,
- "window_words_total": 564,
- "window_words_in_window": 384,
-}
+def compose(text: str, first: dict[str, Any] | None, second: dict[str, Any] | None) -> list[dict[str, Any]]:
+ """Both models' spans at score >= 0.6, windowed when windows were sent, unioned, then name propagation."""
+ merged: dict[tuple[int, int, str], dict[str, Any]] = {}
+ for output in (first, second):
+ for e in sie_spans(output, windowed=True, floor=SCORE_FLOOR):
+ key = (e["start"], e["end"], e["label"])
+ if key not in merged or (e.get("score") or 0) > (merged[key].get("score") or 0):
+ merged[key] = dict(e)
+ spans = sorted(merged.values(), key=lambda s: (s["start"], s["end"]))
+ return sorted(spans + propagated(text, spans), key=lambda s: (s["start"], s["end"]))
+
+
+def occurrences(text: str, needle: str) -> list[tuple[int, int]]:
+ out: list[tuple[int, int]] = []
+ if not needle:
+ return out
+ at = text.find(needle)
+ while at != -1:
+ out.append((at, at + len(needle)))
+ at = text.find(needle, at + 1)
+ return out
+
+
+def llm_spans(text: str, output: dict[str, Any] | None) -> tuple[list[dict[str, Any]], int, bool]:
+ """Masks from an LLM's returned strings (every occurrence), the count of strings found nowhere in the text,
+ and whether the output parsed."""
+ output = output or {}
+ try:
+ entities = list(json.loads(output.get("text") or "").get("entities") or [])
+ parsed = True
+ except (json.JSONDecodeError, AttributeError):
+ entities, parsed = [], False
+ spans, seen, unmatched = [], set(), 0
+ for e in entities:
+ found = occurrences(text, str(e.get("text", "")))
+ unmatched += not found
+ for s, t in found:
+ if (s, t) not in seen:
+ seen.add((s, t))
+ spans.append({"start": s, "end": t, "label": str(e.get("type", ""))})
+ return spans, unmatched, parsed
+
+
+# --- scoring -------------------------------------------------------------------------------------------------------
+
+
+def merge(spans: list[dict[str, Any]]) -> list[tuple[int, int]]:
+ """Overlapping spans become one mask covering all of them."""
+ out: list[list[int]] = []
+ for s in sorted(spans, key=lambda s: (s["start"], s["end"])):
+ if out and s["start"] < out[-1][1]:
+ out[-1][1] = max(out[-1][1], s["end"])
+ else:
+ out.append([s["start"], s["end"]])
+ return [(a, b) for a, b in out]
+
+
+def hidden_in(masks: list[tuple[int, int]], gold: dict[str, Any]) -> set[int]:
+ hidden: set[int] = set()
+ for a, b in masks:
+ if a < gold["end"] and b > gold["start"]:
+ hidden.update(range(max(a, gold["start"]), min(b, gold["end"])))
+ return hidden
+
+
+def covered(text: str, masks: list[tuple[int, int]], gold: dict[str, Any]) -> bool:
+ """Every non-space character of the gold span is under a mask."""
+ hidden = hidden_in(masks, gold)
+ return all(i in hidden or text[i].isspace() for i in range(gold["start"], gold["end"]))
+
+
+_ONE_WORD_STATES = (
+ "Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois "
+ "Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri "
+ "Montana Nebraska Nevada Ohio Oklahoma Oregon Pennsylvania Tennessee Texas Utah Vermont Virginia Washington "
+ "Wisconsin Wyoming Alberta Manitoba Ontario Quebec Saskatchewan Yukon Nunavut"
+)
+_STATES = [
+ *_ONE_WORD_STATES.split(),
+ "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Rhode Island",
+ "South Carolina", "South Dakota", "West Virginia", "District of Columbia", "British Columbia", "New Brunswick",
+ "Nova Scotia", "Prince Edward Island", "Northwest Territories", "Newfoundland and Labrador",
+] # fmt: skip
+_CODE_WORDS = (
+ "AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR "
+ "PA RI SC SD TN TX UT VT VA WA WV WI WY DC AB BC MB NB NL NS NT NU ON PE QC SK YT USA US UK"
+)
+_CODES = _CODE_WORDS.split()
+_COUNTRIES = (
+ "United States", "United States of America", "United Kingdom", "Canada", "Australia", "Germany", "France",
+ "Spain", "Italy", "Netherlands", "Sweden", "Ireland", "India", "China", "Japan", "Mexico", "Brazil",
+ "New Zealand", "Singapore", "Switzerland", "Belgium", "Austria", "Norway", "Denmark", "Finland", "Poland",
+ "Portugal", "South Africa", "Nigeria", "Kenya", "Philippines", "Malaysia", "Indonesia", "South Korea",
+) # fmt: skip
+# The words a span may leave readable and still count under the state-and-country-excused figure.
+EXCUSED = re.compile(
+ r"\b(?:" + "|".join(re.escape(w) for w in sorted([*_STATES, *_COUNTRIES, *_CODES], key=len, reverse=True)) + r")\b"
+)
+
+
+def covered_excusing_state(text: str, masks: list[tuple[int, int]], gold: dict[str, Any]) -> bool:
+ """As covered(), except a U.S. state, Canadian province, country or punctuation may stay readable."""
+ hidden = hidden_in(masks, gold)
+ for m in EXCUSED.finditer(text, gold["start"], gold["end"]):
+ hidden.update(range(m.start(), m.end()))
+ return all(i in hidden or not text[i].isalnum() for i in range(gold["start"], gold["end"]))
+
+
+def doc_stats(doc: dict[str, Any], spans: list[dict[str, Any]], unmatched: int = 0) -> dict[str, int]:
+ """Per-document counts. `unmatched` is an LLM's strings found nowhere in the text: each counts as one
+ mask and one exact false positive, since the LLM claimed personal data that is not there."""
+ text = doc["text"]
+ masks = merge(spans)
+ scoped = doc["scoped"]
+ amounts = [m.span() for m in AMOUNT.finditer(text)]
+ exact_pred = {(s["start"], s["end"]) for s in spans}
+ exact_gold = {(g["start"], g["end"]) for g in scoped}
+ tp = len(exact_pred & exact_gold)
+ return {
+ "gold": len(scoped),
+ "covered": sum(covered(text, masks, g) for g in scoped),
+ "covered_excused": sum(covered_excusing_state(text, masks, g) for g in scoped),
+ "masks": len(masks) + unmatched,
+ # A mask counts toward overlap precision when it touches any gold span, in scope or not.
+ "masks_on_gold": sum(any(a < g["end"] and b > g["start"] for g in doc["gold"]) for a, b in masks),
+ "amounts": len(amounts),
+ "amounts_masked": sum(any(a < e and b > s for a, b in masks) for s, e in amounts),
+ "exact_tp": tp,
+ "exact_fp": len(exact_pred) - tp + unmatched,
+ "exact_fn": len(exact_gold) - tp,
+ }
+
+
+def summarise(stats: list[dict[str, int]]) -> dict[str, Any]:
+ total = {k: sum(d[k] for d in stats) for k in stats[0]}
+ tp, fp, fn = total["exact_tp"], total["exact_fp"], total["exact_fn"]
+ p = tp / (tp + fp) if tp + fp else 0.0
+ r = tp / (tp + fn) if tp + fn else 0.0
+ return {
+ **total,
+ "coverage_recall": total["covered"] / total["gold"],
+ "coverage_recall_state_excused": total["covered_excused"] / total["gold"],
+ "overlap_precision": total["masks_on_gold"] / total["masks"] if total["masks"] else 0.0,
+ "exact_f1": 2 * p * r / (p + r) if p + r else 0.0,
+ }
+
+
+def bootstrap(per_arm: dict[str, list[dict[str, int]]]) -> dict[str, dict[str, list[float]]]:
+ """Paired document-cluster bootstrap: the same resampled documents for every arm in each draw."""
+ n = len(per_arm[COMPOSITION])
+ rng = random.Random(SEED)
+ gold = [d["gold"] for d in per_arm[COMPOSITION]]
+ hits = {arm: [d["covered"] for d in stats] for arm, stats in per_arm.items()}
+ hits_excused = {arm: [d["covered_excused"] for d in stats] for arm, stats in per_arm.items()}
+ draws: dict[str, list[float]] = {arm: [] for arm in per_arm}
+ diffs: dict[str, list[float]] = {arm: [] for arm in per_arm if arm != COMPOSITION}
+ diffs_excused: dict[str, list[float]] = {arm: [] for arm in diffs}
+ for _ in range(RESAMPLES):
+ pick = [rng.randrange(n) for _ in range(n)]
+ denominator = sum(gold[i] for i in pick)
+ value = {arm: sum(h[i] for i in pick) / denominator for arm, h in hits.items()}
+ excused = {arm: sum(h[i] for i in pick) / denominator for arm, h in hits_excused.items()}
+ for arm in per_arm:
+ draws[arm].append(value[arm])
+ for arm, series in diffs.items():
+ series.append(value[COMPOSITION] - value[arm])
+ diffs_excused[arm].append(excused[COMPOSITION] - excused[arm])
+
+ def ci(xs: list[float]) -> list[float]:
+ xs = sorted(xs)
+ return [xs[int(0.025 * len(xs))], xs[int(0.975 * len(xs)) - 1]]
+
+ return {
+ "coverage_ci95": {a: ci(v) for a, v in draws.items()},
+ "composition_minus_ci95": {a: ci(v) for a, v in diffs.items()},
+ "composition_minus_state_excused_ci95": {a: ci(v) for a, v in diffs_excused.items()},
+ }
-def load(path: Path) -> Any:
+# --- price ---------------------------------------------------------------------------------------------------------
+
+
+def monthly_usd(
+ documents: list[dict[str, Any]], rows: dict[str, dict[int, dict[str, Any]]], e2: dict[str, Any]
+) -> dict[str, float]:
+ """$ a month for MONTHLY_DOCUMENTS documents like the study's, per arm."""
+ n = len(documents)
+ per_document = {COMPOSITION: sum(SIE_TOKENS[m] * SIE_PRICE_PER_1M_TOKENS[m] / 1e6 for m in SIE_TOKENS) / n}
+ units = sum(max(COMPREHEND_MIN_UNITS, len(d["text"]) / COMPREHEND_CHARS_PER_UNIT) for d in documents)
+ per_document[COMPREHEND] = units * COMPREHEND_PER_UNIT / n
+ for arm, (price_in, price_out) in LLM_PRICES.items():
+ tokens_in = sum((r["output"] or {}).get("tokens_in", 0) for r in rows[arm].values())
+ tokens_out = sum((r["output"] or {}).get("tokens_out", 0) for r in rows[arm].values())
+ per_document[arm] = (tokens_in * price_in + tokens_out * price_out) / 1e6 / n
+ for arm, box in CONTAINERS.items():
+ per_second = box["gpus"] * L4_PER_S + box["cores"] * CORE_PER_S + box["gib"] * GIB_PER_S
+ per_second = per_second / UTILISATION * REGION_MULTIPLIER
+ per_document[arm] = per_second / e2["self_host"][arm]["documents_per_second"]
+ return {arm: usd * MONTHLY_DOCUMENTS for arm, usd in per_document.items()}
+
+
+# --- io ------------------------------------------------------------------------------------------------------------
+
+
+def read_jsonl(path: Path) -> list[dict[str, Any]]:
+ if not path.exists():
+ raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
+
+
+def read_json(path: Path) -> Any:
if not path.exists():
raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
return json.loads(path.read_text(encoding="utf-8"))
-def keep_all(_call: dict[str, Any]) -> bool:
- """Every recorded call counts toward this task's figures."""
- return True
+def load_documents(evidence: Path) -> list[dict[str, Any]]:
+ documents = read_jsonl(evidence / "inputs" / "gretel-main.jsonl")
+ for d in documents:
+ d["scoped"] = [g for g in d["gold"] if g["label"] in IN_SCOPE]
+ return documents
-def scored_calls(payload: dict[str, Any], keep: Callable[[dict[str, Any]], bool]) -> list[dict[str, Any]]:
- """The calls the figure is computed from, refusing anything that failed.
+def load_rows(path: Path, documents: list[dict[str, Any]]) -> dict[int, dict[str, Any]]:
+ rows = {r["index"]: r for r in read_jsonl(path)}
+ if set(rows) != {d["index"] for d in documents}:
+ raise SystemExit(f"{path}: rows do not match the {len(documents)} documents")
+ return rows
- A recorder that hit an error writes the call with status "error" and sets
- `complete` to false. Scoring such a file would turn a failed run into a
- published number, so it stops here instead.
- """
- if payload.get("complete") is False:
- failed = payload.get("failed_calls", "some")
- raise SystemExit(f"refusing to score: {failed} calls in this calls.json failed, so it is not a complete run")
- calls = [call for call in payload["calls"] if keep(call)]
- broken = [call["id"] for call in calls if call.get("status") != HTTP_OK]
- if broken:
- raise SystemExit("refusing to score calls that did not return 200: " + ", ".join(sorted(broken)))
- return calls
+def arm_spans(
+ arm: str, doc: dict[str, Any], rows: dict[str, dict[int, dict[str, Any]]]
+) -> tuple[list[dict[str, Any]], int]:
+ """An arm's spans for one document, and the count of LLM strings found nowhere in it."""
+ if arm == COMPOSITION:
+ first = rows[f"sie:{FIRST_MODEL}"][doc["index"]]["output"]
+ second = rows[f"sie:{SECOND_MODEL}"][doc["index"]]["output"]
+ return compose(doc["text"], first, second), 0
+ record = rows[arm][doc["index"]]
+ if record.get("error") is not None or record.get("output") is None:
+ return [], 0
+ if arm.startswith("sie:"):
+ return sie_spans(record["output"], windowed=False, floor=None), 0
+ if arm.startswith("llm:"):
+ spans, unmatched, _ = llm_spans(doc["text"], record["output"])
+ return spans, unmatched
+ return list(record["output"]["spans"]), 0
-def covered(entities: list[dict[str, Any]], gold: dict[str, Any]) -> bool:
- """True when the union of returned spans covers every character of gold."""
- overlaps = sorted(
- (max(entity["start"], gold["start"]), min(entity["end"], gold["end"]))
- for entity in entities
- if max(entity["start"], gold["start"]) < min(entity["end"], gold["end"])
- )
- reached = gold["start"]
- for start, end in overlaps:
- if start > reached:
- return False
- reached = max(reached, end)
- if reached >= gold["end"]:
- return True
- return False
-
-
-def mapped_gold(case: dict[str, Any]) -> list[dict[str, Any]]:
- return [span for span in case.get("gold_spans", []) if GOLD_TO_REQUESTED.get(span["label"], "") in case["labels"]]
-
-
-def returned_spans(
- entities: dict[tuple[str, str], list[dict[str, Any]]],
- cases: dict[str, dict[str, Any]],
- case_id: str,
- *,
- sets: tuple[str, ...] = MODEL_SETS,
- chunked: bool = True,
- floor: float = SCORE_FLOOR,
-) -> list[dict[str, Any]]:
- """Spans the named models returned, in the parent document's own offsets.
-
- `chunked` False reads only the whole-document request, which is the
- single-request regime the first step reports.
- """
- parts: list[tuple[str, int]] = [(case_id, 0)]
- if chunked:
- parts += sorted(
- ((case["id"], case["parent_offset"]) for case in cases.values() if case.get("parent_case") == case_id),
- key=lambda part: part[1],
- )
- merged: dict[tuple[int, int, str], dict[str, Any]] = {}
- for part_id, offset in parts:
- for model_set in sets:
- for entity in entities[(model_set, part_id)]:
- if entity["score"] < floor:
- continue
- span = {
- **entity,
- "start": entity["start"] + offset,
- "end": entity["end"] + offset,
- "derived": False,
- }
- key = (span["start"], span["end"], span["label"])
- if key not in merged or merged[key]["score"] < span["score"]:
- merged[key] = span
- return sorted(merged.values(), key=lambda span: (span["start"], span["end"]))
-
-
-def propagated_spans(text: str, spans: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """Every other whole-word, case-sensitive mention of a returned name."""
- tokens = sorted(
- {token for span in spans if span["label"] == PERSON_LABEL for token in NAME_TOKEN.findall(span["text"])}
- )
- added: list[dict[str, Any]] = []
- for token in tokens:
- pattern = re.compile(r"(?<![^\W\d_])" + re.escape(token) + r"(?![^\W\d_])")
- for match in pattern.finditer(text):
- if any(span["start"] <= match.start() and span["end"] >= match.end() for span in spans):
- continue
- added.append(
- {
- "text": token,
- "label": PERSON_LABEL,
- "score": None,
- "start": match.start(),
- "end": match.end(),
- "derived": True,
- }
- )
- return sorted(added, key=lambda span: span["start"])
-
-
-def composed_spans(
- entities: dict[tuple[str, str], list[dict[str, Any]]],
- cases: dict[str, dict[str, Any]],
- case_id: str,
- floor: float = SCORE_FLOOR,
-) -> list[dict[str, Any]]:
- spans = returned_spans(entities, cases, case_id, floor=floor)
- added = propagated_spans(cases[case_id]["text"], spans)
- return sorted(spans + added, key=lambda span: (span["start"], span["end"]))
-
-
-def merged_masks(text: str, spans: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """Overlapping spans collapsed into one mask each.
-
- Two models rarely agree on where a value ends. Keeping whichever span
- sorted first masked the shorter of two that start together, which left
- ", M.D." readable after a masked name and left the last character of a
- password readable on the policyholder letter.
- """
- masks: list[dict[str, Any]] = []
- for span in sorted(spans, key=lambda item: (item["start"], item["end"])):
- if masks and span["start"] < masks[-1]["end"]:
- masks[-1]["end"] = max(masks[-1]["end"], span["end"])
- masks[-1]["spans"].append(span)
- continue
- masks.append({"start": span["start"], "end": span["end"], "spans": [span]})
- for mask in masks:
- best = max(mask["spans"], key=lambda span: span["score"] or 0)
- mask["label"] = best["label"]
- mask["text"] = text[mask["start"] : mask["end"]]
- return masks
+
+# --- output --------------------------------------------------------------------------------------------------------
+
+
+class Checks:
+ def __init__(self) -> None:
+ self.failed: list[str] = []
+
+ def equal(self, what: str, got: Any, expected: Any) -> None:
+ if got != expected:
+ self.failed.append(f"{what}: got {got}, expected {expected}")
+
+
+def pct(x: float) -> str:
+ return f"{100 * x:.1f}%"
+
+
+def points(ci: list[float]) -> str:
+ return f"{100 * ci[0]:+.1f} to {100 * ci[1]:+.1f} points"
def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--data", default="data", help="fetched evidence directory")
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--evidence", type=Path, default=EVIDENCE, help="the directory fetch.py wrote")
+ parser.add_argument("--no-bootstrap", action="store_true", help="skip the 95%% intervals")
parser.add_argument(
- "--floor-0",
- action="store_true",
- help="score every step with the confidence floor removed, to show what it costs",
+ "--sie-rows",
+ type=Path,
+ help="score the two SIE rows files run.py --all wrote in this directory instead of the recorded ones; "
+ "figures are printed, not checked",
)
args = parser.parse_args()
- floor = 0.0 if args.floor_0 else SCORE_FLOOR
- if args.floor_0:
- print("confidence floor removed: every figure below is scored at 0.0\n")
- data_dir = Path(args.data)
-
- cases = {case["id"]: case for case in load(data_dir / "inputs/cases.json")["cases"]}
- entities: dict[tuple[str, str], list[dict[str, Any]]] = {}
- for call in scored_calls(load(data_dir / "calls.json"), keep_all):
- key = (call["set"], call["case"])
- if key in entities:
- print(f"two {call['set']} calls recorded for {call['case']}", file=sys.stderr)
- return 1
- entities[key] = call["response"]["body"]["items"][0]["entities"]
-
- missing = [
- f"{model_set}/{case_id}"
- for model_set in MODEL_SETS
- for case_id in cases
- if (model_set, case_id) not in entities
- ]
- if missing:
- print(f"no call recorded for: {', '.join(missing)}", file=sys.stderr)
- return 1
-
- parents = [case_id for case_id, case in cases.items() if not case.get("parent_case")]
- benchmark = [case_id for case_id in parents if cases[case_id].get("gold_spans")]
-
- # --- the four steps ----------------------------------------------------
- steps = {"step_one_call": 0, "step_chunked": 0, "step_two_models": 0, "step_propagated": 0}
- totals = {"gold_spans": 0, "masks_in_gold_schema": 0, "masks_on_gold": 0}
- per_document: list[tuple[str, int, int, int]] = []
- for case_id in benchmark:
- case = cases[case_id]
- gold = mapped_gold(case)
- one_call = returned_spans(entities, cases, case_id, sets=(FIRST_SET,), chunked=False, floor=floor)
- chunked = returned_spans(entities, cases, case_id, sets=(FIRST_SET,), floor=floor)
- two_models = returned_spans(entities, cases, case_id, floor=floor)
- composed = composed_spans(entities, cases, case_id, floor=floor)
-
- totals["gold_spans"] += len(gold)
- steps["step_one_call"] += sum(1 for span in gold if covered(one_call, span))
- steps["step_chunked"] += sum(1 for span in gold if covered(chunked, span))
- steps["step_two_models"] += sum(1 for span in gold if covered(two_models, span))
- composed_hits = sum(1 for span in gold if covered(composed, span))
- steps["step_propagated"] += composed_hits
- per_document.append((case_id, len(gold), sum(1 for span in gold if covered(one_call, span)), composed_hits))
-
- requested = set(case["labels"])
- for mask in merged_masks(case["text"], composed):
- if mask["label"] not in requested:
- continue
- totals["masks_in_gold_schema"] += 1
- if any(mask["start"] < span["end"] and span["start"] < mask["end"] for span in gold):
- totals["masks_on_gold"] += 1
-
- print(f"benchmark documents scored: {len(benchmark)}")
- for case_id, gold_count, one_call, composed_hits in per_document:
- print(f" {case_id:<36} {one_call} of {gold_count} in one call, {composed_hits} composed")
-
- print("\npublished PII spans masked, by step:")
- total = totals["gold_spans"]
- print(f" {steps['step_one_call']:>2} of {total} one call to {FIRST_MODEL}, whole document")
- print(f" {steps['step_chunked']:>2} of {total} splitting what runs past the model's input window")
- print(f" {steps['step_two_models']:>2} of {total} unioning a second call to {SECOND_MODEL}")
- print(f" {steps['step_propagated']:>2} of {total} masking every later mention of a name already found")
-
- unjudged = totals["masks_in_gold_schema"] - totals["masks_on_gold"]
- print(f"\n{totals['masks_on_gold']} of {totals['masks_in_gold_schema']} masks land on a published gold span")
- print(f"{unjudged} fall outside them, so neither benchmark can confirm or refute those")
-
- # --- what the propagation step added, over every recorded document -----
- propagated: list[str] = []
- for case_id in parents:
- spans = returned_spans(entities, cases, case_id, floor=floor)
- propagated += [span["text"] for span in propagated_spans(cases[case_id]["text"], spans)]
- print(f"\nthe propagation step added {len(propagated)} masks: {', '.join(sorted(set(propagated)))}")
-
- # --- amounts left readable, over every recorded document ---------------
- amounts = {"found": 0, "masked": 0}
- for case_id in parents:
- text = cases[case_id]["text"]
- spans = composed_spans(entities, cases, case_id, floor=floor)
- for match in AMOUNT.finditer(text):
- amounts["found"] += 1
- if any(span["start"] < match.end() and match.start() < span["end"] for span in spans):
- amounts["masked"] += 1
- print(
- f"\n{amounts['masked']} of {amounts['found']} currency amounts masked"
- f" across the {len(parents)} recorded documents"
- )
+ replay = args.sie_rows is None
+
+ documents = load_documents(args.evidence)
+ rows: dict[str, dict[int, dict[str, Any]]] = {}
+ for arm, _, name in ARMS:
+ if name is not None:
+ source = args.sie_rows if not replay and arm.startswith("sie:") else args.evidence / "rows"
+ rows[arm] = load_rows(source / name, documents)
+ recorded = read_json(args.evidence / "results" / "gretel-main_results.json")
+ tokens = read_json(args.evidence / "results" / "gretel-main_tokens.json")
+ e2 = read_json(args.evidence / "results" / "e2_results.json")
+ check = Checks()
+
+ per_arm = {arm: [doc_stats(d, *arm_spans(arm, d, rows)) for d in documents] for arm, _, _ in ARMS}
+ summary = {arm: summarise(stats) for arm, stats in per_arm.items()}
+ gold = summary[COMPOSITION]["gold"]
+ check.equal("documents", len(documents), PUBLISHED_DOCUMENTS)
+ check.equal("in-scope gold spans", gold, PUBLISHED_GOLD)
+ check.equal("in-scope gold spans (recorded)", gold, recorded["gold_spans"])
+
+ print(f"{len(documents)} documents, {gold:,} in-scope personal-data spans")
+ print()
+ print(f"{'Arm':<42} {'Masked':>16} {'Coverage':>9} {'State excused':>14} {'Precision':>10} {'Exact F1':>9}")
+ for arm, name, _ in ARMS:
+ s = summary[arm]
+ print(
+ f"{name:<42} {s['covered']:>7,} of {gold:,} {pct(s['coverage_recall']):>9} "
+ f"{pct(s['coverage_recall_state_excused']):>14} {s['overlap_precision']:>10.3f} {s['exact_f1']:>9.3f}"
+ )
+ if not replay:
+ continue
+ want = recorded["arms"][RECORDED_KEY.get(arm, arm)]
+ for key in ("covered", "masks", "amounts_masked"):
+ check.equal(f"{name} {key}", s[key], want[key])
+ for key in ("coverage_recall", "coverage_recall_state_excused", "overlap_precision", "exact_f1"):
+ check.equal(f"{name} {key}", round(s[key], 12), round(want[key], 12))
+ if arm in PUBLISHED_MASKED:
+ check.equal(f"{name} masked (published)", s["covered"], PUBLISHED_MASKED[arm])
+ for arm in LLM_PRICES:
+ unparsed = sum(
+ not llm_spans(d["text"], rows[arm][d["index"]]["output"])[2]
+ for d in documents
+ if rows[arm][d["index"]]["output"]
+ )
+ print(f" {arm}: {unparsed} of {len(documents)} replies did not parse as JSON and count as no masks")
+ check.equal(f"{arm} unparsed replies", unparsed, recorded["arms"][arm]["unparsed"])
- # --- the input window --------------------------------------------------
- parent = cases[WINDOW_CASE]
- tail = cases[WINDOW_TAIL]
- window_end = parent["gliner_window_end_char"]
- gold = mapped_gold(parent)
- one_call = returned_spans(entities, cases, WINDOW_CASE, sets=(FIRST_SET,), chunked=False, floor=floor)
- composed = composed_spans(entities, cases, WINDOW_CASE, floor=floor)
- window = {
- "total": len(gold),
- "one_request": sum(1 for span in gold if covered(one_call, span)),
- "composed": sum(1 for span in gold if covered(composed, span)),
- "past": sum(1 for span in gold if span["end"] > window_end),
- }
- words = list(GLINER_WORD.finditer(parent["text"]))
- window["words_total"] = len(words)
- window["words_in_window"] = sum(1 for word in words if word.end() <= window_end)
+ s = summary[COMPOSITION]
+ print()
print(
- f"\n{window['words_total']}-word chat, {window['total']} published spans:"
- f" {window['one_request']} masked by one call, {window['composed']} by the composition"
+ f"Currency amounts SIE's masks touch: {s['amounts_masked']} of {s['amounts']:,} "
+ "(the pattern also matches IP addresses)"
)
- print(f" the model reads the first {window['words_in_window']} words, up to character {window_end}")
- print(
- f" {window['past']} of those spans sit past that point,"
- f" and the second request starts at character {tail['parent_offset']}"
+ scoped = [g for d in documents for g in d["scoped"]]
+ bound = sum(g["label"] not in NO_COMPREHEND_TYPE for g in scoped) / len(scoped)
+ print(f"In-scope spans with a documented AWS Comprehend type: {pct(bound)} (Comprehend was not measured)")
+ check.equal(
+ "Comprehend documented-type bound", round(bound, 12), round(recorded["comprehend_documented_type_bound"], 12)
)
- got = {
- "gold_spans": totals["gold_spans"],
- **steps,
- "masks_in_gold_schema": totals["masks_in_gold_schema"],
- "masks_on_gold": totals["masks_on_gold"],
- "propagated_masks": len(propagated),
- "amounts_masked": amounts["masked"],
- "amounts_found": amounts["found"],
- "window_total": window["total"],
- "window_one_request": window["one_request"],
- "window_composed": window["composed"],
- "window_past": window["past"],
- "window_words_total": window["words_total"],
- "window_words_in_window": window["words_in_window"],
+ if not args.no_bootstrap:
+ intervals = bootstrap(per_arm)
+ print()
+ print(f"95% intervals: paired document-cluster bootstrap, {RESAMPLES:,} resamples, seed {SEED}")
+ for arm, name, _ in ARMS:
+ ci = intervals["coverage_ci95"][arm]
+ print(f" {name:<42} coverage {pct(ci[0])} to {pct(ci[1])}")
+ print("SIE minus each arm, paired: coverage recall / with states and countries excused")
+ for arm, name, _ in ARMS[1:]:
+ a = intervals["composition_minus_ci95"][arm]
+ b = intervals["composition_minus_state_excused_ci95"][arm]
+ print(f" {name:<42} {points(a)} / {points(b)}")
+ if replay:
+ for block, values in intervals.items():
+ for arm, ci in values.items():
+ want = recorded[block][RECORDED_KEY.get(arm, arm)]
+ check.equal(f"{block} {arm}", [round(x, 12) for x in ci], [round(x, 12) for x in want])
+
+ for model, count in SIE_TOKENS.items():
+ check.equal(f"{model} tokens", tokens[model], count)
+ check.equal(f"{model} tokens (e2)", e2["sie_tokens"][model], count)
+ usd = monthly_usd(documents, rows, e2)
+ print()
+ print(f"$ a month for {MONTHLY_DOCUMENTS:,} documents like these:")
+ names = {arm: name for arm, name, _ in ARMS} | {COMPOSITION: "SIE", COMPREHEND: "AWS Comprehend"}
+ for arm in (COMPOSITION, "presidio", "privacy-filter", "llm:gpt-6-luna", "llm:claude-haiku-4-5", COMPREHEND):
+ masked = pct(summary[arm]["coverage_recall"]) if arm in summary else "not measured"
+ print(f" {names[arm]:<24} ${usd[arm]:>9,.2f} (${round(usd[arm]):,}) masked {masked}")
+ check.equal(f"{arm} $ a month (published)", round(usd[arm]), PUBLISHED_MONTHLY_USD[arm])
+ priced = e2["usd_per_1m_documents"]
+ recorded_usd = {
+ COMPOSITION: next(v for k, v in priced.items() if k.startswith("sie-composition (")),
+ COMPREHEND: next(v for k, v in priced.items() if k.startswith("aws-comprehend")),
+ "llm:gpt-6-luna": priced["llm:gpt-6-luna"],
+ "llm:claude-haiku-4-5": priced["llm:claude-haiku-4-5"],
+ "presidio": e2["self_host"]["presidio"]["usd_per_1m_documents"],
+ "privacy-filter": e2["self_host"]["privacy-filter"]["usd_per_1m_documents"],
}
- failures = [f"{key}: got {got[key]}, page publishes {want}" for key, want in EXPECTED.items() if got[key] != want]
- # A step can only ever mask more than the one before it. Checked as an
- # ordering rather than only as four constants, because four constants that
- # all move together still pass.
- ladder = [steps["step_one_call"], steps["step_chunked"], steps["step_two_models"], steps["step_propagated"]]
- if ladder != sorted(ladder):
- failures.append(f"the steps do not increase: {ladder}")
- if ladder[-1] != totals["gold_spans"]:
- failures.append(f"the last step masks {ladder[-1]} of {totals['gold_spans']}, not all of them")
- if any(text.isalpha() is False for text in propagated):
- failures.append("the propagation step added something that is not a name")
- if failures:
- sys.stdout.flush()
- print("\nFAILED to reproduce the published figures:", file=sys.stderr)
- for line in failures:
+ for arm, value in recorded_usd.items():
+ check.equal(f"{arm} $ per 1M documents (recorded)", round(usd[arm], 6), round(value, 6))
+
+ print()
+ if not replay:
+ print(f"Scored the SIE rows in {args.sie_rows}; figures are not checked against the recording.")
+ return 0
+ if check.failed:
+ print("FAILED: these figures do not match the recording or the page:", file=sys.stderr)
+ for line in check.failed:
print(f" {line}", file=sys.stderr)
return 1
- print("\nReproduced: 26, 33, 41 and 45 of 45, 42 of 49 on gold, and 0 of 29 amounts masked.")
- if args.floor_0:
- print("Every figure holds with the floor removed, so it costs no coverage in this run.")
+ print("Every figure matches the recorded results and the published page.")
return 0