#!/usr/bin/env python3 """Reconstruct manifest-backed media without using hidden or server-absolute row paths.""" from __future__ import annotations import argparse import hashlib import io import json import os import subprocess import tarfile import urllib.request from pathlib import Path from PIL import Image, ImageDraw, ImageFont ROOT = Path(os.environ.get("STREAMING_OMNI_ROOT", "/home/XuWenqi/ZhouZhifan/StreamingOmniDatasetsWork")) PIPER = ROOT / ".cache/tools/piper/piper" PIPER_MODEL = ROOT / ".cache/tools/piper/en_US-lessac-medium.onnx" def sha256(path: Path): digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def generate_text_image(item: dict, target: Path): width, height = item.get("width", 640), item.get("height", 480) image = Image.new("RGB", (width, height), "white") draw = ImageDraw.Draw(image) font = ImageFont.load_default() text = str(item["text"]) words, lines, current = text.split(), [], "" for word in words: candidate = (current + " " + word).strip() if draw.textlength(candidate, font=font) > width - 40 and current: lines.append(current) current = word else: current = candidate if current: lines.append(current) draw.multiline_text((20, 20), "\n".join(lines), fill="black", font=font, spacing=8) target.parent.mkdir(parents=True, exist_ok=True) image.save(target, format="PNG", optimize=False) def generate_speech(item: dict, target: Path): if not PIPER.exists() or not PIPER_MODEL.exists(): raise RuntimeError("Piper executable/model missing under project-local .cache/tools/piper") target.parent.mkdir(parents=True, exist_ok=True) subprocess.run( [str(PIPER), "--model", str(PIPER_MODEL), "--output_file", str(target)], input=str(item["text"]), text=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def download_member(item: dict, target: Path, cache: Path): url, _, member = str(item["source_url"]).partition("#") cache.mkdir(parents=True, exist_ok=True) archive = cache / (hashlib.sha256(url.encode()).hexdigest() + ".tar") if not archive.exists(): with urllib.request.urlopen(url, timeout=120) as response, archive.open("wb") as output: while block := response.read(1024 * 1024): output.write(block) extracted = cache / (hashlib.sha256((url + "#" + member).encode()).hexdigest() + ".mp4") if not extracted.exists(): with tarfile.open(archive) as tar: candidates = [entry for entry in tar.getmembers() if entry.name == member or entry.name.endswith("/" + member)] if not candidates: raise RuntimeError(f"member not found in upstream archive: {member}") source = tar.extractfile(candidates[0]) if source is None: raise RuntimeError(f"member is not a regular file: {member}") extracted.write_bytes(source.read()) target.parent.mkdir(parents=True, exist_ok=True) start, end = float(item.get("start_sec") or 0), float(item.get("end_sec") or 0) command = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error"] if start > 0: command += ["-ss", str(start)] command += ["-i", str(extracted)] if end > start: command += ["-t", str(end - start)] command += ["-c", "copy", str(target)] subprocess.run(command, check=True) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--limit", type=int) parser.add_argument("--offset", type=int, default=0) args = parser.parse_args() manifest = ROOT / "manifests" / f"{args.config}.jsonl" items = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] items = items[args.offset:args.offset + args.limit if args.limit else None] results = [] for item in items: target = args.output_dir / item["output_relative_path"] try: if item["generator_family"] == "pil_text_renderer": generate_text_image(item, target) elif item["generator_family"] == "piper_tts": generate_speech(item, target) elif item["reconstruction_method"] in {"clip", "download"}: download_member(item, target, ROOT / ".cache/reconstruction") else: raise RuntimeError("unsupported reconstruction recipe") results.append({"manifest_id": item["manifest_id"], "success": True, "path": str(target), "sha256": sha256(target)}) except Exception as exc: results.append({"manifest_id": item["manifest_id"], "success": False, "error": str(exc)[:500]}) print(json.dumps(results, indent=2)) return 0 if results and all(item["success"] for item in results) else 1 if __name__ == "__main__": raise SystemExit(main())