File size: 2,442 Bytes
95a935a 984ec8c 721b0c4 984ec8c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 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]
|