← Back to Research Index View Raw Source

update-audio-manifest.py

#!/usr/bin/env python3
"""
update_audio_manifest.py — Grok Bot Studio Audio Manifest & SHA256SUMS Updater
Copyright © Albert Lane. All Rights Reserved. | License v100.0
"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
from datetime import datetime, timezone
from pathlib import Path

AUDIO_EXTS = {".mp3", ".wav", ".m4a", ".ogg", ".opus", ".flac"}


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def _slug(text: str) -> str:
    return re.sub(r"[^a-z0-9]+", "", text.lower())


def match_episode(stem: str, title_by_ep: dict[str, str]) -> tuple[str | None, str]:
    m = re.search(r"(?:ep(?:isode)?[\s_-]*|^)(\d+)\b", stem, re.IGNORECASE)
    if m:
        ep = f"Episode {m.group(1)}"
        return ep, title_by_ep.get(ep, stem)
    stem_slug = _slug(stem)
    for ep, title in title_by_ep.items():
        ts = _slug(title)
        if ts and (ts in stem_slug or stem_slug in ts):
            return ep, title
    return None, stem


def update_bundle(bundle_dir: Path, audio_subdir: str = "audio") -> dict:
    manifest_path = bundle_dir / "MANIFEST.json"
    sums_path = bundle_dir / "SHA256SUMS"
    audio_dir = bundle_dir / audio_subdir

    if not manifest_path.exists():
        raise FileNotFoundError(f"MANIFEST.json not found in {bundle_dir}")
    if not audio_dir.exists():
        raise FileNotFoundError(f"Audio directory not found: {audio_dir}")

    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    audio_files = sorted(
        p for p in audio_dir.iterdir()
        if p.is_file() and p.suffix.lower() in AUDIO_EXTS
    )
    if not audio_files:
        raise ValueError(f"No audio files ({', '.join(sorted(AUDIO_EXTS))}) found in {audio_dir}")

    hydrated = list(manifest.get("hydrated_artifacts", []))
    by_path = {item["bundle_path"]: item for item in hydrated}

    pending_audio = list(manifest.get("studio_audio_overviews_not_on_disk", []))
    # Preserve canonical episode->title map across reruns by checking existing hydrated entries too
    title_by_ep = {item["episode"]: item["title"] for item in pending_audio if "episode" in item}
    for item in hydrated:
        if item.get("category") == "Audio Overview" and item.get("episode") and item["episode"] != "Unmapped":
            desc = item.get("description", "")
            prefix = "Exported Studio Audio Overview: "
            if desc.startswith(prefix):
                title_by_ep.setdefault(item["episode"], desc[len(prefix):])

    matched_episodes = set()
    added_or_updated = []

    for af in audio_files:
        rel_path = af.relative_to(bundle_dir).as_posix()
        digest = sha256_file(af)
        size = af.stat().st_size
        ep_label, title = match_episode(af.stem, title_by_ep)
        if ep_label:
            matched_episodes.add(ep_label)

        entry = {
            "filename": af.name,
            "bundle_path": rel_path,
            "bytes": size,
            "sha256": digest,
            "category": "Audio Overview",
            "episode": ep_label or "Unmapped",
            "description": f"Exported Studio Audio Overview: {title}",
        }
        by_path[rel_path] = entry
        added_or_updated.append(entry)

    manifest["hydrated_artifacts"] = sorted(by_path.values(), key=lambda x: x["bundle_path"])
    manifest["hydrated_artifact_count"] = len(manifest["hydrated_artifacts"])
    manifest["hydrated_audio_count"] = sum(
        1 for x in manifest["hydrated_artifacts"] if x.get("category") == "Audio Overview"
    )
    manifest["studio_audio_overviews_not_on_disk"] = [
        item for item in pending_audio if item.get("episode") not in matched_episodes
    ]
    manifest["audio_updated_at_utc"] = datetime.now(timezone.utc).isoformat()

    manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")

    skip = {"SHA256SUMS", "INSTALL_RECEIPT.json"}
    lines = []
    for p in sorted(bundle_dir.rglob("*")):
        if not p.is_file():
            continue
        rel = p.relative_to(bundle_dir).as_posix()
        if rel in skip or "/__pycache__/" in rel or rel.endswith(".pyc"):
            continue
        lines.append(f"{sha256_file(p)}  {rel}")

    sums_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return {
        "bundle_dir": str(bundle_dir),
        "audio_files_hashed": len(added_or_updated),
        "matched_episodes": sorted(matched_episodes),
        "remaining_stream_only": len(manifest["studio_audio_overviews_not_on_disk"]),
        "total_sha256_entries": len(lines),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Hash exported Studio audio files into MANIFEST.json and SHA256SUMS.")
    parser.add_argument("--bundle-dir", type=Path, default=Path("."), help="Path to extracted bundle or /workspace/docs/studio-bundle")
    parser.add_argument("--audio-dir", default="audio", help="Relative directory inside bundle-dir containing exported MP3/WAV files")
    args = parser.parse_args()
    summary = update_bundle(args.bundle_dir.resolve(), args.audio_dir)
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()