Repository navigation
Expand file tree
/
Copy pathdownload_data.py
More file actions
2794 lines (2405 loc) · 94 KB
/
Copy pathdownload_data.py
File metadata and controls
2794 lines (2405 loc) · 94 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Download datasets for ArcadeDB import examples.
This script downloads both MovieLens and Stack Exchange datasets with
consistent, pinned versions for reproducibility, and systematically
injects NULL values for comprehensive testing.
Features:
- Progress bars for all long-running operations (requires tqdm: uv add tqdm)
- Timing measurements for performance monitoring
- Memory-efficient streaming for large files
- Smart sampling for fast verification (100K rows)
- Stack Overflow vector conversion (requires sentence-transformers + torch)
- Stack Overflow unified vector ground-truth generation (MSMARCO-style)
Available datasets:
1. MovieLens (movie ratings, tags, genres):
- movielens-small: ~1 MB, ~100K ratings, 9K movies, 600 users
- movielens-large: ~265 MB, ~33M ratings, 86K movies, 280K users
2. Stack Exchange (Q&A posts, users, tags, links):
- stackoverflow-tiny: ~34 MB, ~100K records (subset of stackoverflow-small)
- stackoverflow-small: ~642 MB, 1.41M records (cs.stackexchange.com, 2024-06-30)
- stackoverflow-medium: ~2.9 GB, 5.56M records (stats.stackexchange.com, 2024-06-30)
- stackoverflow-large: ~10 GB, subset of full stackoverflow.com (2024-06-30)
- stackoverflow-xlarge: ~50 GB, subset of full stackoverflow.com (2024-06-30)
- stackoverflow-full: ~323 GB, full stackoverflow.com (2024-06-30)
3. TPC-H (table benchmark):
- tpch-sf1: TPC-H scale factor 1 (dbgen, local generation)
- tpch-sf10: TPC-H scale factor 10 (dbgen, local generation)
- tpch-sf100: TPC-H scale factor 100 (dbgen, local generation)
4. LDBC SNB Interactive v1 (graph benchmark):
- ldbc-snb-sf1: Scale factor 1 (CsvMergeForeign, LongDateFormatter, Docker datagen)
- ldbc-snb-sf10: Scale factor 10 (CsvMergeForeign, LongDateFormatter, Docker datagen)
- ldbc-snb-sf100: Scale factor 100 (CsvMergeForeign, LongDateFormatter, Docker datagen)
5. MSMARCO v2.1 embeddings (vector benchmark):
- msmarco-1m: 1M passage vectors
- msmarco-5m: 5M passage vectors
- msmarco-10m: 10M passage vectors
Stack Exchange Data Note:
- Pinned to 2024-06-30 quarterly dump for reproducibility
- Downloaded from archive.org
- 7z compressed format (requires py7zr library)
- stackoverflow-tiny is derived from stackoverflow-small (first 10k rows per XML,
full Tags.xml)
- stackoverflow-large is derived from stackoverflow-full (proportional subset)
- stackoverflow-xlarge is derived from stackoverflow-full (proportional subset)
NULL Value Injection (MovieLens only):
- Enabled by default for MovieLens CSV files
- Systematically injects empty strings "" (CSV NULL equivalent)
* movies.csv: genres (2%), title (0.5%)
* ratings.csv: timestamp (3%), rating (1%)
* links.csv: imdbId (5%), tmdbId (8%)
* tags.csv: tag (5%), timestamp (2%)
- Uses deterministic random seed (42) for reproducibility
- Can be disabled with --no-nulls flag
- Stack Exchange XML files are downloaded as-is (no modification)
License:
- MovieLens: Free for educational use (grouplens.org)
- Stack Exchange: CC BY-SA (archive.org/details/stackexchange)
- MSMARCO: See dataset card on Hugging Face
- TPC-H: Generated with dbgen (local build or Docker); see TPC license terms
- LDBC SNB: Generated locally via Docker (ldbc/datagen). See LDBC terms.
Usage:
python download_data.py movielens-small
python download_data.py movielens-large
python download_data.py movielens-small --no-nulls # Skip NULL injection
python download_data.py stackoverflow-tiny
python download_data.py stackoverflow-small
python download_data.py stackoverflow-medium
python download_data.py stackoverflow-large
python download_data.py stackoverflow-xlarge
python download_data.py stackoverflow-full
python download_data.py stackoverflow-small --verify-only # Verify existing
python download_data.py tpch-sf1
python download_data.py tpch-sf10
python download_data.py tpch-sf100
python download_data.py ldbc-snb-sf1
python download_data.py ldbc-snb-sf10
python download_data.py ldbc-snb-sf100
python download_data.py msmarco-1m
python download_data.py msmarco-5m
python download_data.py msmarco-10m
python download_data.py stackoverflow-tiny --no-vectors # Skip vector generation
"""
import argparse
import html
import json
import os
import re
import shutil
import ssl
import subprocess
import time
import urllib.error
import urllib.request
import zipfile
from pathlib import Path
try:
from tqdm import tqdm
except ImportError:
# Fallback if tqdm not installed
tqdm = None
def _require_https(url: str) -> str:
"""Reject non-HTTPS URLs before opening them.
Bandit B310 flags urlopen() because it permits file:// and custom schemes.
Examples download from a fixed list of HTTPS dataset URLs, so we enforce
that contract explicitly here.
"""
if not url.startswith("https://"):
raise ValueError(f"Refusing to open non-HTTPS URL: {url!r}")
return url
def ensure_clean_dir(path: Path, label: str) -> None:
if path.exists():
print(f"[CLEAN] Removing existing {label} directory: {path}")
shutil.rmtree(path)
def _format_bytes(num_bytes: int) -> str:
value = float(num_bytes)
for unit in ("B", "KB", "MB", "GB", "TB"):
if value < 1024.0 or unit == "TB":
return f"{value:.1f} {unit}"
value /= 1024.0
return f"{num_bytes} B"
def _download_with_wget(url: str, destination: Path) -> bool:
wget_path = shutil.which("wget")
if not wget_path:
return False
command = [
wget_path,
"--continue",
"--tries=10",
"--waitretry=5",
"--retry-connrefused",
"--timeout=30",
"--read-timeout=30",
"--output-document",
str(destination),
url,
]
print(f"[DOWNLOAD] Using wget with resume support for {destination.name}")
subprocess.run(command, check=True)
return True
def _download_with_curl(url: str, destination: Path) -> bool:
curl_path = shutil.which("curl")
if not curl_path:
return False
command = [
curl_path,
"-L",
"--fail",
"--retry",
"10",
"--retry-delay",
"5",
"--retry-connrefused",
"-C",
"-",
"-o",
str(destination),
url,
]
print(f"[DOWNLOAD] Using curl with resume support for {destination.name}")
subprocess.run(command, check=True)
return True
def _download_with_python(
url: str, destination: Path, chunk_size: int = 8 * 1024 * 1024
) -> None:
resume_from = destination.stat().st_size if destination.exists() else 0
headers = {}
if resume_from > 0:
headers["Range"] = f"bytes={resume_from}-"
print(
f"[DOWNLOAD] Resuming {destination.name} from {_format_bytes(resume_from)}"
)
request = urllib.request.Request(_require_https(url), headers=headers)
with urllib.request.urlopen(request, timeout=60) as response: # nosec B310
status = getattr(response, "status", response.getcode())
if resume_from > 0 and status != 206:
print(
"[DOWNLOAD] Server did not honor Range request; "
"restarting full download"
)
destination.unlink(missing_ok=True)
resume_from = 0
mode = "ab" if resume_from > 0 else "wb"
content_length = response.headers.get("Content-Length")
expected_total = resume_from + int(content_length) if content_length else None
downloaded = resume_from
last_report_time = 0.0
with destination.open(mode) as fout:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
fout.write(chunk)
downloaded += len(chunk)
now = time.time()
if now - last_report_time >= 0.5:
if expected_total and expected_total > 0:
percent = (downloaded / expected_total) * 100
print(
f"\r Progress: {percent:.1f}% "
"("
f"{_format_bytes(downloaded)}/"
f"{_format_bytes(expected_total)}"
")",
end="",
)
else:
print(
f"\r Downloaded: {_format_bytes(downloaded)}",
end="",
)
last_report_time = now
if expected_total and downloaded < expected_total:
raise urllib.error.ContentTooShortError(
"retrieval incomplete: got only "
f"{downloaded} out of {expected_total} bytes",
None,
)
print()
def download_file(url: str, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.exists() and destination.stat().st_size > 0:
print(
f"[DOWNLOAD] Found partial file for {destination.name}: "
f"{_format_bytes(destination.stat().st_size)}"
)
try:
if _download_with_wget(url, destination):
return
except Exception as exc:
print(f"[WARNING] wget download failed, falling back: {exc}")
try:
if _download_with_curl(url, destination):
return
except Exception as exc:
print(f"[WARNING] curl download failed, falling back: {exc}")
print(f"[DOWNLOAD] Using Python downloader for {destination.name}")
_download_with_python(url, destination)
def parse_tpch_ddl(ddl_path: Path) -> dict[str, dict[str, object]]:
ddl_text = ddl_path.read_text(encoding="utf-8", errors="ignore")
tables: dict[str, dict[str, object]] = {}
for match in re.finditer(r"CREATE TABLE\s+(\w+)\s*\((.*?)\);", ddl_text, re.S):
table = match.group(1).lower()
body = match.group(2)
columns = []
types = {}
for raw_line in body.splitlines():
line = raw_line.strip().rstrip(",")
if not line:
continue
col_match = re.match(r"^([A-Z_]+)\s+([A-Z]+(?:\([^)]*\))?)", line)
if not col_match:
continue
col = col_match.group(1).lower()
col_type = col_match.group(2).upper()
if col_type.startswith("DECIMAL"):
inferred = "double"
elif col_type.startswith("INT"):
inferred = "integer"
elif col_type.startswith("DATE"):
inferred = "date"
else:
inferred = "string"
columns.append(col)
types[col] = inferred
tables[table] = {"columns": columns, "types": types}
if not tables:
raise RuntimeError(f"No tables parsed from {ddl_path}")
return tables
def _iter_tpch_records(tbl_path: Path, chunk_size: int = 1024 * 1024):
"""Yield TPC-H records split by the record delimiter '|\n'.
TPC-H .tbl files can contain embedded newlines inside fields, so we
cannot parse line-by-line. The record delimiter is the trailing "|\n".
"""
delimiter = "|\n"
buffer = ""
with tbl_path.open("r", encoding="utf-8", errors="ignore") as fin:
while True:
chunk = fin.read(chunk_size)
if not chunk:
break
buffer += chunk
while True:
idx = buffer.find(delimiter)
if idx == -1:
break
record = buffer[:idx]
buffer = buffer[idx + len(delimiter) :]
yield record
if buffer.strip():
yield buffer.rstrip("|")
def convert_tpch_tbl_to_csv(tbl_path: Path, csv_path: Path, columns: list[str]) -> None:
import csv
csv_path.parent.mkdir(parents=True, exist_ok=True)
with csv_path.open("w", encoding="utf-8", newline="") as fout:
writer = csv.writer(
fout,
delimiter="|",
quoting=csv.QUOTE_NONE,
escapechar="\\",
)
writer.writerow(columns)
for record in _iter_tpch_records(tbl_path):
fields = record.split("|")
if len(fields) != len(columns):
raise ValueError(
f"Unexpected column count in {tbl_path.name}: "
f"{len(fields)} (expected {len(columns)})"
)
fields = [f.replace("\n", " ").replace("\r", " ") for f in fields]
writer.writerow(fields)
def generate_tpch_csv_and_schema(out_dir: Path, ddl_path: Path) -> None:
ddl_schema = parse_tpch_ddl(ddl_path)
csv_dir = out_dir / "csv"
csv_dir.mkdir(parents=True, exist_ok=True)
for table, meta in ddl_schema.items():
columns = meta["columns"]
tbl_path = out_dir / f"{table}.tbl"
if not tbl_path.exists():
raise FileNotFoundError(f"Missing {tbl_path}")
csv_path = csv_dir / f"{table}.csv"
if not csv_path.exists():
print(f"[convert] {tbl_path.name} -> csv/{csv_path.name}")
convert_tpch_tbl_to_csv(tbl_path, csv_path, columns)
schema_path = out_dir / "schema.json"
if not schema_path.exists():
schema_path.write_text(
json.dumps({"tables": ddl_schema}, indent=2), encoding="utf-8"
)
print(f"[schema] wrote {schema_path}")
def _infer_value_type(value: str) -> str:
if value is None:
return "string"
value = value.strip()
if value == "":
return "string"
if value.lower() in {"true", "false"}:
return "boolean"
if re.fullmatch(r"-?\d+", value):
return "integer"
if re.fullmatch(r"-?\d+\.\d+", value):
return "double"
return "string"
def _merge_types(current: str | None, new_type: str) -> str:
if current is None:
return new_type
if current == "string" or new_type == "string":
return "string"
if current == "double" or new_type == "double":
return "double"
if current == "integer" or new_type == "integer":
return "integer"
if current == "boolean" or new_type == "boolean":
return "boolean"
return "string"
def _looks_like_header(row: list[str]) -> bool:
if not row:
return False
tokens = 0
for val in row:
if re.fullmatch(r"[A-Za-z][A-Za-z0-9_.]*", val or ""):
tokens += 1
return tokens >= max(1, int(0.6 * len(row)))
def _apply_ldbc_overrides(name: str, inferred: str) -> str:
lowered = name.lower()
if lowered.endswith(".id") or lowered.endswith("_id"):
return "integer"
if lowered in {"ispartof", "issubclassof"}:
return "integer"
return inferred
def generate_ldbc_snb_schema(out_dir: Path, sample_rows: int = 100_000) -> None:
import csv
schema = {"nodes": {}, "edges": {}}
csv_files = sorted(out_dir.rglob("*.csv"))
if not csv_files:
return
def base_name(path: Path) -> str:
stem = path.stem
return re.sub(r"_\d+_\d+$", "", stem)
for csv_path in csv_files:
if csv_path.name.endswith(".crc"):
continue
base = base_name(csv_path)
if base in schema["nodes"] or base in schema["edges"]:
continue
with csv_path.open("r", encoding="utf-8", errors="ignore", newline="") as f:
reader = csv.reader(f, delimiter="|")
try:
first_row = next(reader)
except StopIteration:
continue
if not _looks_like_header(first_row):
print(f"[schema] skip (no header): {csv_path}")
continue
header = first_row
type_map: dict[str, str | None] = {name: None for name in header}
rows_read = 0
for row in reader:
if not row:
continue
rows_read += 1
for idx, name in enumerate(header):
value = row[idx] if idx < len(row) else ""
inferred = _infer_value_type(value)
type_map[name] = _merge_types(type_map[name], inferred)
if rows_read >= sample_rows:
break
properties = {
name: _apply_ldbc_overrides(name, (type_map[name] or "string"))
for name in header
}
tokens = base.split("_")
if len(tokens) >= 3:
source = tokens[0]
target = tokens[-1]
label = "_".join(tokens[1:-1])
schema["edges"][base] = {
"label": label,
"from": source,
"to": target,
"file": str(csv_path.relative_to(out_dir)),
"properties": properties,
}
else:
schema["nodes"][base] = {
"type": base,
"file": str(csv_path.relative_to(out_dir)),
"properties": properties,
}
schema_path = out_dir / "schema.json"
schema_path.write_text(json.dumps(schema, indent=2), encoding="utf-8")
print(f"[schema] wrote {schema_path}")
def introduce_null_values_movielens(extract_dir):
"""
Systematically introduce NULL values in MovieLens CSV files.
Strategy:
- Uses deterministic random seed (42) for reproducibility
- Injects empty strings "" for nullable fields (CSV NULL equivalent)
- Never NULLs primary/foreign keys (movieId, userId)
- Percentages chosen to mimic realistic missing data patterns
NULL Injection Targets:
- movies.csv: genres (2%), title (0.5%)
- ratings.csv: timestamp (3%), rating (1%)
- links.csv: imdbId (5%), tmdbId (8%)
- tags.csv: tag (5%), timestamp (2%)
"""
import csv
import random
# Seed for reproducibility - same NULLs every time
random.seed(42)
print("\n[WORK] Systematically introducing NULL values in MovieLens CSV files...")
overall_start = time.time()
# Configuration: file -> {nullable_field: percentage}
null_config = {
"movies.csv": {
"genres": 0.02, # 2% NULL genres (unclassified movies)
"title": 0.005, # 0.5% NULL titles (edge case testing)
},
"ratings.csv": {
"timestamp": 0.03, # 3% NULL timestamps (missing metadata)
"rating": 0.01, # 1% NULL ratings (invalid/missing ratings)
},
"links.csv": {
"imdbId": 0.05, # 5% NULL imdbId (movies not in IMDb)
"tmdbId": 0.08, # 8% NULL tmdbId (movies not in TMDb)
},
"tags.csv": {
"tag": 0.05, # 5% NULL tags (empty/missing tags)
"timestamp": 0.02, # 2% NULL timestamps (missing metadata)
},
}
# Process each CSV file based on configuration
for filename, nullable_fields in null_config.items():
csv_path = extract_dir / filename
if not csv_path.exists():
continue
start_time = time.time()
temp_path = csv_path.with_suffix(".csv.tmp")
null_counts = {field: 0 for field in nullable_fields}
# Count total rows for progress bar
total_rows = sum(1 for _ in open(csv_path, encoding="utf-8")) - 1
with (
open(csv_path, "r", encoding="utf-8") as f_in,
open(temp_path, "w", encoding="utf-8", newline="") as f_out,
):
reader = csv.DictReader(f_in)
writer = csv.DictWriter(f_out, fieldnames=reader.fieldnames)
writer.writeheader()
# Progress bar
iterator = reader
if tqdm:
iterator = tqdm(
reader, total=total_rows, desc=f" {filename}", unit=" rows"
)
for row in iterator:
# Inject NULLs based on configuration
for field, percentage in nullable_fields.items():
if random.random() < percentage:
row[field] = ""
null_counts[field] += 1
writer.writerow(row)
# Replace original with modified file
temp_path.replace(csv_path)
elapsed = time.time() - start_time
# Print results
null_summary = ", ".join(
f"{count} NULL {field}" for field, count in null_counts.items()
)
print(f" [OK] {filename}: {null_summary} ({elapsed:.2f}s)")
overall_elapsed = time.time() - overall_start
print(f"\n[TIME] Total CSV NULL injection time: {overall_elapsed:.2f}s")
class DatasetUnavailable(RuntimeError):
"""The dataset host could not be reached. Not a defect in the bindings.
WHY THIS IS A DISTINCT TYPE. On 2026-08-29 the TLS certificate for
files.grouplens.org (University of Minnesota, the MovieLens host) expired,
and every `Test Python Examples` job on BOTH this fork and upstream's main
went red -- 11 and 12 jobs, every OS, every Python from 3.10 to 3.14. The
failing step was `Download datasets`; not one example had run yet.
Re-running does not help, because a re-run executes now and the certificate
is still expired. The examples suite was therefore reporting, to anyone
reading upstream's main, that a Python bindings PR had broken something.
A third party letting a certificate lapse and a genuine regression in these
bindings must not look the same. This type is what lets the caller tell them
apart: raised ONLY for transport failures reaching the dataset, never for a
parse error, a bad checksum, or anything the bindings did.
"""
# Transport-level failures: the host is unreachable, refusing, or presenting a
# certificate we cannot verify. Deliberately NOT a catch-all -- a zip that
# downloads and then fails to extract is a real problem and must still fail.
_TRANSPORT_ERRORS = (
urllib.error.URLError,
urllib.error.HTTPError,
TimeoutError,
ConnectionError,
ssl.SSLError,
)
def download_movielens(size="large", inject_nulls=True):
"""Download and extract MovieLens dataset.
Args:
size: 'large' (~265 MB, ~33M ratings) or 'small' (~1 MB, ~100K ratings)
inject_nulls: Whether to introduce NULL values for testing (default: True)
"""
# Create data directory
data_dir = Path(__file__).parent / "data"
data_dir.mkdir(exist_ok=True)
# Dataset configurations
datasets = {
"small": {
"url": "https://files.grouplens.org/datasets/movielens/ml-latest-small.zip",
"dirname": "movielens-small",
"description": "~100K ratings, ~9K movies",
"size_mb": "~1 MB",
},
"large": {
"url": "https://files.grouplens.org/datasets/movielens/ml-latest.zip",
"dirname": "movielens-large",
"description": "~33M ratings, ~86K movies",
"size_mb": "~265 MB",
},
}
if size not in datasets:
raise ValueError(f"Unknown dataset size: {size}. Choose 'small' or 'large'")
config = datasets[size]
url = config["url"]
dirname = config["dirname"]
zip_path = data_dir / f"movielens-{size}.zip"
extract_dir = data_dir / dirname
# Check if already downloaded
ensure_clean_dir(extract_dir, f"MovieLens {size}")
print(f"[DOWNLOAD] Downloading MovieLens {size} dataset")
print(f" Description: {config['description']} ({config['size_mb']})")
print(f" URL: {url}")
print(" This may take a few minutes...")
print()
download_start = time.time()
try:
# Download with progress
def report_progress(block_num, block_size, total_size):
downloaded = block_num * block_size
percent = min(100, (downloaded / total_size) * 100) if total_size > 0 else 0
downloaded_mb = downloaded / (1024 * 1024)
total_mb = total_size / (1024 * 1024)
print(
f"\r Progress: {percent:.1f}% "
f"({downloaded_mb:.1f}/{total_mb:.1f} MB)",
end="",
)
urllib.request.urlretrieve(
_require_https(url), zip_path, reporthook=report_progress
) # nosec B310
print() # New line after progress
download_elapsed = time.time() - download_start
print(f"[OK] Downloaded to: {zip_path} " f"({download_elapsed:.2f}s)")
# Extract
extract_start = time.time()
print("[EXTRACT] Extracting...")
with zipfile.ZipFile(zip_path, "r") as zip_ref:
# Extract to temp dir (zip contains ml-latest/ml-latest-small)
temp_extract = data_dir / "temp_extract"
zip_ref.extractall(temp_extract)
# Find the extracted folder (ml-latest or ml-latest-small)
extracted_folders = list(temp_extract.iterdir())
if len(extracted_folders) == 1 and extracted_folders[0].is_dir():
source_dir = extracted_folders[0]
# Move contents to our target directory
if extract_dir.exists():
shutil.rmtree(extract_dir)
shutil.move(str(source_dir), str(extract_dir))
# Clean up temp directory
shutil.rmtree(temp_extract)
else:
raise Exception(f"Unexpected zip structure in {temp_extract}")
extract_elapsed = time.time() - extract_start
print(f"[OK] Extracted to: {extract_dir} ({extract_elapsed:.2f}s)")
# Introduce NULL values for testing
if inject_nulls:
introduce_null_values_movielens(extract_dir)
else:
print("\n[SKIP] Skipping NULL value injection (--no-nulls flag)")
# Show file sizes
print("\n[STATS] Dataset contents:")
for csv_file in extract_dir.glob("*.csv"):
size_mb = csv_file.stat().st_size / (1024 * 1024)
print(f" - {csv_file.name}: {size_mb:.1f} MB")
# Clean up zip file
zip_path.unlink()
print("\n[CLEAN] Cleaned up zip file")
return extract_dir
except _TRANSPORT_ERRORS as e:
# The HOST failed us, not the code. Distinguished so CI can skip rather
# than report a bindings regression that did not happen.
print(f"[UNAVAILABLE] Cannot reach the dataset host: {e}")
print(f" URL: {url}")
print(" This is a third-party host, not a defect in arcadedb.")
raise DatasetUnavailable(f"{url}: {e}") from e
except Exception as e:
print(f"[ERROR] Error downloading dataset: {e}")
print(f" You can manually download from: {url}")
raise
def download_stackoverflow(size="small"):
"""Download and extract Stack Exchange dataset.
Args:
size: 'tiny' (~34 MB), 'small' (~80 MB), 'medium' (~500 MB),
'large' (~10 GB subset), 'xlarge' (~50 GB subset), or
'full' (~323 GB)
"""
required_xml_files = (
"Posts.xml",
"Users.xml",
"Comments.xml",
"Tags.xml",
"Badges.xml",
"PostLinks.xml",
"PostHistory.xml",
"Votes.xml",
)
def has_required_xml_files(dataset_dir: Path) -> bool:
return dataset_dir.exists() and all(
(dataset_dir / filename).exists() for filename in required_xml_files
)
# Create data directory
data_dir = Path(__file__).parent / "data"
data_dir.mkdir(exist_ok=True)
if size == "tiny":
source_dir = data_dir / "stackoverflow-small"
if not has_required_xml_files(source_dir):
print(
"[INFO] stackoverflow-small is missing required XML files; "
"downloading a fresh source dataset"
)
download_stackoverflow(size="small")
return create_stackoverflow_tiny(source_dir=source_dir)
if size == "large":
source_dir = data_dir / "stackoverflow-full"
if not has_required_xml_files(source_dir):
print(
"[INFO] stackoverflow-full is missing required XML files; "
"downloading a fresh source dataset"
)
download_stackoverflow(size="full")
return create_stackoverflow_large(
source_dir=source_dir,
target_size_gb=10,
out_name="stackoverflow-large",
label="large",
)
if size == "xlarge":
source_dir = data_dir / "stackoverflow-full"
if not has_required_xml_files(source_dir):
print(
"[INFO] stackoverflow-full is missing required XML files; "
"downloading a fresh source dataset"
)
download_stackoverflow(size="full")
return create_stackoverflow_large(
source_dir=source_dir,
target_size_gb=50,
out_name="stackoverflow-xlarge",
label="xlarge",
)
try:
import py7zr
except ImportError:
print("[ERROR] Missing dependency: py7zr")
print(" Install with: uv add py7zr")
raise
# Dataset configurations (pinned to 2024-06-30 for reproducibility)
datasets = {
"small": {
"urls": [
"https://archive.org/download/stackexchange/" "cs.stackexchange.com.7z"
],
"dirname": "stackoverflow-small",
"site": "cs.stackexchange.com",
"description": "~80K posts (Computer Science)",
"size_mb": "~80 MB",
"date": "2024-06-30",
},
"medium": {
"urls": [
"https://archive.org/download/stackexchange/"
"stats.stackexchange.com.7z"
],
"dirname": "stackoverflow-medium",
"site": "stats.stackexchange.com",
"description": "~300K posts (Statistics)",
"size_mb": "~500 MB",
"date": "2024-06-30",
},
"full": {
# Full Stack Overflow dump split into multiple parts
"urls": [
"https://archive.org/download/stackexchange/"
"stackoverflow.com-Posts.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-Users.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-Comments.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-Tags.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-Votes.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-Badges.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-PostLinks.7z",
"https://archive.org/download/stackexchange/"
"stackoverflow.com-PostHistory.7z",
],
"dirname": "stackoverflow-full",
"site": "stackoverflow.com",
"description": "Full Stack Overflow dump (all XML files)",
"size_mb": "~323 GB",
"date": "2024-06-30",
},
}
if size not in datasets:
raise ValueError(
"Unknown dataset size: "
f"{size}. Choose 'tiny', 'small', 'medium', 'large', 'xlarge', or 'full'"
)
config = datasets[size]
dirname = config["dirname"]
extract_dir = data_dir / dirname
# Check if already downloaded
ensure_clean_dir(extract_dir, f"Stack Exchange {size}")
print(f"[DOWNLOAD] Downloading Stack Exchange {size} dataset")
print(f" Site: {config['site']}")
print(f" Description: {config['description']} ({config['size_mb']})")
print(f" Date: {config['date']} (pinned for reproducibility)")
print(" This may take several minutes...")
print()
download_start = time.time()
try:
extract_dir.mkdir(exist_ok=True)
# Download one or multiple files depending on dataset
for url in config["urls"]:
filename = url.split("/")[-1]
archive_path = data_dir / filename
print(f"\n[DOWNLOAD] Downloading {filename}")
file_start = time.time()
download_file(url, archive_path)
file_elapsed = time.time() - file_start
print(f"[OK] Downloaded to: {archive_path} ({file_elapsed:.2f}s)")
# Extract 7z file
extract_start = time.time()
print(f"[EXTRACT] Extracting {filename}...")
with py7zr.SevenZipFile(archive_path, mode="r") as archive:
archive.extractall(path=extract_dir)
extract_elapsed = time.time() - extract_start
print(f"[OK] Extracted ({extract_elapsed:.2f}s)")
# Clean up archive file
archive_path.unlink()
download_elapsed = time.time() - download_start
print(f"\n[TIME] Total download time: {download_elapsed:.2f}s")
print(f"\n[OK] Extracted to: {extract_dir}")
# Show file sizes
print("\n[STATS] Dataset contents:")
xml_files = list(extract_dir.glob("*.xml"))
if xml_files:
for xml_file in sorted(xml_files):
size_mb = xml_file.stat().st_size / (1024 * 1024)
print(f" - {xml_file.name}: {size_mb:.1f} MB")
else:
print(" [WARNING] No XML files found")
return extract_dir
except _TRANSPORT_ERRORS as e:
# Same split as movielens: the stackoverflow dumps come from a third
# party too, and one unreachable host must not be indistinguishable
# from a broken binding.
print(f"[UNAVAILABLE] Cannot reach the dataset host: {e}")
print(f" URL: {config['urls'][0]}")
print(" This is a third-party host, not a defect in arcadedb.")
raise DatasetUnavailable(f"{config['urls'][0]}: {e}") from e
except Exception as e:
print(f"[ERROR] Error downloading dataset: {e}")
print(f" You can manually download from: {config['urls'][0]}")
raise
def _write_stackoverflow_subset(
source_path: Path,
target_path: Path,
max_rows: int,
) -> int:
"""Write a truncated Stack Exchange XML file with the first max_rows rows."""
root_tag = None
row_count = 0
closed = False
with (
source_path.open("r", encoding="utf-8", errors="ignore") as fin,
target_path.open("w", encoding="utf-8") as fout,
):
for line in fin:
if root_tag is None:
fout.write(line)
match = re.match(r"\s*<(\w+)>\s*$", line)
if match:
root_tag = match.group(1)
continue
if re.match(r"\s*</\w+>\s*$", line):
if not closed:
fout.write(line)
closed = True
break
if re.match(r"\s*<row\b", line):
if row_count < max_rows:
fout.write(line)
row_count += 1
if row_count >= max_rows and root_tag:
fout.write(f"</{root_tag}>\n")
closed = True
break
continue