Files
vpn-dns-gateway/demo/tikzrefinery/documents/update-diagram-index.py
vsun1 27b82c169e
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Add frozen TikZRefinery demo baseline and build pipeline
2026-11-25 22:46:33 -05:00

152 lines
8.5 KiB
Python

"""Index active report figures from authored TeX and final LaTeX build records.
Standard library only. Never extracts PDF text. The manifest supplies reviewed
status/type; figure labels, source paths, hashes and page locations are derived.
"""
import argparse
import hashlib
import json
import re
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
MANIFEST = HERE / 'diagram-manifest.json'
def strip_comments(text):
return re.sub(r'(?<!\\)%[^\n]*', '', text)
def group(text, start):
depth = 1
for i in range(start + 1, len(text)):
if text[i] == '{' and text[i-1] != '\\':
depth += 1
elif text[i] == '}' and text[i-1] != '\\':
depth -= 1
if depth == 0:
return text[start+1:i]
raise ValueError('Unbalanced TeX group')
def sources():
seen = set()
def visit(path):
path = path.resolve()
if path in seen:
return
seen.add(path)
text = strip_comments(path.read_text(encoding='utf-8-sig'))
yield path, text
for name in re.findall(r'\\(?:input|include)\s*\{([^}]+)\}', text):
if '\\' in name or '#' in name:
continue
child = path.parent/name
if not child.suffix:
child = child.with_suffix('.tex')
if not child.is_file():
raise ValueError(f'Missing input: {child}')
yield from visit(child)
yield from visit(HERE/'latex/TikZRefinery.tex')
def inventory():
rows = []
for path, text in sources():
for match in re.finditer(r'\\begin\{figure\}(.*?)\\end\{figure\}', text, re.S):
block = match.group(1)
labels = re.findall(r'\\label\{(Figure:[^}]+)\}', block)
if len(labels) != 1:
raise ValueError(f'Figure must have one stable label: {path}')
inputs = []
for name in re.findall(r'\\(?:input|includegraphics)(?:\[[^]]*\])?\{([^}]+)\}', block):
asset = (path.parent/name).resolve()
if not asset.is_file():
raise ValueError(f'Missing figure asset {asset}')
inputs.append(asset.relative_to(ROOT).as_posix())
caption = re.search(r'\\caption(?:\[[^]]*\])?\s*\{', block)
caption = group(block, caption.end()-1) if caption else ''
caption = re.sub(r'\\label\{[^}]+\}', '', caption)
headings = list(re.finditer(r'\\(?:sub)*section\{([^}]+)\}', text[:match.start()]))
rows.append(dict(label=labels[0], source=path.relative_to(ROOT).as_posix(),
source_line=text[:match.start()].count('\n')+1,
section=headings[-1][1] if headings else path.stem,
assets=inputs, caption_tex=' '.join(caption.split())))
labels = [row['label'] for row in rows]
if len(set(labels)) != len(labels):
raise ValueError('Duplicate active figure labels')
return rows
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--build-directory', type=Path)
parser.add_argument('--submission-only', action='store_true')
parser.add_argument('--inventory-only', action='store_true')
parser.add_argument('--record-sources', action='store_true', help='Snapshot inputs before compilation')
args = parser.parse_args()
rows = inventory()
if args.inventory_only:
print(json.dumps(rows, indent=2))
return
if args.build_directory is None:
parser.error('--build-directory is required unless --inventory-only is used')
# Bind the page index to the actual source set compiled, not newer edits.
dependencies = {path for path, _ in sources()}
dependencies.update((HERE/'latex').glob('*.cls'))
dependencies.update((HERE/'latex').glob('*.bib'))
dependencies.update({MANIFEST, Path(__file__).resolve()})
dependencies.update(ROOT/name for row in rows for name in row['assets'])
fingerprint = {path.relative_to(ROOT).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(dependencies)}
snapshot = args.build_directory/'diagram-source-hashes.json'
if args.record_sources:
snapshot.write_text(json.dumps(fingerprint, indent=2)+'\n', encoding='utf-8')
print(f'PASS diagram build inputs: recorded {len(fingerprint)} source hashes')
return
if not snapshot.is_file() or json.loads(snapshot.read_text()) != fingerprint:
raise ValueError('Sources changed since the build snapshot; rebuild before generating page locations')
manifest = json.loads(MANIFEST.read_text(encoding='utf-8-sig'))
by_label = manifest['figures']
found = {row['label'] for row in rows}
if found != set(by_label):
raise ValueError(f'Classify new figures / remove stale entries: missing={found-set(by_label)}, inactive={set(by_label)-found}')
version = re.search(r'\\newcommand\{\\DocumentVersion\}\{([^}]+)\}', (HERE/'latex/TikZRefinery.tex').read_text())[1]
editions = [('submission', 'TikZRefinerySubmission')]
if not args.submission_only:
editions.append(('developer', 'TikZRefinery'))
for edition, stem in editions:
folder = args.build_directory/stem
# \include writes chapter labels to separate auxiliary files.
aux = '\n'.join(path.read_text(encoding='utf-8-sig') for path in folder.glob('*.aux'))
pages = {}
for line in (folder/f'{stem}.dpages').read_text().splitlines():
printed, physical = line.split('|')
pages.setdefault(printed, []).append(int(physical))
for row in rows:
match = re.search(r'\\newlabel\{'+re.escape(row['label'])+r'\}\{\{([^}]+)\}\{([^}]+)\}', aux)
if not match or len(pages.get(match[2], [])) != 1:
raise ValueError(f'Missing/ambiguous final page: {row["label"]} ({edition})')
row[edition] = dict(figure=match[1], printed=match[2], physical=pages[match[2]][0])
for row in rows:
row.update(by_label[row['label']])
row['source_sha256'] = {name: hashlib.sha256((ROOT/name).read_bytes()).hexdigest() for name in [row['source'], *row['assets']]}
# Sort by final reading order, not filesystem order.
rows.sort(key=lambda row: (row['submission']['physical'], row['submission']['figure']))
output = dict(version=version, provenance='Authored TeX + final .aux and shipout .dpages; no PDF text extraction', figures=rows)
(HERE/'diagram-index.json').write_text(json.dumps(output, indent=2)+'\n', encoding='utf-8')
lines = ['# Report diagram index', '', f'Generated for **{version}** by `update-diagram-index.py`; do not edit this file.', '',
'The [manifest](diagram-manifest.json) controls type, title and current/planned status. The build derives labels, editable inputs, section and pages. New unclassified figures fail generation.', '',
'Page cells give **printed page / physical PDF page** (physical pages start at 1). Use [the JSON index](diagram-index.json) to select render pages and compare source hashes. PDF page links may depend on the viewer.', '',
'This is a navigation aid for targeted figure review. Material design additions/changes still require the whole-document impact and layout review in the AI guide.', '',
'| Figure | View / status | Source and section | Submission | Developer |',
'|---|---|---|---|---|']
for row in rows:
links = [f'[{Path(name).name}]({Path(name).relative_to("documents").as_posix()})' for name in row['assets'] or [row['source']]]
page_cells = []
for edition, pdf in [('submission', 'TikZRefinery.pdf'), ('developer', 'TikZRefinery-Developers-Edition.pdf')]:
page = row.get(edition)
page_cells.append(f'[{page["printed"]} / {page["physical"]}]({pdf}#page={page["physical"]})' if page else 'Not built')
lines.append(f'| {row["submission"]["figure"]}: {row["title"]} | {row["type"]}; **{row["status"]}** | '+', '.join(links)+f'<br>{row["section"]} | '+ ' | '.join(page_cells)+' |')
lines += ['', 'Historical diagrams and archived reports/slides are excluded from active figure numbering. The former frozen deployment source is retained in `assets/diagram-audit-2026-11-24/`; the old UI wireframe is retained in `assets/design-diagrams/current-ui-wireframe.tex`.', '']
(HERE/'DIAGRAM_INDEX.md').write_text('\n'.join(lines), encoding='utf-8')
print(f'PASS diagram index: {len(rows)} classified active figures; '+', '.join(name for name, _ in editions))
if __name__ == '__main__':
main()