Download code/benchmark_audio_compression.py from alpha31476/spotify-metadata-parquet: direct link, hf CLI and curl.
- Browser
- Download file 5.6 kB
-
https://huggingface.co/datasets/alpha31476/spotify-metadata-parquet/resolve/main/code/benchmark_audio_compression.py
- Command line
-
hf download hf://datasets/alpha31476/spotify-metadata-parquet/code/benchmark_audio_compression.py
-
curl -L -o benchmark_audio_compression.py https://huggingface.co/datasets/alpha31476/spotify-metadata-parquet/resolve/main/code/benchmark_audio_compression.py
5.6 kB
| """Compare lossless storage on a distributed sample. Source is read-only.""" | |
| from pathlib import Path | |
| import gc | |
| import json | |
| import sqlite3 | |
| import struct | |
| import time | |
| import duckdb | |
| import pyarrow as pa | |
| import pyarrow.compute | |
| import pyarrow.parquet as pq | |
| ROOT = Path(__file__).parent | |
| SOURCE = None | |
| TOTAL_ROWS = 255594909 | |
| FIELDS = [ | |
| ('rowid', pa.int64()), ('track_id', pa.string()), ('fetched_at', pa.int64()), | |
| ('null_response', pa.int64()), ('duration_ms', pa.int64()), ('time_signature', pa.int64()), | |
| ('tempo', pa.float64()), ('key', pa.int64()), ('mode', pa.int64()), | |
| ('danceability', pa.float64()), ('energy', pa.float64()), ('loudness', pa.float64()), | |
| ('speechiness', pa.float64()), ('acousticness', pa.float64()), | |
| ('instrumentalness', pa.float64()), ('liveness', pa.float64()), ('valence', pa.float64()), | |
| ] | |
| SCHEMA = pa.schema(FIELDS) | |
| def exact_equal(left, right): | |
| assert left.column_names == right.column_names | |
| assert left.num_rows == right.num_rows | |
| for field in left.schema: | |
| a, b = left[field.name].combine_chunks(), right[field.name].combine_chunks() | |
| if pa.types.is_floating(field.type): | |
| # Check binary float values as well as NULL positions. | |
| assert a.is_null().equals(b.is_null()), field.name | |
| assert pa.compute.fill_null(a, 0).buffers()[1].to_pybytes() == pa.compute.fill_null(b, 0).buffers()[1].to_pybytes(), field.name | |
| else: | |
| assert a.equals(b), field.name | |
| def main(): | |
| conn = sqlite3.connect(SOURCE.as_uri() + '?mode=ro&immutable=1', uri=True) | |
| conn.execute('PRAGMA cache_size=-8192') | |
| last = conn.execute('SELECT rowid FROM track_audio_features ORDER BY rowid DESC LIMIT 1').fetchone()[0] | |
| batches = [] | |
| windows = 32 | |
| window_rows = 8192 | |
| names = ','.join('"' + name + '"' for name, _ in FIELDS) | |
| for i in range(windows): | |
| start = 1 + ((last - window_rows - 1) * i // (windows - 1)) | |
| rows = conn.execute(f'SELECT {names} FROM track_audio_features WHERE rowid>=? ORDER BY rowid LIMIT ?', (start, window_rows)).fetchall() | |
| arrays = [pa.array([row[j] for row in rows], type=kind) for j, (_, kind) in enumerate(FIELDS)] | |
| batches.append(pa.RecordBatch.from_arrays(arrays, schema=SCHEMA)) | |
| del rows, arrays | |
| conn.close() | |
| table = pa.Table.from_batches(batches) | |
| print('SAMPLE', table.num_rows, 'rows', 'Arrow_bytes', table.nbytes, 'max_rowid', last, flush=True) | |
| dictionaries = [name for name, _ in FIELDS if name != 'track_id'] | |
| encodings = {name: ('BYTE_STREAM_SPLIT' if pa.types.is_floating(kind) else 'DELTA_LENGTH_BYTE_ARRAY' if pa.types.is_string(kind) else 'DELTA_BINARY_PACKED') for name, kind in FIELDS} | |
| configs = [ | |
| ('snappy_dictionary', {'compression': 'snappy', 'use_dictionary': dictionaries}), | |
| ('zstd9_dictionary', {'compression': 'zstd', 'compression_level': 9, 'use_dictionary': dictionaries}), | |
| ('zstd19_dictionary', {'compression': 'zstd', 'compression_level': 19, 'use_dictionary': dictionaries}), | |
| ('zstd19_split_delta', {'compression': 'zstd', 'compression_level': 19, 'use_dictionary': False, 'column_encoding': encodings}), | |
| ] | |
| results = [] | |
| for label, config in configs: | |
| target = ROOT / ('audio_sample_' + label + '.parquet') | |
| start = time.monotonic() | |
| pq.write_table(table, target, row_group_size=262144, write_statistics=True, **config) | |
| seconds = time.monotonic() - start | |
| exact_equal(table, pq.read_table(target)) | |
| size = target.stat().st_size | |
| result = {'format': label, 'sample_rows': table.num_rows, 'sample_bytes': size, 'projected_full_GiB': size / table.num_rows * TOTAL_ROWS / 2**30, 'write_seconds': round(seconds, 3), 'all_values_exact': True} | |
| results.append(result) | |
| print(json.dumps(result), flush=True) | |
| target = ROOT / 'audio_sample.duckdb' | |
| assert not target.exists(), target | |
| db = duckdb.connect(str(target)) | |
| db.execute("SET memory_limit='256MB'") | |
| db.register('audio_sample', table) | |
| start = time.monotonic() | |
| db.execute('CREATE TABLE track_audio_features AS SELECT * FROM audio_sample') | |
| db.execute('CHECKPOINT') | |
| seconds = time.monotonic() - start | |
| restored = db.execute('SELECT * FROM track_audio_features').fetch_arrow_table() | |
| exact_equal(table, restored) | |
| db.close() | |
| size = target.stat().st_size | |
| result = {'format': 'duckdb_native', 'sample_rows': table.num_rows, 'sample_bytes': size, 'projected_full_GiB': size / table.num_rows * TOTAL_ROWS / 2**30, 'write_seconds': round(seconds, 3), 'all_values_exact': True} | |
| results.append(result) | |
| print(json.dumps(result), flush=True) | |
| (ROOT / 'audio_compression_results.json').write_text(json.dumps({'source_bytes': SOURCE.stat().st_size, 'source_rows': TOTAL_ROWS, 'sample_windows': windows, 'results': results}, indent=2), encoding='utf-8') | |
| if __name__ == '__main__': | |
| import argparse | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--database', type=Path, required=True) | |
| parser.add_argument('--output-dir', type=Path, required=True) | |
| parser.add_argument('--total-rows', type=int, default=TOTAL_ROWS) | |
| args = parser.parse_args() | |
| SOURCE = args.database.resolve(strict=True) | |
| ROOT = args.output_dir.resolve() | |
| ROOT.mkdir(parents=True, exist_ok=True) | |
| if any(ROOT.iterdir()): | |
| parser.error('Choose an empty benchmark output directory') | |
| TOTAL_ROWS = args.total_rows | |
| main() | |