| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- from __future__ import annotations
-
- import json
- from pathlib import Path
-
- from bs4 import BeautifulSoup
-
- HTML_TEMPLATE = """\
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>{title} — Surya 2</title>
- <script>
- MathJax = {{
- tex: {{
- inlineMath: [['$', '$']],
- displayMath: [['$$', '$$']],
- packages: {{'[+]': ['ams']}}
- }},
- loader: {{load: ['[tex]/ams']}}
- }};
- </script>
- <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async></script>
- <style>
- body {{ font-family: serif; max-width: 800px; margin: 2em auto; padding: 0 1em; line-height: 1.6; }}
- h2 {{ margin-top: 1.5em; }}
- .equation {{ text-align: center; margin: 1em 0; }}
- .header {{ font-weight: bold; }}
- p {{ margin: 0.5em 0; text-indent: 1.5em; }}
- </style>
- </head>
- <body>
- {body}
- </body>
- </html>
- """
-
-
- def surya_json_to_html(json_path: str | Path) -> str:
- data = json.loads(Path(json_path).read_text())
- blocks = data.get("blocks", [])
-
- html_parts: list[str] = []
- for b in blocks:
- label = b.get("label", "")
- raw_html = b.get("html", "")
- if not raw_html.strip():
- continue
-
- if label == "Equation":
- clean = raw_html.replace('<math display="block">', "").replace("</math>", "").strip()
- html_parts.append(f'\n<div class="equation">$$\n{clean}\n$$</div>')
- continue
-
- soup = BeautifulSoup(raw_html, "html.parser")
- for math_tag in soup.find_all("math"):
- display = math_tag.get("display", "") == "block"
- latex = math_tag.get_text().strip()
- math_tag.replace_with(f"$$\n{latex}\n$$" if display else f"${latex}$")
-
- text = " ".join(soup.stripped_strings)
- if not text:
- continue
-
- if label in ("SectionHeader",):
- html_parts.append(f"<h2>{text}</h2>")
- elif label == "PageHeader":
- html_parts.append(f'<p class="header">{text}</p>')
- else:
- html_parts.append(f"<p>{text}</p>")
-
- body = "\n".join(html_parts)
- return HTML_TEMPLATE.format(title=Path(json_path).stem, body=body)
|