Files

473 lines
24 KiB
Python
Raw Permalink Normal View History

2026-10-17 14:59:30 -06:00
"""Build reviewed, source-cited media discovery bundles. No network or inference calls."""
from __future__ import annotations
import argparse
import hashlib
import html
import json
import re
import shutil
import sys
import tempfile
from pathlib import Path
from urllib.parse import parse_qsl, urlsplit
from xml.etree import ElementTree as ET
from jsonschema import Draft202012Validator, FormatChecker
ROOT = Path(__file__).resolve().parents[1]
2026-10-18 09:21:12 -06:00
VERSION = "0.3.0"
2026-10-17 14:59:30 -06:00
def require(condition, message):
if not condition:
raise ValueError(message)
def load(path):
def pairs(items):
result = {}
for key, value in items:
require(key not in result, f"Duplicate JSON key: {key}")
result[key] = value
return result
def bad_constant(value):
raise ValueError(f"Non-finite JSON number: {value}")
return json.loads(Path(path).read_text(encoding="utf-8-sig"),
object_pairs_hook=pairs, parse_constant=bad_constant)
def encoded(value):
return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2,
allow_nan=False) + "\n").encode("utf-8")
def digest(value):
return hashlib.sha256(value).hexdigest()
def validate(value, schema):
spec = load(ROOT / "schemas" / f"{schema}.schema.json")
Draft202012Validator(spec, format_checker=FormatChecker()).validate(value)
def https(value):
parsed = urlsplit(value)
require(parsed.scheme == "https" and parsed.hostname and not parsed.username
and not parsed.password and not re.search(r"[\s<>\"{}]", value),
"Expected a stable public HTTPS URL without credentials or unsafe characters")
keys = [key.casefold() for key, _ in parse_qsl(parsed.query)]
require(not any(key in {"token", "access_token", "signature", "sig", "credential", "password", "api_key"}
or key.startswith(("x-amz-", "x-goog-")) for key in keys),
"Do not publish signed or credential-bearing URLs")
def relative_file(base, name):
path = (base / name).resolve()
require(path.is_relative_to(base.resolve()) and path.is_file(),
f"Source must be an existing file inside {base}: {name}")
return path
def seconds(value):
require(re.fullmatch(r"(?:\d{2,}:)?[0-5]\d:[0-5]\d\.\d{3}", value),
f"Unsupported WebVTT timestamp: {value}")
parts = value.split(":")
return round(sum(float(x) * (60 ** i) for i, x in enumerate(reversed(parts))), 3)
def parse_vtt(text, duration):
"""Strict portable subset. Reject inline karaoke/rolling overlaps rather than lose data."""
text = text.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n")
blocks = re.split(r"\n[ \t]*\n", text.strip())
require(blocks and re.fullmatch(r"WEBVTT(?:[ \t][^\n]*)?", blocks[0]),
"Expected WEBVTT header (header metadata requires normalization)")
cues = []
last_end = 0
native_ids = set()
for block in blocks[1:]:
lines = block.strip().splitlines()
if not lines or lines[0] == "NOTE" or lines[0].startswith(("NOTE ", "NOTE\t")):
continue
require(lines[0] not in ("STYLE", "REGION"),
"Normalize STYLE/REGION WebVTT before semantic processing")
native_id = None
if "-->" not in lines[0]:
native_id = lines.pop(0)
require(native_id not in native_ids, "Duplicate WebVTT cue identifier")
native_ids.add(native_id)
require(len(lines) >= 2, "WebVTT cue needs timing and text")
match = re.fullmatch(r"(\S+)\s+-->\s+(\S+)(?:[ \t]+.*)?", lines[0])
require(match, f"Invalid WebVTT cue timing: {lines[0]}")
start, end = seconds(match[1]), seconds(match[2])
require(0 <= start < end <= duration, "Cue outside declared media duration")
require(start >= last_end, "Overlapping/out-of-order cues require reviewed normalization")
body = "\n".join(lines[1:])
voices = re.findall(r"<v(?:\.[^ >]+)*\s+([^>]+)>", body)
require(len(set(voices)) <= 1, "Split cues containing multiple voice labels")
body = re.sub(r"</?(?:v(?:\.[^ >]+)*(?:\s+[^>]+)?|b|i|u|c(?:\.[^ >]+)*|lang(?:\s+[^>]+)?)>", "", body)
require(not re.search(r"<[^>]+>", body),
"Unsupported WebVTT markup; normalize it explicitly")
body = " ".join(html.unescape(body).split())
require(body, "Empty WebVTT cue")
cues.append({"cue_id": f"cue-{len(cues)+1:06}", "source_cue_id": native_id,
"start_seconds": start, "end_seconds": end,
"speaker": html.unescape(voices[0]) if voices else None, "text": body})
last_end = end
require(cues, "No WebVTT cues found")
return cues
def inputs(manifest_path, plan_path):
manifest_path, plan_path = Path(manifest_path).resolve(), Path(plan_path).resolve()
media, plan = load(manifest_path), load(plan_path)
validate(media, "media")
validate(plan, "plan")
base = manifest_path.parent
vtt_path = relative_file(base, media["transcripts"]["vtt"])
txt_path = relative_file(base, media["transcripts"]["txt"])
for field in ("canonical_url", "content_url", "embed_url", "thumbnail_url"):
if media.get(field):
https(media[field])
for field in ("license", "usage_info"):
if media["rights"].get(field):
https(media["rights"][field])
require(media.get("content_url") or media.get("embed_url"),
"Provide a stable media content_url or embed_url")
vtt_bytes, txt_bytes = vtt_path.read_bytes(), txt_path.read_bytes()
cues = parse_vtt(vtt_bytes.decode("utf-8-sig"), media["duration_seconds"])
transcript = " ".join(c["text"] for c in cues)
txt = " ".join(txt_bytes.decode("utf-8-sig").split())
require(txt == transcript,
"TXT/VTT text differs. Reconcile reviewed copies; never invent timings from TXT.")
hash_inputs = {
"builder_version": VERSION, "manifest": media,
"vtt_sha256": digest(vtt_bytes),
"txt_sha256": digest(txt_bytes),
"plan": {k: v for k, v in plan.items() if k != "review"},
}
return media, plan, cues, transcript, digest(encoded(hash_inputs)), vtt_bytes, txt_bytes
def unique(items, key):
ids = [item[key] for item in items]
require(len(ids) == len(set(ids)), f"Duplicate {key}")
def citation(media, cue):
return {"media_id": media["media_id"], "cue_id": cue["cue_id"],
"start_seconds": cue["start_seconds"], "end_seconds": cue["end_seconds"],
"transcript_url": media["canonical_url"] + "#" + cue["cue_id"],
"playback_url": playback(media, cue["start_seconds"])}
def playback(media, start):
# The generated native player supports this query. External embeds have no implied seek support.
return (media["canonical_url"] + f"?t={start:g}") if media.get("content_url") else None
def artifacts(manifest_path, plan_path):
media, plan, cues, text, signature, vtt, txt = inputs(manifest_path, plan_path)
require(plan["media_id"] == media["media_id"], "Plan/manifest identity mismatch")
review = plan["review"]
require(review["status"] == "approved" and review["reviewer"].strip()
and review["reviewed_at"] and review["input_sha256"] == signature,
"Review missing or stale. Review content and paste the current signature.")
require(media["publication"]["consent"] == "cleared"
and media["publication"]["privacy_review"] == "cleared"
and media["rights"]["redistribution_allowed"],
"Public output requires cleared consent/privacy and redistribution rights")
unique(plan["chunks"], "chunk_id")
unique(plan["chunks"], "knowledge_id")
unique(plan["qa"], "qa_id")
unique(plan["chapters"], "chapter_id")
by_cue = {c["cue_id"]: c for c in cues}
assigned = []
chunks = []
for order, chunk in enumerate(plan["chunks"], 1):
ids = chunk["cue_ids"]
require(all(i in by_cue for i in ids), "Chunk refers to missing cue")
selected = [by_cue[i] for i in ids]
assigned.extend(ids)
chunks.append({**chunk, "media_id": media["media_id"], "order": order,
"content": " ".join(c["text"] for c in selected),
"start_seconds": selected[0]["start_seconds"],
"end_seconds": selected[-1]["end_seconds"],
"speakers": list(dict.fromkeys(c["speaker"] for c in selected if c["speaker"])),
"citations": [citation(media, c) for c in selected]})
require(assigned == list(by_cue),
"Chunks must cover every cue exactly once, contiguously and in source order")
by_chunk = {c["chunk_id"]: c for c in chunks}
qa = []
for item in plan["qa"]:
evidence = []
for e in item["evidence"]:
require(e["chunk_id"] in by_chunk and e["cue_id"] in by_cue,
"Q&A evidence refers to missing source")
require(e["cue_id"] in by_chunk[e["chunk_id"]]["cue_ids"],
"Q&A cue does not belong to cited chunk")
require(e["quote"] in by_cue[e["cue_id"]]["text"],
"Evidence quote is not an exact substring of the cited cue")
evidence.append({**e, **citation(media, by_cue[e["cue_id"]])})
qa.append({**item, "media_id": media["media_id"], "evidence": evidence})
chapters = []
chapter_end = 0
for chapter in plan["chapters"]:
require(chapter["start_cue_id"] in by_cue and chapter["end_cue_id"] in by_cue,
"Chapter refers to missing cue")
start = by_cue[chapter["start_cue_id"]]["start_seconds"]
end = by_cue[chapter["end_cue_id"]]["end_seconds"]
require(chapter_end <= start < end, "Chapters must be ordered and non-overlapping")
chapters.append({"startTime": start, "endTime": end, "title": chapter["title"],
"url": media["canonical_url"] + "#" + chapter["start_cue_id"]})
chapter_end = end
envelope = {"schema_version": "1.0", "media_id": media["media_id"],
"canonical_url": media["canonical_url"], "language": media["language"],
"rights": media["rights"], "input_sha256": signature}
result = {
"transcript.json": {**envelope, "cues": cues},
"chunks.json": {**envelope, "chunks": chunks},
"qa.json": {**envelope, "qa": qa},
"chapters.json": {"version": "1.2.0", "chapters": chapters},
}
for name in ("transcript", "chunks", "qa"):
validate(result[name + ".json"], name)
return media, plan, result, text, vtt, txt
def schema_org(media, data, text):
obj = {"@context": "https://schema.org", "@type": "VideoObject" if media["kind"] == "video" else "AudioObject",
"@id": media["canonical_url"] + "#media", "url": media["canonical_url"],
"name": media["title"], "description": media["description"],
"inLanguage": media["language"], "duration": f"PT{media['duration_seconds']:g}S",
"uploadDate": media["published_at"], "transcript": text,
"copyrightNotice": media["rights"]["statement"]}
for source, target in (("content_url", "contentUrl"), ("embed_url", "embedUrl"),
("thumbnail_url", "thumbnailUrl")):
if media.get(source):
obj[target] = media[source]
for source, target in (("license", "license"), ("usage_info", "usageInfo")):
if media["rights"].get(source):
obj[target] = media["rights"][source]
if media["kind"] == "video" and media.get("content_url"):
obj["hasPart"] = [{"@type": "Clip", "name": c["title"],
"startOffset": c["startTime"], "endOffset": c["endTime"],
"url": playback(media, c["startTime"])}
for c in data["chapters.json"]["chapters"]]
return obj
def page_html(media, data, ld):
esc = html.escape
title = esc(media["title"])
links = "".join(f'<link rel="alternate" type="{mime}" href="{name}" title="{label}">'
for name, mime, label in (("transcript.txt", "text/plain", "Transcript"),
("transcript.vtt", "text/vtt", "Timed transcript"),
("chunks.json", "application/json", "Chunks"),
("qa.json", "application/json", "Questions and answers")))
player = f'<p><a href="{esc(media["embed_url"], quote=True)}">Open recording</a></p>' if media.get("embed_url") else ""
if media.get("content_url"):
tag = "video" if media["kind"] == "video" else "audio"
player = (f'<{tag} id="player" controls preload="metadata" src="{esc(media["content_url"], quote=True)}">'
f'<track kind="captions" src="transcript.vtt" srclang="{esc(media["language"])}" '
f'label="{esc(media["language"])}"></{tag}>')
cues = "\n".join(f'<p id="{c["cue_id"]}"><a href="?t={c["start_seconds"]:g}">{c["start_seconds"]:g}s</a> '
f'{esc(c["speaker"] + ": " if c["speaker"] else "")}{esc(c["text"])}</p>'
if media.get("content_url") else
f'<p id="{c["cue_id"]}">{c["start_seconds"]:g}s {esc(c["text"])}</p>'
for c in data["transcript.json"]["cues"])
qa = "\n".join(f'<section><h3>{esc(q["question"])}</h3><p>{esc(q["answer"])}</p><p>'
+ " ".join(f'<a href="#{e["cue_id"]}">Evidence at {e["start_seconds"]:g}s</a>' for e in q["evidence"])
+ '</p></section>' for q in data["qa.json"]["qa"])
chapters = "".join(f'<li><a href="{esc(c["url"], quote=True)}">{esc(c["title"])}</a></li>'
for c in data["chapters.json"]["chapters"])
ld_text = json.dumps(ld, ensure_ascii=False).replace("<", "\\u003c")
banner = '<p><strong>Synthetic example. Media URLs are placeholders.</strong></p>' if media["synthetic"] else ""
return f'''<!doctype html>
<html lang="{esc(media['language'])}"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><title>{title}</title>
<meta name="description" content="{esc(media['description'], quote=True)}">
<link rel="canonical" href="{esc(media['canonical_url'], quote=True)}">{links}
<script type="application/ld+json">{ld_text}</script>
<style>body{{font:18px/1.6 system-ui;max-width:900px;margin:2rem auto;padding:0 1rem}}video{{width:100%}}:target{{background:#fff2b3}}a{{color:#174e92}}</style>
</head><body><h1>{title}</h1>{banner}<p>{esc(media['description'])}</p>{player}
<p><a href="transcript.txt">TXT</a> · <a href="transcript.vtt">VTT</a> · <a href="transcript.json">Timed JSON</a> ·
<a href="chunks.json">Chunks</a> · <a href="qa.json">Q&amp;A</a> · <a href="chapters.json">Chapters</a></p>
<h2>Chapters</h2><ul>{chapters}</ul><h2>Questions and answers</h2>{qa}
<h2>Transcript</h2>{cues}<footer><p>{esc(media['rights']['statement'])}</p></footer>
<script>const p=document.getElementById('player');const t=Number(new URLSearchParams(location.search).get('t'));
if(p && Number.isFinite(t) && t>=0) p.addEventListener('loadedmetadata',()=>{{p.currentTime=Math.min(t,p.duration);}},{{once:true}});</script>
</body></html>'''
def write(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(encoded(value) if not isinstance(value, str) else value.encode("utf-8"))
def build(catalog_path, output):
catalog_path, output = Path(catalog_path).resolve(), Path(output).resolve()
require(not output.exists(), "Output already exists. Use a new release directory.")
catalog = load(catalog_path)
validate(catalog, "catalog")
site = catalog["site_url"].rstrip("/")
https(site)
require(not urlsplit(site).query and not urlsplit(site).fragment, "site_url cannot contain query/fragment")
prepared = []
for entry in catalog["items"]:
manifest = relative_file(catalog_path.parent, entry["manifest"])
plan = relative_file(catalog_path.parent, entry["plan"])
require(not output.is_relative_to(manifest.parent), "Keep generated output outside media source folders")
bundle = artifacts(manifest, plan)
media = bundle[0]
require(media["canonical_url"] == f"{site}/media/{media['media_id']}/",
"Canonical URL must match site_url/media/media_id/")
require(catalog["allow_synthetic"] or not media["synthetic"],
"Synthetic media blocked in this catalog")
prepared.append(bundle)
unique([p[0] for p in prepared], "media_id")
output.parent.mkdir(parents=True, exist_ok=True)
temp = Path(tempfile.mkdtemp(prefix=".media-build-", dir=output.parent))
try:
index = {"schema_version": "1.0", "site_url": site, "items": []}
sitemap = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
for media, plan, data, text, vtt, txt in prepared:
folder = temp / "media" / media["media_id"]
for name, value in data.items():
write(folder / name, value)
(folder / "transcript.vtt").write_bytes(vtt)
(folder / "transcript.txt").write_bytes(txt)
# Source filenames/paths and private ingestion notes never enter the public export.
public_media = {k: v for k, v in media.items() if k != "transcripts"}
write(folder / "media.json", public_media)
ld = schema_org(media, data, text)
write(folder / "schema.jsonld", ld)
write(folder / "index.html", page_html(media, data, ld))
index["items"].append({"media_id": media["media_id"], "title": media["title"],
"description": media["description"], "kind": media["kind"],
"language": media["language"], "synthetic": media["synthetic"],
"canonical_url": media["canonical_url"], "updated_at": media["updated_at"],
"rights": media["rights"],
"artifacts": {n: media["canonical_url"] + n for n in
("media.json", "transcript.txt", "transcript.vtt", "transcript.json",
"chunks.json", "qa.json", "chapters.json", "schema.jsonld")}})
node = ET.SubElement(sitemap, "url")
ET.SubElement(node, "loc").text = media["canonical_url"]
ET.SubElement(node, "lastmod").text = media["updated_at"]
validate(index, "ai-index")
write(temp / "ai-index.json", index)
write(temp / "sitemap.xml", ET.tostring(sitemap, encoding="unicode"))
write(temp / "llms.txt", "# " + catalog["title"] + "\n\n"
+ "> Reviewed media with timed transcript citations.\n\n"
+ "Read [the index](" + site + "/ai-index.json), then chunks and Q&A; cite original cue URLs.\n"
+ "Q&A is reviewed synthesis; transcript text records what was said, not independently verified facts.\n"
+ "API and MCP services are not provided by this static export.\n\n"
+ "## Recordings\n\n"
+ "\n".join(f"- [{m['title']}]({m['canonical_url']}): {m['description']}" for m, *_ in prepared) + "\n")
write(temp / "index.html", '<!doctype html><html lang="en"><meta charset="utf-8"><title>'
+ html.escape(catalog["title"]) + '</title><h1>' + html.escape(catalog["title"]) + '</h1><ul>'
+ ''.join(f'<li><a href="media/{m["media_id"]}/">{html.escape(m["title"])}</a></li>' for m, *_ in prepared)
+ '</ul><a href="ai-index.json">AI index</a></html>')
files = {p.relative_to(temp).as_posix(): digest(p.read_bytes())
for p in sorted(temp.rglob("*")) if p.is_file()}
write(temp / "build-receipt.json", {"builder_version": VERSION,
"catalog_sha256": digest(catalog_path.read_bytes()), "files": files,
"inputs": {m["media_id"]: data["chunks.json"]["input_sha256"] for m, _, data, *_ in prepared},
"deployment_verified": False})
temp.rename(output)
finally:
if temp.exists():
shutil.rmtree(temp)
return {"output": str(output), "media_count": len(prepared), "deployment_verified": False}
def verify_export(root):
root = Path(root).resolve()
receipt = load(root / "build-receipt.json")
actual = {p.relative_to(root).as_posix(): digest(p.read_bytes()) for p in root.rglob("*")
if p.is_file() and p.name != "build-receipt.json"}
require(actual == receipt["files"], "Export files differ from build receipt")
return root
def search(root, query, limit=5):
root = verify_export(root)
require(1 <= limit <= 100, "limit must be between 1 and 100")
terms = set(re.findall(r"\w+", query.casefold()))
require(terms, "Search query is empty")
results = []
index = load(root / "ai-index.json")
for item in index["items"]:
folder = root / "media" / item["media_id"]
for kind, filename in (("chunks", "chunks.json"), ("qa", "qa.json")):
for record in load(folder / filename)[kind]:
body = (record["title"] + " " + record["summary"] + " " + record["content"]
if kind == "chunks" else record["question"] + " " + record["answer"])
score = len(terms & set(re.findall(r"\w+", body.casefold())))
if score:
results.append({"media_id": item["media_id"], "type": kind,
"id": record.get("chunk_id", record.get("qa_id")),
"score": score, "text": body, "rights": item["rights"],
"citations": record.get("citations", record.get("evidence"))})
return sorted(results, key=lambda r: (-r["score"], r["media_id"], r["id"]))[:limit]
def draft(manifest_path, plan_path):
path = Path(plan_path)
require(not path.exists(), "Plan already exists; preserve assigned IDs")
media = load(manifest_path)
validate(media, "media")
cues = parse_vtt(relative_file(Path(manifest_path).resolve().parent,
media["transcripts"]["vtt"]).read_text(encoding="utf-8-sig"),
media["duration_seconds"])
plan = {"schema_version": "1.0", "media_id": media["media_id"],
"chunks": [{"chunk_id": media["media_id"] + ":chunk:introduction",
"knowledge_id": media["media_id"] + ":knowledge:introduction",
"version": 1, "supersedes": [], "title": media["title"],
"heading_path": [media["title"]], "summary": "REVIEW: split into conceptual units",
"tags": [], "cue_ids": [c["cue_id"] for c in cues]}],
"qa": [], "chapters": [],
"review": {"status": "draft", "reviewer": "", "reviewed_at": None, "input_sha256": None}}
write(path, plan)
return {"plan": str(path), "status": "draft", "cue_count": len(cues)}
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
for command in ("draft", "signature", "validate"):
p = sub.add_parser(command)
p.add_argument("--manifest", type=Path, required=True)
p.add_argument("--plan", type=Path, required=True)
p = sub.add_parser("build")
p.add_argument("--catalog", type=Path, required=True)
p.add_argument("--output", type=Path, required=True)
p = sub.add_parser("search")
p.add_argument("--root", type=Path, required=True)
p.add_argument("--query", required=True)
p.add_argument("--limit", type=int, default=5)
p = sub.add_parser("verify")
p.add_argument("--root", type=Path, required=True)
args = parser.parse_args()
try:
if args.command == "draft":
result = draft(args.manifest, args.plan)
elif args.command == "signature":
result = {"input_sha256": inputs(args.manifest, args.plan)[4]}
elif args.command == "validate":
result = {"media_id": artifacts(args.manifest, args.plan)[0]["media_id"], "valid": True}
elif args.command == "build":
result = build(args.catalog, args.output)
elif args.command == "search":
result = search(args.root, args.query, args.limit)
else:
result = {"root": str(verify_export(args.root)), "valid": True}
print(encoded(result).decode("utf-8"), end="")
except Exception as error:
print(f"ERROR: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())