"""Create native viewer tables, documentation and an exact public allowlist.""" from collections import Counter from hashlib import sha256 import json from pathlib import Path import shutil import statistics import pyarrow as pa import pyarrow.parquet as pq HERE = Path(__file__).resolve().parent STAGE = HERE / "stage" WORK = HERE / "work" def dump(path, value): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def main(): counts = json.loads((WORK / "counts.json").read_text()) packets = pq.read_table(STAGE / "data/claim_packets/corpus.parquet").to_pylist() papers = pq.read_table(STAGE / "data/papers/corpus.parquet").to_pylist() challenges = [] for packet in packets: for prompt in packet["challenge_prompts"]: challenges.append({"id": packet["id"] + ":" + prompt["kind"], "packet_id": packet["id"], "document_id": packet["document_id"], "pmcid": packet["pmcid"], "title": packet["title"], "kind": prompt["kind"], "question": prompt["question"], "original_claim": packet["claim"], "source_anchor": prompt["source_anchor"], "gold_answer": None, "annotation_status": "unannotated", "human_review_count": 0}) references = json.loads((WORK / "retrieval_reference_index.json").read_text()) predictions = json.loads((WORK / "retrieval_predictions.json").read_text()) for name, rows in (("review_prompts", challenges), ("retrieval_reference_index", references), ("retrieval_evaluation", predictions)): folder = STAGE / "data" / name folder.mkdir(parents=True, exist_ok=True) pq.write_table(pa.Table.from_pylist(rows), folder / "corpus.parquet", compression="zstd") tools = STAGE / "tools" tools.mkdir(exist_ok=True) for name in ("build_study.py", "retrieval_benchmark.py", "analyze_retrieval.py", "study_search.py", "validate_study.py", "test_study.py", "finalize_release.py", "requirements.txt", "requirements-retrieval.txt"): shutil.copy2(HERE / name, tools / name) for name in ("SCHEMA.md", "ANNOTATION.md"): shutil.copy2(HERE / name, STAGE / name) examples = STAGE / "examples" examples.mkdir(exist_ok=True) for name in ("search_example_lexical.json", "search_example_hybrid.json"): if (WORK / name).exists(): shutil.copy2(WORK / name, examples / name) results = json.loads((WORK / "retrieval_results.json").read_text()) integrity = json.loads((STAGE / "integrity_report.json").read_text()) assert integrity["status"] == "pass" and integrity["paragraphs"] == counts["paragraphs"] and integrity["packets"] == counts["claim_packets"] for name, fingerprint in integrity["artifact_sha256"].items(): assert sha256((STAGE / name).read_bytes()).hexdigest() == fingerprint source_manifest_sha = sha256((STAGE / "source_split_manifest.json").read_bytes()).hexdigest() reproduction = json.loads((WORK / "reproduction_parity_final.json").read_text()) search_checks = json.loads((WORK / "search_validation.json").read_text()) assert reproduction["source_manifest_sha256"] == search_checks["source_manifest_sha256"] == source_manifest_sha assert reproduction["all_packet_fields_identical"] and all(x["all_result_and_window_source_spans_verified"] for x in search_checks["examples"]) assert "Ran 8 tests" in (WORK / "unit-test-final.log").read_text() and "\nOK" in (WORK / "unit-test-final.log").read_text() dump(STAGE / "validation_receipts.json", {"source_manifest_sha256": source_manifest_sha, "source_integrity_assertions": integrity["assertions"], "unit_tests": {"passed": 8, "failed": 0}, "frozen_input_reproduction": reproduction, "local_search_smoke": search_checks, "human_retrieval_restore": json.loads((WORK / "retrieval-restore.log").read_text()), "new_human_reviews": 0}) audit = HERE.parent / "quality/ACADEMIC_RETRIEVAL_INTEGRITY.json" assert json.loads(audit.read_text())["status"] == "pass" shutil.copy2(audit, STAGE / "evaluation/independent_retrieval_audit.json") errors = json.loads((WORK / "retrieval_error_analysis.json").read_text()) metrics = results["methods"] metric_rows = "\n".join(f"| {name} | {row['human_span_hit@5']:.2%} | {row['complete_human_rationale_set@5']:.2%} | {row['MRR50']:.4f} | {errors['method_failures'][name]['human_span_misses_at5']} |" for name, row in metrics.items()) coverage = results["source_coverage"] truncated = sum(x["dense_truncated_units"] for x in coverage) total_units = sum(x["retrieval_units"] for x in coverage) topics = Counter(x["corpus_slice"] for x in papers) languages = Counter(x["language"] for x in papers) schema = {"version": "0.2.0", "offset_unit": "unicode_code_points", "page_mapping": "null_for_JATS_XML", "tables": {name: {"path": str(path.relative_to(STAGE)), "rows": pq.read_metadata(path).num_rows, "arrow_schema": str(pq.read_schema(path))} for path in sorted((STAGE / "data").glob("*/corpus.parquet")) for name in [path.parent.name]}, "political_packet_annotation_status": "unannotated", "political_packet_gold_label": None, "political_human_reviews": 0, "trained_model_promoted": False} dump(STAGE / "schema.json", schema) dump(STAGE / "summary_statistics.json", { "claim_characters": {"minimum": min(len(x["claim"]) for x in packets), "median": statistics.median(len(x["claim"]) for x in packets), "maximum": max(len(x["claim"]) for x in packets)}, "focal_paragraph_characters_median": statistics.median(len(x["focal_paragraph"]["quote"]) for x in packets), "source_prose_characters": sum(len(x["text"]) for x in papers), "source_slices": dict(topics), "source_languages": dict(languages), "supervised_training_eligible": 0, "gold_evaluation_eligible": 0, "candidate_unsupervised_training_packets": sum(x["retrieval_unsupervised_eligible"] for x in packets), "candidate_contexts_are_reference_labels": False, }) configs = "\n".join(f" - config_name: {name}\n data_files:\n - split: corpus\n path: data/{name}/corpus.parquet" for name in schema["tables"]) card = f'''--- pretty_name: DOXA Study Evidence — exact claims and full-paper context language: {chr(10).join(' - ' + language for language in sorted(languages))} license: other license_name: source-specific-cc-by-and-cc0 license_link: LICENSE task_categories: - text-retrieval tags: - political-science - public-policy - evidence-retrieval - scientific-literature - source-provenance - tacitus - doxa size_categories: - 1K 0 LIMIT 20; SELECT kind, count(*) AS review_questions FROM read_parquet('hf://datasets/Giuliocc/doxa-study-evidence/data/review_prompts/corpus.parquet') GROUP BY kind; SELECT pmcid, title, license.identifier, source_xml_sha256 FROM read_parquet('hf://datasets/Giuliocc/doxa-study-evidence/data/papers/corpus.parquet') ORDER BY pmcid LIMIT 20; ''', encoding="utf-8") report = f'''# Academic evidence release report Local staged release: {counts['papers']} explicitly licensed papers, {counts['paragraphs']} paragraphs, {counts['claim_packets']} distinct claim/context packets and {len(challenges)} rule-authored review questions. Collection target of approximately 300 papers / at least 5,000 packets: **{'met' if counts['targets_met'] else 'not yet met'}**. No completed political human reviews; no supervised/gold-eligible political packets; no trained political verifier promoted. Zero new spend. The frozen human retrieval diagnostic contains {results['query_count']} prompts from {results['source_count']} papers, with all four methods and all failures retained. BM25 hit@5 68.53%, MiniLM 56.35%, RRF 65.48%, fixed slot reranker 77.66%. The latter requires supplied human outcome/intervention/comparator slots and remains a biomedical retrieval diagnostic. Dense truncation affects {truncated}/{total_units} chunks. The political search smoke uses complete overlapping token windows and exact source spans; it is not an accuracy reference. Sources, rights, exact spans, candidate self-copy exclusions, annotation provenance and serialized integrity are checked. Independent release quality review is owned separately under expansion_release/quality. Publication is owned by the parent release process. Expected repository: https://huggingface.co/datasets/Giuliocc/doxa-study-evidence . This local report does not claim the URL has been published or verified. Public files are exclusively under stage/ and its exact publication_manifest.json. Private upstream source caches, raw XML, query/rationale quotations from the biomedical diagnostic, model cache, virtual environments and work logs are excluded. Frozen licensed prose input, rights/source receipts, native Parquet viewers, original tools, protocol/results/failures and annotation instructions are included. ''' (HERE / "RELEASE_REPORT.md").write_text(report, encoding="utf-8") (STAGE / "RELEASE_REPORT.md").write_text(report, encoding="utf-8") allowed = { "README.md", "LICENSE", "RELEASE_REPORT.md", "SCHEMA.md", "ANNOTATION.md", "counts.json", "exclusions.json", "schema.json", "summary_statistics.json", "queries.sql", "integrity_report.json", "source_split_manifest.json", "duplicate_quarantine.json", "validation_receipts.json", "sources/articles.jsonl.gz", "sources/raw_xml_fetch_receipts.json", "examples/search_example_lexical.json", "examples/search_example_hybrid.json", *("data/" + name + "/corpus.parquet" for name in schema["tables"]), *("tools/" + name for name in ("build_study.py", "retrieval_benchmark.py", "analyze_retrieval.py", "study_search.py", "validate_study.py", "test_study.py", "finalize_release.py", "requirements.txt", "requirements-retrieval.txt")), *("evaluation/" + name for name in ("retrieval_protocol.json", "retrieval_reference_index.json", "retrieval_frozen_manifest.json", "retrieval_source_exclusions.json", "retrieval_results.json", "retrieval_results_first.json", "retrieval_predictions.json", "retrieval_error_analysis.json", "retrieval_failures.json", "first_scoring_receipt.json", "independent_retrieval_audit.json", "upstream_LICENSE", "upstream_README.annotation_process.md", "upstream_annotations_README.md")), } actual = {str(path.relative_to(STAGE)) for path in STAGE.rglob("*") if path.is_file() and path.name != "publication_manifest.json"} assert actual == allowed, {"unexpected": sorted(actual - allowed), "missing": sorted(allowed - actual)} manifest = [{"path": name, "sha256": sha256((STAGE / name).read_bytes()).hexdigest(), "bytes": (STAGE / name).stat().st_size} for name in sorted(allowed)] dump(STAGE / "publication_manifest.json", {"repository": "Giuliocc/doxa-study-evidence", "repository_type": "dataset", "visibility": "public", "publish_authorization_owner": "parent_release_process", "files": manifest, "total_bytes": sum(x["bytes"] for x in manifest), "excluded": ["work/", "cache/", "raw XML", "upstream biomedical question/rationale/article text", "model weights", "credentials"]}) print(json.dumps({"papers": counts['papers'], "packets": counts['claim_packets'], "review_prompts": len(challenges), "public_files": len(manifest), "public_bytes": sum(x["bytes"] for x in manifest)}, indent=2)) if __name__ == "__main__": main()