ricklon Claude Sonnet 4.6 commited on
Commit
a53cc22
·
1 Parent(s): b1169dd

Replace MathJax+gr.HTML with gr.Markdown+KaTeX for reliable math rendering

Browse files

MathJax + gr.HTML was unreliable: the typeset JS callback couldn't find
.math-preview due to Gradio's shadow DOM isolation, and the head= script
injection had no guaranteed timing. Switch to gr.Markdown with built-in
KaTeX via latex_delimiters — math rendering is handled natively by Gradio
with no external scripts or JS callbacks needed.

- Remove MATHJAX_HEAD, md_lib import, pymdownx.arithmatex dependency
- Replace to_math_html() with to_math_md(): just converts \[...\] → $$...$$
and \(...\) → $...$ for gr.Markdown's KaTeX renderer
- Replace gr.HTML with gr.Markdown(latex_delimiters=[...])
- Remove submit_event MathJax typeset JS handler
- Remove head=MATHJAX_HEAD from launch()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +15 -99
app.py CHANGED
@@ -11,7 +11,7 @@ import fitz
11
  import re
12
  import numpy as np
13
  import base64
14
- import markdown as md_lib
15
  from io import StringIO, BytesIO
16
 
17
  # Model options — swap MODEL_NAME to reduce VRAM usage on GPUs with <= 8GB
@@ -112,82 +112,17 @@ def clean_output(text, include_images=False):
112
 
113
  return text.strip()
114
 
115
- MATHJAX_HEAD = """
116
- <script>
117
- window.MathJax = {
118
- loader: {load: ['[tex]/mathtools']},
119
- tex: {
120
- packages: {'[+]': ['mathtools']},
121
- inlineMath: [['\\\\(', '\\\\)']],
122
- displayMath: [['\\\\[', '\\\\]']],
123
- processEscapes: true,
124
- tags: 'ams'
125
- },
126
- options: {
127
- skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre']
128
- },
129
- startup: {
130
- typeset: false
131
- }
132
- };
133
- </script>
134
- <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async></script>
135
- <style>
136
- .math-preview {
137
- padding: 1.5em;
138
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
139
- font-size: 15px;
140
- line-height: 1.8;
141
- color: #1a1a1a;
142
- max-width: 100%;
143
- overflow-x: auto;
144
- }
145
- .math-preview h1 { font-size: 1.8em; font-weight: 700; margin: 1em 0 0.4em; border-bottom: 2px solid #e0e0e0; padding-bottom: 0.3em; }
146
- .math-preview h2 { font-size: 1.4em; font-weight: 600; margin: 1em 0 0.4em; border-bottom: 1px solid #e0e0e0; padding-bottom: 0.2em; }
147
- .math-preview h3 { font-size: 1.15em; font-weight: 600; margin: 0.9em 0 0.3em; }
148
- .math-preview h4, .math-preview h5, .math-preview h6 { font-weight: 600; margin: 0.8em 0 0.3em; }
149
- .math-preview p { margin: 0.6em 0; }
150
- .math-preview ul, .math-preview ol { padding-left: 1.8em; margin: 0.5em 0; }
151
- .math-preview li { margin: 0.25em 0; }
152
- .math-preview table { border-collapse: collapse; width: 100%; margin: 1em 0; font-size: 0.95em; }
153
- .math-preview th, .math-preview td { border: 1px solid #ccc; padding: 0.45em 0.75em; text-align: left; }
154
- .math-preview th { background: #f2f2f2; font-weight: 600; }
155
- .math-preview tr:nth-child(even) { background: #fafafa; }
156
- .math-preview code { background: #f4f4f4; padding: 0.15em 0.4em; border-radius: 3px; font-family: 'Courier New', monospace; font-size: 0.88em; }
157
- .math-preview pre { background: #f4f4f4; padding: 1em; border-radius: 5px; overflow-x: auto; margin: 0.8em 0; }
158
- .math-preview pre code { background: none; padding: 0; }
159
- .math-preview blockquote { border-left: 4px solid #ccc; margin: 0.8em 0; padding: 0.4em 1em; color: #555; background: #fafafa; }
160
- .math-preview img { max-width: 100%; height: auto; display: block; margin: 0.8em 0; }
161
- .math-preview .arithmatex { overflow-x: auto; }
162
- .math-preview mjx-container[display="true"] { display: block; overflow-x: auto; padding: 0.5em 0; }
163
- </style>
164
- """
165
-
166
- def to_math_html(text):
167
  if not text:
168
  return ""
169
- # Pre-convert \[...\] and \(...\) to $$...$$ and $...$
170
- # Markdown strips backslashes before arithmatex can protect them,
171
- # so convert to $-delimiters first (arithmatex recognises those).
172
- #
173
- # IMPORTANT: the model outputs " \[ content \] " with surrounding spaces.
174
- # Naively replacing to "$$ content $$" (space after $$) causes arithmatex
175
- # to mis-parse as inline math surrounded by literal $ signs, which is why
176
- # equations appeared as "$ ... $" instead of rendered display math.
177
- # Fix: use the multi-line block form ($$\ncontent\n$$) and strip whitespace.
178
  text = re.sub(r'\\\[(.+?)\\\]',
179
  lambda m: f'\n\n$$\n{m.group(1).strip()}\n$$\n\n',
180
  text, flags=re.DOTALL)
 
181
  text = re.sub(r'\\\((.+?)\\\)', lambda m: f'${m.group(1).strip()}$', text)
182
- html = md_lib.markdown(text, extensions=[
183
- 'pymdownx.arithmatex',
184
- 'tables',
185
- 'fenced_code',
186
- 'sane_lists',
187
- ], extension_configs={
188
- 'pymdownx.arithmatex': {'generic': True}
189
- })
190
- return f'<div class="math-preview">{html}</div>'
191
 
192
  def embed_images(markdown, crops):
193
  if not crops:
@@ -338,7 +273,7 @@ with gr.Blocks(title="DeepSeek-OCR-2") as demo:
338
  **Model uses DeepEncoder v2 and achieves 91.09% on OmniDocBench (+3.73% over v1).**
339
 
340
  Built on the original [DeepSeek-OCR-2 Demo](https://huggingface.co/spaces/merterbak/DeepSeek-OCR-2) by **Mert Erbak** — thank you for the excellent foundation.
341
- This fork adds **MathJax rendering** in the Markdown Preview tab so that equations from scanned papers and textbooks display as proper math notation.
342
  """)
343
 
344
  with gr.Row():
@@ -355,7 +290,13 @@ with gr.Blocks(title="DeepSeek-OCR-2") as demo:
355
  with gr.Tab("Text", id="tab_text"):
356
  text_out = gr.Textbox(lines=20, buttons=["copy"], show_label=False)
357
  with gr.Tab("Markdown Preview", id="tab_markdown"):
358
- md_out = gr.HTML("")
 
 
 
 
 
 
359
  with gr.Tab("Boxes", id="tab_boxes"):
360
  img_out = gr.Image(type="pil", height=500, show_label=False)
361
  with gr.Tab("Cropped Images", id="tab_crops"):
@@ -428,36 +369,12 @@ with gr.Blocks(title="DeepSeek-OCR-2") as demo:
428
  dl_tmp.write(cleaned)
429
  dl_tmp.close()
430
 
431
- return (text_display, to_math_html(markdown), raw, img_out, crops,
432
  gr.DownloadButton(value=dl_tmp.name, visible=True))
433
 
434
  submit_event = btn.click(run, [input_img, file_in, task, prompt, page_selector],
435
  [text_out, md_out, raw_out, img_out, gallery, download_btn])
436
  submit_event.then(select_boxes, [task], [tabs])
437
- submit_event.then(fn=None, js="""() => {
438
- const tryTypeset = () => {
439
- if (!window.MathJax || !MathJax.typesetPromise) { setTimeout(tryTypeset, 100); return; }
440
- // Gradio renders gr.HTML inside a shadow DOM, so document.querySelector
441
- // won't find .math-preview. Walk all shadow roots to locate it.
442
- const findInShadows = (root) => {
443
- const el = root.querySelector('.math-preview');
444
- if (el) return el;
445
- for (const node of root.querySelectorAll('*')) {
446
- if (node.shadowRoot) {
447
- const found = findInShadows(node.shadowRoot);
448
- if (found) return found;
449
- }
450
- }
451
- return null;
452
- };
453
- const el = findInShadows(document);
454
- if (!el) { MathJax.typesetPromise(); return; }
455
- MathJax.typesetClear([el]);
456
- MathJax.typesetPromise([el]);
457
- };
458
- setTimeout(tryTypeset, 200); // primary: catches most cases
459
- setTimeout(tryTypeset, 2000); // fallback: GPU cold-start can delay DOM update
460
- }""")
461
 
462
  if __name__ == "__main__":
463
  # server_name="0.0.0.0" is needed locally (WSL2 → Windows access)
@@ -466,6 +383,5 @@ if __name__ == "__main__":
466
  demo.queue(max_size=20).launch(
467
  theme=gr.themes.Soft(),
468
  server_name="0.0.0.0" if local else None,
469
- head=MATHJAX_HEAD, # Gradio 6.0: head moved from Blocks() to launch()
470
  ssr_mode=False, # SSR is experimental in Gradio 6 and breaks HF Spaces routing
471
  )
 
11
  import re
12
  import numpy as np
13
  import base64
14
+
15
  from io import StringIO, BytesIO
16
 
17
  # Model options — swap MODEL_NAME to reduce VRAM usage on GPUs with <= 8GB
 
112
 
113
  return text.strip()
114
 
115
+ def to_math_md(text):
116
+ """Convert model output to markdown with $$/$ delimiters for gr.Markdown + KaTeX."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  if not text:
118
  return ""
119
+ # \[...\] $$\ncontent\n$$ (block display math)
 
 
 
 
 
 
 
 
120
  text = re.sub(r'\\\[(.+?)\\\]',
121
  lambda m: f'\n\n$$\n{m.group(1).strip()}\n$$\n\n',
122
  text, flags=re.DOTALL)
123
+ # \(...\) → $...$ (inline math)
124
  text = re.sub(r'\\\((.+?)\\\)', lambda m: f'${m.group(1).strip()}$', text)
125
+ return text
 
 
 
 
 
 
 
 
126
 
127
  def embed_images(markdown, crops):
128
  if not crops:
 
273
  **Model uses DeepEncoder v2 and achieves 91.09% on OmniDocBench (+3.73% over v1).**
274
 
275
  Built on the original [DeepSeek-OCR-2 Demo](https://huggingface.co/spaces/merterbak/DeepSeek-OCR-2) by **Mert Erbak** — thank you for the excellent foundation.
276
+ This fork adds **math rendering** in the Markdown Preview tab so that equations from scanned papers and textbooks display as proper math notation.
277
  """)
278
 
279
  with gr.Row():
 
290
  with gr.Tab("Text", id="tab_text"):
291
  text_out = gr.Textbox(lines=20, buttons=["copy"], show_label=False)
292
  with gr.Tab("Markdown Preview", id="tab_markdown"):
293
+ md_out = gr.Markdown(
294
+ "",
295
+ latex_delimiters=[
296
+ {"left": "$$", "right": "$$", "display": True},
297
+ {"left": "$", "right": "$", "display": False},
298
+ ],
299
+ )
300
  with gr.Tab("Boxes", id="tab_boxes"):
301
  img_out = gr.Image(type="pil", height=500, show_label=False)
302
  with gr.Tab("Cropped Images", id="tab_crops"):
 
369
  dl_tmp.write(cleaned)
370
  dl_tmp.close()
371
 
372
+ return (text_display, to_math_md(markdown), raw, img_out, crops,
373
  gr.DownloadButton(value=dl_tmp.name, visible=True))
374
 
375
  submit_event = btn.click(run, [input_img, file_in, task, prompt, page_selector],
376
  [text_out, md_out, raw_out, img_out, gallery, download_btn])
377
  submit_event.then(select_boxes, [task], [tabs])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
 
379
  if __name__ == "__main__":
380
  # server_name="0.0.0.0" is needed locally (WSL2 → Windows access)
 
383
  demo.queue(max_size=20).launch(
384
  theme=gr.themes.Soft(),
385
  server_name="0.0.0.0" if local else None,
 
386
  ssr_mode=False, # SSR is experimental in Gradio 6 and breaks HF Spaces routing
387
  )