"""Usage: python -I assemble.py RAW_JSON OUT_JSON  -> builds benchmark.json from run.py output"""
import json, sys, random
raw = json.load(open(sys.argv[1]))
U = "https://huggingface.co/datasets/gretelai/synthetic_pii_finance_multilingual"
# confusions: seeded pick, balanced across detectors, synthetic text only
rnd = random.Random(7); conf = []
for d in ["presidio", "scrubadub", "gliner-multi-pii"]:
    c = [x for x in raw["conf"] if x["detector"] == d and x["language"] == "en" and "\n" not in x["text"][:0]]
    fp = [x for x in c if x["kind"] == "fp"]; fn = [x for x in c if x["kind"] == "fn"]
    for pool, k in ((fp, 3), (fn, 3)):
        for x in rnd.sample(pool, min(k, len(pool))):
            conf.append({"detector": d, "text": x["text"].replace("\n", " "), "expected": x["expected"], "found": x["found"],
                         "note": ("false positive" if x["kind"] == "fp" else "missed") + " (English, synthetic text)"})
for x in conf[:]: pass
out = {"edition": "2026-12", "run_date": "2026-12-04",
 "datasets": [{"name": "gretelai/synthetic_pii_finance_multilingual (test split, English/German/French files)", "url": U,
   "licence": "Apache-2.0 (card metadata and README header 'released under Apache 2.0'; read 2026-12-04)", "licence_url": U + "/blob/main/README.md",
   "revision": "7b844d16738527a04264f50214cb426a4cea0897",
   "records_used": {"en": 1000, "de": 300, "fr": 300}, "languages": ["en", "de", "fr"],
   "sample_rule": "random.Random(20261204).sample of rows from each language test parquet, then fixed shuffle (seed 20261204+1). GLiNER scored on the first 300 en / 100 de / 100 fr of the same lists (CPU time)."},
  {"name": "ai4privacy/pii-masking-300k (NOT USED)", "url": "https://huggingface.co/datasets/ai4privacy/pii-masking-300k",
   "licence": "Custom 'other' licence (LICENSE.md): academic/non-commercial use only; redistribution, sharing and derivative works require written licence; commercial use needs licensing@ai4privacy.com. Read 2026-12-04. Excluded.",
   "licence_url": "https://huggingface.co/datasets/ai4privacy/pii-masking-300k/blob/main/LICENSE.md", "records_used": 0, "languages": [], "sample_rule": "not used"}],
 "detectors": [
  {"slug": "presidio", "name": "Microsoft Presidio Analyzer", "version": "presidio-analyzer 2.2.366; spaCy 3.8.18; en_core_web_lg 3.8.0, de_core_news_md 3.8.0, fr_core_news_md 3.8.0", "config": "default predefined recognizers for en/de/fr, score threshold 0 (presidio-analyzer default; run.py passes none), language passed per record", "url": "https://github.com/data-privacy-stack/presidio", "licence": "MIT"},
  {"slug": "scrubadub", "name": "scrubadub", "version": "2.0.1", "config": "default Scrubber() detectors; only email, phone, name, credit_card, ssn filth types are mapped", "url": "https://github.com/LeapBeyond/scrubadub", "licence": "MIT"},
  {"slug": "gliner-multi-pii", "name": "GLiNER multi PII (urchade/gliner_multi_pii-v1)", "version": "gliner 0.2.30, torch 2.15.0+cpu, transformers 5.22.2; model revision 1fcf13e85f4eef5394e1fcd406cf2ca9ea82351d", "config": "threshold 0.5, 12 zero-shot labels (person, organization, email, phone number, address, credit card number, iban, social security number, date, ip address, passport number, driver license number); CPU, 2 vCPU", "url": "https://huggingface.co/urchade/gliner_multi_pii-v1", "licence": "Apache-2.0 (model card, read 2026-12-04)"}],
 "excluded_detectors": [{"slug": "piiranha", "reason": "iiiorg/piiranha-v1-detect-personal-information is CC-BY-NC-ND-4.0 (non-commercial, no derivatives); not used"}],
 "match_rule": "Span-level, character offsets. A predicted span matches a gold span if the common entity type is equal and overlap_chars / max(len(gold), len(pred)) >= 0.5; one-to-one greedy matching by largest overlap. Unmatched predictions are FP, unmatched gold are FN. Gold labels outside the mapping are ignored, and predictions overlapping them are dropped (not counted FP). Predictions of types not in the common set are dropped.",
 "mapping": {"gold": {"name, first_name, last_name": "PERSON", "company": "ORG", "street_address": "ADDRESS", "date, date_of_birth, date_time": "DATE", "phone_number": "PHONE", "email": "EMAIL", "ssn": "SSN", "credit_card_number": "CREDIT_CARD", "iban": "IBAN", "ipv4, ipv6": "IP", "passport_number": "PASSPORT", "driver_license_number": "DRIVER_LICENSE",
   "ignored (unmapped)": "time, employee_id, swift_bic_code, customer_id, bban, bank_routing_number, account_pin, credit_card_security_code, local_latlng, api_key, password, user_name"},
  "presidio": {"PERSON": "PERSON", "EMAIL_ADDRESS": "EMAIL", "PHONE_NUMBER": "PHONE", "LOCATION": "ADDRESS", "CREDIT_CARD": "CREDIT_CARD", "IBAN_CODE": "IBAN", "US_SSN": "SSN", "DATE_TIME": "DATE", "IP_ADDRESS": "IP", "US_PASSPORT": "PASSPORT", "US_DRIVER_LICENSE": "DRIVER_LICENSE"},
  "scrubadub": {"email": "EMAIL", "phone": "PHONE", "name": "PERSON", "credit_card": "CREDIT_CARD", "ssn": "SSN"},
  "gliner-multi-pii": {"person": "PERSON", "organization": "ORG", "email": "EMAIL", "phone number": "PHONE", "address": "ADDRESS", "credit card number": "CREDIT_CARD", "iban": "IBAN", "social security number": "SSN", "date": "DATE", "ip address": "IP", "passport number": "PASSPORT", "driver license number": "DRIVER_LICENSE"}},
 "results": raw["res"],
 "overall": [{k: o[k] for k in ("detector", "language", "precision", "recall", "f1")} for o in raw["overall"]],
 "confusions": conf, "runtime": raw["runtime"],
 "limits": [
  "Synthetic LLM-generated finance documents with a single dataset; results do not transfer to real data or other domains.",
  "Gold annotations cover only the dataset's own PII labels; unlabelled PII in the text (e.g. a person name not annotated) counts as FP, so precision is understated for all detectors.",
  "Gold 'company' and 'name' are generic; detectors without ORG support (Presidio, scrubadub) score 0 recall on ORG by design, which pulls down micro averages. Compare per-entity rows.",
  "Presidio LOCATION is mapped to ADDRESS; it finds cities/countries, not street addresses, so ADDRESS scores are low by construction. Only generic recognizers apply for de/fr; US-specific ones (SSN, passport, driver licence) do not target DE/FR formats.",
  "scrubadub 2.0.1 default Scrubber() has no person-name or address detector (name needs optional extras not installed), so its PERSON, ADDRESS, DATE recall is 0 by configuration, not a defect.",
  "Default configurations only; no tuning, no score thresholds sweep, no custom recognizers. GLiNER threshold 0.5 and label wording were not tuned.",
  "GLiNER was run on a subset (300 en, 100 de, 100 fr) of the same sample because of CPU time; its numbers are not on identical records to the others' full sample.",
  "Overlap >= 50% rule is lenient on boundaries (char overlap / longer span); exact-match scores would be lower.",
  "Micro 'overall' includes entity types a detector does not support, so it favours detectors with broader type coverage.",
  "ai4privacy/pii-masking-300k excluded for licence reasons; piiranha excluded (CC-BY-NC-ND-4.0).",
  "Runtime measured on a shared 2 vCPU GitHub runner; GLiNER used CPU with model cache in /dev/shm because of disk limits."]}
if len(sys.argv) > 4:
    # optional: assemble.py RAW OUT subset500_raw.json truncation.json
    sub = json.load(open(sys.argv[3])); tr = json.load(open(sys.argv[4]))
    gl = [{k: o[k] for k in ("detector", "language", "precision", "recall", "f1")} for o in raw["overall"] if o["detector"] == "gliner-multi-pii"]
    out["results_subset500"] = {"note": "Presidio and scrubadub rescored on the same 500 records GLiNER ran on (first 300 en, 100 de, 100 fr of the seeded sample), by subset500.py; GLiNER rows are the same as in overall.",
        "overall": [{k: o[k] for k in ("detector", "language", "precision", "recall", "f1")} for o in sub] + gl}
    out["truncation"] = tr
    if len(sys.argv) > 5:
        # optional: subset500_entities.json (subset500.py third argument): per-entity rows for Presidio and scrubadub on the same 500 records, plus GLiNER's rows
        ents = json.load(open(sys.argv[5]))
        gl_ent = [{k: x[k] for k in ("detector", "language", "entity", "tp", "fp", "fn", "precision", "recall", "f1", "support")} for x in raw["res"] if x["detector"] == "gliner-multi-pii"]
        out["results_subset500"]["results"] = ents + gl_ent
    out["limits"] = [l for l in out["limits"] if not l.startswith("GLiNER was run on a subset")] + [
        "GLiNER ran on 500 of the 1,600 records (300 en, 100 de, 100 fr) because of CPU time; Presidio and scrubadub are also scored on those same 500 in results_subset500.",
        "GLiNER multi PII reads at most 384 words per call and the run passed whole records. %d of the %d GLiNER records have more than 384 words by GLiNER's own splitter (truncation.json), so labeled spans after the cut count as misses and GLiNER's recall is a lower bound." % (tr["records_over_384"], tr["records"])]
json.dump(out, open(sys.argv[2], "w"), indent=1, ensure_ascii=False)
for o in out["overall"]: print(o)
print(out["runtime"])
