Download validate.py from cometadata/crossref-datacite-citations-datacite-enrichment-format: direct link, hf CLI and curl.
- Browser
- Download file 4.55 kB
-
https://huggingface.co/datasets/cometadata/crossref-datacite-citations-datacite-enrichment-format/resolve/main/validate.py
- Command line
-
hf download hf://datasets/cometadata/crossref-datacite-citations-datacite-enrichment-format/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/cometadata/crossref-datacite-citations-datacite-enrichment-format/resolve/main/validate.py
4.55 kB
| #!/usr/bin/env python3 | |
| """Read every output record, validate its schemas and independently recompute its key.""" | |
| import argparse | |
| from collections import Counter | |
| import gzip | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import re | |
| import fastjsonschema | |
| import xxhash | |
| DOI_NAME = re.compile(r"\A10\.[0-9]+(?:\.[0-9]+)*/.+\Z") | |
| CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]") | |
| def is_lowercase_doi_name(value: str) -> bool: | |
| return (value.strip() == value and not CONTROL.search(value) | |
| and DOI_NAME.match(value) is not None and value == value.lower()) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("dataset_dir", type=Path) | |
| args = parser.parse_args() | |
| root = args.dataset_dir | |
| manifest = json.loads((root / "manifest.json").read_text()) | |
| check_enrichment = fastjsonschema.compile(json.loads( | |
| (root / "provenance/enrichment_input_schema.json").read_text())) | |
| check_value = fastjsonschema.compile(json.loads( | |
| (root / "provenance/related_identifier_subset_schema.json").read_text())) | |
| expected = manifest["counts"] | |
| counts = Counter() | |
| keys = set() | |
| dois = set() | |
| files = manifest["data_files"] | |
| # Every file under data/, not only data/*.jsonl.gz, so a leftover | |
| # subdirectory that the default config would not load also fails. | |
| on_disk = {str(p.relative_to(root)) for p in (root / "data").rglob("*") if p.is_file()} | |
| listed = {item["path"] for item in files} | |
| assert on_disk == listed, f"unlisted {sorted(on_disk - listed)}, missing {sorted(listed - on_disk)}" | |
| for item in files: | |
| path = root / item["path"] | |
| with path.open("rb") as stream: | |
| digest = hashlib.file_digest(stream, "sha256").hexdigest() | |
| assert digest == item["sha256"], f"{item['path']}: sha256 {digest} != manifest {item['sha256']}" | |
| n = 0 | |
| with gzip.open(path, "rt", encoding="utf-8") as stream: | |
| for line in stream: | |
| row = json.loads(line) | |
| check_enrichment(row) | |
| value = row["enrichedValue"] | |
| check_value(value) | |
| assert set(row) == {"doi", "action", "field", "enrichedValue", "sourceId", "contentKey"} | |
| assert row["action"] == "insert" and row["field"] == "relatedIdentifiers" | |
| assert row["sourceId"] == manifest["source_id"], f"sourceId {row['sourceId']!r}" | |
| assert is_lowercase_doi_name(row["doi"]), row["doi"] | |
| assert is_lowercase_doi_name(value["relatedIdentifier"]), value["relatedIdentifier"] | |
| # Every object key here is ASCII and every value is a string. | |
| # Sorted, compact UTF-8 JSON is therefore JCS for this domain. | |
| # This intentionally uses a different serializer than convert.py. | |
| canonical = json.dumps( | |
| [manifest["method"]["name"], row["doi"], row["field"], row["action"], value], | |
| ensure_ascii=False, sort_keys=True, separators=(",", ":"), | |
| ).encode("utf-8") | |
| expected_key = xxhash.xxh3_128_hexdigest(canonical) | |
| assert row["contentKey"] == expected_key, ( | |
| f"{item['path']}: contentKey {row['contentKey']} != recomputed {expected_key}") | |
| key = bytes.fromhex(expected_key) | |
| assert key not in keys, f"{item['path']}: duplicate contentKey {expected_key}" | |
| keys.add(key) | |
| dois.add(row["doi"]) | |
| counts["enrichments"] += 1 | |
| counts["to_arxiv_dois"] += row["doi"].startswith("10.48550/") | |
| n += 1 | |
| assert n == item["rows"], f"{item['path']}: {n} records != manifest {item['rows']}" | |
| print(f"Validated {item['path']}: {n:,} records", flush=True) | |
| assert counts["enrichments"] == expected["enrichments"] | |
| assert len(dois) == expected["unique_enriched_dois"] | |
| assert counts["to_arxiv_dois"] == expected["enrichments_to_arxiv_dois"] | |
| report = {"status": "passed", "records_read_and_validated": counts["enrichments"], | |
| "unique_target_dois": len(dois), "data_shards": len(files), | |
| "enrichments_to_arxiv_dois": counts["to_arxiv_dois"], | |
| "schema_errors": 0, "content_key_mismatches": 0, "duplicate_content_keys": 0, | |
| "file_checksum_mismatches": 0} | |
| (root / "validation_report.json").write_text(json.dumps(report, indent=2) + "\n") | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |