Download synth/build.py from 5000dev/noirci-bench: direct link, hf CLI and curl.
- Browser
- Download file 6.19 kB
-
https://huggingface.co/datasets/5000dev/noirci-bench/resolve/main/synth/build.py
- Command line
-
hf download hf://datasets/5000dev/noirci-bench/synth/build.py
-
curl -L -o build.py https://huggingface.co/datasets/5000dev/noirci-bench/resolve/main/synth/build.py
6.19 kB
| """Construction du corpus synthetique : templates + PII generees + offsets gold. | |
| Usage : | |
| # jeu d'evaluation (templates du pool EVAL, jamais vus en train) | |
| python -m bench.synth.build --split eval --n 1500 --out data/bench_v1.jsonl | |
| # corpus d'entrainement (hors git, regenerable a l'identique par seed) | |
| python -m bench.synth.build --split train --n 100000 \ | |
| --out data/corpus_train_100k.jsonl | |
| Chaque segment est un objet JSONL au format du harness (voir harness/score.py). | |
| ~30 % des segments recoivent un bruitage OCR a longueur constante (offsets | |
| inchanges, flag "noise": true), ~8 % sont des negatifs purs sans PII, et les | |
| valeurs longues (IBAN, NIR...) peuvent etre coupees par un saut de ligne | |
| (piege OCR/PDF, longueur conservee). | |
| Limite assumee : synthetique pur. L'eval reelle annotee main (Judilibre, | |
| BODACC, documents fictifs relus) reste indispensable avant toute conclusion — | |
| analyse §4.3 : "jamais du synthetique seul". | |
| """ | |
| import argparse | |
| import json | |
| import random | |
| import re | |
| from pathlib import Path | |
| from bench.pii.generators import Person, PiiFactory | |
| from bench.synth.noise import apply_noise | |
| from bench.synth.templates import NEGATIVES, all_templates | |
| _SLOT_RE = re.compile(r"\{([a-z_]+?)(\d+)(_v)?\}") | |
| # prefixe de slot -> (methode factory, label ; None = distracteur non etiquete) | |
| _SLOT_TYPES = { | |
| "person": "PERSON", "company": "COMPANY", "address": "ADDRESS", | |
| "city": "CITY", "email": "EMAIL", "phone": "PHONE", "date": "DATE", | |
| "date_birth": "DATE_BIRTH", "iban": "IBAN", "nir": "NIR", | |
| "siren": "SIREN", "siret": "SIRET", "tva": "TVA", "card": "CARD", | |
| "plate": "PLATE", "rg": "RG", "cadastre": "CADASTRE", "ip": "IP", | |
| "amount": "AMOUNT", "ref": None, | |
| } | |
| def _maybe_linebreak(surface: str, rng: random.Random) -> str: | |
| """Piege PDF/OCR : coupe une valeur longue par un saut de ligne (meme | |
| longueur, un espace interieur remplace par \\n).""" | |
| if len(surface) < 14 or " " not in surface[2:-2] or rng.random() > 0.04: | |
| return surface | |
| spaces = [i for i, c in enumerate(surface) if c == " " and 1 < i < len(surface) - 2] | |
| i = rng.choice(spaces) | |
| return surface[:i] + "\n" + surface[i + 1:] | |
| def fill_template(template: str, factory: PiiFactory, rng: random.Random, | |
| ref_label: str | None = None) -> dict: | |
| values: dict[tuple[str, str], object] = {} | |
| text_parts: list[str] = [] | |
| entities: list[dict] = [] | |
| pos = 0 | |
| cursor = 0 | |
| for m in _SLOT_RE.finditer(template): | |
| name, idx, variant = m.group(1), m.group(2), m.group(3) | |
| if name not in _SLOT_TYPES: | |
| raise ValueError(f"slot inconnu : {m.group(0)}") | |
| text_parts.append(template[cursor:m.start()]) | |
| pos += m.start() - cursor | |
| cursor = m.end() | |
| key = (name, idx) | |
| if key not in values: | |
| values[key] = getattr(factory, name)() | |
| val = values[key] | |
| if isinstance(val, Person): | |
| surface = rng.choice(val.variants()[1:]) if variant else val.full | |
| else: | |
| surface = _maybe_linebreak(str(val), rng) | |
| etype = _SLOT_TYPES[name] | |
| if name == "ref" and ref_label: | |
| etype = ref_label | |
| if etype is not None: | |
| entities.append( | |
| {"start": pos, "end": pos + len(surface), "type": etype, "value": surface} | |
| ) | |
| text_parts.append(surface) | |
| pos += len(surface) | |
| text_parts.append(template[cursor:]) | |
| return {"text": "".join(text_parts), "entities": entities} | |
| def build_corpus(n: int, seed: int, noise_share: float, | |
| split: str = "all", negative_share: float = 0.08, | |
| values: str = "faker", ref_label: str | None = None) -> list[dict]: | |
| rng = random.Random(seed) | |
| if values == "real": | |
| from bench.pii.real_factory import RealValuesFactory | |
| factory = RealValuesFactory(seed=seed) | |
| else: | |
| factory = PiiFactory(seed=seed) | |
| templates = all_templates(split) | |
| domains = list(templates) | |
| segments = [] | |
| for i in range(n): | |
| if rng.random() < negative_share: | |
| domain = "negatif" | |
| seg = fill_template(rng.choice(NEGATIVES), factory, rng, ref_label=ref_label) | |
| else: | |
| domain = domains[i % len(domains)] | |
| seg = fill_template(rng.choice(templates[domain]), factory, rng, ref_label=ref_label) | |
| noised = rng.random() < noise_share | |
| if noised: | |
| seg["text"] = apply_noise(seg["text"], rng) | |
| for e in seg["entities"]: | |
| e["value"] = seg["text"][e["start"]:e["end"]] | |
| seg = {"id": f"{split}-{domain}-{i:06d}", "domain": domain, | |
| "noise": noised, **seg} | |
| segments.append(seg) | |
| return segments | |
| def main(): | |
| ap = argparse.ArgumentParser(description="Genere le corpus benchmark synthetique") | |
| ap.add_argument("--n", type=int, default=600) | |
| ap.add_argument("--seed", type=int, default=42) | |
| ap.add_argument("--noise-share", type=float, default=0.3) | |
| ap.add_argument("--negative-share", type=float, default=0.08) | |
| ap.add_argument("--split", choices=["train", "eval", "all"], default="all") | |
| ap.add_argument("--values", choices=["faker", "real"], default="faker", | |
| help="real = pools BODACC (anti-contamination fine-tune)") | |
| ap.add_argument("--label-refs", action="store_true", | |
| help="etiquette les {ref} en REF (convention 2026-07-29)") | |
| ap.add_argument("--out", default="data/bench_v0.jsonl") | |
| args = ap.parse_args() | |
| segments = build_corpus(args.n, args.seed, args.noise_share, | |
| args.split, args.negative_share, args.values, | |
| "REF" if args.label_refs else None) | |
| out = Path(args.out) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| with out.open("w", encoding="utf-8") as f: | |
| for seg in segments: | |
| f.write(json.dumps(seg, ensure_ascii=False) + "\n") | |
| n_ent = sum(len(s["entities"]) for s in segments) | |
| n_noise = sum(1 for s in segments if s["noise"]) | |
| print(f"{len(segments)} segments ({n_noise} bruites), {n_ent} entites -> {out}") | |
| if __name__ == "__main__": | |
| main() | |