Spaces:
Configuration error
Fix aligned environments breaking KaTeX: collapse math to single line
Browse filesTwo root causes for equations not rendering after the first few:
1. LaTeX \\ (line-break inside \begin{aligned}) was being processed by
Gradio's markdown engine as a hard line-break (<br>) before KaTeX saw
the content. Multi-line $$ ... $$ blocks may also not be recognised by
the underlying marked.js parser. Fix: collapse all whitespace (including
real newlines) inside \[...\] content to a single space before wrapping
in $$content$$. \\ is two backslash characters, not whitespace, so it
is preserved and KaTeX receives valid aligned-environment LaTeX.
2. Truncated model output (page content cut off mid-equation) left an
unclosed \[ in the text with no matching \], which appeared as raw LaTeX.
Fix: after converting all complete \[...\] pairs, strip any remaining
orphaned \[ to end-of-string.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
|
@@ -116,11 +116,21 @@ def to_math_md(text):
|
|
| 116 |
"""Convert model output to markdown with $$/$ delimiters for gr.Markdown + KaTeX."""
|
| 117 |
if not text:
|
| 118 |
return ""
|
| 119 |
-
# \[...\]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
text = re.sub(r'\\\[(.+?)\\\]',
|
| 121 |
-
lambda m: f'\n\n$$
|
| 122 |
text, flags=re.DOTALL)
|
| 123 |
-
# \
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
text = re.sub(r'\\\((.+?)\\\)', lambda m: f'${m.group(1).strip()}$', text)
|
| 125 |
return text
|
| 126 |
|
|
|
|
| 116 |
"""Convert model output to markdown with $$/$ delimiters for gr.Markdown + KaTeX."""
|
| 117 |
if not text:
|
| 118 |
return ""
|
| 119 |
+
# Collapse all whitespace inside \[...\] to a single line before converting to
|
| 120 |
+
# $$content$$. This fixes two problems:
|
| 121 |
+
# 1. Markdown parsers that don't recognise multi-line $$ ... $$ blocks.
|
| 122 |
+
# 2. LaTeX \\ (line-break inside aligned) being processed by the markdown
|
| 123 |
+
# engine as a hard line-break (<br>) before KaTeX ever sees it, which
|
| 124 |
+
# breaks every aligned/cases/gathered environment.
|
| 125 |
+
# Note: \\ is two backslash characters — not whitespace — so it survives split().
|
| 126 |
text = re.sub(r'\\\[(.+?)\\\]',
|
| 127 |
+
lambda m: f'\n\n$${" ".join(m.group(1).split())}$$\n\n',
|
| 128 |
text, flags=re.DOTALL)
|
| 129 |
+
# Remove any orphaned \[ without a closing \] (model output truncated mid-equation).
|
| 130 |
+
# After the substitution above all complete pairs are gone, so any remaining \[
|
| 131 |
+
# is unclosed and would appear as raw LaTeX in the output.
|
| 132 |
+
text = re.sub(r'\\\[.*', '', text, flags=re.DOTALL)
|
| 133 |
+
# Inline math
|
| 134 |
text = re.sub(r'\\\((.+?)\\\)', lambda m: f'${m.group(1).strip()}$', text)
|
| 135 |
return text
|
| 136 |
|