MetaScore-SFT-100 / reconstruction /preprocess /step2_build_slices.py
naivecynics's picture
Release fixed MetaScore-SFT-100 benchmark and source assets with per-piece attribution
42d9e00 verified
Raw History Blame Contribute Delete
34.3 kB
"""Step 2: serialize indexed piano MIDI into sharded 16-bar JSONL.
Every JSONL line contains one non-overlapping 16-counted-bar window:
{
"content": [{"start": 16, "pitch": 60, "duration": 4}],
"split": 80,
"barlines": [16, 32, ..., 272],
}
The first four reconstructed bars precede ``split`` and the remaining twelve
bars follow it. ``barlines`` contains the 17 window-local boundaries of those
16 counted bars, while locations 0--15 remain reserved for an optional pickup.
Bar boundaries are reconstructed from MIDI time-signature events using the same
snapping behaviour observed when MuseScore imports MIDI: a time-signature
change is snapped backwards to the latest completed barline. If the first
sounding note would not start at location 16, the first reconstructed bar is
treated as an uncounted pickup bar.
"""
from __future__ import annotations
import argparse
import bisect
import csv
import gzip
import hashlib
import json
import os
import sys
import tempfile
from collections import defaultdict, deque
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass
from fractions import Fraction
from pathlib import Path
from typing import Iterable, Iterator, Sequence
import mido
from .config import (
DATASETS,
INDEX_DIR,
PIPELINE_VERSION,
RAW_DIR,
REQUIRED_CATEGORIES,
REQUIRE_4_4,
SLICES_DIR,
SOURCES_PER_SHARD,
WORKERS,
)
PIANO_PROGRAMS = frozenset(range(8))
PICKUP_STEPS = 16
WINDOW_BARS = 16
PROMPT_BARS = 4
class SerializationError(ValueError):
"""Raised when a MIDI cannot be serialized without silently repairing it."""
@dataclass(frozen=True, order=True)
class Note:
start: int
end: int
pitch: int
@dataclass(frozen=True)
class TimeSignature:
tick: int
numerator: int
denominator: int
@dataclass(frozen=True)
class ParsedMidi:
ticks_per_beat: int
notes: tuple[Note, ...]
time_signatures: tuple[TimeSignature, ...]
@dataclass(frozen=True)
class PianoPartSelection:
extraction_mode: str
selected_port: int | None
selected_channel: int | None
selected_note_count: int
selected_active_bars: int | None
@dataclass(frozen=True)
class FileResult:
input_path: Path
output_path: Path
bar_count: int
window_count: int
note_count: int
@dataclass(frozen=True)
class DirectoryResult:
files: tuple[FileResult, ...]
failures: tuple[tuple[Path, str], ...]
@property
def total_windows(self) -> int:
return sum(result.window_count for result in self.files)
@dataclass(frozen=True)
class _TimedEvent:
tick: int
track_index: int
event_index: int
port: int
message: mido.Message | mido.MetaMessage
@dataclass(frozen=True)
class _Window:
start_bar: int
anchor_bar: int
split_bar: int
end_bar: int
def _normalize_time_signatures(
events: Iterable[tuple[int, int, int]]
) -> tuple[TimeSignature, ...]:
by_tick: dict[int, tuple[int, int]] = {}
for tick, numerator, denominator in events:
if numerator <= 0 or denominator <= 0:
raise SerializationError(
f"invalid time signature at tick {tick}: "
f"{numerator}/{denominator}"
)
signature = (numerator, denominator)
previous = by_tick.get(tick)
if previous is not None and previous != signature:
raise SerializationError(
f"conflicting time signatures at tick {tick}: "
f"{previous[0]}/{previous[1]} and "
f"{numerator}/{denominator}"
)
by_tick[tick] = signature
if 0 not in by_tick:
by_tick[0] = (4, 4)
return tuple(
TimeSignature(tick, numerator, denominator)
for tick, (numerator, denominator) in sorted(by_tick.items())
)
def parse_midi(path: Path) -> ParsedMidi:
"""Strictly parse one single-piano MIDI into paired notes and meter events."""
try:
midi = mido.MidiFile(path, clip=False)
except Exception as exc:
raise SerializationError(f"cannot parse MIDI: {exc}") from exc
if midi.type == 2:
raise SerializationError("MIDI type 2 contains asynchronous tracks")
if midi.ticks_per_beat <= 0:
raise SerializationError(
f"invalid ticks_per_beat: {midi.ticks_per_beat}"
)
timed_events: list[_TimedEvent] = []
signature_events: list[tuple[int, int, int]] = []
for track_index, track in enumerate(midi.tracks):
tick = 0
port = 0
for event_index, message in enumerate(track):
tick += message.time
if tick < 0:
raise SerializationError(
f"negative absolute tick in track {track_index}"
)
if message.type == "midi_port":
port = message.port
elif message.type == "time_signature":
signature_events.append(
(tick, message.numerator, message.denominator)
)
if message.type in {"program_change", "note_on", "note_off"}:
timed_events.append(
_TimedEvent(
tick=tick,
track_index=track_index,
event_index=event_index,
port=port,
message=message,
)
)
timed_events.sort(
key=lambda event: (
event.tick,
event.track_index,
event.event_index,
)
)
programs: defaultdict[tuple[int, int], int] = defaultdict(int)
active: defaultdict[
tuple[int, int, int, int], deque[int]
] = defaultdict(deque)
audible_parts: set[tuple[int, int]] = set()
notes: list[Note] = []
for event in timed_events:
message = event.message
part = (event.port, message.channel)
if message.type == "program_change":
programs[part] = message.program
continue
key = (
event.track_index,
event.port,
message.channel,
message.note,
)
is_note_on = message.type == "note_on" and message.velocity > 0
if is_note_on:
if message.channel == 9:
raise SerializationError(
f"drum note at tick {event.tick} is not allowed"
)
program = programs[part]
if program not in PIANO_PROGRAMS:
raise SerializationError(
f"non-piano program {program} sounds at tick {event.tick}"
)
audible_parts.add(part)
if len(audible_parts) > 1:
raise SerializationError(
"multiple piano logical parts are not allowed: "
+ ", ".join(
f"port={port},channel={channel}"
for port, channel in sorted(audible_parts)
)
)
active[key].append(event.tick)
continue
starts = active.get(key)
if not starts:
raise SerializationError(
f"unmatched note-off for pitch {message.note} "
f"at tick {event.tick} in track {event.track_index}"
)
start = starts.popleft()
if not starts:
del active[key]
if event.tick <= start:
raise SerializationError(
f"non-positive note duration for pitch {message.note} "
f"at tick {start}"
)
notes.append(Note(start, event.tick, message.note))
if active:
key, starts = next(iter(active.items()))
raise SerializationError(
f"unmatched note-on for pitch {key[3]} at tick {starts[0]} "
f"in track {key[0]}"
)
if not notes:
raise SerializationError("MIDI contains no sounding notes")
return ParsedMidi(
ticks_per_beat=midi.ticks_per_beat,
notes=tuple(sorted(notes)),
time_signatures=_normalize_time_signatures(signature_events),
)
def parse_dominant_piano_part(
path: Path,
) -> tuple[ParsedMidi, PianoPartSelection]:
"""Extract the dominant pure-piano logical part from an ensemble MIDI.
A logical part is a ``(port, channel)`` pair. Parts that sound under any
non-piano program are excluded. Candidates are ranked by sounding note
count, then active-bar coverage, then ascending port/channel.
"""
try:
midi = mido.MidiFile(path, clip=False)
except Exception as exc:
raise SerializationError(f"cannot parse MIDI: {exc}") from exc
if midi.type == 2:
raise SerializationError("MIDI type 2 contains asynchronous tracks")
if midi.ticks_per_beat <= 0:
raise SerializationError(
f"invalid ticks_per_beat: {midi.ticks_per_beat}"
)
timed_events: list[_TimedEvent] = []
signature_events: list[tuple[int, int, int]] = []
for track_index, track in enumerate(midi.tracks):
tick = 0
port = 0
for event_index, message in enumerate(track):
tick += message.time
if tick < 0:
raise SerializationError(
f"negative absolute tick in track {track_index}"
)
if message.type == "midi_port":
port = message.port
elif message.type == "time_signature":
signature_events.append(
(tick, message.numerator, message.denominator)
)
if message.type in {"program_change", "note_on", "note_off"}:
timed_events.append(
_TimedEvent(
tick=tick,
track_index=track_index,
event_index=event_index,
port=port,
message=message,
)
)
timed_events.sort(
key=lambda event: (
event.tick,
event.track_index,
event.event_index,
)
)
programs: defaultdict[tuple[int, int], int] = defaultdict(int)
sounding_programs: defaultdict[tuple[int, int], set[int]] = defaultdict(set)
onset_ticks: defaultdict[tuple[int, int], list[int]] = defaultdict(list)
for event in timed_events:
message = event.message
part = (event.port, message.channel)
if message.type == "program_change":
programs[part] = message.program
continue
if message.type != "note_on" or message.velocity == 0:
continue
if message.channel == 9:
continue
program = programs[part]
sounding_programs[part].add(program)
onset_ticks[part].append(event.tick)
candidates = [
part
for part, part_programs in sounding_programs.items()
if part_programs and part_programs.issubset(PIANO_PROGRAMS)
]
if not candidates:
raise SerializationError("MIDI contains no pure piano logical part")
signatures = _normalize_time_signatures(signature_events)
last_onset = max(tick for part in candidates for tick in onset_ticks[part])
coverage_source = ParsedMidi(
ticks_per_beat=midi.ticks_per_beat,
notes=(Note(0, max(1, last_onset + 1), 0),),
time_signatures=signatures,
)
boundaries = reconstruct_bar_boundaries(coverage_source)
def active_bar_count(part: tuple[int, int]) -> int:
return len(
{
max(0, bisect.bisect_right(boundaries, tick) - 1)
for tick in onset_ticks[part]
}
)
active_bars = {part: active_bar_count(part) for part in candidates}
selected = min(
candidates,
key=lambda part: (
-len(onset_ticks[part]),
-active_bars[part],
part,
),
)
active: defaultdict[
tuple[int, int, int, int], deque[int]
] = defaultdict(deque)
notes: list[Note] = []
for event in timed_events:
message = event.message
part = (event.port, message.channel)
if message.type == "program_change" or part != selected:
continue
key = (
event.track_index,
event.port,
message.channel,
message.note,
)
is_note_on = message.type == "note_on" and message.velocity > 0
if is_note_on:
active[key].append(event.tick)
continue
starts = active.get(key)
if not starts:
raise SerializationError(
f"unmatched note-off for selected piano pitch "
f"{message.note} at tick {event.tick}"
)
start = starts.popleft()
if not starts:
del active[key]
if event.tick <= start:
raise SerializationError(
f"non-positive selected piano note duration for pitch "
f"{message.note} at tick {start}"
)
notes.append(Note(start, event.tick, message.note))
if active:
key, starts = next(iter(active.items()))
raise SerializationError(
f"unmatched note-on for selected piano pitch {key[3]} "
f"at tick {starts[0]}"
)
if not notes:
raise SerializationError("selected piano logical part has no notes")
return (
ParsedMidi(
ticks_per_beat=midi.ticks_per_beat,
notes=tuple(sorted(notes)),
time_signatures=signatures,
),
PianoPartSelection(
extraction_mode="dominant_piano_part",
selected_port=selected[0],
selected_channel=selected[1],
selected_note_count=len(onset_ticks[selected]),
selected_active_bars=active_bars[selected],
),
)
def reconstruct_bar_boundaries(parsed: ParsedMidi) -> tuple[Fraction, ...]:
"""Reconstruct MuseScore-style bar boundaries from time signatures.
MIDI does not carry explicit barline events. MuseScore imports a
time-signature change by snapping it backwards to the most recent complete
bar under the preceding signature. Any residual ticks are therefore
absorbed into the first bar under the new signature rather than counted as
an extra short measure.
"""
last_note_end = max(note.end for note in parsed.notes)
cursor = Fraction(0)
boundaries: list[Fraction] = [cursor]
signatures = parsed.time_signatures
for index, signature in enumerate(signatures):
stop = (
Fraction(signatures[index + 1].tick)
if index + 1 < len(signatures)
else Fraction(last_note_end)
)
if stop < cursor:
raise SerializationError(
f"time-signature change at tick {stop} precedes "
f"the reconstructed bar cursor {cursor}"
)
bar_length = Fraction(
parsed.ticks_per_beat * 4 * signature.numerator,
signature.denominator,
)
if bar_length <= 0:
raise SerializationError(
f"invalid bar length for "
f"{signature.numerator}/{signature.denominator}"
)
complete_bars = int((stop - cursor) // bar_length)
for _ in range(complete_bars):
cursor += bar_length
boundaries.append(cursor)
if cursor < last_note_end:
final_signature = signatures[-1]
final_bar_length = Fraction(
parsed.ticks_per_beat * 4 * final_signature.numerator,
final_signature.denominator,
)
cursor += final_bar_length
boundaries.append(cursor)
return tuple(boundaries)
def round_half_up(value: Fraction) -> int:
"""Round halves away from zero using exact rational arithmetic."""
if value < 0:
return -round_half_up(-value)
return (2 * value.numerator + value.denominator) // (
2 * value.denominator
)
def ticks_to_steps(ticks: Fraction, ticks_per_beat: int) -> int:
return round_half_up(ticks * 4 / ticks_per_beat)
def has_pickup(parsed: ParsedMidi) -> bool:
"""Apply the project heuristic for an uncounted opening pickup bar."""
first_note_tick = min(note.start for note in parsed.notes)
ordinary_start = PICKUP_STEPS + ticks_to_steps(
Fraction(first_note_tick),
parsed.ticks_per_beat,
)
return ordinary_start != PICKUP_STEPS
def _window_layout(bar_count: int, pickup: bool) -> tuple[_Window, ...]:
windows: list[_Window] = []
next_bar = 0
if pickup:
if bar_count >= WINDOW_BARS + 1:
windows.append(
_Window(
start_bar=0,
anchor_bar=1,
split_bar=1 + PROMPT_BARS,
end_bar=1 + WINDOW_BARS,
)
)
next_bar = WINDOW_BARS + 1
while next_bar + WINDOW_BARS <= bar_count:
windows.append(
_Window(
start_bar=next_bar,
anchor_bar=next_bar,
split_bar=next_bar + PROMPT_BARS,
end_bar=next_bar + WINDOW_BARS,
)
)
next_bar += WINDOW_BARS
return tuple(windows)
def serialize_windows(
parsed: ParsedMidi,
boundaries: Sequence[Fraction],
*,
pickup: bool | None = None,
) -> list[dict[str, object]]:
"""Convert complete non-overlapping 16-bar windows to JSON objects.
``pickup`` overrides the MIDI-only heuristic when an authoritative score
representation (for example MuseScore XML) provides the opening-measure
length. Existing training preprocessing keeps the heuristic by omitting
this argument.
"""
bar_count = len(boundaries) - 1
layout = _window_layout(
bar_count,
has_pickup(parsed) if pickup is None else pickup,
)
notes = parsed.notes
next_note = 0
active: list[Note] = []
windows: list[dict[str, object]] = []
for window_index, window in enumerate(layout):
window_start = boundaries[window.start_bar]
location_anchor = boundaries[window.anchor_bar]
split_tick = boundaries[window.split_bar]
window_end = boundaries[window.end_bar]
window_steps = ticks_to_steps(
window_end - location_anchor,
parsed.ticks_per_beat,
)
if window_steps <= 0:
raise SerializationError(
f"window {window_index} has non-positive quantized length"
)
active = [note for note in active if note.end > window_start]
while (
next_note < len(notes)
and notes[next_note].start < window_end
):
note = notes[next_note]
if note.end > window_start:
active.append(note)
next_note += 1
quantized_notes: set[tuple[int, int, int]] = set()
for note in active:
clipped_start = max(Fraction(note.start), window_start)
clipped_end = min(Fraction(note.end), window_end)
if clipped_end <= clipped_start:
continue
relative_start = ticks_to_steps(
clipped_start - location_anchor,
parsed.ticks_per_beat,
)
relative_end = ticks_to_steps(
clipped_end - location_anchor,
parsed.ticks_per_beat,
)
# Nearest-grid quantization can round a very late onset exactly to
# the right boundary. Pull it back one step so every serialized
# note remains inside its 16-bar window.
relative_start = min(
max(relative_start, -PICKUP_STEPS),
window_steps - 1,
)
relative_end = min(
window_steps,
max(relative_start + 1, relative_end),
)
duration = relative_end - relative_start
quantized_notes.add(
(
PICKUP_STEPS + relative_start,
note.pitch,
duration,
)
)
content = [
{"start": start, "pitch": pitch, "duration": duration}
for start, pitch, duration in sorted(quantized_notes)
]
split = PICKUP_STEPS + ticks_to_steps(
split_tick - location_anchor,
parsed.ticks_per_beat,
)
barlines = [
PICKUP_STEPS
+ ticks_to_steps(
boundaries[bar_index] - location_anchor,
parsed.ticks_per_beat,
)
for bar_index in range(
window.anchor_bar,
window.end_bar + 1,
)
]
if len(barlines) != WINDOW_BARS + 1:
raise SerializationError(
f"window {window_index} has {len(barlines)} barlines; "
f"expected {WINDOW_BARS + 1}"
)
if barlines[0] != PICKUP_STEPS:
raise SerializationError(
f"window {window_index} starts at location {barlines[0]}; "
f"expected {PICKUP_STEPS}"
)
if any(
right <= left
for left, right in zip(barlines, barlines[1:])
):
raise SerializationError(
f"window {window_index} has non-increasing quantized barlines"
)
if barlines[PROMPT_BARS] != split:
raise SerializationError(
f"window {window_index} split {split} does not match "
f"barline {barlines[PROMPT_BARS]}"
)
windows.append(
{
"content": content,
"split": split,
"barlines": barlines,
}
)
return windows
def _write_jsonl_atomic(
output_path: Path,
rows: Iterable[dict[str, object]],
) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
temporary_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
newline="\n",
prefix=f".{output_path.name}.",
suffix=".tmp",
dir=output_path.parent,
delete=False,
) as output:
temporary_path = Path(output.name)
for row in rows:
json.dump(
row,
output,
ensure_ascii=False,
separators=(",", ":"),
)
output.write("\n")
output.flush()
os.fsync(output.fileno())
os.replace(temporary_path, output_path)
except Exception:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
raise
def serialize_file(input_path: Path, output_path: Path) -> FileResult:
parsed = parse_midi(input_path)
boundaries = reconstruct_bar_boundaries(parsed)
windows = serialize_windows(parsed, boundaries)
_write_jsonl_atomic(output_path, windows)
return FileResult(
input_path=input_path,
output_path=output_path,
bar_count=len(boundaries) - 1,
window_count=len(windows),
note_count=len(parsed.notes),
)
def _midi_paths(input_dir: Path) -> list[Path]:
paths = sorted(
path
for path in input_dir.iterdir()
if path.is_file() and path.suffix.lower() in {".mid", ".midi"}
)
stems: dict[str, Path] = {}
for path in paths:
previous = stems.get(path.stem)
if previous is not None:
raise SerializationError(
f"output filename collision: {previous.name} and {path.name}"
)
stems[path.stem] = path
return paths
def serialize_directory(
input_dir: Path,
output_dir: Path,
) -> DirectoryResult:
if not input_dir.is_dir():
raise FileNotFoundError(f"input directory not found: {input_dir}")
output_dir.mkdir(parents=True, exist_ok=True)
successes: list[FileResult] = []
failures: list[tuple[Path, str]] = []
for input_path in _midi_paths(input_dir):
output_path = output_dir / f"{input_path.stem}.jsonl"
try:
result = serialize_file(input_path, output_path)
except Exception as exc:
failures.append((input_path, str(exc)))
print(f"[error] {input_path.name}: {exc}", file=sys.stderr)
continue
successes.append(result)
print(
f"[ok] {input_path.name}: "
f"{result.bar_count} bars, "
f"{result.window_count} windows, "
f"{result.note_count} notes"
)
return DirectoryResult(tuple(successes), tuple(failures))
def _eligible(row: dict[str, str]) -> bool:
return (
row["parse_status"] == "ok"
and row["category"] in REQUIRED_CATEGORIES
and (not REQUIRE_4_4 or row["all_4_4"] == "1")
)
def iter_index_rows(
index_dir: Path,
dataset: str,
limit: int | None = None,
) -> Iterator[dict[str, str]]:
if limit == 0:
return
path = index_dir / f"{dataset}.csv.gz"
if not path.is_file():
raise FileNotFoundError(f"index not found: {path}")
count = 0
with gzip.open(path, "rt", encoding="utf-8", newline="") as source:
for row in csv.DictReader(source):
if not _eligible(row):
continue
yield row
count += 1
if limit is not None and count >= limit:
return
def _chunks(
rows: Iterable[dict[str, str]],
size: int,
) -> Iterator[list[dict[str, str]]]:
chunk: list[dict[str, str]] = []
for row in rows:
chunk.append(row)
if len(chunk) == size:
yield chunk
chunk = []
if chunk:
yield chunk
def _dataset_root(dataset: str, raw_dir: Path) -> Path:
if dataset == "all":
return raw_dir
if dataset == "notagen":
return raw_dir / "notagen_pretrain-" / "midi"
if dataset == "chongchong":
return raw_dir / "chongchong-" / "midi"
raise ValueError(f"unknown dataset: {dataset}")
def _serialize_index_row(
task: tuple[dict[str, str], str],
) -> tuple[list[dict[str, object]], dict[str, object] | None]:
row, dataset_root_text = task
input_path = Path(dataset_root_text) / row["relative_path"]
try:
if row["category"] == "single_piano":
parsed = parse_midi(input_path)
selection = PianoPartSelection(
extraction_mode="full_single_piano",
selected_port=None,
selected_channel=None,
selected_note_count=len(parsed.notes),
selected_active_bars=None,
)
elif row["category"] == "contains_piano":
parsed, selection = parse_dominant_piano_part(input_path)
else:
raise SerializationError(
f"unsupported indexed category: {row['category']}"
)
boundaries = reconstruct_bar_boundaries(parsed)
windows = serialize_windows(parsed, boundaries)
except Exception as exc:
return [], {
"sample_id": row["sample_id"],
"dataset": row["dataset"],
"relative_path": row["relative_path"],
"error": str(exc),
"error_type": type(exc).__name__,
}
metadata = {
"sample_id": row["sample_id"],
"dataset": row["dataset"],
"source_partition": row["source_partition"],
"relative_path": row["relative_path"],
"sha256": row["sha256"],
"source_category": row["category"],
"extraction_mode": selection.extraction_mode,
"selected_port": selection.selected_port,
"selected_channel": selection.selected_channel,
"selected_piano_note_count": selection.selected_note_count,
"selected_piano_active_bars": selection.selected_active_bars,
}
slices = [
{
**metadata,
"slice_id": f"{row['sample_id']}#{window_index:06d}",
"window_index": window_index,
**window,
}
for window_index, window in enumerate(windows)
]
return slices, None
def _write_json_atomic(path: Path, value: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.tmp")
temporary.write_text(
json.dumps(value, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
os.replace(temporary, path)
def _shard_complete(
output_path: Path,
errors_path: Path,
done_path: Path,
input_sha256: str,
) -> bool:
if (
not output_path.is_file()
or not errors_path.is_file()
or not done_path.is_file()
):
return False
try:
metadata = json.loads(done_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return False
return (
metadata.get("pipeline_version") == PIPELINE_VERSION
and metadata.get("input_sha256") == input_sha256
)
def _chunk_checksum(rows: Sequence[dict[str, str]]) -> str:
digest = hashlib.sha256()
for row in rows:
digest.update(row["sample_id"].encode("utf-8"))
digest.update(b"\0")
digest.update(row["sha256"].encode("ascii"))
digest.update(b"\0")
return digest.hexdigest()
def build_slices(
*,
raw_dir: Path,
index_dir: Path,
output_dir: Path,
datasets: Sequence[str],
workers: int,
sources_per_shard: int,
limit: int | None = None,
) -> dict[str, int]:
output_dir.mkdir(parents=True, exist_ok=True)
summary = {"sources": 0, "slices": 0, "errors": 0, "shards": 0}
executor = ProcessPoolExecutor(max_workers=workers) if workers > 1 else None
try:
for dataset in datasets:
dataset_root = _dataset_root(dataset, raw_dir)
rows = iter_index_rows(index_dir, dataset, limit)
for shard_index, chunk in enumerate(_chunks(rows, sources_per_shard)):
stem = f"{dataset}-{shard_index:06d}"
output_path = output_dir / f"{stem}.jsonl"
errors_path = output_dir / f"{stem}.errors.jsonl"
done_path = output_dir / f"{stem}.done.json"
input_sha256 = _chunk_checksum(chunk)
if _shard_complete(
output_path,
errors_path,
done_path,
input_sha256,
):
metadata = json.loads(done_path.read_text(encoding="utf-8"))
for key in summary:
summary[key] += int(metadata.get(key, 0))
print(f"[resume] {stem}")
continue
tasks = ((row, str(dataset_root)) for row in chunk)
results = (
executor.map(_serialize_index_row, tasks, chunksize=16)
if executor is not None
else map(_serialize_index_row, tasks)
)
slices: list[dict[str, object]] = []
errors: list[dict[str, object]] = []
for source_slices, error in results:
slices.extend(source_slices)
if error is not None:
errors.append(error)
shard_summary = {
"sources": len(chunk),
"slices": len(slices),
"errors": len(errors),
"shards": 1,
"pipeline_version": PIPELINE_VERSION,
"input_sha256": input_sha256,
}
_write_jsonl_atomic(output_path, slices)
_write_jsonl_atomic(errors_path, errors)
_write_json_atomic(done_path, shard_summary)
for key in summary:
summary[key] += int(shard_summary[key])
print(
f"[ok] {stem}: {len(chunk)} sources, "
f"{len(slices)} slices, {len(errors)} errors"
)
finally:
if executor is not None:
executor.shutdown()
_write_json_atomic(output_dir / "summary.json", summary)
return summary
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--raw-dir",
type=Path,
default=RAW_DIR,
)
parser.add_argument(
"--index-dir",
type=Path,
default=INDEX_DIR,
)
parser.add_argument("--output-dir", type=Path, default=SLICES_DIR)
parser.add_argument(
"--datasets",
nargs="+",
choices=("all", "notagen", "chongchong"),
default=DATASETS,
)
parser.add_argument("--workers", type=int, default=WORKERS)
parser.add_argument(
"--sources-per-shard",
type=int,
default=SOURCES_PER_SHARD,
)
parser.add_argument("--limit", type=int)
return parser.parse_args(argv)
def main(argv: Sequence[str] | None = None) -> int:
args = parse_args(argv)
if args.workers < 1:
raise ValueError("--workers must be at least 1")
if args.sources_per_shard < 1:
raise ValueError("--sources-per-shard must be at least 1")
if args.limit is not None and args.limit < 0:
raise ValueError("--limit must be non-negative")
summary = build_slices(
raw_dir=args.raw_dir.resolve(),
index_dir=args.index_dir.resolve(),
output_dir=args.output_dir.resolve(),
datasets=tuple(dict.fromkeys(args.datasets)),
workers=args.workers,
sources_per_shard=args.sources_per_shard,
limit=args.limit,
)
json.dump(summary, sys.stdout, indent=2, sort_keys=True)
sys.stdout.write("\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())