Bagpiper_TTS_SFT_Data_ESPnet / rebalance_streams.py
JinchuanTian's picture
Publish conversion recovery tests and ESPnet recipe preparation patch
ce9fc1b verified
Raw History Blame Contribute Delete
3 kB
#!/usr/bin/env python3
"""Split only unconverted work, retaining each parent's audio and row state."""
import argparse
from collections import Counter
from datetime import datetime, timezone
import json
from pathlib import Path
import sqlite3
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--max-shards", type=int, default=160)
args = parser.parse_args()
root = args.root
plan_path = root / "STREAM_PLAN.json"
old_plan = json.loads(plan_path.read_text())
aggregate = sqlite3.connect(root / "conversion.sqlite3")
done = {path for (path,) in aggregate.execute("SELECT path FROM shards")}
aggregate.close()
inventory = json.loads((root / "SOURCE_MANIFEST.json").read_text())["shards"]
assert Counter(x for s in old_plan for x in s["paths"]) == Counter(
r["path"] for r in inventory
)
assert not (
root / "STREAM_PLAN.before-rebalance.json"
).exists(), "Already rebalanced"
new_plan = []
for stream in old_plan:
converted = [p for p in stream["paths"] if p in done]
remaining = [p for p in stream["paths"] if p not in done]
if converted:
new_plan.append(dict(stream, paths=converted))
source = sqlite3.connect(root / f"conversion-{stream['stream_id']}.sqlite3")
for index in range(0, len(remaining), args.max_shards):
name = f"{stream['stream_id']}-resume{index // args.max_shards:02}"
destination = root / f"conversion-{name}.sqlite3"
assert (
not destination.exists()
), f"Unexpected existing stream: {destination}"
state = sqlite3.connect(destination)
source.backup(state)
state.close()
new_plan.append(
dict(
partition=stream["partition"],
stream_id=name,
paths=remaining[index : index + args.max_shards],
parent_stream=stream["stream_id"],
)
)
source.close()
assert Counter(x for s in new_plan for x in s["paths"]) == Counter(
r["path"] for r in inventory
)
plan_path.replace(root / "STREAM_PLAN.before-rebalance.json")
plan_path.write_text(json.dumps(new_plan, indent=2) + "\n")
(root / "REBALANCE.json").write_text(
json.dumps(
dict(
created_at=datetime.now(timezone.utc).isoformat(),
original_streams=len(old_plan),
new_streams=len(new_plan),
completed_shards=len(done),
remaining_shards=len(inventory) - len(done),
max_shards_per_new_stream=args.max_shards,
state_copied_before_scheduling=True,
),
indent=2,
)
+ "\n"
)
print((root / "REBALANCE.json").read_text())
if __name__ == "__main__":
main()