spotify-metadata-parquet / code /export_sqlite_to_parquet.py
alpha31476's picture
Add dataset card, analysis code, and release documentation
9a1f607 verified
Raw History Blame Contribute Delete
16.9 kB
"""Export every Spotify SQLite table to validated, lossless Zstd Parquet.
Sources are opened read-only. No source file or source index is modified.
Each completed part is read back and compared with its source Arrow values.
Output is resumable by SQLite rowid. The manifest retains original SQL.
"""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor
from collections import deque
import gc
import hashlib
import json
import os
from pathlib import Path
import shutil
import sqlite3
import sys
import threading
import time
HERE = Path(__file__).resolve().parent
import adbc_driver_sqlite.dbapi as adbc
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
SOURCE = None
DEST = None
SCRATCH = None
HELPER = '__sqlite_rowid'
COUNTS = {}
DATABASES = ['spotify_clean_audio_features.sqlite3', 'spotify_clean_track_files.sqlite3', 'spotify_clean.sqlite3', 'spotify_tracks_ranking.sqlite3']
PRINT_LOCK = threading.Lock()
START = time.monotonic()
def emit(event, **items):
with PRINT_LOCK:
print(json.dumps({'event': event, 'elapsed_s': round(time.monotonic() - START, 1), **items}), flush=True)
def quote(name):
return '"' + name.replace('"', '""') + '"'
def readonly(path):
conn = sqlite3.connect(path.as_uri() + '?mode=ro&immutable=1', uri=True)
conn.execute('PRAGMA query_only=ON')
conn.execute('PRAGMA cache_size=-8192')
return conn
def source_identity(path):
stat = path.stat()
return {'bytes': stat.st_size, 'mtime_ns': stat.st_mtime_ns}
def json_atomic(path, data):
temp = path.with_suffix(path.suffix + '.tmp')
temp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding='utf-8')
temp.replace(path)
def schema_for(conn, table):
info = list(conn.execute('PRAGMA table_info(' + quote(table) + ')'))
sample = conn.execute('SELECT * FROM ' + quote(table) + ' LIMIT 64').fetchall()
fields = [pa.field(HELPER, pa.int64())]
for index, (_, name, declared, _, _, _) in enumerate(info):
declared = declared.upper()
if table == 'track_audio_features' and name == 'tempo':
kind = pa.float64()
elif any(token in declared for token in ('REAL', 'FLOA', 'DOUB', 'DEC', 'NUM')):
kind = pa.float64()
elif 'INT' in declared:
kind = pa.int64()
elif 'BLOB' in declared:
kind = pa.binary()
elif any(token in declared for token in ('TEXT', 'CHAR', 'CLOB')):
kind = pa.string()
else:
types = {type(row[index]) for row in sample if row[index] is not None}
kind = pa.binary() if bytes in types else pa.float64() if float in types else pa.int64() if types == {int} else pa.string()
fields.append(pa.field(name, kind))
return pa.schema(fields)
def sentinel_query(table, schema, after=None, limit=None):
sentinel = []
for field in schema:
value = "''" if pa.types.is_string(field.type) else "x''" if pa.types.is_binary(field.type) else '0.0' if pa.types.is_floating(field.type) else '0'
sentinel.append(value + ' AS ' + quote(field.name))
real = ['_rowid_ AS ' + quote(HELPER)] + [quote(field.name) for field in schema if field.name != HELPER]
where = '' if after is None else ' WHERE _rowid_ > ' + str(int(after))
sql = 'SELECT ' + ','.join(sentinel) + ' UNION ALL SELECT ' + ','.join(real) + ' FROM ' + quote(table) + ' NOT INDEXED' + where
if limit is not None:
sql += ' LIMIT ' + str(int(limit) + 1)
return sql
def exact_equal(left, right):
assert left.schema.equals(right.schema, check_metadata=False), (left.schema, right.schema)
assert left.num_rows == right.num_rows
digest = hashlib.sha256()
for field in left.schema:
a = left[field.name].combine_chunks()
b = right[field.name].combine_chunks()
assert a.is_null().equals(b.is_null()), field.name + ': null mask'
if pa.types.is_floating(field.type):
a_data = pc.fill_null(a, 0).buffers()[1].to_pybytes()
b_data = pc.fill_null(b, 0).buffers()[1].to_pybytes()
assert a_data == b_data, field.name + ': float bits'
else:
assert a.equals(b), field.name + ': values'
return True
def options(schema, level):
# Unique identifiers compress better without a redundant dictionary.
unique = {'track_id', 'id', 'sha256_original', 'sha256_with_embedded_meta', 'prefixed_ogg_packet'}
unique.update(field.name for field in schema if field.name.startswith('file_id_'))
dictionary = [field.name for field in schema if field.name not in unique and field.name not in {HELPER, 'rowid'}]
return {'compression': 'zstd', 'compression_level': level, 'use_dictionary': dictionary, 'write_statistics': True, 'row_group_size': 262144, 'write_page_checksum': True}
def estimate(level):
results = []
folder = SCRATCH / 'compression_estimates'
folder.mkdir(exist_ok=True)
for filename in DATABASES:
path = SOURCE / filename
with readonly(path) as conn:
for (table,) in conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"):
schema = schema_for(conn, table)
bounds = [conn.execute('SELECT _rowid_ FROM ' + quote(table) + ' ORDER BY _rowid_ ' + order + ' LIMIT 1').fetchone()[0] for order in ['ASC', 'DESC']]
chunks = []
with adbc.connect(path.as_uri() + '?mode=ro&immutable=1') as src:
for i in range(8):
offset = bounds[0] + (bounds[1] - bounds[0]) * i // 8 - 1
with src.cursor() as cur:
cur.adbc_statement.set_options(**{'adbc.sqlite.query.batch_rows': '8193'})
cur.execute(sentinel_query(table, schema, offset, 8192))
chunk = cur.fetch_arrow_table().slice(1).cast(schema)
chunks.append(chunk)
data = pa.concat_tables(chunks)
output = folder / (path.stem + '--' + table + '.parquet')
pq.write_table(data, output, **options(schema, level))
exact_equal(data, pq.read_table(output))
expected_rows = COUNTS[filename + '|' + table]
entry = {'database': filename, 'table': table, 'rows': expected_rows, 'sample_rows': data.num_rows, 'sample_bytes': output.stat().st_size, 'projected_GiB': output.stat().st_size / data.num_rows * expected_rows / 2**30, 'sample_arrow_bytes_per_row': data.nbytes / data.num_rows, 'schema': str(schema)}
results.append(entry)
emit('estimate', **{key: val for key, val in entry.items() if key != 'schema'})
total = sum(item['projected_GiB'] for item in results)
report = {'compression_level': level, 'projected_total_GiB': total, 'destination': str(DEST), 'free_destination_GiB': shutil.disk_usage(DEST.parent if DEST.parent.exists() else HERE.parent).free / 2**30, 'tables': results}
json_atomic(SCRATCH / 'all_compression_estimates.json', report)
emit('estimate_complete', **{key: val for key, val in report.items() if key != 'tables'})
def write_part(data, path, schema, level, index):
if shutil.disk_usage(path.parent).free < max(4 * 2**30, data.nbytes * 4):
raise RuntimeError('Insufficient free space for safe export; originals are unchanged')
assert not path.exists(), path
pending = path.with_suffix('.parquet.partial')
started = time.monotonic()
pq.write_table(data, pending, **options(schema, level))
restored = pq.read_table(pending, page_checksum_verification=True)
exact_equal(data, restored)
nulls = {name: data[name].null_count for name in data.column_names}
first = data[HELPER][0].as_py()
last = data[HELPER][-1].as_py()
assert first <= last
result = {'part': path.name, 'index': index, 'rows': data.num_rows, 'first_sqlite_rowid': first, 'last_sqlite_rowid': last, 'bytes': pending.stat().st_size, 'null_counts': nulls, 'verified_exact': True, 'seconds': round(time.monotonic() - started, 3)}
pending.replace(path)
return result
def convert(level, workers):
DEST.mkdir(parents=True, exist_ok=True)
manifest_path = DEST / 'manifest.json'
if manifest_path.exists():
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
assert manifest['compression_level'] == level
else:
manifest = {'format': 'Parquet', 'compression': 'Zstd', 'compression_level': level, 'source_folder': SOURCE.name, 'originals_modified': False, 'helper_column': HELPER, 'status': 'running', 'databases': {}}
manifest['status'] = 'running'
json_atomic(manifest_path, manifest)
for filename in DATABASES:
path = SOURCE / filename
identity = source_identity(path)
for suffix in ('-wal', '-journal'):
sidecar = Path(str(path) + suffix)
assert not sidecar.exists() or sidecar.stat().st_size == 0, sidecar
with readonly(path) as conn:
database = manifest['databases'].setdefault(filename, {'source_identity': identity, 'sql_objects': [dict(zip(('type', 'name', 'table', 'sql'), row)) for row in conn.execute('SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name')], 'tables': {}})
assert database['source_identity'] == identity, 'Source changed since export started'
tables = [row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")]
for table in tables:
schema = schema_for(conn, table)
folder = DEST / path.stem / table
folder.mkdir(parents=True, exist_ok=True)
table_manifest = database['tables'].setdefault(table, {'schema': [{'name': field.name, 'type': str(field.type)} for field in schema], 'expected_rows': COUNTS[filename + '|' + table], 'parts': [], 'status': 'running'})
if table_manifest['status'] == 'complete':
emit('skip_complete', database=filename, table=table)
continue
parts = table_manifest['parts']
# Recover validated parts written immediately before interruption.
known = {part['part'] for part in parts}
expected_index = len(parts)
for candidate in sorted(folder.glob('part-*.parquet')):
if candidate.name not in known:
candidate_index = int(candidate.stem.split('-')[1])
if candidate_index != expected_index:
# A parallel writer can finish beyond an interrupted gap.
# Preserve that orphan and regenerate the continuous range.
assert DEST.resolve() in candidate.resolve().parents
candidate.replace(candidate.with_suffix('.parquet.orphan-' + str(time.time_ns())))
continue
data = pq.read_table(candidate, page_checksum_verification=True)
assert data.schema.equals(schema, check_metadata=False)
parts.append({'part': candidate.name, 'index': int(candidate.stem.split('-')[1]), 'rows': data.num_rows, 'first_sqlite_rowid': data[HELPER][0].as_py(), 'last_sqlite_rowid': data[HELPER][-1].as_py(), 'bytes': candidate.stat().st_size, 'null_counts': {name: data[name].null_count for name in data.column_names}, 'verified_exact': True, 'recovered_after_interruption': True})
expected_index += 1
parts.sort(key=lambda part: part['index'])
after = parts[-1]['last_sqlite_rowid'] if parts else None
processed = sum(part['rows'] for part in parts)
index = len(parts)
last_report = time.monotonic()
emit('table_start', database=filename, table=table, rows=table_manifest['expected_rows'], resume_after=after)
queue = deque()
def accept(future):
nonlocal processed, last_report
entry = future.result()
if parts:
assert entry['first_sqlite_rowid'] > parts[-1]['last_sqlite_rowid'], 'Row ordering changed'
parts.append(entry)
processed += entry['rows']
if time.monotonic() - last_report >= 15:
json_atomic(manifest_path, manifest)
emit('progress', database=filename, table=table, rows=processed, percent=round(processed / table_manifest['expected_rows'] * 100, 2), output_GiB=round(sum(part['bytes'] for part in parts) / 2**30, 3), free_GiB=round(shutil.disk_usage(DEST).free / 2**30, 2))
last_report = time.monotonic()
with ThreadPoolExecutor(max_workers=workers) as pool, adbc.connect(path.as_uri() + '?mode=ro&immutable=1') as source:
with source.cursor() as cursor:
# Wide file-registry rows need smaller batches to bound RAM.
batch_rows = 65536 if table == 'track_files' else 262144
cursor.adbc_statement.set_options(**{'adbc.sqlite.query.batch_rows': str(batch_rows)})
cursor.execute(sentinel_query(table, schema, after))
first_batch = True
for batch in cursor.fetch_record_batch():
if first_batch:
batch = batch.slice(1)
first_batch = False
if batch.num_rows == 0:
continue
data = pa.Table.from_batches([batch]).cast(schema, safe=True)
target = folder / f'part-{index:06d}.parquet'
queue.append(pool.submit(write_part, data, target, schema, level, index))
index += 1
if len(queue) >= workers:
accept(queue.popleft())
while queue:
accept(queue.popleft())
assert processed == table_manifest['expected_rows'], (table, processed, table_manifest['expected_rows'])
assert source_identity(path) == identity, 'Source changed during export'
table_manifest['status'] = 'complete'
table_manifest['rows'] = processed
table_manifest['bytes'] = sum(part['bytes'] for part in parts)
json_atomic(manifest_path, manifest)
emit('table_complete', database=filename, table=table, rows=processed, output_GiB=round(table_manifest['bytes'] / 2**30, 4))
gc.collect()
manifest['status'] = 'complete'
manifest['total_source_bytes'] = sum(db['source_identity']['bytes'] for db in manifest['databases'].values())
manifest['total_parquet_bytes'] = sum(table['bytes'] for db in manifest['databases'].values() for table in db['tables'].values())
manifest['total_rows'] = sum(table['rows'] for db in manifest['databases'].values() for table in db['tables'].values())
json_atomic(manifest_path, manifest)
emit('complete', source_GiB=manifest['total_source_bytes'] / 2**30, parquet_GiB=manifest['total_parquet_bytes'] / 2**30, rows=manifest['total_rows'], destination=str(DEST))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--estimate', action='store_true')
parser.add_argument('--level', type=int, default=9)
parser.add_argument('--workers', type=int, default=4)
parser.add_argument('--source-dir', type=Path, required=True)
parser.add_argument('--output-dir', type=Path, required=True)
parser.add_argument('--source-counts', type=Path, default=HERE.parent / 'metadata' / 'source_counts.json')
parser.add_argument('--work-dir', type=Path, default=HERE.parent / 'work')
args = parser.parse_args()
SOURCE = args.source_dir.resolve(strict=True)
DEST = args.output_dir.resolve()
SCRATCH = args.work_dir.resolve()
SCRATCH.mkdir(parents=True, exist_ok=True)
entries = json.loads(args.source_counts.read_text(encoding='utf-8-sig'))
COUNTS = {item['File'] + '|' + item['Table']: item['Rows'] for item in entries}
if args.estimate:
estimate(args.level)
else:
convert(args.level, args.workers)