"""Build development examples, paired audits and public-law retrieval seeds.""" import argparse import csv from hashlib import sha256 import json from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq ROOT = Path(__file__).parent PROJECT = ROOT.parent VERSION = "0.1.0" # The same proposition is tested under different presentation and context. # Variants are generated from authored templates and retained as families. TEMPLATES = ( ("asserted", "assertion", "{claim}. The outcome already applies across the program.", "This is the reporter's own summary. {context}"), ("attributed", "attribution", "{actor} said that {claim}. The statement was made at the briefing.", "This is coverage of the briefing. {context}"), ("qualified", "qualification", "The early figures could suggest that {claim}. The available figures are preliminary.", "The writer offers an inference and states a limitation. {context}"), ("insufficient_context", "fragment", "{claim}.", "{context} The surviving fragment has no title, author or quotation markers. Its relation to the coverage is unresolved."), ("asserted", "context_flip", "{claim}.", "{context} In the complete article this is the reporter's own concluding statement."), ("attributed", "context_flip", "{claim}.", "{context} In the complete transcript this is a selected quotation attributed to the agency representative. The reporter makes no independent assertion."), ("attributed", "rebuttal", "{claim}. The finding was cited in the meeting.", "{context} This line paraphrases a claim the review panel expressly rejected. It is retained in the record to document the disagreement."), ("qualified", "scope_boundary", "The committee argues that {claim}. If the recorded sample is representative, the result might hold more broadly.", "{context} The analyst treats the result as conditional on sample coverage."), ) RATIONALES = { "asserted": "The focal coverage adopts the proposition as its own conclusion.", "attributed": "The proposition is reported as someone else's statement, with its speaker supplied.", "qualified": "The focal coverage explicitly conditions the conclusion on uncertainty or scope.", "insufficient_context": "The retained fragment lacks enough information to identify the focal speaker's commitment.", } def digest(value): return sha256(value.encode()).hexdigest() def sentence_case(text): return text[:1].upper() + text[1:] def unit(event, index, role, label, family, passage, context, split): event_id = event["event_id"] ident = digest(f"{event_id}|{index}|{role}")[:18] start = 0 end = passage.index(".") + 1 if family == "context_flip" or label == "insufficient_context": start = context.index(event["context"]) + len(event["context"]) + 1 end = len(context) source = context segment = "context" else: source = passage if family == "scope_boundary": start = end + 1 end = len(passage) segment = "passage" return { "unit_id": ident, "event_id": event_id, "beat": event["beat"], "claim_type": event["claim_type"], "role": role, "actor": event[f"actor_{role}"], "source_cohort": "fictional-desk", "genre": "report", "published_at": "2024-07-02T12:00:00Z", "evidence_available_at": "2024-07-02T09:00:00Z", "evidence_status": "uncorroborated", "source_url": None, "text": passage, "context": context, "family": family, "split": split, "label": label, "rationale": RATIONALES[label], "origin": "fictional", "annotation_status": "ai_provisional", "reference_span": {"segment": segment, "start": start, "end": end, "quote": source[start:end]}, } def build(): with (ROOT / "corpus" / "dossiers.tsv").open() as source: events = list(csv.DictReader(source, delimiter="\t")) strata = {} for event in events: strata.setdefault(event["beat"], []).append(event["event_id"]) splits = {} for ids in strata.values(): ordered = sorted(ids, key=lambda value: digest("1729|" + value)) splits.update(zip(ordered, ("train", "train", "train", "validation", "development_test"), strict=True)) rows = [] audit = [] for index, event in enumerate(events): event_id = event["event_id"] split = splits[event_id] statuses = ("asserted", "attributed") if index % 5 < 3 else ( ("attributed", "qualified") if index % 5 == 3 else ("insufficient_context", "asserted") ) paired = {} for role, label in zip(("left", "right"), statuses, strict=True): claim = event[f"{role}_claim"] actor = event[f"actor_{role}"] sentences = { "asserted": f"{sentence_case(claim)}. The changes are visible in the current period.", "attributed": f"{actor} announced that {claim}. The review is still open.", "qualified": f"Initial accounts suggest {claim}. The evidence remains provisional.", "insufficient_context": f"{sentence_case(claim)}.", } context = event["context"] if label == "insufficient_context": context += " The surviving fragment has no attribution or surrounding text." item = unit(event, 99, role, label, "matched_claim", sentences[label], context, split) rows.append(item) paired[role] = item audit.append({"pair_id": digest("audit|" + event_id)[:18], **paired}) for offset, (label, family, text, context) in enumerate(TEMPLATES): role = "left" if offset in (3, 4, 5) else ("right" if offset % 2 else "left") replacements = {"claim": event[f"{role}_claim"], "actor": event[f"actor_{role}"], "context": event["context"]} row = unit(event, offset, role, label, family, sentence_case(text.format(**replacements)), context.format(**replacements), split) rows.append(row) assert len({row["unit_id"] for row in rows}) == 200 for row in rows: span = row["reference_span"] text = row["context"] if span["segment"] == "context" else row["text"] assert span["quote"] and text[span["start"]:span["end"]] == span["quote"] # Each context switch shares the passage byte for byte and changes only the context. for event in events: variants = [x for x in rows if x["event_id"] == event["event_id"] and x["family"] == "context_flip"] assert len(variants) == 2 and variants[0]["text"] == variants[1]["text"] assert {x["label"] for x in variants} == {"asserted", "attributed"} controls = [ ("genre_mismatch", "genre", "opinion"), ("time_mismatch", "published_at", "2024-07-05T12:00:00Z"), ("later_evidence", "evidence_available_at", "2024-07-06T09:00:00Z"), ("different_support", "evidence_status", "corroborated"), ("policy_stance", "claim_type", "normative_position"), ] for index, (name, key, value) in enumerate(controls): fixture = audit[index] ident = f"audit-control-{name}" left = {**fixture["left"], "unit_id": ident+"-left", "event_id": ident} right = {**fixture["right"], "unit_id": ident+"-right", "event_id": ident, key:value} if name == "policy_stance": left.update(claim_type=value, text="We strongly oppose the rent advice pilot. Funding legal assistance is a better choice.", label=None, rationale=None, reference_span=None) right.update(text="We strongly oppose the landlord mediation pilot. Funding mediation is a better choice.", label=None, rationale=None, reference_span=None) audit.append({"pair_id": ident, "left": left, "right": right}) return rows, audit, splits def json_file(path, value): path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--out", type=Path, default=ROOT / "work") parser.add_argument("--evidence", type=Path, default=PROJECT / "release_staging" / "conflict" / "passages.parquet") args = parser.parse_args() out = args.out out.mkdir(parents=True, exist_ok=True) rows, audit, splits = build() for split in ("train", "validation", "development_test"): pq.write_table(pa.Table.from_pylist([row for row in rows if row["split"] == split]), out / f"{split}.parquet") pq.write_table(pa.Table.from_pylist(audit), out / "audit_pairs.parquet") retrieved = pq.read_table(args.evidence) pq.write_table(retrieved, out / "licensed_evidence.parquet") json_file(out / "audit_pairs.json", audit) json_file(out / "split_manifest.json", {"revision": VERSION, "assignment": splits, "algorithm": "sha256 within beat"}) print(f"{len(rows)} fictional development rows, {len(audit)} matched pairs, {retrieved.num_rows} public-law evidence passages") if __name__ == "__main__": main()