reading-coach / tools /embed_library.py
immu2able's picture
Reading Coach: in-browser Sanskrit recogniser (static)
e699214 verified
Raw History Blame Contribute Delete
1.14 kB
#!/usr/bin/env python3
"""Embed library/*.txt into index.html (<script type="application/json" id="rc-library">) so the
library also works when opened via file:// or offline. Re-run after editing the library texts."""
import json, re, pathlib
root = pathlib.Path(__file__).resolve().parent.parent
books = []
for f in sorted((root / 'library').glob('*.txt')):
text = f.read_text(encoding='utf-8')
title = next((l.strip() for l in text.splitlines() if l.strip()), f.stem)
books.append({'file': f.name, 'title': title, 'text': text})
blob = json.dumps({'books': books}, ensure_ascii=False).replace('</', '<\\/')
tag = f'<script type="application/json" id="rc-library">{blob}</script>'
html = (root / 'index.html').read_text(encoding='utf-8')
if 'id="rc-library"' in html:
html = re.sub(r'<script type="application/json" id="rc-library">.*?</script>', lambda m: tag, html, flags=re.S)
else:
html = html.replace('<!-- ===================== Core logic', tag + '\n<!-- ===================== Core logic', 1)
(root / 'index.html').write_text(html, encoding='utf-8')
print(f'embedded {len(books)} books, {len(blob)//1024} KB')