Files
ingglish-hyperdope-gematria/packaging/bundle/scripts/manage_lecture_artifacts.py
T

253 lines
8.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""
manage_lecture_artifacts.py
Deterministic Naming-Convention Validator, Host-Mount Resolver, and .gitignore Manager
for the `isopsephic-lecture-synthesis` skill.
Naming Convention:
Stem: lecture-<topic-slug>-ingglish-aq
Slug regex: ^[a-z0-9]+(?:-[a-z0-9]+)*$
Files:
- /workspace/lecture-<topic-slug>-ingglish-aq.md
- /workspace/lecture-<topic-slug>-ingglish-aq.mp3
- /workspace/lecture-<topic-slug>-ingglish-aq.pdf (optional)
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Any
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
LECTURE_FILE_RE = re.compile(r"^lecture-([a-z0-9]+(?:-[a-z0-9]+)*)-ingglish-aq\.(md|mp3|pdf)$")
GITIGNORE_HEADER = "# --- Isopsephic Lecture Artifacts (strict naming convention) ---"
GITIGNORE_FOOTER = "# --- End Isopsephic Lecture Artifacts ---"
def normalize_slug(raw: str) -> str:
"""Normalize arbitrary topic string or filename into canonical <topic-slug>."""
s = raw.strip().lower()
# Strip directory and extension if a filename was passed
s = os.path.basename(s)
for ext in (".md", ".mp3", ".pdf"):
if s.endswith(ext):
s = s[: -len(ext)]
if s.startswith("lecture-"):
s = s[len("lecture-") :]
if s.endswith("-ingglish-aq"):
s = s[: -len("-ingglish-aq")]
s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
if not s or not SLUG_RE.fullmatch(s):
raise ValueError(f"Cannot normalize '{raw}' into valid kebab-case slug.")
return s
def canonical_stem(slug: str) -> str:
norm = normalize_slug(slug)
return f"lecture-{norm}-ingglish-aq"
def resolve_host_workspace_mount(container_workspace: str = "/workspace") -> str:
"""
Resolve the host filesystem path backing /workspace from /proc/self/mountinfo
so host-executed tools like text_to_speech(output_path=...) write directly into /workspace.
"""
mountinfo = Path("/proc/self/mountinfo")
if mountinfo.exists():
for line in mountinfo.read_text(encoding="utf-8", errors="ignore").splitlines():
parts = line.split()
if len(parts) >= 5 and parts[4] == container_workspace:
return parts[3]
return container_workspace
def update_gitignore(
workspace_dir: str,
mode: str = "audio-only",
slug: str | None = None,
) -> dict[str, Any]:
"""
Idempotently add or update the lecture naming-convention block in /workspace/.gitignore.
Modes:
- audio-only: ignores lecture-*-ingglish-aq.mp3
- audio-and-pdf: ignores lecture-*-ingglish-aq.mp3 and lecture-*-ingglish-aq.pdf
- all-lecture-files: ignores lecture-*-ingglish-aq.* (.md, .mp3, .pdf)
- explicit-slug: ignores lecture-<slug>-ingglish-aq.mp3 (and .md/.pdf if present)
"""
gitignore_path = Path(workspace_dir) / ".gitignore"
existing = gitignore_path.read_text(encoding="utf-8") if gitignore_path.exists() else ""
if mode == "audio-only":
patterns = ["lecture-*-ingglish-aq.mp3"]
elif mode == "audio-and-pdf":
patterns = ["lecture-*-ingglish-aq.mp3", "lecture-*-ingglish-aq.pdf"]
elif mode == "all-lecture-files":
patterns = [
"lecture-*-ingglish-aq.mp3",
"lecture-*-ingglish-aq.md",
"lecture-*-ingglish-aq.pdf",
]
elif mode == "explicit-slug":
if not slug:
raise ValueError("--slug is required when --gitignore-mode=explicit-slug")
stem = canonical_stem(slug)
patterns = [f"{stem}.mp3", f"{stem}.pdf"]
else:
raise ValueError(f"Unsupported mode: {mode}")
block_lines = [GITIGNORE_HEADER] + patterns + [GITIGNORE_FOOTER]
new_block = "\n".join(block_lines)
block_re = re.compile(
rf"{re.escape(GITIGNORE_HEADER)}.*?{re.escape(GITIGNORE_FOOTER)}",
re.S,
)
if block_re.search(existing):
updated = block_re.sub(new_block, existing)
else:
sep = "" if (not existing or existing.endswith("\n")) else "\n"
updated = f"{existing}{sep}{new_block}\n"
changed = updated != existing
if changed or not gitignore_path.exists():
gitignore_path.write_text(updated, encoding="utf-8")
return {
"gitignore_path": str(gitignore_path),
"mode": mode,
"patterns_active": patterns,
"updated": changed,
}
def check_git_ignored(workspace_dir: str, rel_path: str) -> dict[str, Any]:
proc = subprocess.run(
["git", "check-ignore", "-v", rel_path],
cwd=workspace_dir,
text=True,
capture_output=True,
)
return {
"file": rel_path,
"ignored": proc.returncode == 0,
"rule": proc.stdout.strip() if proc.returncode == 0 else None,
}
def audit_workspace_lectures(workspace_dir: str, target_slug: str | None = None) -> dict[str, Any]:
ws = Path(workspace_dir)
all_lecture_files = sorted(
p.name for p in ws.iterdir() if p.is_file() and p.name.startswith("lecture-")
)
conforming = []
non_conforming = []
stems: dict[str, dict[str, Any]] = {}
for fname in all_lecture_files:
m = LECTURE_FILE_RE.fullmatch(fname)
if not m:
non_conforming.append(fname)
continue
conforming.append(fname)
slug_part, ext = m.group(1), m.group(2)
stem = f"lecture-{slug_part}-ingglish-aq"
info = stems.setdefault(
stem,
{
"slug": slug_part,
"stem": stem,
"extensions": [],
"sizes": {},
},
)
info["extensions"].append(ext)
info["sizes"][ext] = (ws / fname).stat().st_size
target_report = None
if target_slug:
stem = canonical_stem(target_slug)
md_file = ws / f"{stem}.md"
mp3_file = ws / f"{stem}.mp3"
pdf_file = ws / f"{stem}.pdf"
target_report = {
"slug": normalize_slug(target_slug),
"canonical_stem": stem,
"host_tts_output_path": f"{resolve_host_workspace_mount(workspace_dir)}/{stem}.mp3",
"container_md_path": str(md_file),
"container_mp3_path": str(mp3_file),
"md_exists": md_file.exists() and md_file.stat().st_size > 0,
"mp3_exists": mp3_file.exists() and mp3_file.stat().st_size > 0,
"pdf_exists": pdf_file.exists() and pdf_file.stat().st_size > 0,
"stem_match": md_file.stem == mp3_file.stem == stem,
"pair_valid": bool(
md_file.exists()
and mp3_file.exists()
and md_file.stat().st_size > 0
and mp3_file.stat().st_size > 0
and md_file.stem == mp3_file.stem == stem
),
"git_ignore_mp3": check_git_ignored(workspace_dir, f"{stem}.mp3"),
"git_ignore_md": check_git_ignored(workspace_dir, f"{stem}.md"),
}
return {
"workspace": workspace_dir,
"host_workspace_mount": resolve_host_workspace_mount(workspace_dir),
"conforming_files": conforming,
"non_conforming_files": non_conforming,
"lecture_stems": stems,
"target_verification": target_report,
}
def main() -> int:
parser = argparse.ArgumentParser(
description="Validate lecture naming conventions and manage .gitignore rules."
)
parser.add_argument("--workspace", default="/workspace")
parser.add_argument("--slug", default=None, help="Topic slug to normalize/verify.")
parser.add_argument(
"--gitignore-mode",
choices=["none", "audio-only", "audio-and-pdf", "all-lecture-files", "explicit-slug"],
default="none",
help="Update /workspace/.gitignore using the strict lecture naming convention.",
)
parser.add_argument(
"--verify-pair",
action="store_true",
help="Exit non-zero if the target slug's .md and .mp3 pair is missing or mismatched.",
)
args = parser.parse_args()
gitignore_res = None
if args.gitignore_mode != "none":
gitignore_res = update_gitignore(
args.workspace, mode=args.gitignore_mode, slug=args.slug
)
audit = audit_workspace_lectures(args.workspace, target_slug=args.slug)
if gitignore_res is not None:
audit["gitignore_update"] = gitignore_res
print(json.dumps(audit, indent=2))
if args.verify_pair:
if not args.slug:
sys.stderr.write("ERROR: --verify-pair requires --slug\n")
return 2
tv = audit.get("target_verification") or {}
if not tv.get("pair_valid") or audit.get("non_conforming_files"):
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())