| |
| """Prepare the PATSTAT AI master dataset for a private Hugging Face repository.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import gzip |
| import hashlib |
| import json |
| import shutil |
| from pathlib import Path |
|
|
| import pyarrow as pa |
| import pyarrow.csv as pacsv |
| import pyarrow.parquet as pq |
|
|
|
|
| PERIODS = ( |
| (0, 1950, "before_1950"), |
| (1950, 1959, "1950s"), |
| (1960, 1969, "1960s"), |
| (1970, 1979, "1970s"), |
| (1980, 1989, "1980s"), |
| (1990, 1999, "1990s"), |
| (2000, 2009, "2000s"), |
| (2010, 2019, "2010s"), |
| (2020, 2026, "2020_2026"), |
| ) |
|
|
|
|
| def period_label(year: int | None) -> str: |
| if year is None: |
| return "unknown_year" |
| for start, end, label in PERIODS: |
| if start <= year <= end: |
| return label |
| return "after_2026" |
|
|
|
|
| def sha256(path: Path) -> str: |
| digest = hashlib.sha256() |
| with path.open("rb") as stream: |
| for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): |
| digest.update(block) |
| return digest.hexdigest() |
|
|
|
|
| def copy_supporting_files(source_dir: Path, output_dir: Path) -> None: |
| mappings = { |
| "HUGGINGFACE_README.md": "README.md", |
| "PATSTAT_AI_COMPLETE_MASTER_TECHNICAL_REPORT.pdf": "documentation/technical_report.pdf", |
| "PATSTAT_AI_COMPLETE_MASTER_TECHNICAL_REPORT.tex": "documentation/technical_report.tex", |
| "DATASET_REPORT.md": "documentation/dataset_report.md", |
| "final_master_column_descriptive_statistics.csv": "metadata/column_descriptive_statistics.csv", |
| "ipc_cpc_missingness_by_year.csv": "metadata/ipc_cpc_missingness_by_year.csv", |
| "integration_report.json": "metadata/integration_report.json", |
| "coalesced_fields_report.json": "metadata/coalesced_fields_report.json", |
| "ipc_cpc_backfill_1950_2026_report.json": "metadata/ipc_cpc_backfill_report.json", |
| "build_complete_master_20260712.py": "code/build_complete_master.py", |
| "finalize_legacy_country_flags.py": "code/finalize_legacy_country_flags.py", |
| "coalesce_new_source_fields.py": "code/coalesce_new_source_fields.py", |
| "apply_ipc_cpc_backfill_1990_2022.py": "code/apply_ipc_cpc_backfill.py", |
| "prepare_huggingface_dataset.py": "code/prepare_huggingface_dataset.py", |
| } |
| for source_name, target_name in mappings.items(): |
| source = source_dir / source_name |
| if source.exists(): |
| target = output_dir / target_name |
| target.parent.mkdir(parents=True, exist_ok=True) |
| shutil.copy2(source, target) |
|
|
|
|
| def build_dataset(source: Path, output_dir: Path) -> dict: |
| data_dir = output_dir / "data" / "by_priority_period" |
| if data_dir.exists(): |
| shutil.rmtree(data_dir) |
| data_dir.mkdir(parents=True, exist_ok=True) |
| writers: dict[str, pq.ParquetWriter] = {} |
| counts: dict[str, int] = {} |
| schema: pa.Schema | None = None |
|
|
| with gzip.open(source, "rt", encoding="utf-8-sig", newline="") as stream: |
| columns = next(csv.reader(stream)) |
| read_options = pacsv.ReadOptions( |
| block_size=64 * 1024 * 1024, |
| use_threads=True, |
| column_names=columns, |
| skip_rows=1, |
| encoding="utf8", |
| ) |
| convert_options = pacsv.ConvertOptions( |
| column_types={column: pa.string() for column in columns}, |
| strings_can_be_null=True, |
| ) |
| reader = pacsv.open_csv(source, read_options=read_options, convert_options=convert_options) |
|
|
| try: |
| for batch in reader: |
| table = pa.Table.from_batches([batch]) |
| if schema is None: |
| schema = table.schema |
| years = table.column("priority_year").to_pylist() |
| labels = [period_label(int(value)) if value is not None else "unknown_year" for value in years] |
| for label in sorted(set(labels)): |
| indices = pa.array([index for index, item in enumerate(labels) if item == label]) |
| subset = table.take(indices) |
| target = data_dir / f"patstat_ai_{label}.parquet" |
| if label not in writers: |
| writers[label] = pq.ParquetWriter( |
| target, |
| subset.schema, |
| compression="zstd", |
| compression_level=6, |
| use_dictionary=True, |
| ) |
| writers[label].write_table(subset, row_group_size=50_000) |
| counts[label] = counts.get(label, 0) + subset.num_rows |
| finally: |
| for writer in writers.values(): |
| writer.close() |
|
|
| if schema is None: |
| raise RuntimeError("The source dataset is empty.") |
|
|
| manifest_rows = [] |
| for path in sorted(data_dir.glob("*.parquet")): |
| label = path.stem.removeprefix("patstat_ai_") |
| manifest_rows.append( |
| { |
| "category": label, |
| "rows": counts[label], |
| "bytes": path.stat().st_size, |
| "sha256": sha256(path), |
| "path": str(path.relative_to(output_dir)), |
| } |
| ) |
|
|
| metadata_dir = output_dir / "metadata" |
| metadata_dir.mkdir(parents=True, exist_ok=True) |
| with (metadata_dir / "file_manifest.csv").open("w", encoding="utf-8", newline="") as stream: |
| writer = csv.DictWriter(stream, fieldnames=["category", "rows", "bytes", "sha256", "path"]) |
| writer.writeheader() |
| writer.writerows(manifest_rows) |
| with (metadata_dir / "schema.json").open("w", encoding="utf-8") as stream: |
| json.dump( |
| [{"name": field.name, "type": str(field.type), "nullable": field.nullable} for field in schema], |
| stream, |
| indent=2, |
| ) |
|
|
| return { |
| "source": str(source), |
| "source_sha256": sha256(source), |
| "rows": sum(counts.values()), |
| "columns": len(schema), |
| "categories": counts, |
| "files": manifest_rows, |
| } |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--source", type=Path, required=True) |
| parser.add_argument("--output", type=Path, required=True) |
| args = parser.parse_args() |
| args.output.mkdir(parents=True, exist_ok=True) |
| result = build_dataset(args.source, args.output) |
| copy_supporting_files(args.source.parent, args.output) |
| with (args.output / "metadata" / "build_summary.json").open("w", encoding="utf-8") as stream: |
| json.dump(result, stream, indent=2) |
| print(json.dumps(result, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|