added
This commit is contained in:
commit
4eaec52904
55 files changed
+5044
No files matched your search
@@ -0,0 +1,71 @@
|
||||
"""Check repository JSON, document links, manifest paths, and local schema references."""
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SKIP = {'build', '.git', '__pycache__', '.test-work', '.venv'}
|
||||
|
||||
|
||||
def check():
|
||||
files = [p for p in ROOT.rglob('*') if p.is_file() and not (set(p.relative_to(ROOT).parts) & SKIP)]
|
||||
count = {'json': 0, 'markdown_links': 0, 'schema_refs': 0, 'python': 0}
|
||||
errors = []
|
||||
def local_ref(base, ref):
|
||||
filename, _, pointer = ref.partition('#')
|
||||
path = (base.parent / filename).resolve() if filename else base
|
||||
assert path.is_relative_to(ROOT) and path.is_file(), f'Missing/outside reference {ref}'
|
||||
doc = json.loads(path.read_text(encoding='utf-8-sig'))
|
||||
for key in pointer.lstrip('/').split('/') if pointer else []:
|
||||
key = unquote(key).replace('~1', '/').replace('~0', '~')
|
||||
doc = doc[int(key)] if isinstance(doc, list) else doc[key]
|
||||
def walk_refs(value, base):
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
if key == '$ref' and not item.startswith(('https:', 'http:')):
|
||||
local_ref(base, item)
|
||||
count['schema_refs'] += 1
|
||||
else:
|
||||
walk_refs(item, base)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
walk_refs(item, base)
|
||||
for path in files:
|
||||
try:
|
||||
if path.suffix in {'.md', '.py', '.json', '.txt', '.vtt'} or path.name in {'.gitignore', '.gitattributes', 'VERSION'}:
|
||||
text = path.read_text(encoding='utf-8-sig')
|
||||
assert all(line == line.rstrip(' \t') for line in text.splitlines()), 'Trailing whitespace'
|
||||
assert not re.search(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}', text), 'Potential credential pattern'
|
||||
if path.suffix == '.json':
|
||||
value = json.loads(path.read_text(encoding='utf-8-sig'))
|
||||
count['json'] += 1
|
||||
walk_refs(value, path)
|
||||
if path.name.endswith('.schema.json'):
|
||||
Draft202012Validator.check_schema(value)
|
||||
elif path.suffix == '.py':
|
||||
ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
|
||||
count['python'] += 1
|
||||
elif path.suffix == '.md':
|
||||
for target in re.findall(r'\[[^\]]*\]\(([^)]+)\)', path.read_text(encoding='utf-8')):
|
||||
if target.startswith(('http:', 'https:', '#', 'mailto:')):
|
||||
continue
|
||||
linked = (path.parent / unquote(target.split('#')[0])).resolve()
|
||||
assert linked.is_relative_to(ROOT) and linked.exists(), f'Missing local link {target}'
|
||||
count['markdown_links'] += 1
|
||||
except Exception as error:
|
||||
errors.append(f'{path.relative_to(ROOT)}: {error}')
|
||||
manifest = json.loads((ROOT/'repository.json').read_text(encoding='utf-8'))
|
||||
for name in list(manifest['entrypoints'].values()) + [v['path'] for v in manifest['contents']]:
|
||||
if not (ROOT/name).exists():
|
||||
errors.append('Missing manifest path: ' + name)
|
||||
if errors:
|
||||
raise ValueError('\n'.join(errors))
|
||||
print(json.dumps({'valid': True, **count}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
check()
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Inspect media folders and build in-folder draft assets before human review."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import difflib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
import media_builder as core
|
||||
|
||||
MEDIA_EXTENSIONS = {'.mp3', '.wav', '.m4a', '.flac', '.ogg', '.mp4', '.mov', '.mkv', '.webm', '.aac'}
|
||||
VERSION = (core.ROOT / 'VERSION').read_text(encoding='utf-8').strip()
|
||||
|
||||
|
||||
def sha_file(path):
|
||||
import hashlib
|
||||
h = hashlib.sha256()
|
||||
with path.open('rb') as f:
|
||||
for block in iter(lambda: f.read(1024 * 1024), b''):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def mp3_duration(path):
|
||||
"""Read MPEG frame timing; return unknown for unsupported/corrupt streams."""
|
||||
if path.suffix.lower() != '.mp3':
|
||||
return None
|
||||
data = path.read_bytes()
|
||||
pos = 0
|
||||
if data[:3] == b'ID3' and len(data) >= 10:
|
||||
pos = 10 + sum((b & 127) << shift for b, shift in zip(data[6:10], (21, 14, 7, 0)))
|
||||
if data[5] & 16:
|
||||
pos += 10
|
||||
total = 0.0
|
||||
frames = 0
|
||||
rates1 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]
|
||||
rates2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]
|
||||
while pos + 4 <= len(data):
|
||||
if data[pos:pos+3] in (b'TAG', b'APE'):
|
||||
break
|
||||
header = int.from_bytes(data[pos:pos+4], 'big')
|
||||
if header >> 21 != 2047:
|
||||
# Allow padding after the final frame, but never scan past corrupt audio.
|
||||
if frames and not any(data[pos:]):
|
||||
break
|
||||
return None
|
||||
version, layer = (header >> 19) & 3, (header >> 17) & 3
|
||||
rate_index, sample_index = (header >> 12) & 15, (header >> 10) & 3
|
||||
if version == 1 or layer != 1 or rate_index in (0, 15) or sample_index == 3:
|
||||
return None
|
||||
sample = [44100, 48000, 32000][sample_index] / (1 if version == 3 else 2 if version == 2 else 4)
|
||||
bitrate = (rates1 if version == 3 else rates2)[rate_index] * 1000
|
||||
length = int((144 if version == 3 else 72) * bitrate / sample) + ((header >> 9) & 1)
|
||||
if pos + length > len(data):
|
||||
return None
|
||||
total += (1152 if version == 3 else 576) / sample
|
||||
pos += length
|
||||
frames += 1
|
||||
return round(total, 3) if frames else None
|
||||
|
||||
|
||||
def source_paths(folder, source_files=None):
|
||||
folder = Path(folder).resolve()
|
||||
core.require(folder.is_dir(), 'Media folder does not exist')
|
||||
if source_files:
|
||||
paths = {key: core.relative_file(folder, name) for key, name in source_files.items()}
|
||||
else:
|
||||
paths = {}
|
||||
for key, extensions in [('media', MEDIA_EXTENSIONS), ('txt', {'.txt'}), ('vtt', {'.vtt'})]:
|
||||
matches = [p for p in folder.iterdir() if p.is_file() and p.suffix.lower() in extensions]
|
||||
core.require(len(matches) == 1, f'Expected one {key} file; choose source_files explicitly when ambiguous')
|
||||
paths[key] = matches[0]
|
||||
core.require(len(set(paths.values())) == 3, 'Media, TXT, and VTT must be distinct files')
|
||||
core.require(paths['media'].suffix.lower() in MEDIA_EXTENSIONS, 'Unsupported media extension')
|
||||
core.require(paths['txt'].suffix.lower() == '.txt' and paths['vtt'].suffix.lower() == '.vtt', 'Expected TXT and VTT sources')
|
||||
return folder, paths
|
||||
|
||||
|
||||
def inspect(folder, source_files=None):
|
||||
folder, paths = source_paths(folder, source_files)
|
||||
raw_vtt = paths['vtt'].read_text(encoding='utf-8-sig')
|
||||
timestamps = re.findall(r'-->\s*(\S+)', raw_vtt)
|
||||
core.require(timestamps, 'No VTT timing found')
|
||||
end = max(core.seconds(t) for t in timestamps)
|
||||
cues = core.parse_vtt(raw_vtt, end)
|
||||
a = ' '.join(c['text'] for c in cues)
|
||||
b = ' '.join(paths['txt'].read_text(encoding='utf-8-sig').split())
|
||||
duration = mp3_duration(paths['media'])
|
||||
core.require(duration is None or end <= duration + 0.1,
|
||||
'Transcript extends beyond measured MPEG audio duration')
|
||||
files = {key: {'path': p.relative_to(folder).as_posix(), 'bytes': p.stat().st_size,
|
||||
'sha256': sha_file(p)} for key, p in paths.items()}
|
||||
result = {'source_files': files, 'cue_count': len(cues), 'word_count': len(a.split()),
|
||||
'transcript_end_seconds': end, 'media_duration_seconds': duration,
|
||||
'duration_method': 'MPEG frame scan (encoded duration; encoder padding may apply)' if duration else 'unknown',
|
||||
'txt_vtt_match': a == b, 'speaker_labels_present': any(c['speaker'] for c in cues),
|
||||
'notes': []}
|
||||
if a != b:
|
||||
result['notes'].append('TXT and VTT differ. Draft uses timed VTT text; reconcile before publication.')
|
||||
result['text_difference_sample'] = list(difflib.unified_diff(b.split(), a.split(), n=4))[:50]
|
||||
if not result['speaker_labels_present']:
|
||||
result['notes'].append('No VTT speaker labels. Do not infer cue-level speaker identity.')
|
||||
return result, cues
|
||||
|
||||
|
||||
def prepare(folder, output):
|
||||
path = Path(output)
|
||||
core.require(not path.exists(), 'Intake exists; preserve existing answers')
|
||||
audit, _ = inspect(folder)
|
||||
slug = re.sub(r'[^a-z0-9]+', '-', Path(folder).name.lower()).strip('-')
|
||||
metadata = {key: None for key in ('title', 'recording_date', 'recording_timezone', 'organizer',
|
||||
'series', 'session_type', 'description', 'language', 'attribution', 'rights_statement',
|
||||
'license', 'sharing_notes', 'stt_tool', 'stt_model')}
|
||||
value = {'schema_version': '1.0', 'media_id': slug,
|
||||
'source_files': {k: v['path'] for k, v in audit['source_files'].items()},
|
||||
'metadata': metadata, 'participants': [], 'audience': [], 'topics': [], 'priority_questions': [],
|
||||
'urls': {k: None for k in ('original', 'canonical', 'content', 'slides')}, 'related_links': [],
|
||||
'field_sources': {}, 'unknowns': [], 'quality_notes': [], 'excluded_cue_ids': [],
|
||||
'interview': {'status': 'pending', 'questions_asked': [], 'notes': []}}
|
||||
core.validate(value, 'intake')
|
||||
core.write(path, value)
|
||||
return {'intake': str(path), 'status': 'pending', 'source_audit': audit}
|
||||
|
||||
|
||||
def seed(folder, intake_path, output):
|
||||
intake = core.load(intake_path)
|
||||
core.validate(intake, 'intake')
|
||||
audit, cues = inspect(folder, intake['source_files'])
|
||||
excluded = set(intake['excluded_cue_ids'])
|
||||
core.require(excluded <= {c['cue_id'] for c in cues}, 'Excluded cue does not exist')
|
||||
included = [c['cue_id'] for c in cues if c['cue_id'] not in excluded]
|
||||
core.require(included, 'No included cues')
|
||||
title = intake['metadata']['title'] or Path(folder).name
|
||||
plan = {'schema_version': '1.0', 'media_id': intake['media_id'],
|
||||
'chunks': [{'chunk_id': intake['media_id'] + ':chunk:starter',
|
||||
'knowledge_id': intake['media_id'] + ':knowledge:starter', 'version': 1,
|
||||
'supersedes': [], 'title': title, 'heading_path': [title],
|
||||
'summary': 'DRAFT: replace starter with conceptual chunks.', 'tags': [], 'cue_ids': included}],
|
||||
'qa': [], 'chapters': [],
|
||||
'review': {'status': 'draft', 'reviewer': '', 'reviewed_at': None, 'input_sha256': None}}
|
||||
core.require(not Path(output).exists(), 'Plan exists; preserve authored IDs and content')
|
||||
core.write(Path(output), plan)
|
||||
return {'plan': str(output), 'status': 'draft'}
|
||||
|
||||
|
||||
def timecode(sec):
|
||||
sec = int(sec)
|
||||
return f'{sec//3600:02}:{sec//60%60:02}:{sec%60:02}'
|
||||
|
||||
|
||||
def build(folder, intake_path, plan_path, output):
|
||||
folder, output = Path(folder).resolve(), Path(output).resolve()
|
||||
core.require(output.parent == folder, 'Draft output must be a new immediate subfolder of the media folder')
|
||||
core.require(not output.exists(), 'Output exists; choose a new review directory')
|
||||
intake, plan = core.load(intake_path), core.load(plan_path)
|
||||
core.validate(intake, 'intake')
|
||||
core.validate(plan, 'plan')
|
||||
core.require(plan['review']['status'] == 'draft', 'Folder builds are drafts; use the public workflow for approved releases')
|
||||
core.require(not plan['review']['reviewer'] and plan['review']['reviewed_at'] is None,
|
||||
'Do not mix a draft build with a claimed human approval')
|
||||
core.require(plan['media_id'] == intake['media_id'], 'Plan/intake ID mismatch')
|
||||
audit, cues = inspect(folder, intake['source_files'])
|
||||
source_snapshot = {k: v['sha256'] for k, v in audit['source_files'].items()}
|
||||
excluded = set(intake['excluded_cue_ids'])
|
||||
core.require(excluded <= {c['cue_id'] for c in cues}, 'Excluded cue does not exist')
|
||||
cues = [c for c in cues if c['cue_id'] not in excluded]
|
||||
by_cue = {c['cue_id']: c for c in cues}
|
||||
title = intake['metadata']['title'] or folder.name
|
||||
for key in ('chunks', 'qa', 'chapters'):
|
||||
core.unique(plan[key], {'chunks':'chunk_id', 'qa':'qa_id', 'chapters':'chapter_id'}[key])
|
||||
core.unique(plan['chunks'], 'knowledge_id')
|
||||
for value in list(intake['urls'].values()) + [r['url'] for r in intake['related_links']]:
|
||||
if value:
|
||||
core.https(value)
|
||||
fingerprint = core.digest(core.encoded({'builder_version': VERSION, 'intake': intake,
|
||||
'plan': plan, 'source_files': audit['source_files']}))
|
||||
common = {'schema_version': '1.0', 'profile': 'local-review', 'status': 'draft',
|
||||
'media_id': intake['media_id'], 'title': title, 'input_sha256': fingerprint,
|
||||
'canonical_url': intake['urls']['canonical']}
|
||||
def cite(cue):
|
||||
return {'media_id': intake['media_id'], 'cue_id': cue['cue_id'],
|
||||
'start_seconds': cue['start_seconds'], 'end_seconds': cue['end_seconds'],
|
||||
'transcript_ref': 'transcript.md#' + cue['cue_id'],
|
||||
'transcript_url': (intake['urls']['canonical'].rstrip('/') + '/#' + cue['cue_id']) if intake['urls']['canonical'] else None,
|
||||
'source_media': '../' + audit['source_files']['media']['path'], 'playback_url': None}
|
||||
chunks = []
|
||||
assigned = []
|
||||
for order, item in enumerate(plan['chunks'], 1):
|
||||
core.require(all(i in by_cue for i in item['cue_ids']), 'Chunk references missing or excluded cue')
|
||||
selection = [by_cue[i] for i in item['cue_ids']]
|
||||
assigned.extend(item['cue_ids'])
|
||||
content = ' '.join(c['text'] for c in selection)
|
||||
chunks.append({**item, 'order': order, 'media_id': intake['media_id'], 'content': content,
|
||||
'content_sha256': core.digest(content.encode('utf-8')),
|
||||
'start_seconds': selection[0]['start_seconds'], 'end_seconds': selection[-1]['end_seconds'],
|
||||
'speakers': list(dict.fromkeys(c['speaker'] for c in selection if c['speaker'])),
|
||||
'citations': [cite(c) for c in selection]})
|
||||
core.require(assigned == list(by_cue), 'Chunks must cover each included cue exactly once 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']:
|
||||
core.require(e['chunk_id'] in by_chunk and e['cue_id'] in by_cue, 'Missing Q&A source')
|
||||
core.require(e['cue_id'] in by_chunk[e['chunk_id']]['cue_ids'], 'Q&A cue is outside cited chunk')
|
||||
core.require(e['quote'] in by_cue[e['cue_id']]['text'], 'Q&A evidence quote is not an exact source substring')
|
||||
evidence.append({**e, **cite(by_cue[e['cue_id']])})
|
||||
qa.append({**item, 'media_id': intake['media_id'], 'evidence': evidence})
|
||||
chapters = []
|
||||
previous_end = 0
|
||||
for item in plan['chapters']:
|
||||
core.require(item['start_cue_id'] in by_cue and item['end_cue_id'] in by_cue, 'Chapter cue missing or excluded')
|
||||
start, end = by_cue[item['start_cue_id']]['start_seconds'], by_cue[item['end_cue_id']]['end_seconds']
|
||||
core.require(previous_end <= start < end, 'Chapters must be ordered, non-overlapping ranges')
|
||||
chapters.append({'startTime': start, 'endTime': end, 'title': item['title'],
|
||||
'url': 'transcript.md#' + item['start_cue_id']})
|
||||
previous_end = end
|
||||
media = {**common, 'metadata': intake['metadata'], 'participants': intake['participants'],
|
||||
'audience': intake['audience'], 'topics': intake['topics'], 'priority_questions': intake['priority_questions'],
|
||||
'urls': intake['urls'], 'related_links': intake['related_links'], 'field_sources': intake['field_sources'],
|
||||
'unknowns': intake['unknowns'], 'quality_notes': intake['quality_notes'], 'source_audit': audit,
|
||||
'human_approval': False, 'publication_ready': False}
|
||||
data = {'media.json': media,
|
||||
'transcript.json': {**common, 'artifact_type':'transcript', 'cues':cues, 'excluded_cue_ids':sorted(excluded)},
|
||||
'chunks.json': {**common, 'artifact_type':'chunks', 'chunks':chunks},
|
||||
'qa.json': {**common, 'artifact_type':'qa', 'qa':qa},
|
||||
'chapters.json': {'version':'1.2.0','chapters':[{k:v for k,v in c.items() if k != 'url'} for c in chapters]},
|
||||
'ai-index.json': {**common, 'artifact_type':'index', 'description':intake['metadata']['description'],
|
||||
'artifacts': {name:name for name in ('media.json','transcript.json','chunks.json','qa.json','chapters.json','schema.jsonld','README.md','review.md')}}}
|
||||
for name in ('transcript.json', 'chunks.json', 'qa.json', 'ai-index.json'):
|
||||
core.validate(data[name], 'folder-export')
|
||||
# Only known values become Schema.org properties. No public URL, date, or license is invented.
|
||||
kind = 'AudioObject' if Path(audit['source_files']['media']['path']).suffix.lower() in {'.mp3','.wav','.m4a','.flac','.ogg','.aac'} else 'VideoObject'
|
||||
ld = {'@context':'https://schema.org', '@type':kind, 'name':title,
|
||||
'transcript':' '.join(c['text'] for c in cues)}
|
||||
for source, target in [('description','description'),('language','inLanguage'),('recording_date','dateCreated'),('license','license')]:
|
||||
if intake['metadata'].get(source):
|
||||
ld[target] = intake['metadata'][source]
|
||||
for source,target in [('canonical','url'),('content','contentUrl')]:
|
||||
if intake['urls'][source]:
|
||||
ld[target] = intake['urls'][source]
|
||||
if audit['media_duration_seconds'] is not None:
|
||||
ld['duration'] = f"PT{audit['media_duration_seconds']:g}S"
|
||||
data['schema.jsonld'] = ld
|
||||
def clean(value):
|
||||
return str(value or 'Unknown / pending confirmation').replace('\n',' ')
|
||||
intro = (f'# {title}\n\n**Draft for human review.** Built from the supplied recording, TXT, and VTT.\n\n'
|
||||
+ (intake['metadata']['description'] or 'Description pending review.') + '\n\n'
|
||||
+ f"- Recording: [{audit['source_files']['media']['path']}](../{quote(audit['source_files']['media']['path'])})\n"
|
||||
+ f"- Timed transcript: {timecode(audit['transcript_end_seconds'])}; {len(cues)} included cues.\n"
|
||||
+ f"- Structure: {len(chunks)} chunks, {len(qa)} Q&A entries, {len(chapters)} chapters.\n"
|
||||
+ '- [Review notes and unknowns](review.md) · [Transcript](transcript.md) · [Chunks](chunks.json) · [Q&A](qa.json)\n\n'
|
||||
+ '## Recording metadata\n\n'
|
||||
+ '\n'.join(f'- **{key.replace("_"," ").title()}:** {clean(intake["metadata"].get(key))}' for key in
|
||||
('title','recording_date','recording_timezone','publication_date','organizer','series','attribution','rights_statement'))
|
||||
+ '\n\n## Audience and topics\n\n'
|
||||
+ '- Audience: ' + ', '.join(intake['audience']) + '\n'
|
||||
+ '- Topics: ' + ', '.join(intake['topics']) + '\n\n'
|
||||
+ '## Participants and credits\n\n'
|
||||
+ '\n'.join(f'- **{person["name"]}** — {clean(person["role"])}; {clean(person["affiliation"])}. '
|
||||
f'Source status: {person["status"]}.' for person in intake['participants'])
|
||||
+ '\n\nParticipant metadata does not establish cue-level speaker labels.\n\n'
|
||||
+ '## Source pages and supporting material\n\n'
|
||||
+ (f'- [Published source page]({intake["urls"]["original"]})\n' if intake['urls']['original'] else '- Published source page: unknown.\n')
|
||||
+ (f'- [Slides]({intake["urls"]["slides"]})\n' if intake['urls']['slides'] else '')
|
||||
+ '\n'.join(f'- [{item["label"]}]({item["url"]})' for item in intake['related_links'])
|
||||
+ '\n\n## Chapters\n\n'
|
||||
+ '\n'.join(f'- [{timecode(c["startTime"])} — {c["title"]}]({c["url"]})' for c in chapters)
|
||||
+ '\n\n## Conceptual chunks\n\n'
|
||||
+ '\n\n'.join(f'### {timecode(c["start_seconds"])} — {c["title"]}\n\n{c["summary"]}\n\n'
|
||||
f'[Source](transcript.md#{c["cue_ids"][0]}) · `{c["chunk_id"]}`' for c in chunks)
|
||||
+ '\n\n## Questions this recording can answer\n\n'
|
||||
+ '\n\n'.join(f'### {q["question"]}\n\n{q["answer"]}\n\n' + ' · '.join(
|
||||
f'[Evidence {timecode(e["start_seconds"])}]({e["transcript_ref"]})' for e in q['evidence']) for q in qa)
|
||||
+ '\n\nThese answers summarize attributed transcript content. They are not independent verification of speaker claims.\n')
|
||||
review = (f'# Review: {title}\n\nStatus: **draft — not human approved or publication ready**.\n\n'
|
||||
+ '## Please review\n\n'
|
||||
+ '- [ ] Confirm title, date, people/affiliations, and attribution.\n'
|
||||
+ '- [ ] Check chunk boundaries, summaries, Q&A support, and chapter labels.\n'
|
||||
+ '- [ ] Check names, acronyms, statistics, and caveats against the recording/slides.\n'
|
||||
+ '- [ ] Resolve sharing permissions and public URLs before publication.\n\n'
|
||||
+ '## Missing or unconfirmed metadata\n\n'
|
||||
+ ('\n'.join('- '+x for x in intake['unknowns']) or '- See metadata fields for any unknown values.') + '\n\n'
|
||||
+ '## Source and processing notes\n\n'
|
||||
+ '\n'.join('- '+x for x in audit['notes'] + intake['quality_notes'])
|
||||
+ f'\n- Excluded cues: {len(excluded)}. Original files remain untouched.\n'
|
||||
+ '- Transcript wording is preserved, including apparent STT errors; no cue-level speaker identities were inferred.\n'
|
||||
+ '- This run reads existing transcript text; it does not listen to the full recording or inspect missing slides/video.\n'
|
||||
+ '- Mechanical checks establish source consistency and exact evidence quotes, not factual accuracy or human approval.\n')
|
||||
data['README.md'], data['review.md'] = intro, review
|
||||
data['transcript.md'] = '# Timed transcript\n\nSource wording; speaker labels only where provided by VTT.\n\n' + '\n\n'.join(
|
||||
f'<a id="{c["cue_id"]}"></a>\n\n**{timecode(c["start_seconds"])}–{timecode(c["end_seconds"])}** '
|
||||
+ (f'[{c["speaker"]}] ' if c['speaker'] else '') + c['text'] for c in cues) + '\n'
|
||||
data['llms.txt'] = f'# {title}\n\n> Local draft for review; publication details may be unknown.\n\n## Assets\n\n' + '\n'.join(
|
||||
f'- [{name}]({name})' for name in ('media.json','chunks.json','qa.json','transcript.json','review.md')) + '\n'
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = Path(tempfile.mkdtemp(prefix='.structured-draft-', dir=output.parent))
|
||||
try:
|
||||
for name,value in data.items():
|
||||
core.write(temp/name, value)
|
||||
# A source change while structuring invalidates the build rather than mixing revisions.
|
||||
_, paths = source_paths(folder, intake['source_files'])
|
||||
core.require({k:sha_file(p) for k,p in paths.items()} == source_snapshot, 'Source changed during build')
|
||||
receipt = {'builder_version': VERSION, 'profile':'local-review', 'status':'draft',
|
||||
'input_sha256':fingerprint, 'source_files':audit['source_files'],
|
||||
'source_files_unchanged':True, 'human_approval':False, 'publication_ready':False,
|
||||
'counts':{'cues':len(cues),'chunks':len(chunks),'qa':len(qa),'chapters':len(chapters)},
|
||||
'files':{p.name:sha_file(p) for p in sorted(temp.iterdir()) if p.is_file()}}
|
||||
core.write(temp/'build-receipt.json', receipt)
|
||||
temp.rename(output)
|
||||
finally:
|
||||
if temp.exists():
|
||||
shutil.rmtree(temp)
|
||||
return {'output':str(output),'status':'draft',**receipt['counts'],'source_files_unchanged':True}
|
||||
|
||||
|
||||
def verify(output, check_sources=True):
|
||||
output = Path(output).resolve()
|
||||
receipt = core.load(output/'build-receipt.json')
|
||||
actual = {p.relative_to(output).as_posix():sha_file(p) for p in output.rglob('*')
|
||||
if p.is_file() and p != output/'build-receipt.json'}
|
||||
core.require(actual == receipt['files'], 'Draft output differs from receipt')
|
||||
for name in ('transcript.json','chunks.json','qa.json','ai-index.json'):
|
||||
core.validate(core.load(output/name), 'folder-export')
|
||||
if check_sources:
|
||||
for record in receipt['source_files'].values():
|
||||
path = core.relative_file(output.parent, record['path'])
|
||||
core.require(sha_file(path) == record['sha256'], 'Original source changed since build')
|
||||
return {'valid':True,'status':'draft','source_files_checked':check_sources,**receipt['counts']}
|
||||
|
||||
|
||||
def search(output, query, limit=5):
|
||||
verify(output)
|
||||
core.require(1 <= limit <= 100, 'Limit must be between 1 and 100')
|
||||
terms = set(re.findall(r'\w+', query.casefold()))
|
||||
core.require(terms, 'Empty query')
|
||||
results = []
|
||||
for kind in ('chunks','qa'):
|
||||
for r in core.load(Path(output)/(kind+'.json'))[kind]:
|
||||
text = (r['title']+' '+r['summary']+' '+r['content']) if kind=='chunks' else r['question']+' '+r['answer']
|
||||
heading = r['title'] if kind == 'chunks' else r['question']
|
||||
abstract = r['summary'] if kind == 'chunks' else r['answer']
|
||||
score = (len(terms & set(re.findall(r'\w+',text.casefold())))
|
||||
+ 3 * len(terms & set(re.findall(r'\w+',heading.casefold())))
|
||||
+ 2 * len(terms & set(re.findall(r'\w+',abstract.casefold()))))
|
||||
if score:
|
||||
results.append({'id':r.get('chunk_id',r.get('qa_id')),'type':kind,'score':score,
|
||||
'text':text,'citations':r.get('citations',r.get('evidence')),'status':'draft'})
|
||||
return sorted(results,key=lambda r:(-r['score'],r['id']))[:limit]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
sub = p.add_subparsers(dest='command', required=True)
|
||||
for command in ('inspect','prepare','seed','build'):
|
||||
cmd = sub.add_parser(command)
|
||||
cmd.add_argument('--folder',type=Path,required=True)
|
||||
if command in ('seed','build'):
|
||||
cmd.add_argument('--intake',type=Path,required=True)
|
||||
if command=='build':
|
||||
cmd.add_argument('--plan',type=Path,required=True)
|
||||
if command!='inspect':
|
||||
cmd.add_argument('--output',type=Path,required=True)
|
||||
for command in ('verify','search'):
|
||||
cmd = sub.add_parser(command)
|
||||
cmd.add_argument('--output',type=Path,required=True)
|
||||
if command=='search':
|
||||
cmd.add_argument('--query',required=True)
|
||||
cmd.add_argument('--limit',type=int,default=5)
|
||||
a = p.parse_args()
|
||||
try:
|
||||
if a.command=='inspect': result=inspect(a.folder)[0]
|
||||
elif a.command=='prepare': result=prepare(a.folder,a.output)
|
||||
elif a.command=='seed': result=seed(a.folder,a.intake,a.output)
|
||||
elif a.command=='build': result=build(a.folder,a.intake,a.plan,a.output)
|
||||
elif a.command=='verify': result=verify(a.output)
|
||||
else: result=search(a.output,a.query,a.limit)
|
||||
print(core.encoded(result).decode('utf-8'),end='')
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f'ERROR: {e}',file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,473 @@
|
||||
"""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]
|
||||
VERSION = "0.2.0"
|
||||
|
||||
|
||||
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&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())
|
||||
Reference in new issue
Block a user