Datasets:
Download scripts/validate_updated_snapshot.py from haydn-jones/PubMed-Metadata: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/haydn-jones/PubMed-Metadata/resolve/main/scripts/validate_updated_snapshot.py
- Command line
-
hf download hf://datasets/haydn-jones/PubMed-Metadata/scripts/validate_updated_snapshot.py
-
curl -L -o validate_updated_snapshot.py https://huggingface.co/datasets/haydn-jones/PubMed-Metadata/resolve/main/scripts/validate_updated_snapshot.py
10.8 kB
| #!/usr/bin/env python3 | |
| """Independently validate an incrementally updated PubMed-Metadata snapshot.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import duckdb | |
| import pyarrow.parquet as pq | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--old-data-dir", type=Path, required=True) | |
| parser.add_argument("--new-data-dir", type=Path, required=True) | |
| parser.add_argument("--active-at-cutoff", type=Path, required=True) | |
| parser.add_argument("--active-current", type=Path, required=True) | |
| parser.add_argument("--changed-rows", type=Path, required=True) | |
| parser.add_argument("--manifest", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--temp-dir", type=Path, required=True) | |
| parser.add_argument("--shard-rows", type=int, default=200_000) | |
| return parser.parse_args() | |
| def sql_path(path: Path) -> str: | |
| return str(path).replace("'", "''") | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| while chunk := handle.read(8 * 1024 * 1024): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def main() -> None: | |
| args = parse_args() | |
| manifest = json.loads(args.manifest.read_text()) | |
| expected_rows = int(manifest["output"]["rows"]) | |
| expected_shards = int(manifest["output"]["shards"]) | |
| expected_supplement_rows = int(manifest["merge"]["output_supplement_rows"]) | |
| expected_old_supplement_rows = int(manifest["merge"]["old_supplement_rows"]) | |
| expected_pmcid_fallback_rows = int(manifest["merge"]["pmcid_fallback_rows"]) | |
| expected_current_rows = int(manifest["source"]["active_current"]) | |
| old_files = sorted(args.old_data_dir.glob("train-*.parquet")) | |
| new_files = sorted(args.new_data_dir.glob("train-*.parquet")) | |
| if not old_files or not new_files: | |
| raise ValueError("Both data directories must contain train Parquet shards") | |
| schema = pq.ParquetFile(old_files[0]).schema_arrow | |
| footer_rows = 0 | |
| footer_bytes = 0 | |
| schema_mismatches: list[str] = [] | |
| shard_rows: list[int] = [] | |
| checksum_mismatches: list[str] = [] | |
| manifest_files = {Path(row["path"]).name: row for row in manifest["output"]["files"]} | |
| for path in new_files: | |
| parquet_file = pq.ParquetFile(path) | |
| footer_rows += parquet_file.metadata.num_rows | |
| footer_bytes += path.stat().st_size | |
| shard_rows.append(parquet_file.metadata.num_rows) | |
| if not parquet_file.schema_arrow.equals(schema, check_metadata=True): | |
| schema_mismatches.append(path.name) | |
| expected = manifest_files.get(path.name) | |
| if expected is None or sha256_file(path) != expected["sha256"]: | |
| checksum_mismatches.append(path.name) | |
| expected_names = [ | |
| f"train-{index:05d}-of-{expected_shards:05d}.parquet" | |
| for index in range(expected_shards) | |
| ] | |
| args.temp_dir.mkdir(parents=True, exist_ok=True) | |
| connection = duckdb.connect( | |
| config={ | |
| "threads": "24", | |
| "memory_limit": "96GB", | |
| "temp_directory": str(args.temp_dir), | |
| } | |
| ) | |
| old_glob = sql_path(args.old_data_dir / "train-*.parquet") | |
| new_glob = sql_path(args.new_data_dir / "train-*.parquet") | |
| cutoff_path = sql_path(args.active_at_cutoff) | |
| current_path = sql_path(args.active_current) | |
| changed_path = sql_path(args.changed_rows) | |
| connection.execute(f"CREATE VIEW old_data AS SELECT * FROM read_parquet('{old_glob}')") | |
| connection.execute(f"CREATE VIEW new_data AS SELECT * FROM read_parquet('{new_glob}')") | |
| connection.execute(f"CREATE VIEW cutoff_pmids AS SELECT pmid FROM read_parquet('{cutoff_path}')") | |
| connection.execute(f"CREATE VIEW current_pmids AS SELECT pmid FROM read_parquet('{current_path}')") | |
| connection.execute(f"CREATE VIEW changed_rows AS SELECT * FROM read_parquet('{changed_path}')") | |
| connection.execute( | |
| """ | |
| CREATE VIEW old_supplement AS | |
| SELECT old_data.* | |
| FROM old_data | |
| LEFT JOIN cutoff_pmids USING (pmid) | |
| WHERE old_data.pmid IS NULL OR cutoff_pmids.pmid IS NULL | |
| """ | |
| ) | |
| connection.execute( | |
| """ | |
| CREATE VIEW old_supplement_noncurrent AS | |
| SELECT old_supplement.* | |
| FROM old_supplement | |
| ANTI JOIN current_pmids USING (pmid) | |
| """ | |
| ) | |
| connection.execute( | |
| """ | |
| CREATE VIEW new_supplement AS | |
| SELECT new_data.* | |
| FROM new_data | |
| ANTI JOIN current_pmids USING (pmid) | |
| """ | |
| ) | |
| aggregate_row = connection.execute( | |
| """ | |
| SELECT | |
| count(*) AS total_rows, | |
| count(pmid) AS nonnull_pmids, | |
| count(DISTINCT pmid) AS distinct_pmids, | |
| count(*) - count(pmid) AS null_pmids, | |
| count(pmcid) AS rows_with_pmcid, | |
| count(DISTINCT pmcid) AS distinct_pmcids, | |
| count(*) FILTER (WHERE is_oa) AS oa_rows, | |
| count(*) FILTER (WHERE pmcid IS NOT NULL AND NOT is_oa) AS pmcid_not_oa, | |
| count(*) FILTER (WHERE is_oa AND pmcid IS NULL) AS oa_without_pmcid, | |
| count(title) AS titled_rows, | |
| count(abstract) AS abstract_rows, | |
| count(doi) AS doi_rows | |
| FROM new_data | |
| """ | |
| ).fetchone() | |
| aggregate_names = [column[0] for column in connection.description] | |
| aggregate = dict(zip(aggregate_names, aggregate_row, strict=True)) | |
| counts = { | |
| "current_pmids_missing": connection.execute( | |
| "SELECT count(*) FROM current_pmids ANTI JOIN new_data USING (pmid)" | |
| ).fetchone()[0], | |
| "duplicate_nonnull_pmids": connection.execute( | |
| """ | |
| SELECT count(*) FROM ( | |
| SELECT pmid FROM new_data WHERE pmid IS NOT NULL | |
| GROUP BY pmid HAVING count(*) > 1 | |
| ) | |
| """ | |
| ).fetchone()[0], | |
| "old_supplement_rows": connection.execute("SELECT count(*) FROM old_supplement").fetchone()[0], | |
| "new_supplement_rows": connection.execute("SELECT count(*) FROM new_supplement").fetchone()[0], | |
| "old_supplement_pmcids_missing": connection.execute( | |
| "SELECT count(*) FROM old_supplement ANTI JOIN new_data USING (pmcid)" | |
| ).fetchone()[0], | |
| "preserved_supplement_rows_missing": connection.execute( | |
| """ | |
| SELECT count(*) FROM ( | |
| SELECT * FROM old_supplement_noncurrent | |
| EXCEPT | |
| SELECT * FROM new_supplement | |
| ) | |
| """ | |
| ).fetchone()[0], | |
| "unexpected_new_supplement_rows": connection.execute( | |
| """ | |
| SELECT count(*) FROM ( | |
| SELECT * FROM new_supplement | |
| EXCEPT | |
| SELECT * FROM old_supplement_noncurrent | |
| ) | |
| """ | |
| ).fetchone()[0], | |
| "changed_rows_missing": connection.execute( | |
| "SELECT count(*) FROM changed_rows ANTI JOIN new_data USING (pmid)" | |
| ).fetchone()[0], | |
| } | |
| unchanged_columns = [ | |
| field.name for field in schema if field.name not in {"pmcid", "is_oa", "article_ids"} | |
| ] | |
| changed_differences = " OR ".join( | |
| f'changed_rows."{column}" IS DISTINCT FROM new_data."{column}"' | |
| for column in unchanged_columns | |
| if column != "pmid" | |
| ) | |
| counts["changed_core_mismatches"] = connection.execute( | |
| f""" | |
| SELECT count(*) | |
| FROM changed_rows | |
| INNER JOIN new_data USING (pmid) | |
| WHERE {changed_differences} | |
| """ | |
| ).fetchone()[0] | |
| counts["changed_nonnull_pmcid_mismatches"] = connection.execute( | |
| """ | |
| SELECT count(*) | |
| FROM changed_rows | |
| INNER JOIN new_data USING (pmid) | |
| WHERE changed_rows.pmcid IS NOT NULL | |
| AND changed_rows.pmcid IS DISTINCT FROM new_data.pmcid | |
| """ | |
| ).fetchone()[0] | |
| counts["pmcid_fallback_rows"] = connection.execute( | |
| """ | |
| SELECT count(*) | |
| FROM changed_rows | |
| INNER JOIN new_data USING (pmid) | |
| WHERE changed_rows.pmcid IS NULL AND new_data.pmcid IS NOT NULL | |
| """ | |
| ).fetchone()[0] | |
| checks = { | |
| "file_count": len(new_files) == expected_shards, | |
| "file_names": [path.name for path in new_files] == expected_names, | |
| "footer_rows": footer_rows == expected_rows, | |
| "footer_bytes": footer_bytes == int(manifest["output"]["bytes"]), | |
| "shard_row_limits": ( | |
| all(rows == args.shard_rows for rows in shard_rows[:-1]) | |
| and shard_rows[-1] == expected_rows % args.shard_rows | |
| ), | |
| "schema_matches_existing": not schema_mismatches, | |
| "checksums_match_manifest": not checksum_mismatches, | |
| "aggregate_rows": aggregate["total_rows"] == expected_rows, | |
| "nonnull_pmids_unique": aggregate["nonnull_pmids"] == aggregate["distinct_pmids"], | |
| "current_pubmed_complete": counts["current_pmids_missing"] == 0, | |
| "official_row_count": expected_rows - counts["new_supplement_rows"] == expected_current_rows, | |
| "old_supplement_count": counts["old_supplement_rows"] == expected_old_supplement_rows, | |
| "new_supplement_count": counts["new_supplement_rows"] == expected_supplement_rows, | |
| "all_old_supplement_pmcids_present": counts["old_supplement_pmcids_missing"] == 0, | |
| "preserved_supplement_exact": counts["preserved_supplement_rows_missing"] == 0, | |
| "no_unexpected_supplement_rows": counts["unexpected_new_supplement_rows"] == 0, | |
| "all_changed_rows_present": counts["changed_rows_missing"] == 0, | |
| "changed_core_rows_exact": counts["changed_core_mismatches"] == 0, | |
| "changed_nonnull_pmcids_exact": counts["changed_nonnull_pmcid_mismatches"] == 0, | |
| "expected_pmcid_fallbacks": counts["pmcid_fallback_rows"] == expected_pmcid_fallback_rows, | |
| "pmcid_implies_oa": aggregate["pmcid_not_oa"] == 0, | |
| } | |
| output = { | |
| "all_checks_pass": all(checks.values()), | |
| "checks": checks, | |
| "files": { | |
| "old_shards": len(old_files), | |
| "new_shards": len(new_files), | |
| "footer_rows": footer_rows, | |
| "footer_bytes": footer_bytes, | |
| "schema_mismatches": schema_mismatches, | |
| "checksum_mismatches": checksum_mismatches, | |
| }, | |
| "aggregate": aggregate, | |
| "comparison_counts": counts, | |
| } | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(output, indent=2) + "\n") | |
| print(json.dumps(output, indent=2), flush=True) | |
| if not output["all_checks_pass"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |