scan, split, OCR, prepare for LLM
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

surya2html.py 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from __future__ import annotations
  2. import json
  3. from pathlib import Path
  4. from bs4 import BeautifulSoup
  5. HTML_TEMPLATE = """\
  6. <!DOCTYPE html>
  7. <html lang="en">
  8. <head>
  9. <meta charset="utf-8">
  10. <title>{title} — Surya 2</title>
  11. <script>
  12. MathJax = {{
  13. tex: {{
  14. inlineMath: [['$', '$']],
  15. displayMath: [['$$', '$$']],
  16. packages: {{'[+]': ['ams']}}
  17. }},
  18. loader: {{load: ['[tex]/ams']}}
  19. }};
  20. </script>
  21. <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async></script>
  22. <style>
  23. body {{ font-family: serif; max-width: 800px; margin: 2em auto; padding: 0 1em; line-height: 1.6; }}
  24. h2 {{ margin-top: 1.5em; }}
  25. .equation {{ text-align: center; margin: 1em 0; }}
  26. .header {{ font-weight: bold; }}
  27. p {{ margin: 0.5em 0; text-indent: 1.5em; }}
  28. </style>
  29. </head>
  30. <body>
  31. {body}
  32. </body>
  33. </html>
  34. """
  35. def surya_json_to_html(json_path: str | Path) -> str:
  36. data = json.loads(Path(json_path).read_text())
  37. blocks = data.get("blocks", [])
  38. html_parts: list[str] = []
  39. for b in blocks:
  40. label = b.get("label", "")
  41. raw_html = b.get("html", "")
  42. if not raw_html.strip():
  43. continue
  44. if label == "Equation":
  45. clean = raw_html.replace('<math display="block">', "").replace("</math>", "").strip()
  46. html_parts.append(f'\n<div class="equation">$$\n{clean}\n$$</div>')
  47. continue
  48. soup = BeautifulSoup(raw_html, "html.parser")
  49. for math_tag in soup.find_all("math"):
  50. display = math_tag.get("display", "") == "block"
  51. latex = math_tag.get_text().strip()
  52. math_tag.replace_with(f"$$\n{latex}\n$$" if display else f"${latex}$")
  53. text = " ".join(soup.stripped_strings)
  54. if not text:
  55. continue
  56. if label in ("SectionHeader",):
  57. html_parts.append(f"<h2>{text}</h2>")
  58. elif label == "PageHeader":
  59. html_parts.append(f'<p class="header">{text}</p>')
  60. else:
  61. html_parts.append(f"<p>{text}</p>")
  62. body = "\n".join(html_parts)
  63. return HTML_TEMPLATE.format(title=Path(json_path).stem, body=body)