doxa-context-bias / tools /build_context_packets.py
Giuliocc's picture
Release source-grounded context, event references and study evidence with exact rights and annotation status
7bc8e75 verified
Raw History Blame Contribute Delete
10.5 kB
"""Build licensed source/context nominations without assigning bias labels."""
from __future__ import annotations
from collections import Counter, defaultdict
import argparse
import json
from pathlib import Path
import re
from build_basil import ROOT, sha, write_json, write_jsonl
PROJECT = ROOT.parents[1]
ATLAS = PROJECT / "research_atlas"
def records(path):
with path.open() as stream:
return [json.loads(line) for line in stream if line.strip()]
def build_packets(atlas: Path = ATLAS):
document_file = atlas / "metadata" / "documents.jsonl"
passage_file = atlas / "data" / "passages.jsonl"
nomination_file = atlas / "data" / "review_queue.jsonl"
source_manifest = atlas / "document_split_manifest.json"
if not document_file.exists():
document_file = atlas / "work" / "documents.jsonl"
passage_file = atlas / "work" / "passages.jsonl"
nomination_file = atlas / "stage" / "data" / "review_queue.jsonl"
source_manifest = atlas / "work" / "document_split_manifest.json"
documents = {row["id"]: row for row in records(document_file)}
passages = records(passage_file)
nominations = {row["passage_id"]: row for row in records(nomination_file)}
normalized_groups = defaultdict(list)
for passage in passages:
normalized_groups[sha(" ".join(re.findall(r"\w+", passage["text"].casefold())))].append(passage)
duplicate_groups = {key: rows for key, rows in normalized_groups.items()
if len({row["document_id"] for row in rows}) > 1}
quarantined_ids = {row["id"] for rows in duplicate_groups.values() for row in rows}
quarantine = [{"source_passage_id": row["id"], "source_document_id": row["document_id"],
"normalized_text_sha256": key, "reason": "all_occurrences_of_cross_document_normalized_duplicate",
"excluded_from": ["focal_packet", "neighbor_context"], "old_release_modified": False}
for key, rows in sorted(duplicate_groups.items()) for row in rows]
groups = defaultdict(list)
for passage in passages:
groups[passage["document_id"]].append(passage)
packets = []
attribution = []
patterns = [
("quotation_candidate", re.compile(r"“[^”]{12,}”|\"[^\"\n]{12,}\"")),
("reporting_candidate", re.compile(r"\b(?:according to|reported|argued|alleged|claimed|said|states?)\b", re.I)),
("rebuttal_or_negation_candidate", re.compile(r"\b(?:cannot|could not|did not|does not|no evidence|rejected|refuted|disputed)\b", re.I)),
]
for document_id, rows in sorted(groups.items()):
document = documents[document_id]
if document["license"]["identifier"] not in {"CC-BY-4.0", "CC-BY-3.0", "CC-BY-2.5", "CC-BY-2.0", "CC0-1.0"}:
raise ValueError("License requires separate admission: " + document_id)
if sha(document["text"]) != document["source_text_sha256"]:
raise ValueError("Source text hash mismatch")
rows.sort(key=lambda row: row["source_text_start"])
source_positions = {(row["source_section"], row["paragraph_index"]): row for row in rows}
if len(source_positions) != len(rows):
raise ValueError("Source paragraph positions are not unique")
for index, passage in enumerate(rows):
if passage["id"] in quarantined_ids:
continue
start, end = passage["source_text_start"], passage["source_text_end"]
if document["text"][start:end] != passage["text"] or sha(passage["text"]) != passage["text_sha256"]:
raise ValueError("Source passage mismatch: " + passage["id"])
before = source_positions.get((passage["source_section"], passage["paragraph_index"] - 1))
after = source_positions.get((passage["source_section"], passage["paragraph_index"] + 1))
# Do not bridge a removed paragraph or source-region boundary: the exact
# source substring would otherwise silently restore excluded material.
before = before if before and before["id"] not in quarantined_ids else None
after = after if after and after["id"] not in quarantined_ids else None
before_start = before["source_text_start"] if before else start
after_end = after["source_text_end"] if after else end
nomination = nominations.get(passage["id"])
packet = {
"id": "doxa-context:" + passage["id"], "schema_version": "doxa-context-packet-v1",
"unit_type": "research_paragraph_context_nomination", "source_kind": "academic_research_exposition",
"source_document_id": document_id, "source_passage_id": passage["id"],
"text": passage["text"], "text_sha256": passage["text_sha256"],
"context_before": document["text"][before_start:start], "context_after": document["text"][end:after_end],
"context_before_passage_id": before["id"] if before else None,
"context_after_passage_id": after["id"] if after else None,
"context_before_start": before_start, "source_text_start": start, "source_text_end": end,
"context_after_end": after_end, "offset_unit": "unicode_code_points",
"source_text_sha256": document["source_text_sha256"], "source_xml_sha256": document["source_xml_sha256"],
"source_xpath": passage["source_xpath"], "paragraph_index": passage["paragraph_index"],
"source_section": passage["source_section"], "section_title": passage["section_title"],
"source_url": passage["source_url"], "document_url": passage["document_url"],
"title": document["title"], "authors": document["authors"], "year": document["year"],
"doi": document["doi"], "pmcid": document["pmcid"], "language": passage["language"],
"license": passage["license"], "document_group": passage["document_group"], "reserved_split": passage["split"],
"upstream_collection": "doxa-research-atlas-v0.1.0", "new_source_discovery": False,
"role_provenance": "inherited_original_atlas_source_group_reservation_not_future_fit_clearance",
"neighbor_policy": "immediately_adjacent_original_paragraph_in_same_source_region_only; no gap or quarantined paragraph bridging",
"annotation_status": "unannotated", "gold_label": None, "human_review_count": 0,
"training_eligible": False, "evaluation_eligible": False,
"candidate_dimensions": nomination["candidate_dimensions"] if nomination else [],
"nomination_task_family": nomination["task_family"] if nomination else "reading_context_candidate",
"review_instruction": "Establish the actual communication, claim, comparison or study unit before assigning a mechanism. A research discussion supplies context and no positive bias label for the paper or author.",
}
packets.append(packet)
surface = []
for kind, pattern in patterns:
for match in list(pattern.finditer(passage["text"]))[:3]:
surface.append({"kind": kind, "start": match.start(), "end": match.end(), "text": match.group()})
if surface:
attribution.append({"id": packet["id"] + ":attribution", "packet_id": packet["id"],
"source_passage_id": passage["id"], "text_sha256": passage["text_sha256"],
"task": "review_source_attribution", "surface_cues": surface,
"cue_provenance": "deterministic_nomination", "speaker": None,
"stance": None, "gold_label": None, "annotation_status": "unannotated",
"human_review_count": 0, "training_eligible": False,
"review_instruction": "Identify quotation scope, the actual speaker and whether the focal author endorses, reports, rejects or leaves the proposition ambiguous."})
write_jsonl(ROOT / "work" / "licensed_context_packets.jsonl", packets)
write_jsonl(ROOT / "work" / "attribution_nominations.jsonl", attribution)
write_jsonl(ROOT / "work" / "context_duplicate_quarantine.jsonl", quarantine)
source_hashes = {name: sha(path.read_bytes()) for name, path in {
"documents": document_file, "passages": passage_file,
"review_queue": nomination_file, "source_group_manifest": source_manifest}.items()}
counts = {"licensed_context_packets": len(packets), "distinct_focal_texts": len({row["text_sha256"] for row in packets}),
"source_documents": len(groups), "attribution_nominations": len(attribution),
"nomination_task_family": dict(Counter(row["nomination_task_family"] for row in packets)),
"context_availability": {"before": sum(bool(row["context_before"]) for row in packets),
"after": sum(bool(row["context_after"]) for row in packets)},
"source_licenses": dict(Counter(documents[identifier]["license"]["identifier"] for identifier in groups)),
"bias_gold_labels": 0, "new_independent_human_reviews": 0,
"reused_from_frozen_research_atlas": True, "new_discovery_count": 0,
"source_input_passages": len(passages), "cross_document_normalized_duplicate_groups_quarantined": len(duplicate_groups),
"duplicate_passage_occurrences_quarantined": len(quarantined_ids),
"inherited_role_policy": "Original source-group roles are reservations only; new context keeps all occurrences of cross-document normalized duplicates out of focal and neighbor units. Future fit still needs portfolio-wide exact/near checks.",
"neighbor_policy": "Only immediate original paragraph indices within the same source section; removed/gap context is never bridged.",
"upstream_file_sha256": source_hashes}
write_json(ROOT / "work" / "licensed_context_counts.json", counts)
print(json.dumps(counts, indent=2, sort_keys=True))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--atlas-root", type=Path, default=ATLAS)
parser.add_argument("--output-root", type=Path, default=ROOT)
args = parser.parse_args()
ROOT = args.output_root.resolve()
build_packets(args.atlas_root)