Download convert.py from semvec/subreddits-directory: direct link, hf CLI and curl.
- Browser
- Download file 7.42 kB
-
https://huggingface.co/datasets/semvec/subreddits-directory/resolve/main/convert.py
- Command line
-
hf download hf://datasets/semvec/subreddits-directory/convert.py
-
curl -L -o convert.py https://huggingface.co/datasets/semvec/subreddits-directory/resolve/main/convert.py
7.42 kB
| """Convert subreddit metadata to Parquet with explicit semantic types. | |
| Usage: python convert.py path/to/subreddits_with_details.csv output_directory | |
| Requires pyarrow. No Reddit requests, filtering, or metadata refresh. | |
| """ | |
| import csv | |
| import hashlib | |
| import itertools | |
| import json | |
| import sys | |
| from datetime import datetime, timedelta, timezone | |
| from decimal import Decimal | |
| from pathlib import Path | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) | |
| TIMESTAMP = pa.timestamp("us", tz="UTC") | |
| TYPES = { | |
| "created_utc": TIMESTAMP, | |
| "retrieved_on": TIMESTAMP, | |
| "over18": pa.bool_(), | |
| "subscribers": pa.int64(), | |
| } | |
| def parse_cell(name, value): | |
| if value == "": | |
| return None | |
| if name == "created_utc": | |
| parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) | |
| if parsed.tzinfo is None: | |
| raise ValueError(f"Creation timestamp lacks timezone: {value!r}") | |
| return parsed.astimezone(timezone.utc) | |
| if name == "retrieved_on": | |
| micros = Decimal(value) * 1_000_000 | |
| if not micros.is_finite() or micros != micros.to_integral_value(): | |
| raise ValueError(f"Invalid or sub-microsecond retrieval timestamp: {value!r}") | |
| return EPOCH + timedelta(microseconds=int(micros)) | |
| if name == "over18": | |
| if value not in ("True", "False"): | |
| raise ValueError(f"Unexpected boolean: {value!r}") | |
| return value == "True" | |
| if name == "subscribers": | |
| if not value.isascii() or not value.isdecimal(): | |
| raise ValueError(f"Invalid subscriber count: {value!r}") | |
| return int(value) | |
| return value | |
| def verify_cell(name, original, converted): | |
| """Check output against source using inverse semantic comparisons.""" | |
| if original == "": | |
| return converted is None | |
| if converted is None: | |
| return False | |
| if name == "created_utc": | |
| # The source uses either minute or second precision, always UTC. | |
| return original in ( | |
| converted.strftime("%Y-%m-%dT%H:%M:%SZ"), | |
| converted.strftime("%Y-%m-%dT%H:%MZ") | |
| if converted.second == converted.microsecond == 0 else "", | |
| ) and converted.utcoffset() == timedelta(0) | |
| if name == "retrieved_on": | |
| delta = converted - EPOCH | |
| micros = (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds | |
| return Decimal(micros) / 1_000_000 == Decimal(original) | |
| if name == "over18": | |
| return type(converted) is bool and str(converted) == original | |
| if name == "subscribers": | |
| return type(converted) is int and Decimal(converted) == Decimal(original) | |
| return converted == original | |
| def sha256(path): | |
| with path.open("rb") as stream: | |
| return hashlib.file_digest(stream, "sha256").hexdigest() | |
| def convert(source, output): | |
| csv.field_size_limit(sys.maxsize) | |
| output.mkdir(parents=True, exist_ok=True) | |
| target = output / "data" / "data.parquet" | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| row_count = 0 | |
| with source.open(encoding="utf-8", newline="") as stream: | |
| reader = csv.reader(stream, strict=True) | |
| columns = next(reader) | |
| assert len(set(columns)) == len(columns), "Duplicate source column names" | |
| schema = pa.schema([(name, TYPES.get(name, pa.string())) for name in columns]) | |
| empty_counts = dict.fromkeys(columns, 0) | |
| with pq.ParquetWriter(target, schema, compression="zstd", write_page_index=True) as writer: | |
| while rows := list(itertools.islice(reader, 5000)): | |
| assert all(len(row) == len(columns) for row in rows), "Ragged CSV row" | |
| arrays = [] | |
| for index, name in enumerate(columns): | |
| values = [row[index] for row in rows] | |
| empty_counts[name] += values.count("") | |
| arrays.append(pa.array( | |
| [parse_cell(name, value) for value in values], | |
| type=schema.field(name).type, | |
| )) | |
| writer.write_table(pa.Table.from_arrays(arrays, schema=schema)) | |
| row_count += len(rows) | |
| # Independently read the original CSV again and compare every output cell. | |
| verified_rows = 0 | |
| null_counts = dict.fromkeys(columns, 0) | |
| parquet = pq.ParquetFile(target) | |
| assert parquet.schema_arrow.equals(schema), "Parquet schema mismatch" | |
| with source.open(encoding="utf-8", newline="") as stream: | |
| reader = csv.reader(stream, strict=True) | |
| assert next(reader) == columns | |
| for batch in parquet.iter_batches(batch_size=5000): | |
| assert batch.schema.names == columns | |
| for name, array in zip(columns, batch.columns): | |
| null_counts[name] += array.null_count | |
| for row in zip(*(column.to_pylist() for column in batch.columns)): | |
| original = next(reader) | |
| assert all( | |
| verify_cell(name, old, new) | |
| for name, old, new in zip(columns, original, row) | |
| ), f"Mismatch at row {verified_rows}" | |
| verified_rows += 1 | |
| assert next(reader, None) is None, "Source has additional rows" | |
| assert verified_rows == row_count | |
| assert null_counts == empty_counts, "Null counts differ from source empty cells" | |
| manifest = { | |
| "source": "https://www.kaggle.com/datasets/hashiromer/subreddits-directory", | |
| "source_filename": source.name, | |
| "source_bytes": source.stat().st_size, | |
| "source_sha256": sha256(source), | |
| "source_license_identifier": "reddit-api", | |
| "parquet_file": target.relative_to(output).as_posix(), | |
| "parquet_bytes": target.stat().st_size, | |
| "parquet_sha256": sha256(target), | |
| "row_count": row_count, | |
| "column_count": len(columns), | |
| "columns": columns, | |
| "column_types": {field.name: str(field.type) for field in schema}, | |
| "source_empty_string_counts": empty_counts, | |
| "null_counts": null_counts, | |
| "validation": { | |
| "method": "Full cell-by-cell comparison: exact nonempty text, inverse semantic comparisons for typed values, empty cells mapped to null", | |
| "verified_rows": verified_rows, | |
| "all_semantic_values_match": True, | |
| "nonempty_text_unchanged": True, | |
| "null_counts_match_source_empty_cells": True, | |
| "row_order_preserved": True, | |
| "column_order_preserved": True, | |
| }, | |
| "conversion": { | |
| "pyarrow_version": pa.__version__, | |
| "compression": "zstd", | |
| "csv_encoding": "utf-8", | |
| "type_inference": False, | |
| "empty_fields": "Only exact empty strings become null; literal null-like text is preserved", | |
| "created_utc": "ISO 8601 UTC to timestamp[us, tz=UTC]", | |
| "retrieved_on": "Unix seconds to timestamp[us, tz=UTC] using exact decimal arithmetic", | |
| "over18": "True/False text to boolean", | |
| "subscribers": "Nonnegative integer text to int64", | |
| "write_page_index": True, | |
| "metadata_refreshed": False, | |
| }, | |
| } | |
| (output / "conversion-manifest.json").write_text( | |
| json.dumps(manifest, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| print(json.dumps(manifest, indent=2)) | |
| if __name__ == "__main__": | |
| convert(Path(sys.argv[1]), Path(sys.argv[2])) | |