BuddyMath / utils /math_utils.py
dotandru's picture
V9.0.3: CRITICAL Hotfixes - Anchor Validator NameError & SymPy LaTeX Multiplication Support
721b0c4
Raw
History Blame Contribute Delete
2.44 kB
import re
def sanitize_latex_for_sympy(latex_str: str) -> str:
"""
ืžืกื™ืจ ืคืงื•ื“ื•ืช ืขื™ืฆื•ื‘ ืฉืœ LaTeX (ื›ืžื• ืฆื‘ืขื™ื) ื›ื“ื™ ืฉ-SymPy ื™ื•ื›ืœ ืœืคืขื ื— ืืช ื”ื‘ื™ื˜ื•ื™.
ืœื“ื•ื’ืžื”: ื”ื•ืคืš ืืช \color{red}{5} ืœ- 5.
"""
if not latex_str:
return latex_str
# ืฉืœื‘ 1: ืžื—ืœืฅ ืืช ื”ืชื•ื›ืŸ ืžืชื•ืš ืคืงื•ื“ื•ืช \color{...}{content}
cleaned = re.sub(r'\\color\{.*?\}\{(.*?)\}', r'\1', latex_str)
# ืฉืœื‘ 2: ืžื•ื—ืง ืคืงื•ื“ื•ืช \color{...} ื’ืœืžื•ื“ื•ืช ืฉืœื ืขื•ื˜ืคื•ืช ื›ืœื•ื
cleaned = re.sub(r'\\color\{.*?\}', '', cleaned)
# ืฉืœื‘ 3: ืžื—ื™ืงืช ืคืงื•ื“ื•ืช \text{} (SymPy ืฉื•ื ื ื˜ืงืกื˜ ื—ื•ืคืฉื™)
cleaned = re.sub(r'\\text\{.*?\}', '', cleaned)
# ืฉืœื‘ 4: ื ื™ืงื•ื™ ืกื•ื’ืจื™ื™ื ืžืกื•ื’ \left( \right)
cleaned = cleaned.replace(r'\left', '').replace(r'\right', '')
return cleaned
from typing import List
def aggressive_sympy_sanitizer(latex_str: str) -> List[str]:
"""
V9.0.1: Cleans dirty LaTeX generated by the LLM before feeding it to SymPy.
Splits comma-separated equations into a list of pure math strings.
"""
if not latex_str:
return []
s = latex_str
# 1. Strip Hebrew Content including surrounding parentheses (e.g. (ืœื›ืŸ C))
# This prevents leaving behind empty shells like "( C)" which crash SymPy.
s = re.sub(r'\([^)]*[\u0590-\u05FF]+[^)]*\)', '', s)
s = re.sub(r'[\u0590-\u05FF]+', '', s)
# 2. Strip formatting tags (\text{} and \color{})
s = re.sub(r'\\text\{.*?\}', '', s)
s = re.sub(r'\\color\{.*?\}', '', s)
# 3. Replace Logical Arrows with Equals (to maintain equation structure)
arrows = [r'\Rightarrow', r'\implies', r'\iff', r'\rightarrow']
for arrow in arrows:
s = s.replace(arrow, '=')
# --- ๐Ÿš€ BEGIN HOTFIX V9.0.3: LATEX MULTIPLICATION ---
s = s.replace(r'\cdot', '*').replace(r'\times', '*')
# --- END HOTFIX ---
# 4. Split multiple equations
# SymPy cannot parse "x=0, y=9" as a single AST node.
# We must split by comma and return a list of clean equations.
# We also run the existing sanitize_latex_for_sympy on each part.
expressions = [sanitize_latex_for_sympy(expr.strip()) for expr in s.split(',')]
# Filter out empty strings that might have resulted from the split/regex
return [e for e in expressions if e]