"""Restore pinned BASIL locally and freeze label-blind source/event roles.""" from __future__ import annotations import argparse from collections import Counter, defaultdict import hashlib import json from pathlib import Path import re import tarfile from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit from urllib.request import Request, urlopen ROOT = Path(__file__).resolve().parent REVISION = "4fdbc4f68d5ddae648990063cb6dd11424d96222" ARCHIVE_SHA256 = "de3cc99f9498620e4b1d776e3c77c76b0a9d77950548024ee89c7a697f02dc80" ARCHIVE_URL = f"https://codeload.github.com/launchnlp/BASIL/tar.gz/{REVISION}" NEAR_SENTENCE_THRESHOLD = 0.90 NEAR_ARTICLE_THRESHOLD = 0.80 FREEZE_VERSION = "v2" def sha(value: str | bytes) -> str: if isinstance(value, str): value = value.encode("utf-8") return hashlib.sha256(value).hexdigest() def write_json(path: Path, value): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n") def write_jsonl(path: Path, rows): path.parent.mkdir(parents=True, exist_ok=True) with path.open("w") as stream: for row in rows: stream.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") def canonical_url(value: str) -> str: parts = urlsplit(value.strip()) host = (parts.hostname or "").lower().removeprefix("www.") path = re.sub(r"/{2,}", "/", parts.path).rstrip("/") tracking = {"_r", "ref", "ref_src", "ref_url", "fbclid", "gclid", "output", "cmpid", "ncid"} query = sorted((key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True) if key.lower() not in tracking and not key.lower().startswith("utm_")) return urlunsplit(("https", host, path, urlencode(query), "")) def normalize(value: str) -> str: return " ".join(re.findall(r"\w+", value.casefold())) def shingles(value: str) -> frozenset[tuple[str, ...]]: words = normalize(value).split() return frozenset(tuple(words[index:index + 5]) for index in range(max(0, len(words) - 4))) def read_source(archive_path: Path): if not archive_path.exists(): archive_path.parent.mkdir(parents=True, exist_ok=True) with urlopen(Request(ARCHIVE_URL, headers={"User-Agent": "DOXA-Context-Research/0.1"}), timeout=60) as response: content = response.read(20 * 1024 * 1024) archive_path.write_bytes(content) if sha(archive_path.read_bytes()) != ARCHIVE_SHA256: raise ValueError("The pinned BASIL archive hash does not match") records = {} hashes = {} with tarfile.open(archive_path) as archive: for member in archive.getmembers(): relative = member.name.split("/", 1)[-1] if member.isfile() and relative.endswith(".json") and relative.startswith(("articles/", "annotations/")): content = archive.extractfile(member).read() records[relative] = json.loads(content) hashes[relative] = sha(content) return records, hashes def restore_articles(records, hashes): articles = [] sentences = [] title_annotations = [] source_index = [] for path in sorted(records): if not path.startswith("articles/"): continue source = records[path] annotation_path = path.replace("articles/", "annotations/").replace(".json", "_ann.json") annotations = records[annotation_path] source_event = source.get("triplet-uuid", source.get("pair-uuid")) annotation_event = annotations.get("triplet-uuid", annotations.get("pair-uuid")) if source.get("uuid") != annotations.get("uuid") or not source_event or source_event != annotation_event: raise ValueError("Source identity mismatch: " + path) upstream_uuid = source.get("uuid") if isinstance(upstream_uuid, str) and re.fullmatch(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", upstream_uuid): article_id = "basil-article-" + upstream_uuid identity_basis = "upstream_uuid" else: article_id = "basil-article-source-" + sha(path)[:24] identity_basis = "pinned_upstream_source_path" event_id = "basil-event-" + source_event body = source["body-paragraphs"] text = source["title"] + "\n\n" spans_by_sentence = defaultdict(list) for position, annotation in enumerate(annotations["phrase-level-annotations"]): if annotation["bias"] not in {"lex", "inf"}: raise ValueError("Unrecognized upstream bias label") identifier = annotation["id"] if identifier != "title" and not re.fullmatch(r"p\d+", identifier): raise ValueError("Unrecognized upstream sentence ID") spans_by_sentence[identifier].append({**annotation, "upstream_span_index": position}) units = [] flat_index = 0 paragraphs = [] for paragraph_index, paragraph in enumerate(body): if not isinstance(paragraph, list) or not all(isinstance(value, str) for value in paragraph): raise ValueError("Invalid upstream paragraph structure") paragraph_start = len(text) for sentence_index, sentence in enumerate(paragraph): if sentence_index: text += " " start = len(text) text += sentence units.append({"text": sentence, "sentence_id": "p" + str(flat_index), "sentence_index": flat_index, "paragraph_index": paragraph_index, "start": start, "end": len(text)}) flat_index += 1 paragraphs.append({"start": paragraph_start, "end": len(text), "text": text[paragraph_start:]}) if paragraph_index + 1 < len(body): text += "\n\n" for unit in units: human_spans = spans_by_sentence.pop(unit["sentence_id"], []) for span in human_spans: if unit["text"][span["start"]:span["end"]] != span["txt"]: raise ValueError("Upstream span is not an exact source match: " + path) index = unit["sentence_index"] before_start = units[max(0, index - 2)]["start"] after_end = units[min(len(units) - 1, index + 2)]["end"] paragraph = paragraphs[unit["paragraph_index"]] sentences.append({ "id": article_id + ":" + unit["sentence_id"], **unit, "input_eligible": bool(normalize(unit["text"])), "input_exclusion_reason": None if normalize(unit["text"]) else "normalized_empty_source_target", "labels": {"lexical_bias": int(any(span["bias"] == "lex" for span in human_spans)), "informational_bias": int(any(span["bias"] == "inf" for span in human_spans))}, "task": "basil_sentence_annotated_span_presence", "label_scope": "Presence of a released upstream lexical or informational span in this sentence; an unmarked sentence supplies no global unbiased label.", "annotation": {"provenance": "upstream_human_consensus_derived_sentence_labels", "process_annotators_reported": 2, "individual_votes_available": False, "new_doxa_human_review_count": 0, "source": "https://aclanthology.org/D19-1664/"}, "upstream_spans": human_spans, "article_id": article_id, "event_id": event_id, "source_url": source["url"], "canonical_source_url": canonical_url(source["url"]), "outlet": source["source"].lower(), "date": source["date"], "paragraph_text": paragraph["text"], "paragraph_start": paragraph["start"], "paragraph_end": paragraph["end"], "context_before": text[before_start:unit["start"]], "context_after": text[unit["end"]:after_end], "context_before_start": before_start, "context_after_end": after_end, "document_path": "../articles-v2/" + article_id + ".json", "offset_unit": "unicode_codepoints", "text_sha256": sha(unit["text"]), "normalized_text_sha256": sha(normalize(unit["text"])), "document_text_sha256": sha(text), "upstream_revision": REVISION, "upstream_article_path": path, "rights": {"article_text_redistribution": "unresolved", "annotation_redistribution": "unresolved", "public_release_text": False, "public_release_annotations": False, "training_permission_evidence": "No explicit dataset permission found in the checked official repositories or attachment", "public_weights_eligibility": "requires_separate_rights_assessment"}, }) titles = spans_by_sentence.pop("title", []) if spans_by_sentence: raise ValueError("An annotation refers to an absent sentence") for span in titles: if source["title"][span["start"]:span["end"]] != span["txt"]: raise ValueError("Title span mismatch") title_annotations.append({"article_id": article_id, "event_id": event_id, "text": source["title"], "annotation": span, "offset_unit": "unicode_codepoints"}) article = {"id": article_id, "event_id": event_id, "upstream_uuid": upstream_uuid, "identity_basis": identity_basis, "source_path": path, "text": text, "body_start": len(source["title"]) + 2, "title": source["title"], "source_url": source["url"], "canonical_source_url": canonical_url(source["url"]), "outlet": source["source"].lower(), "date": source["date"], "upstream_source": source, "upstream_document_annotations": annotations["article-level-annotations"], "text_sha256": sha(text), "normalized_body_sha256": sha(normalize(text[len(source["title"]) + 2:]))} articles.append(article) source_index.append({"article_id": article_id, "event_id": event_id, "source_url": source["url"], "upstream_uuid": upstream_uuid, "identity_basis": identity_basis, "canonical_source_url": article["canonical_source_url"], "date": source["date"], "outlet": article["outlet"], "upstream_article_path": path, "upstream_annotation_path": annotation_path, "upstream_article_file_sha256": hashes[path], "upstream_annotation_file_sha256": hashes[annotation_path], "canonical_text_sha256": article["text_sha256"], "body_sentence_count": len(units), "source_revision": REVISION, "article_text_in_public_package": False, "annotations_in_public_package": False}) if len(articles) != 300 or len({row["event_id"] for row in articles}) != 100: raise ValueError("Pinned source article/event counts changed") if sum(len(row["upstream_spans"]) for row in sentences) + len(title_annotations) != 1726: raise ValueError("Pinned source annotation count changed") if len({article["id"] for article in articles}) != len(articles) or len({row["id"] for row in sentences}) != len(sentences): raise ValueError("Source identities are not unique") if any(row["upstream_spans"] for row in sentences if not row["input_eligible"]): raise ValueError("An input-excluded target has an upstream annotation and needs separate review") return articles, sentences, title_annotations, source_index class Components: def __init__(self, identifiers): self.parent = {identifier: identifier for identifier in identifiers} def find(self, identifier): parent = self.parent[identifier] if parent != identifier: self.parent[identifier] = self.find(parent) return self.parent[identifier] def union(self, left, right): left, right = sorted([self.find(left), self.find(right)]) self.parent[right] = left def near_pairs(rows, threshold, minimum_words, cross_rows=None): """Exact shingle candidate intersection, without random similarity sampling.""" index = defaultdict(list) sets = [] indexed_rows = [] queries = rows if cross_rows is not None: for row in cross_rows: grams = shingles(row["text"]) if len(normalize(row["text"]).split()) < minimum_words: continue position = len(sets) sets.append(grams) indexed_rows.append(row) for gram in grams: index[gram].append(position) for row in queries: grams = shingles(row["text"]) if len(normalize(row["text"]).split()) < minimum_words: continue candidates = Counter(position for gram in grams for position in index[gram]) for position, shared in candidates.items(): candidate = indexed_rows[position] if row.get("event_id") and row.get("event_id") == candidate.get("event_id"): continue denominator = len(grams) + len(sets[position]) - shared similarity = shared / denominator if denominator else 0 if similarity >= threshold: yield row, candidate, similarity if cross_rows is None: position = len(sets) sets.append(grams) indexed_rows.append(row) for gram in grams: index[gram].append(position) def freeze_roles(articles, sentences, prior_babe_path: Path): components = Components(article["event_id"] for article in articles) edges = [] for field, reason in [("canonical_source_url", "same_canonical_url"), ("normalized_body_sha256", "same_normalized_article")]: seen = {} for article in articles: other = seen.get(article[field]) if other and article["event_id"] != other["event_id"]: components.union(article["event_id"], other["event_id"]) edges.append({"left": article["id"], "right": other["id"], "reason": reason}) seen[article[field]] = article for kind, rows, threshold, words in [("article", articles, NEAR_ARTICLE_THRESHOLD, 100), ("sentence", sentences, NEAR_SENTENCE_THRESHOLD, 12)]: for left, right, similarity in near_pairs(rows, threshold, words): components.union(left["event_id"], right["event_id"]) edges.append({"left": left["id"], "right": right["id"], "reason": "cross_event_near_" + kind, "jaccard_word_5grams": similarity}) prior = [] prior_sha = None if prior_babe_path.exists(): prior_sha = sha(prior_babe_path.read_bytes()) prior = [json.loads(line) for line in prior_babe_path.read_text().splitlines() if line] prior_urls = defaultdict(list) for row in prior: prior_urls[canonical_url(row["source_url"])].append(row["id"]) overlap = [] for article in articles: matches = prior_urls[article["canonical_source_url"]] if matches: overlap.append({"article_id": article["id"], "event_id": article["event_id"], "reason": "prior_babe_source_url", "prior_ids": sorted(matches)}) for left, right, similarity in near_pairs(sentences, 0.85, 12, cross_rows=prior): overlap.append({"article_id": left["article_id"], "event_id": left["event_id"], "sentence_id": left["id"], "reason": "prior_babe_near_sentence", "prior_ids": [right["id"]], "prior_split": right["split"], "jaccard_word_5grams": similarity}) event_members = defaultdict(list) for event in sorted(components.parent): event_members[components.find(event)].append(event) prior_seen = {components.find(row["event_id"]) for row in overlap} event_roles = {} event_groups = {} groups = [] for representative, members in sorted(event_members.items()): group = "basil-source-family-" + sha("\n".join(sorted(members)))[:24] bucket = int(sha("doxa-basil-context-v0.1.0|" + group)[:8], 16) % 100 role = "train" if bucket < 70 else "validation" if bucket < 85 else "test" if representative in prior_seen: role = "train" for event in members: event_roles[event] = role event_groups[event] = group groups.append({"group_id": group, "event_ids": members, "split": role, "prior_babe_overlap": representative in prior_seen, "fresh_evaluation_eligible": representative not in prior_seen}) manifest = {"method": "doxa-basil-context-source-family-v2", "freeze_version": FREEZE_VERSION, "identity_rule": "Use a valid upstream UUID; use the pinned source-path hash for sentinel or missing UUIDs.", "target_admission": "Exclude normalized-empty unannotated targets from model files; retain all source rows in a separate receipt.", "upstream_revision": REVISION, "archive_sha256": ARCHIVE_SHA256, "prior_babe_input_sha256": prior_sha, "grouping": {"upstream_event_triplets": True, "canonical_urls": True, "normalized_exact_articles": True, "cross_event_word_5gram_jaccard_article": NEAR_ARTICLE_THRESHOLD, "cross_event_word_5gram_jaccard_sentence": NEAR_SENTENCE_THRESHOLD, "sentence_minimum_words": 12, "article_minimum_words": 100, "prior_babe_near_sentence_threshold": 0.85, "prior_babe_overlap_handling": "Entire connected event family assigned train; excluded from validation and test"}, "groups": groups, "event_assignments": event_roles, "event_group_ids": event_groups, "cross_event_connections": edges, "prior_babe_overlap": overlap, "freeze_basis": "Only source identities, source wording, upstream event IDs and prior-dataset overlap informed grouping; bias labels were excluded from role assignment."} manifest["freeze_sha256"] = sha(json.dumps(manifest, sort_keys=True, ensure_ascii=False)) return manifest def build(archive: Path, prior_babe: Path): records, hashes = read_source(archive) articles, sentences, titles, source_index = restore_articles(records, hashes) manifest = freeze_roles(articles, sentences, prior_babe) frozen = ROOT / "local" / "frozen-v2" old_manifest = frozen / "split_manifest.json" if old_manifest.exists() and json.loads(old_manifest.read_text())["freeze_sha256"] != manifest["freeze_sha256"]: raise RuntimeError("A different source-group freeze already exists. Create a new version before changing roles.") for row in sentences: row["split"] = manifest["event_assignments"][row["event_id"]] row["group_id"] = manifest["event_group_ids"][row["event_id"]] for article in articles: write_json(ROOT / "local" / "articles-v2" / (article["id"] + ".json"), article) eligible = [row for row in sentences if row["input_eligible"]] write_jsonl(frozen / "all_source_rows.jsonl", sentences) write_jsonl(frozen / "excluded_source_targets.jsonl", (row for row in sentences if not row["input_eligible"])) write_jsonl(frozen / "all.jsonl", eligible) for role in ["train", "validation", "test"]: write_jsonl(frozen / (role + ".jsonl"), (row for row in eligible if row["split"] == role)) write_jsonl(ROOT / "local" / "title_annotations-v2.jsonl", titles) write_json(ROOT / "work" / "source_index.json", source_index) write_json(old_manifest, manifest) counts = {"articles": len(articles), "events": len({article["event_id"] for article in articles}), "body_sentences": len(sentences), "model_eligible_sentences": len(eligible), "excluded_empty_targets": len(sentences) - len(eligible), "source_identity_path_fallbacks": sum(article["identity_basis"] != "upstream_uuid" for article in articles), "body_annotated_spans": sum(len(row["upstream_spans"]) for row in sentences), "title_annotated_spans": len(titles), "all_annotated_spans": sum(len(row["upstream_spans"]) for row in sentences) + len(titles), "span_types": dict(Counter(span["bias"] for row in sentences for span in row["upstream_spans"]) + Counter(row["annotation"]["bias"] for row in titles)), "body_sentence_label_combinations": dict(Counter(str(row["labels"]["lexical_bias"]) + str(row["labels"]["informational_bias"]) for row in sentences)), "split_sentences": dict(Counter(row["split"] for row in eligible)), "split_event_groups": dict(Counter(group["split"] for group in manifest["groups"])), "source_families": len(manifest["groups"]), "prior_babe_overlap_records": len(manifest["prior_babe_overlap"]), "freeze_sha256": manifest["freeze_sha256"], "new_independent_human_reviews": 0, "source_text_public_release": False, "upstream_annotations_public_release": False} write_json(ROOT / "work" / "basil_counts.json", counts) print(json.dumps(counts, indent=2, sort_keys=True)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--archive", type=Path, default=ROOT / "work" / "BASIL-4fdbc4f.tar.gz") parser.add_argument("--prior-babe", type=Path, default=ROOT.parents[1] / "improvement_release" / "benchmark" / "local" / "frozen" / "all.jsonl") parser.add_argument("--output-root", type=Path, default=ROOT, help="Write local restoration below this directory. Nothing is uploaded.") args = parser.parse_args() if not args.prior_babe.is_file(): parser.error("Supply --prior-babe with the exact prior BABE all.jsonl; an absent overlap audit cannot reproduce the release freeze.") ROOT = args.output_root.resolve() build(args.archive, args.prior_babe)