File size: 7,421 Bytes
d554fd2
62e272e
 
d554fd2
62e272e
 
 
 
 
 
 
d554fd2
 
62e272e
 
 
 
 
d554fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62e272e
 
 
 
 
 
 
 
 
b44dc01
62e272e
 
 
 
 
 
d554fd2
62e272e
d554fd2
62e272e
 
 
 
 
 
d554fd2
 
 
 
62e272e
 
 
 
 
d554fd2
 
 
62e272e
 
 
d554fd2
62e272e
d554fd2
 
62e272e
d554fd2
 
 
 
 
62e272e
 
 
d554fd2
62e272e
 
 
 
 
 
 
 
 
 
 
 
 
d554fd2
 
 
62e272e
d554fd2
62e272e
d554fd2
 
 
62e272e
 
 
 
 
 
 
 
d554fd2
 
 
 
 
 
62e272e
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""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]))