Paul Gessinger commited on
Commit
ad8a5f9
·
1 Parent(s): c863db5

update script

Browse files
Files changed (1) hide show
  1. scripts/manage_dataset_files.py +1112 -109
scripts/manage_dataset_files.py CHANGED
@@ -6,6 +6,7 @@
6
  # "typer>=0.9",
7
  # "rich",
8
  # "PyYAML",
 
9
  # ]
10
  # ///
11
  """Download ColliderML dataset assets and manage README URL updates."""
@@ -14,15 +15,19 @@ from __future__ import annotations
14
 
15
  import asyncio
16
  import contextlib
 
17
  import logging
 
 
18
  import shutil
19
  import tempfile
20
  from dataclasses import dataclass
21
  from pathlib import Path
22
- from typing import Annotated, Any, List, Sequence
23
  from urllib.parse import urlparse
24
 
25
  import aiohttp
 
26
  import typer
27
  import yaml
28
  from rich.console import Console
@@ -39,7 +44,7 @@ from rich.table import Table
39
 
40
 
41
  console = Console()
42
- app = typer.Typer(help="Manage dataset file URLs declared in README front matter.")
43
 
44
  # Set up logging with rich handler
45
  logging.basicConfig(
@@ -51,6 +56,23 @@ logging.basicConfig(
51
  logger = logging.getLogger(__name__)
52
 
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  @dataclass
55
  class DataFileEntry:
56
  config_name: str
@@ -85,6 +107,28 @@ class VerifyResult:
85
  order: int = 0
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def read_front_matter(readme_path: Path) -> tuple[str, str]:
89
  text = readme_path.read_text(encoding="utf-8")
90
  if not text.startswith("---\n"):
@@ -131,27 +175,21 @@ def replace_once(text: str, old: str, new: str) -> str:
131
  return f"{text[:index]}{new}{text[index + len(old):]}"
132
 
133
 
134
- def render_rewrite_template(
135
- template: str, result: DownloadResult, output_dir: Path
136
  ) -> str:
137
- entry = result.entry
138
- netloc, remote_path = entry.parsed()
 
 
 
 
 
 
139
  relative_path = result.path.relative_to(output_dir)
140
- context = {
141
- "config": entry.config_name,
142
- "filename": Path(remote_path).name,
143
- "stem": Path(remote_path).stem,
144
- "netloc": netloc,
145
- "remote_path": remote_path,
146
- "relative_path": relative_path.as_posix(),
147
- "local_path": result.path.as_posix(),
148
- "output_dir": output_dir.as_posix(),
149
- }
150
- try:
151
- return template.format(**context)
152
- except KeyError as exc:
153
- missing = ", ".join(sorted(set(exc.args)))
154
- raise typer.BadParameter(f"Template is missing keys: {missing}") from exc
155
 
156
 
157
  def resolve_destination(entry: DataFileEntry, output_dir: Path) -> Path:
@@ -161,6 +199,46 @@ def resolve_destination(entry: DataFileEntry, output_dir: Path) -> Path:
161
  return (base_dir / filename).resolve()
162
 
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  async def download_one(
165
  entry: DataFileEntry,
166
  output_dir: Path,
@@ -224,10 +302,14 @@ async def download_one(
224
  # File doesn't exist or skip_existing is disabled
225
  if not destination.exists():
226
  size_info = f" ({total_bytes:,} bytes)" if total_bytes else ""
227
- logger.info(f"Downloading {destination.name}{size_info} - file not found locally")
 
 
228
  else:
229
  size_info = f" ({total_bytes:,} bytes)" if total_bytes else ""
230
- logger.info(f"Downloading {destination.name}{size_info} - skip_existing is disabled")
 
 
231
 
232
  if total_bytes:
233
  progress.update(task_id, total=total_bytes)
@@ -236,13 +318,26 @@ async def download_one(
236
  handle.write(chunk)
237
  progress.update(task_id, advance=len(chunk))
238
 
 
 
 
 
239
  # Move from .part to final location
240
  tmp_path.rename(download_dest)
241
 
242
- # If using staging, move from staging to final destination asynchronously
243
  if staging_dir:
244
- logger.info(f"Moving {download_dest.name} from staging to {destination.parent.name}/")
245
- await asyncio.to_thread(shutil.move, str(download_dest), str(destination))
 
 
 
 
 
 
 
 
 
246
 
247
  return DownloadResult(
248
  entry=entry,
@@ -252,6 +347,8 @@ async def download_one(
252
  order=order,
253
  )
254
  except Exception as exc: # noqa: BLE001
 
 
255
  with contextlib.suppress(FileNotFoundError):
256
  tmp_path.unlink()
257
  return DownloadResult(
@@ -326,6 +423,57 @@ async def perform_downloads(
326
  return results
327
 
328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  async def verify_one(
330
  entry: DataFileEntry,
331
  session: aiohttp.ClientSession,
@@ -400,34 +548,159 @@ async def perform_verification(
400
  return results
401
 
402
 
403
- def rewrite_readme(
404
- readme_path: Path,
405
- front_matter_text: str,
406
- body_text: str,
407
- results: Sequence[DownloadResult],
408
- template: str,
409
- output_dir: Path,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  ) -> None:
411
- updated_front = front_matter_text
412
- replacements: list[tuple[DownloadResult, str]] = []
413
- for result in results:
414
- new_url = render_rewrite_template(template, result, output_dir=output_dir)
415
- updated_front = replace_once(updated_front, result.entry.url, new_url)
416
- replacements.append((result, new_url))
417
 
418
- readme_path.write_text(f"---\n{updated_front}\n---\n{body_text}", encoding="utf-8")
 
 
 
419
 
420
- table = Table(title="README URL updates")
421
- table.add_column("Config")
422
- table.add_column("Old URL", overflow="fold")
423
- table.add_column("New URL", overflow="fold")
424
- for result, new_url in replacements:
425
- table.add_row(result.entry.config_name, result.entry.url, new_url)
426
- console.print(table)
427
 
428
 
429
- def ensure_all_success(results: Sequence[DownloadResult]) -> bool:
430
- return all(result.success for result in results)
431
 
432
 
433
  @app.command()
@@ -471,16 +744,6 @@ def download(
471
  help="Request timeout in seconds.",
472
  ),
473
  ] = 600.0,
474
- rewrite_template: Annotated[
475
- str | None,
476
- typer.Option(
477
- "--rewrite-template",
478
- help=(
479
- "Optional template for rewriting URLs in README. "
480
- "Placeholders: {relative_path}, {remote_path}, {filename}, {stem}, {config}, {netloc}, {local_path}, {output_dir}."
481
- ),
482
- ),
483
- ] = None,
484
  dry_run: Annotated[
485
  bool,
486
  typer.Option(
@@ -505,57 +768,197 @@ def download(
505
  help="Download to a temporary staging directory first, then move to final destination.",
506
  ),
507
  ] = False,
 
 
 
 
 
 
 
508
  ) -> None:
509
  front_matter_text, body_text = read_front_matter(readme_path)
510
  entries = load_data_file_entries(front_matter_text)
511
  if not entries:
512
- console.print(
513
- "[yellow]No data_files entries found in README front matter.[/yellow]"
514
- )
515
  raise typer.Exit(code=0)
516
 
517
- console.print(
518
- f"[cyan]Found {len(entries)} data file URLs across {readme_path}.[/cyan]"
519
- )
520
  output_dir = output_dir.resolve()
521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  if dry_run:
 
 
 
 
 
 
 
 
 
 
523
  preview = Table(title="Download plan (dry-run)")
524
  preview.add_column("Config")
525
  preview.add_column("Local file", overflow="fold")
 
 
 
526
  preview.add_column("Source URL", overflow="fold")
527
- preview.add_column(
528
- "Rewritten URL" if rewrite_template else "Rewritten URL (n/a)",
529
- overflow="fold",
530
- )
531
  for order, entry in enumerate(entries):
532
  destination = resolve_destination(entry, output_dir)
533
  try:
534
  relative = destination.relative_to(output_dir)
535
  except ValueError:
536
  relative = Path(destination)
537
- new_url = "-"
538
- if rewrite_template:
539
- fake_result = DownloadResult(
540
- entry=entry,
541
- path=destination,
542
- success=True,
543
- skipped=False,
544
- order=order,
545
- )
546
- new_url = render_rewrite_template(
547
- rewrite_template, fake_result, output_dir
548
- )
549
- preview.add_row(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  entry.config_name,
551
  relative.as_posix(),
 
 
 
552
  entry.url,
553
- new_url,
554
- )
 
 
555
  console.print(preview)
556
- console.print(
557
- "[yellow]Dry run: no files downloaded and README left unchanged.[/yellow]"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  )
 
559
  return
560
 
561
  output_dir.mkdir(parents=True, exist_ok=True)
@@ -574,34 +977,151 @@ def download(
574
  successes = sum(1 for item in results if item.success)
575
  failures = len(results) - successes
576
  skipped = sum(1 for item in results if item.skipped)
577
- console.print(
578
- f"[green]{successes}[/green] succeeded, [red]{failures}[/red] failed, [yellow]{skipped}[/yellow] skipped."
579
- )
580
 
581
  if failures:
582
  for item in results:
583
  if not item.success:
584
- console.print(f"[red]Error:[/red] {item.entry.url} -> {item.error}")
 
 
585
 
586
- if rewrite_template:
587
- if not ensure_all_success(results):
588
- console.print(
589
- "[red]README rewrite skipped because some downloads failed.[/red]"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  )
591
  raise typer.Exit(code=1)
592
- rewrite_readme(
593
- readme_path,
594
- front_matter_text,
595
- body_text,
596
- results,
597
- rewrite_template,
598
- output_dir=output_dir,
599
  )
600
- console.print("[green]README.md updated with new URLs.[/green]")
601
 
602
- if failures:
 
603
  raise typer.Exit(code=1)
604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
605
 
606
  @app.command()
607
  def verify(
@@ -639,12 +1159,10 @@ def verify(
639
  front_matter_text, _ = read_front_matter(readme_path)
640
  entries = load_data_file_entries(front_matter_text)
641
  if not entries:
642
- console.print(
643
- "[yellow]No data_files entries found in README front matter.[/yellow]"
644
- )
645
  raise typer.Exit(code=0)
646
 
647
- console.print(f"[cyan]Verifying {len(entries)} URLs from {readme_path}.[/cyan]")
648
  results = asyncio.run(
649
  perform_verification(
650
  entries=entries,
@@ -677,9 +1195,494 @@ def verify(
677
 
678
  console.print(table)
679
  if failed:
680
- console.print(f"[red]{failed} URLs failed verification.[/red]")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  raise typer.Exit(code=1)
682
- console.print("[green]All URLs verified successfully.[/green]")
683
 
684
 
685
  if __name__ == "__main__":
 
6
  # "typer>=0.9",
7
  # "rich",
8
  # "PyYAML",
9
+ # "pyarrow",
10
  # ]
11
  # ///
12
  """Download ColliderML dataset assets and manage README URL updates."""
 
15
 
16
  import asyncio
17
  import contextlib
18
+ import hashlib
19
  import logging
20
+ import os
21
+ import re
22
  import shutil
23
  import tempfile
24
  from dataclasses import dataclass
25
  from pathlib import Path
26
+ from typing import Annotated, Any, Dict, List, Sequence
27
  from urllib.parse import urlparse
28
 
29
  import aiohttp
30
+ import pyarrow.parquet as pq
31
  import typer
32
  import yaml
33
  from rich.console import Console
 
44
 
45
 
46
  console = Console()
47
+ app = typer.Typer()
48
 
49
  # Set up logging with rich handler
50
  logging.basicConfig(
 
56
  logger = logging.getLogger(__name__)
57
 
58
 
59
+ @app.callback()
60
+ def main_callback(
61
+ verbose: Annotated[
62
+ bool,
63
+ typer.Option(
64
+ "--verbose",
65
+ "-v",
66
+ help="Enable verbose logging.",
67
+ ),
68
+ ] = False,
69
+ ) -> None:
70
+ """Manage dataset file URLs declared in README front matter."""
71
+ if verbose:
72
+ logging.getLogger().setLevel(logging.DEBUG)
73
+ logger.debug("Verbose logging enabled")
74
+
75
+
76
  @dataclass
77
  class DataFileEntry:
78
  config_name: str
 
107
  order: int = 0
108
 
109
 
110
+ @dataclass
111
+ class ChecksumResult:
112
+ entry: DataFileEntry
113
+ filename: str
114
+ computed_hash: str | None
115
+ expected_hash: str | None
116
+ matches: bool
117
+ success: bool
118
+ error: Exception | None = None
119
+ order: int = 0
120
+
121
+
122
+ @dataclass
123
+ class SchemaInfo:
124
+ config_name: str
125
+ filename: str
126
+ columns: List[tuple[str, str]] # (column_name, data_type)
127
+ num_rows: int | None
128
+ success: bool
129
+ error: Exception | None = None
130
+
131
+
132
  def read_front_matter(readme_path: Path) -> tuple[str, str]:
133
  text = readme_path.read_text(encoding="utf-8")
134
  if not text.startswith("---\n"):
 
175
  return f"{text[:index]}{new}{text[index + len(old):]}"
176
 
177
 
178
+ def build_rewritten_url(
179
+ result: DownloadResult, output_dir: Path, base_url: str
180
  ) -> str:
181
+ """Build new URL by replacing output_dir with base_url in the file path.
182
+
183
+ For example:
184
+ - File path: /data/output/particles/file.parquet
185
+ - Output dir: /data/output
186
+ - Base URL: https://example.com/files
187
+ - Result: https://example.com/files/particles/file.parquet
188
+ """
189
  relative_path = result.path.relative_to(output_dir)
190
+ # Ensure base_url doesn't end with slash, relative_path is POSIX-style
191
+ base_url = base_url.rstrip("/")
192
+ return f"{base_url}/{relative_path.as_posix()}"
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
 
195
  def resolve_destination(entry: DataFileEntry, output_dir: Path) -> Path:
 
199
  return (base_dir / filename).resolve()
200
 
201
 
202
+ def move_with_progress(src: Path, dst: Path, progress: Progress, task_id: int) -> None:
203
+ """Move file with progress tracking for cross-filesystem moves."""
204
+ # Try fast rename first (works if same filesystem)
205
+ try:
206
+ os.rename(src, dst)
207
+ return
208
+ except OSError:
209
+ # Cross-filesystem move - need to copy with progress
210
+ pass
211
+
212
+ # Get file size for progress tracking
213
+ file_size = src.stat().st_size
214
+ progress.update(task_id, total=file_size)
215
+
216
+ # Copy with progress tracking - use larger buffers for remote filesystems
217
+ buffer_size = 8 << 20 # 8 MB chunks for better performance on remote FS
218
+ with src.open("rb") as fsrc, dst.open("wb") as fdst:
219
+ copied = 0
220
+ while True:
221
+ buf = fsrc.read(buffer_size)
222
+ if not buf:
223
+ break
224
+ fdst.write(buf)
225
+ copied += len(buf)
226
+ progress.update(task_id, completed=copied)
227
+
228
+ # Ensure data is flushed to disk (critical for remote filesystems)
229
+ fdst.flush()
230
+ os.fsync(fdst.fileno())
231
+
232
+ # Verify file was written correctly before removing source
233
+ if dst.stat().st_size != file_size:
234
+ raise IOError(
235
+ f"File size mismatch after copy: expected {file_size}, got {dst.stat().st_size}"
236
+ )
237
+
238
+ # Remove source after successful copy
239
+ src.unlink()
240
+
241
+
242
  async def download_one(
243
  entry: DataFileEntry,
244
  output_dir: Path,
 
302
  # File doesn't exist or skip_existing is disabled
303
  if not destination.exists():
304
  size_info = f" ({total_bytes:,} bytes)" if total_bytes else ""
305
+ logger.info(
306
+ f"Downloading {destination.name}{size_info} - file not found locally"
307
+ )
308
  else:
309
  size_info = f" ({total_bytes:,} bytes)" if total_bytes else ""
310
+ logger.info(
311
+ f"Downloading {destination.name}{size_info} - skip_existing is disabled"
312
+ )
313
 
314
  if total_bytes:
315
  progress.update(task_id, total=total_bytes)
 
318
  handle.write(chunk)
319
  progress.update(task_id, advance=len(chunk))
320
 
321
+ # Flush and sync to ensure data is written (critical for remote filesystems)
322
+ handle.flush()
323
+ os.fsync(handle.fileno())
324
+
325
  # Move from .part to final location
326
  tmp_path.rename(download_dest)
327
 
328
+ # If using staging, move from staging to final destination with progress
329
  if staging_dir:
330
+ logger.info(
331
+ f"Moving {download_dest.name} from staging to {destination.parent.name}/"
332
+ )
333
+ # Update progress bar description for move operation
334
+ if task_id is not None:
335
+ progress.update(
336
+ task_id, description=f"{entry.config_name}: Moving {terse_name}"
337
+ )
338
+ await asyncio.to_thread(
339
+ move_with_progress, download_dest, destination, progress, task_id
340
+ )
341
 
342
  return DownloadResult(
343
  entry=entry,
 
347
  order=order,
348
  )
349
  except Exception as exc: # noqa: BLE001
350
+ # Report error immediately
351
+ logger.error(f"Failed to download {entry.config_name}/{filename}: {exc}")
352
  with contextlib.suppress(FileNotFoundError):
353
  tmp_path.unlink()
354
  return DownloadResult(
 
423
  return results
424
 
425
 
426
+ async def get_remote_file_size(
427
+ entry: DataFileEntry,
428
+ session: aiohttp.ClientSession,
429
+ semaphore: asyncio.Semaphore,
430
+ ) -> int | None:
431
+ """Get remote file size via HEAD request."""
432
+ async with semaphore:
433
+ try:
434
+ async with session.head(entry.url, allow_redirects=True) as response:
435
+ if response.status < 400:
436
+ return response.content_length
437
+ except Exception: # noqa: BLE001
438
+ pass
439
+ return None
440
+
441
+
442
+ async def fetch_remote_sizes(
443
+ entries: Sequence[DataFileEntry],
444
+ max_concurrency: int,
445
+ timeout: float,
446
+ ) -> Dict[str, int | None]:
447
+ """Fetch remote file sizes for all entries."""
448
+ semaphore = asyncio.Semaphore(max_concurrency)
449
+ timeout_cfg = aiohttp.ClientTimeout(total=timeout)
450
+ sizes: Dict[str, int | None] = {}
451
+
452
+ progress = Progress(
453
+ TextColumn("Fetching remote file sizes..."),
454
+ BarColumn(),
455
+ TextColumn("{task.completed}/{task.total}"),
456
+ TimeElapsedColumn(),
457
+ console=console,
458
+ )
459
+
460
+ async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
461
+ with progress:
462
+ task_id = progress.add_task("Fetching sizes", total=len(entries))
463
+ tasks = {
464
+ entry.url: asyncio.create_task(
465
+ get_remote_file_size(entry, session, semaphore)
466
+ )
467
+ for entry in entries
468
+ }
469
+ for url, task in tasks.items():
470
+ size = await task
471
+ sizes[url] = size
472
+ progress.advance(task_id)
473
+
474
+ return sizes
475
+
476
+
477
  async def verify_one(
478
  entry: DataFileEntry,
479
  session: aiohttp.ClientSession,
 
548
  return results
549
 
550
 
551
+ async def compute_file_hash(
552
+ entry: DataFileEntry,
553
+ session: aiohttp.ClientSession,
554
+ semaphore: asyncio.Semaphore,
555
+ progress: Progress,
556
+ order: int,
557
+ ) -> ChecksumResult:
558
+ """Download file to temp location and compute SHA256 hash."""
559
+ # Extract filename from URL
560
+ _, remote_path = entry.parsed()
561
+ filename = Path(remote_path).name or remote_path
562
+ terse_name = (filename[:32] + "…") if len(filename) > 33 else filename
563
+ description = f"{entry.config_name}: {terse_name}"
564
+
565
+ async with semaphore:
566
+ task_id: int | None = None
567
+ try:
568
+ task_id = progress.add_task(description, total=0, start=False)
569
+ progress.start_task(task_id)
570
+
571
+ async with session.get(entry.url) as response:
572
+ response.raise_for_status()
573
+ total_bytes = response.content_length or 0
574
+
575
+ if total_bytes:
576
+ progress.update(task_id, total=total_bytes)
577
+
578
+ hasher = hashlib.sha256()
579
+ async for chunk in response.content.iter_chunked(1 << 17):
580
+ hasher.update(chunk)
581
+ progress.update(task_id, advance=len(chunk))
582
+
583
+ computed_hash = hasher.hexdigest()
584
+ return ChecksumResult(
585
+ entry=entry,
586
+ filename=filename,
587
+ computed_hash=computed_hash,
588
+ expected_hash=None, # Will be filled in later
589
+ matches=False, # Will be determined later
590
+ success=True,
591
+ order=order,
592
+ )
593
+ except Exception as exc: # noqa: BLE001
594
+ return ChecksumResult(
595
+ entry=entry,
596
+ filename=filename,
597
+ computed_hash=None,
598
+ expected_hash=None,
599
+ matches=False,
600
+ success=False,
601
+ error=exc,
602
+ order=order,
603
+ )
604
+ finally:
605
+ if task_id is not None:
606
+ progress.remove_task(task_id)
607
+
608
+
609
+ async def perform_checksum_verification(
610
+ entries: Sequence[DataFileEntry],
611
+ expected_hashes_by_config: Dict[str, Dict[str, str]],
612
+ max_concurrency: int,
613
+ timeout: float,
614
+ ) -> List[ChecksumResult]:
615
+ """Download files and verify their checksums.
616
+
617
+ expected_hashes_by_config: dict mapping config_name -> (filename -> hash)
618
+ """
619
+ if not entries:
620
+ return []
621
+
622
+ semaphore = asyncio.Semaphore(max_concurrency)
623
+ timeout_cfg = aiohttp.ClientTimeout(total=timeout)
624
+ results: List[ChecksumResult] = []
625
+ progress = Progress(
626
+ TextColumn("{task.description}"),
627
+ BarColumn(),
628
+ DownloadColumn(),
629
+ TransferSpeedColumn(),
630
+ TimeElapsedColumn(),
631
+ console=console,
632
+ )
633
+
634
+ async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
635
+ with progress:
636
+ tasks = [
637
+ asyncio.create_task(
638
+ compute_file_hash(
639
+ entry, session, semaphore, order=order, progress=progress
640
+ )
641
+ )
642
+ for order, entry in enumerate(entries)
643
+ ]
644
+ for future in asyncio.as_completed(tasks):
645
+ result = await future
646
+ # Fill in expected hash and match status
647
+ config_hashes = expected_hashes_by_config.get(
648
+ result.entry.config_name, {}
649
+ )
650
+ result.expected_hash = config_hashes.get(result.filename)
651
+ if result.success and result.expected_hash:
652
+ result.matches = result.computed_hash == result.expected_hash
653
+ results.append(result)
654
+
655
+ results.sort(key=lambda item: item.order)
656
+ return results
657
+
658
+
659
+ def load_checksums_for_config(checksum_dir: Path, config_name: str) -> Dict[str, str]:
660
+ """Load expected hashes from SHA256SUM-style file for a specific config.
661
+
662
+ Returns a dict mapping filename -> hash.
663
+ """
664
+ checksum_file = checksum_dir / f"{config_name}.sha256"
665
+ if not checksum_file.exists():
666
+ return {}
667
+
668
+ hashes: Dict[str, str] = {}
669
+ try:
670
+ with checksum_file.open("r", encoding="utf-8") as f:
671
+ for line in f:
672
+ line = line.strip()
673
+ if not line or line.startswith("#"):
674
+ continue
675
+ # Format: <hash> <filename>
676
+ parts = line.split(None, 1)
677
+ if len(parts) == 2:
678
+ hash_value, filename = parts
679
+ hashes[filename] = hash_value
680
+ except OSError as exc:
681
+ logger.warning(f"Failed to load checksum file {checksum_file}: {exc}")
682
+
683
+ return hashes
684
+
685
+
686
+ def save_checksums_for_config(
687
+ checksum_dir: Path, config_name: str, file_hashes: Dict[str, str]
688
  ) -> None:
689
+ """Save hashes to SHA256SUM-style file for a specific config.
 
 
 
 
 
690
 
691
+ file_hashes: dict mapping filename -> hash
692
+ """
693
+ checksum_dir.mkdir(parents=True, exist_ok=True)
694
+ checksum_file = checksum_dir / f"{config_name}.sha256"
695
 
696
+ with checksum_file.open("w", encoding="utf-8") as f:
697
+ for filename in sorted(file_hashes.keys()):
698
+ hash_value = file_hashes[filename]
699
+ f.write(f"{hash_value} {filename}\n")
700
+
701
+ logger.info(f"Saved {len(file_hashes)} checksums to {checksum_file}")
 
702
 
703
 
 
 
704
 
705
 
706
  @app.command()
 
744
  help="Request timeout in seconds.",
745
  ),
746
  ] = 600.0,
 
 
 
 
 
 
 
 
 
 
747
  dry_run: Annotated[
748
  bool,
749
  typer.Option(
 
768
  help="Download to a temporary staging directory first, then move to final destination.",
769
  ),
770
  ] = False,
771
+ clean_invalid: Annotated[
772
+ bool,
773
+ typer.Option(
774
+ "--clean-invalid",
775
+ help="Delete files with incorrect sizes but don't download. Useful for cleaning up failed downloads.",
776
+ ),
777
+ ] = False,
778
  ) -> None:
779
  front_matter_text, body_text = read_front_matter(readme_path)
780
  entries = load_data_file_entries(front_matter_text)
781
  if not entries:
782
+ logger.warning("No data_files entries found in README front matter.")
 
 
783
  raise typer.Exit(code=0)
784
 
785
+ logger.info(f"Found {len(entries)} data file URLs across {readme_path}.")
 
 
786
  output_dir = output_dir.resolve()
787
 
788
+ if clean_invalid:
789
+ # Fetch remote file sizes
790
+ logger.info("Fetching remote file sizes to check for invalid files...")
791
+ remote_sizes = asyncio.run(
792
+ fetch_remote_sizes(
793
+ entries=entries,
794
+ max_concurrency=max_concurrency,
795
+ timeout=timeout,
796
+ )
797
+ )
798
+
799
+ # Check and delete invalid files
800
+ deleted = 0
801
+ skipped = 0
802
+ missing = 0
803
+ size_unknown = 0
804
+
805
+ table = Table(title="Cleaning invalid files")
806
+ table.add_column("Config")
807
+ table.add_column("File")
808
+ table.add_column("Status")
809
+ table.add_column("Local size")
810
+ table.add_column("Remote size")
811
+
812
+ for entry in entries:
813
+ destination = resolve_destination(entry, output_dir)
814
+ _, remote_path = entry.parsed()
815
+ filename = Path(remote_path).name or remote_path
816
+
817
+ if not destination.exists():
818
+ missing += 1
819
+ table.add_row(
820
+ entry.config_name,
821
+ filename,
822
+ "[dim]Not found[/dim]",
823
+ "-",
824
+ "-",
825
+ )
826
+ continue
827
+
828
+ local_size = destination.stat().st_size
829
+ remote_size = remote_sizes.get(entry.url)
830
+
831
+ if not remote_size:
832
+ size_unknown += 1
833
+ table.add_row(
834
+ entry.config_name,
835
+ filename,
836
+ "[cyan]Skipped (remote size unknown)[/cyan]",
837
+ f"{local_size:,}",
838
+ "Unknown",
839
+ )
840
+ continue
841
+
842
+ if local_size == remote_size:
843
+ skipped += 1
844
+ table.add_row(
845
+ entry.config_name,
846
+ filename,
847
+ "[green]Valid[/green]",
848
+ f"{local_size:,}",
849
+ f"{remote_size:,}",
850
+ )
851
+ else:
852
+ # Size mismatch - delete the file
853
+ destination.unlink()
854
+ deleted += 1
855
+ logger.warning(
856
+ f"Deleted {destination} (size mismatch: {local_size:,} != {remote_size:,})"
857
+ )
858
+ table.add_row(
859
+ entry.config_name,
860
+ filename,
861
+ "[red]Deleted (size mismatch)[/red]",
862
+ f"{local_size:,}",
863
+ f"{remote_size:,}",
864
+ )
865
+
866
+ console.print(table)
867
+ logger.info(
868
+ f"Summary: {deleted} deleted, {skipped} valid, {missing} missing, {size_unknown} unknown size"
869
+ )
870
+ return
871
+
872
  if dry_run:
873
+ # Fetch remote file sizes
874
+ logger.info("Fetching remote file sizes for dry-run preview...")
875
+ remote_sizes = asyncio.run(
876
+ fetch_remote_sizes(
877
+ entries=entries,
878
+ max_concurrency=max_concurrency,
879
+ timeout=timeout,
880
+ )
881
+ )
882
+
883
  preview = Table(title="Download plan (dry-run)")
884
  preview.add_column("Config")
885
  preview.add_column("Local file", overflow="fold")
886
+ preview.add_column("Status")
887
+ preview.add_column("Local size")
888
+ preview.add_column("Remote size")
889
  preview.add_column("Source URL", overflow="fold")
890
+
 
 
 
891
  for order, entry in enumerate(entries):
892
  destination = resolve_destination(entry, output_dir)
893
  try:
894
  relative = destination.relative_to(output_dir)
895
  except ValueError:
896
  relative = Path(destination)
897
+
898
+ # Check local file
899
+ local_exists = destination.exists()
900
+ local_size = destination.stat().st_size if local_exists else None
901
+ remote_size = remote_sizes.get(entry.url)
902
+
903
+ # Determine status
904
+ if not local_exists:
905
+ status = "[yellow]Will download[/yellow]"
906
+ local_size_str = "-"
907
+ elif not skip_existing:
908
+ status = "[red]Will overwrite[/red]"
909
+ local_size_str = f"{local_size:,}"
910
+ elif remote_size and local_size == remote_size:
911
+ status = "[green]Will skip (exists)[/green]"
912
+ local_size_str = f"{local_size:,}"
913
+ elif not remote_size:
914
+ status = "[cyan]Will skip (exists, size unknown)[/cyan]"
915
+ local_size_str = f"{local_size:,}"
916
+ else:
917
+ # skip_existing=True but sizes don't match
918
+ status = "[red]Will overwrite (size mismatch)[/red]"
919
+ local_size_str = f"{local_size:,}"
920
+
921
+ remote_size_str = f"{remote_size:,}" if remote_size else "Unknown"
922
+
923
+ row_data = [
924
  entry.config_name,
925
  relative.as_posix(),
926
+ status,
927
+ local_size_str,
928
+ remote_size_str,
929
  entry.url,
930
+ ]
931
+
932
+ preview.add_row(*row_data)
933
+
934
  console.print(preview)
935
+
936
+ # Summary statistics
937
+ will_download = 0
938
+ will_skip = 0
939
+ will_overwrite = 0
940
+
941
+ for entry in entries:
942
+ dest = resolve_destination(entry, output_dir)
943
+ local_exists = dest.exists()
944
+ local_size = dest.stat().st_size if local_exists else None
945
+ remote_size = remote_sizes.get(entry.url)
946
+
947
+ if not local_exists:
948
+ will_download += 1
949
+ elif not skip_existing:
950
+ will_overwrite += 1
951
+ elif remote_size and local_size == remote_size:
952
+ will_skip += 1
953
+ elif not remote_size:
954
+ will_skip += 1
955
+ else:
956
+ will_overwrite += 1
957
+
958
+ logger.info(
959
+ f"Summary: {will_download} new, {will_skip} will skip, {will_overwrite} will overwrite"
960
  )
961
+ logger.info("Dry run: no files downloaded and README left unchanged.")
962
  return
963
 
964
  output_dir.mkdir(parents=True, exist_ok=True)
 
977
  successes = sum(1 for item in results if item.success)
978
  failures = len(results) - successes
979
  skipped = sum(1 for item in results if item.skipped)
980
+ logger.info(f"{successes} succeeded, {failures} failed, {skipped} skipped.")
 
 
981
 
982
  if failures:
983
  for item in results:
984
  if not item.success:
985
+ logger.error(f"Error: {item.entry.url} -> {item.error}")
986
+ raise typer.Exit(code=1)
987
+
988
 
989
+ @app.command()
990
+ def rewrite(
991
+ output_dir: Annotated[
992
+ Path,
993
+ typer.Option(
994
+ "--output-dir",
995
+ "-o",
996
+ help="Directory where downloaded files are stored.",
997
+ resolve_path=True,
998
+ ),
999
+ ],
1000
+ base_url: Annotated[
1001
+ str,
1002
+ typer.Option(
1003
+ "--base-url",
1004
+ "-u",
1005
+ help=(
1006
+ "Base URL for rewriting URLs in README. Files under output_dir will be rewritten "
1007
+ "to use this base URL. Example: if output_dir=/data/files and base_url=https://example.com/dataset, "
1008
+ "then /data/files/particles/file.parquet becomes https://example.com/dataset/particles/file.parquet"
1009
+ ),
1010
+ ),
1011
+ ],
1012
+ readme_path: Annotated[
1013
+ Path,
1014
+ typer.Option(
1015
+ "--readme-path",
1016
+ "-r",
1017
+ help="Path to the README file with YAML front matter.",
1018
+ exists=True,
1019
+ resolve_path=True,
1020
+ dir_okay=False,
1021
+ ),
1022
+ ] = Path("README.md"),
1023
+ dry_run: Annotated[
1024
+ bool,
1025
+ typer.Option(
1026
+ "--dry-run/--no-dry-run",
1027
+ show_default=True,
1028
+ help="Preview URL rewrites without modifying the README.",
1029
+ ),
1030
+ ] = False,
1031
+ skip_missing: Annotated[
1032
+ bool,
1033
+ typer.Option(
1034
+ "--skip-missing/--no-skip-missing",
1035
+ show_default=True,
1036
+ help="Skip rewriting URLs for files that don't exist locally.",
1037
+ ),
1038
+ ] = True,
1039
+ ) -> None:
1040
+ """Rewrite URLs in README to point to local files served at a base URL."""
1041
+ front_matter_text, body_text = read_front_matter(readme_path)
1042
+ entries = load_data_file_entries(front_matter_text)
1043
+ if not entries:
1044
+ logger.warning("No data_files entries found in README front matter.")
1045
+ raise typer.Exit(code=0)
1046
+
1047
+ logger.info(f"Found {len(entries)} data file URLs in {readme_path}.")
1048
+ output_dir = output_dir.resolve()
1049
+
1050
+ # Build list of results for files that exist
1051
+ results: List[DownloadResult] = []
1052
+ missing_files = []
1053
+
1054
+ for order, entry in enumerate(entries):
1055
+ destination = resolve_destination(entry, output_dir)
1056
+ if destination.exists():
1057
+ results.append(
1058
+ DownloadResult(
1059
+ entry=entry,
1060
+ path=destination,
1061
+ success=True,
1062
+ skipped=False,
1063
+ order=order,
1064
+ )
1065
+ )
1066
+ else:
1067
+ missing_files.append((entry, destination))
1068
+
1069
+ if missing_files:
1070
+ if not skip_missing:
1071
+ logger.error(f"Found {len(missing_files)} missing files:")
1072
+ for entry, dest in missing_files:
1073
+ logger.error(f" {entry.config_name}: {dest}")
1074
+ logger.error(
1075
+ "Use --skip-missing to rewrite URLs only for existing files, "
1076
+ "or download the missing files first."
1077
  )
1078
  raise typer.Exit(code=1)
1079
+ else:
1080
+ logger.warning(
1081
+ f"Skipping {len(missing_files)} missing files "
1082
+ f"(rewriting {len(results)} existing files)"
 
 
 
1083
  )
 
1084
 
1085
+ if not results:
1086
+ logger.error("No files found to rewrite URLs for.")
1087
  raise typer.Exit(code=1)
1088
 
1089
+ # Preview or perform rewrite
1090
+ table = Table(title="URL rewrite preview" if dry_run else "README URL updates")
1091
+ table.add_column("Config")
1092
+ table.add_column("Local file", overflow="fold")
1093
+ table.add_column("Old URL", overflow="fold")
1094
+ table.add_column("New URL", overflow="fold")
1095
+
1096
+ replacements: list[tuple[DownloadResult, str]] = []
1097
+ for result in results:
1098
+ relative_path = result.path.relative_to(output_dir)
1099
+ new_url = build_rewritten_url(result, output_dir, base_url)
1100
+ replacements.append((result, new_url))
1101
+ table.add_row(
1102
+ result.entry.config_name,
1103
+ relative_path.as_posix(),
1104
+ result.entry.url,
1105
+ new_url,
1106
+ )
1107
+
1108
+ console.print(table)
1109
+
1110
+ if dry_run:
1111
+ logger.info(
1112
+ f"Dry run: would rewrite {len(results)} URLs. "
1113
+ "Remove --dry-run to apply changes."
1114
+ )
1115
+ return
1116
+
1117
+ # Apply rewrites
1118
+ updated_front = front_matter_text
1119
+ for result, new_url in replacements:
1120
+ updated_front = replace_once(updated_front, result.entry.url, new_url)
1121
+
1122
+ readme_path.write_text(f"---\n{updated_front}\n---\n{body_text}", encoding="utf-8")
1123
+ logger.info(f"Successfully rewrote {len(results)} URLs in {readme_path}")
1124
+
1125
 
1126
  @app.command()
1127
  def verify(
 
1159
  front_matter_text, _ = read_front_matter(readme_path)
1160
  entries = load_data_file_entries(front_matter_text)
1161
  if not entries:
1162
+ logger.warning("No data_files entries found in README front matter.")
 
 
1163
  raise typer.Exit(code=0)
1164
 
1165
+ logger.info(f"Verifying {len(entries)} URLs from {readme_path}.")
1166
  results = asyncio.run(
1167
  perform_verification(
1168
  entries=entries,
 
1195
 
1196
  console.print(table)
1197
  if failed:
1198
+ logger.error(f"{failed} URLs failed verification.")
1199
+ raise typer.Exit(code=1)
1200
+ logger.info("All URLs verified successfully.")
1201
+
1202
+
1203
+ @app.command()
1204
+ def checksum(
1205
+ readme_path: Annotated[
1206
+ Path,
1207
+ typer.Option(
1208
+ "--readme-path",
1209
+ "-r",
1210
+ help="Path to the README file with YAML front matter.",
1211
+ exists=True,
1212
+ resolve_path=True,
1213
+ dir_okay=False,
1214
+ ),
1215
+ ] = Path("README.md"),
1216
+ checksum_dir: Annotated[
1217
+ Path,
1218
+ typer.Option(
1219
+ "--checksum-dir",
1220
+ "-d",
1221
+ help="Directory containing SHA256 checksum files (one per config).",
1222
+ resolve_path=True,
1223
+ ),
1224
+ ] = Path("checksums"),
1225
+ max_concurrency: Annotated[
1226
+ int,
1227
+ typer.Option(
1228
+ "--max-concurrency",
1229
+ "-c",
1230
+ min=1,
1231
+ show_default=True,
1232
+ help="Maximum concurrent checksum operations.",
1233
+ ),
1234
+ ] = 8,
1235
+ timeout: Annotated[
1236
+ float,
1237
+ typer.Option(
1238
+ "--timeout",
1239
+ min=1.0,
1240
+ show_default=True,
1241
+ help="Request timeout in seconds.",
1242
+ ),
1243
+ ] = 300.0,
1244
+ generate: Annotated[
1245
+ bool,
1246
+ typer.Option(
1247
+ "--generate",
1248
+ help="Generate/update checksum files with current remote file checksums.",
1249
+ ),
1250
+ ] = False,
1251
+ update_mismatches: Annotated[
1252
+ bool,
1253
+ typer.Option(
1254
+ "--update-mismatches",
1255
+ help="Update checksum files with new hashes for files that don't match.",
1256
+ ),
1257
+ ] = False,
1258
+ ) -> None:
1259
+ """Verify file integrity using SHA256 checksums."""
1260
+ front_matter_text, _ = read_front_matter(readme_path)
1261
+ entries = load_data_file_entries(front_matter_text)
1262
+ if not entries:
1263
+ logger.warning("No data_files entries found in README front matter.")
1264
+ raise typer.Exit(code=0)
1265
+
1266
+ logger.info(f"Computing checksums for {len(entries)} files from {readme_path}.")
1267
+
1268
+ # Get unique config names
1269
+ config_names = sorted(set(entry.config_name for entry in entries))
1270
+
1271
+ # Load existing hashes per config unless we're regenerating
1272
+ expected_hashes_by_config: Dict[str, Dict[str, str]] = {}
1273
+ if not generate:
1274
+ for config_name in config_names:
1275
+ expected_hashes_by_config[config_name] = load_checksums_for_config(
1276
+ checksum_dir, config_name
1277
+ )
1278
+
1279
+ # Compute checksums
1280
+ results = asyncio.run(
1281
+ perform_checksum_verification(
1282
+ entries=entries,
1283
+ expected_hashes_by_config=expected_hashes_by_config,
1284
+ max_concurrency=max_concurrency,
1285
+ timeout=timeout,
1286
+ )
1287
+ )
1288
+
1289
+ # Display results
1290
+ table = Table(title="Checksum verification results")
1291
+ table.add_column("Config")
1292
+ table.add_column("Filename")
1293
+ table.add_column("Status")
1294
+ table.add_column("SHA256", overflow="fold")
1295
+
1296
+ failed = 0
1297
+ mismatched = 0
1298
+ # new_hashes_by_config: config_name -> (filename -> hash)
1299
+ new_hashes_by_config: Dict[str, Dict[str, str]] = {}
1300
+
1301
+ for result in results:
1302
+ if not result.success:
1303
+ failed += 1
1304
+ error_msg = str(result.error) if result.error else "Unknown error"
1305
+ table.add_row(
1306
+ result.entry.config_name,
1307
+ result.filename,
1308
+ "[red]ERROR[/red]",
1309
+ error_msg,
1310
+ )
1311
+ elif generate:
1312
+ # In generate mode, just collect all hashes
1313
+ if result.entry.config_name not in new_hashes_by_config:
1314
+ new_hashes_by_config[result.entry.config_name] = {}
1315
+ new_hashes_by_config[result.entry.config_name][result.filename] = (
1316
+ result.computed_hash or ""
1317
+ )
1318
+ table.add_row(
1319
+ result.entry.config_name,
1320
+ result.filename,
1321
+ "[cyan]COMPUTED[/cyan]",
1322
+ result.computed_hash or "-",
1323
+ )
1324
+ elif result.expected_hash is None:
1325
+ # No expected hash available
1326
+ table.add_row(
1327
+ result.entry.config_name,
1328
+ result.filename,
1329
+ "[yellow]NEW[/yellow]",
1330
+ result.computed_hash or "-",
1331
+ )
1332
+ if update_mismatches and result.computed_hash:
1333
+ if result.entry.config_name not in new_hashes_by_config:
1334
+ new_hashes_by_config[result.entry.config_name] = {}
1335
+ new_hashes_by_config[result.entry.config_name][
1336
+ result.filename
1337
+ ] = result.computed_hash
1338
+ elif result.matches:
1339
+ # Hash matches
1340
+ table.add_row(
1341
+ result.entry.config_name,
1342
+ result.filename,
1343
+ "[green]OK[/green]",
1344
+ result.computed_hash or "-",
1345
+ )
1346
+ else:
1347
+ # Hash mismatch
1348
+ mismatched += 1
1349
+ table.add_row(
1350
+ result.entry.config_name,
1351
+ result.filename,
1352
+ "[red]MISMATCH[/red]",
1353
+ f"Expected: {result.expected_hash}\nComputed: {result.computed_hash}",
1354
+ )
1355
+ if update_mismatches and result.computed_hash:
1356
+ if result.entry.config_name not in new_hashes_by_config:
1357
+ new_hashes_by_config[result.entry.config_name] = {}
1358
+ new_hashes_by_config[result.entry.config_name][
1359
+ result.filename
1360
+ ] = result.computed_hash
1361
+
1362
+ console.print(table)
1363
+
1364
+ # Handle checksum file updates
1365
+ if generate:
1366
+ total_saved = 0
1367
+ for config_name, file_hashes in new_hashes_by_config.items():
1368
+ save_checksums_for_config(checksum_dir, config_name, file_hashes)
1369
+ total_saved += len(file_hashes)
1370
+ logger.info(
1371
+ f"Generated {len(new_hashes_by_config)} checksum files with {total_saved} total checksums."
1372
+ )
1373
+ elif update_mismatches and new_hashes_by_config:
1374
+ total_updated = 0
1375
+ for config_name, new_file_hashes in new_hashes_by_config.items():
1376
+ # Merge with existing hashes for this config
1377
+ all_hashes = load_checksums_for_config(checksum_dir, config_name)
1378
+ all_hashes.update(new_file_hashes)
1379
+ save_checksums_for_config(checksum_dir, config_name, all_hashes)
1380
+ total_updated += len(new_file_hashes)
1381
+ logger.warning(
1382
+ f"Updated {total_updated} checksums across {len(new_hashes_by_config)} checksum files."
1383
+ )
1384
+
1385
+ # Exit with appropriate code
1386
+ if failed:
1387
+ logger.error(f"{failed} files failed checksum computation.")
1388
+ raise typer.Exit(code=1)
1389
+ if mismatched and not update_mismatches:
1390
+ logger.error(f"{mismatched} files have checksum mismatches.")
1391
+ logger.warning("Use --update-mismatches to update the checksum files.")
1392
+ raise typer.Exit(code=1)
1393
+ if not generate and not mismatched and not failed:
1394
+ logger.info("All checksums verified successfully.")
1395
+
1396
+
1397
+ def clean_arrow_type(type_str: str) -> str:
1398
+ """Clean up Arrow type string for display."""
1399
+ # Remove "element: " from list types
1400
+ # Pattern: list<element: TYPE> -> list<TYPE>
1401
+ cleaned = re.sub(r"list<element:\s*", "list<", type_str)
1402
+ return cleaned
1403
+
1404
+
1405
+ def escape_latex(text: str) -> str:
1406
+ """Escape special LaTeX characters."""
1407
+ # Map of characters to escape
1408
+ replacements = {
1409
+ "\\": r"\\", # Backslash must be first to avoid double-escaping
1410
+ "&": r"\&",
1411
+ "%": r"\%",
1412
+ "$": r"\$",
1413
+ "#": r"\#",
1414
+ "_": r"\_",
1415
+ "{": r"\{",
1416
+ "}": r"\}",
1417
+ "~": r"\textasciitilde{}",
1418
+ "^": r"\^{}",
1419
+ }
1420
+ for char, escaped in replacements.items():
1421
+ text = text.replace(char, escaped)
1422
+ return text
1423
+
1424
+
1425
+ async def inspect_file_schema(
1426
+ entry: DataFileEntry,
1427
+ session: aiohttp.ClientSession,
1428
+ semaphore: asyncio.Semaphore,
1429
+ progress: Progress,
1430
+ ) -> SchemaInfo:
1431
+ """Download file and extract schema information using PyArrow."""
1432
+ _, remote_path = entry.parsed()
1433
+ filename = Path(remote_path).name or remote_path
1434
+ terse_name = (filename[:32] + "…") if len(filename) > 33 else filename
1435
+ description = f"{entry.config_name}: {terse_name}"
1436
+
1437
+ async with semaphore:
1438
+ task_id: int | None = None
1439
+ temp_file = None
1440
+ try:
1441
+ task_id = progress.add_task(description, total=0, start=False)
1442
+ progress.start_task(task_id)
1443
+
1444
+ # Download to temporary file
1445
+ async with session.get(entry.url) as response:
1446
+ response.raise_for_status()
1447
+ total_bytes = response.content_length or 0
1448
+
1449
+ if total_bytes:
1450
+ progress.update(task_id, total=total_bytes)
1451
+
1452
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".parquet") as f:
1453
+ temp_file = Path(f.name)
1454
+ async for chunk in response.content.iter_chunked(1 << 17):
1455
+ f.write(chunk)
1456
+ progress.update(task_id, advance=len(chunk))
1457
+
1458
+ # Read schema with PyArrow
1459
+ parquet_file = pq.read_table(temp_file)
1460
+ schema = parquet_file.schema
1461
+
1462
+ columns = [
1463
+ (field.name, clean_arrow_type(str(field.type))) for field in schema
1464
+ ]
1465
+ num_rows = len(parquet_file)
1466
+
1467
+ return SchemaInfo(
1468
+ config_name=entry.config_name,
1469
+ filename=filename,
1470
+ columns=columns,
1471
+ num_rows=num_rows,
1472
+ success=True,
1473
+ )
1474
+
1475
+ except Exception as exc: # noqa: BLE001
1476
+ return SchemaInfo(
1477
+ config_name=entry.config_name,
1478
+ filename=filename,
1479
+ columns=[],
1480
+ num_rows=None,
1481
+ success=False,
1482
+ error=exc,
1483
+ )
1484
+ finally:
1485
+ if task_id is not None:
1486
+ progress.remove_task(task_id)
1487
+ # Clean up temp file
1488
+ if temp_file and temp_file.exists():
1489
+ temp_file.unlink()
1490
+
1491
+
1492
+ async def perform_schema_inspection(
1493
+ entries: Sequence[DataFileEntry],
1494
+ max_concurrency: int,
1495
+ timeout: float,
1496
+ ) -> List[SchemaInfo]:
1497
+ """Download first file from each config and inspect schema."""
1498
+ if not entries:
1499
+ return []
1500
+
1501
+ semaphore = asyncio.Semaphore(max_concurrency)
1502
+ timeout_cfg = aiohttp.ClientTimeout(total=timeout)
1503
+ results: List[SchemaInfo] = []
1504
+ progress = Progress(
1505
+ TextColumn("{task.description}"),
1506
+ BarColumn(bar_width=None),
1507
+ DownloadColumn(),
1508
+ TransferSpeedColumn(),
1509
+ TimeElapsedColumn(),
1510
+ console=console,
1511
+ )
1512
+
1513
+ async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
1514
+ with progress:
1515
+ tasks = [
1516
+ asyncio.create_task(
1517
+ inspect_file_schema(entry, session, semaphore, progress)
1518
+ )
1519
+ for entry in entries
1520
+ ]
1521
+ for future in asyncio.as_completed(tasks):
1522
+ result = await future
1523
+ results.append(result)
1524
+
1525
+ # Sort by config name for consistent output
1526
+ results.sort(key=lambda r: r.config_name)
1527
+ return results
1528
+
1529
+
1530
+ @app.command()
1531
+ def schema(
1532
+ readme_path: Annotated[
1533
+ Path,
1534
+ typer.Option(
1535
+ "--readme-path",
1536
+ "-r",
1537
+ help="Path to the README file with YAML front matter.",
1538
+ exists=True,
1539
+ resolve_path=True,
1540
+ dir_okay=False,
1541
+ ),
1542
+ ] = Path("README.md"),
1543
+ output_file: Annotated[
1544
+ Path | None,
1545
+ typer.Option(
1546
+ "--output-file",
1547
+ "-o",
1548
+ help="Write schema information to plain text file.",
1549
+ resolve_path=True,
1550
+ dir_okay=False,
1551
+ ),
1552
+ ] = None,
1553
+ latex: Annotated[
1554
+ bool,
1555
+ typer.Option(
1556
+ "--latex",
1557
+ help="Output schema in LaTeX format (requires --output-file).",
1558
+ ),
1559
+ ] = False,
1560
+ max_concurrency: Annotated[
1561
+ int,
1562
+ typer.Option(
1563
+ "--max-concurrency",
1564
+ "-c",
1565
+ min=1,
1566
+ show_default=True,
1567
+ help="Maximum concurrent downloads.",
1568
+ ),
1569
+ ] = 4,
1570
+ timeout: Annotated[
1571
+ float,
1572
+ typer.Option(
1573
+ "--timeout",
1574
+ min=1.0,
1575
+ show_default=True,
1576
+ help="Request timeout in seconds.",
1577
+ ),
1578
+ ] = 300.0,
1579
+ types: Annotated[bool, typer.Option(help="Add column type info")] = True,
1580
+ ) -> None:
1581
+ """Inspect schema of first file from each dataset config."""
1582
+ # Validate options
1583
+ if latex and not output_file:
1584
+ logger.error("--latex requires --output-file to be specified.")
1585
+ raise typer.Exit(code=1)
1586
+
1587
+ front_matter_text, _ = read_front_matter(readme_path)
1588
+ entries = load_data_file_entries(front_matter_text)
1589
+ if not entries:
1590
+ logger.warning("No data_files entries found in README front matter.")
1591
+ raise typer.Exit(code=0)
1592
+
1593
+ # Get first file from each config
1594
+ configs_seen = set()
1595
+ first_files = []
1596
+ for entry in entries:
1597
+ if entry.config_name not in configs_seen:
1598
+ first_files.append(entry)
1599
+ configs_seen.add(entry.config_name)
1600
+
1601
+ logger.info(f"Inspecting schema for {len(first_files)} configs.")
1602
+
1603
+ # Perform schema inspection
1604
+ results = asyncio.run(
1605
+ perform_schema_inspection(
1606
+ entries=first_files,
1607
+ max_concurrency=max_concurrency,
1608
+ timeout=timeout,
1609
+ )
1610
+ )
1611
+
1612
+ # Display results
1613
+ failed = 0
1614
+ text_output_lines = []
1615
+ latex_items = []
1616
+
1617
+ for result in results:
1618
+ if not result.success:
1619
+ failed += 1
1620
+ error_msg = str(result.error) if result.error else "Unknown error"
1621
+ logger.error(
1622
+ f"Failed to inspect {result.config_name}/{result.filename}: {error_msg}"
1623
+ )
1624
+ continue
1625
+
1626
+ # Prepare output file content
1627
+ if output_file:
1628
+ if latex:
1629
+ # LaTeX format: \item \textbf{CONFIG}: \texttt{col1} (\texttt{type1}), ...
1630
+ escaped_config = escape_latex(result.config_name)
1631
+ column_parts = []
1632
+ for col_name, col_type in result.columns:
1633
+ escaped_col = escape_latex(col_name)
1634
+ escaped_type = escape_latex(col_type)
1635
+ part = f"\\texttt{{{escaped_col}}}"
1636
+ if types:
1637
+ part += f" (\\texttt{{{escaped_type}}})"
1638
+ column_parts.append(part)
1639
+ columns_str = ", ".join(column_parts)
1640
+ latex_items.append(
1641
+ f"\\item \\textbf{{{escaped_config}}}: {columns_str}"
1642
+ )
1643
+ else:
1644
+ # Plain text format
1645
+ text_output_lines.append(f"# {result.config_name} — {result.filename}")
1646
+ if result.num_rows is not None:
1647
+ text_output_lines.append(
1648
+ f"# {len(result.columns)} columns, {result.num_rows:,} rows"
1649
+ )
1650
+ text_output_lines.append("")
1651
+ for col_name, col_type in result.columns:
1652
+ text_output_lines.append(f"{col_name}: {col_type}")
1653
+ text_output_lines.append("")
1654
+
1655
+ # Create table for console display
1656
+ table = Table(title=f"[bold]{result.config_name}[/bold] — {result.filename}")
1657
+ table.add_column("Column", style="cyan")
1658
+ table.add_column("Type", style="yellow")
1659
+
1660
+ for col_name, col_type in result.columns:
1661
+ table.add_row(col_name, col_type)
1662
+
1663
+ console.print(table)
1664
+ if result.num_rows is not None:
1665
+ logger.info(
1666
+ f"{result.config_name}: {len(result.columns)} columns, {result.num_rows:,} rows"
1667
+ )
1668
+ console.print() # Empty line between configs
1669
+
1670
+ # Write to output file if specified
1671
+ if output_file:
1672
+ if latex and latex_items:
1673
+ latex_content = (
1674
+ "\\begin{itemize}\n" + "\n".join(latex_items) + "\n\\end{itemize}"
1675
+ )
1676
+ output_file.write_text(latex_content, encoding="utf-8")
1677
+ logger.info(f"Wrote LaTeX schema to {output_file}")
1678
+ elif text_output_lines:
1679
+ output_file.write_text("\n".join(text_output_lines), encoding="utf-8")
1680
+ logger.info(f"Wrote schema information to {output_file}")
1681
+
1682
+ if failed:
1683
+ logger.error(f"{failed} configs failed schema inspection.")
1684
  raise typer.Exit(code=1)
1685
+ logger.info("Schema inspection completed successfully.")
1686
 
1687
 
1688
  if __name__ == "__main__":