#!/usr/bin/env python3 # Copyright (c) 2026 Salesforce, Inc. # SPDX-License-Identifier: Apache-2.0 """Safely extract BLIP-Live-780K video shards into a loader-compatible video root.""" from __future__ import annotations import argparse import hashlib import os import tarfile from pathlib import Path, PurePosixPath DEFAULT_PACKAGE = Path(__file__).resolve().parents[1] def sha256_file(path: Path, chunk_size: int = 8 * 1024**2) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(chunk_size): digest.update(chunk) return digest.hexdigest() def expected_checksums(package: Path) -> dict[str, str]: checksums: dict[str, str] = {} path = package / "manifests" / "checksums.sha256" with path.open(encoding="utf-8") as handle: for line in handle: digest, relative = line.rstrip("\n").split(" ", 1) checksums[relative] = digest return checksums def validate_member(member: tarfile.TarInfo) -> None: path = PurePosixPath(member.name) if path.is_absolute() or ".." in path.parts: raise RuntimeError(f"unsafe archive member: {member.name!r}") if not path.parts or path.parts[0] != "videos": raise RuntimeError(f"archive member is outside videos/: {member.name!r}") if not member.isfile(): raise RuntimeError(f"unexpected non-file archive member: {member.name!r}") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--package", type=Path, default=DEFAULT_PACKAGE) parser.add_argument( "--destination", type=Path, required=True, help="Directory under which videos/... will be created.", ) parser.add_argument("--skip-shard-checksums", action="store_true") return parser.parse_args() def main() -> None: args = parse_args() package = args.package.resolve() destination = args.destination.resolve() destination.mkdir(parents=True, exist_ok=True) checksums = expected_checksums(package) shards = sorted((package / "shards").glob("videos-*.tar")) if not shards: raise RuntimeError(f"no shards found under {package / 'shards'}") for index, shard in enumerate(shards, 1): relative = shard.relative_to(package).as_posix() expected = checksums.get(relative) if expected is None: raise RuntimeError(f"shard missing from checksum manifest: {relative}") if not args.skip_shard_checksums: actual = sha256_file(shard) if actual != expected: raise RuntimeError(f"checksum mismatch: {relative}") with tarfile.open(shard, mode="r:") as archive: members = archive.getmembers() for member in members: validate_member(member) archive.extractall(destination, members=members, filter="data") print(f"[{index}/{len(shards)}] extracted {relative}") marker = destination / ".blip-live-780k-extracted" temporary = marker.with_suffix(".incomplete") temporary.write_text("complete\n", encoding="utf-8") os.replace(temporary, marker) print(f"EXTRACTION_COMPLETE: {destination / 'videos'}") if __name__ == "__main__": main()