Spaces:
Sleeping
Sleeping
File size: 3,241 Bytes
565499c |
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# latex_formatter.py
import re
class LatexFormatter:
"""LaTeX μμ ν¬λ§·ν
μ μν ν΄λμ€"""
def __init__(self):
# LaTeX νΉμ λͺ
λ Ήμ΄ λ§€ν
self.latex_commands = {
r'\left': r'\\left',
r'\right': r'\\right',
r'\bigcirc': r'\\bigcirc',
r'\square': r'\\square',
r'\quad': r'\\quad',
r'\div': r'\\div',
r'\ldots': r'\\ldots',
r'\times': r'\\times',
r'\pm': r'\\pm',
r'\infty': r'\\infty',
r'\neq': r'\\neq',
r'\leq': r'\\leq',
r'\geq': r'\\geq'
}
# μν μ©μ΄ λ§€ν
self.math_terms = [
'decimalplaces', 'rounded to', 'What is',
'Calculate', 'Solve', 'Evaluate', 'Simplify'
]
def format_expression(self, text: str) -> str:
"""LaTeX μμ λ³νμ λ©μΈ ν¨μ"""
# 1. κΈ°μ‘΄ LaTeX μμ 보쑴
latex_parts = []
def save_latex(match):
latex_parts.append(match.group(0))
return f"LATEX_{len(latex_parts)-1}_PLACEHOLDER"
text = re.sub(r'\$\$.*?\$\$', save_latex, text)
# 2. νΉμ λͺ
λ Ήμ΄ μ²λ¦¬
for cmd, latex_cmd in self.latex_commands.items():
text = text.replace(cmd, latex_cmd)
# 3. λ¨μ΄ λΆλ¦¬ λ° ν
μ€νΈ μ 리
text = self._clean_text(text)
# 4. μμ μ²λ¦¬
text = self._process_math_expressions(text)
# 5. LaTeX μμ 볡μ
for i, latex in enumerate(latex_parts):
text = text.replace(f"LATEX_{i}_PLACEHOLDER", latex)
# 6. μ΅μ’
μ 리
if not text.startswith('$$') and not text.endswith('$$'):
text = f"$${text}$$"
return text.replace('\\\\', '\\')
def _clean_text(self, text: str) -> str:
"""ν
μ€νΈ μ μ²λ¦¬"""
# λΆμ΄μλ λ¨μ΄ λΆλ¦¬
text = re.sub(r'([a-z])([A-Z])', r'\1 \2', text)
text = re.sub(r'([A-Za-z])(\d)', r'\1 \2', text)
text = re.sub(r'(\d)([A-Za-z])', r'\1 \2', text)
# μν μ©μ΄λ₯Ό LaTeX ν
μ€νΈλ‘ λ³ν
for term in self.math_terms:
text = re.sub(
rf'\b{term}\b',
f'\\text{{{term}}}',
text,
flags=re.IGNORECASE
)
return text
def _process_math_expressions(self, text: str) -> str:
"""μν ννμ μ²λ¦¬"""
# κ΄νΈ μμ μμ μ²λ¦¬
def process_math(match):
content = match.group(1)
# μ§μ μ²λ¦¬
if '^' in content:
base, exp = content.split('^')
return f'\\left({base}\\right)^{{{exp}}}'
# λΆμ μ²λ¦¬
if '/' in content and not any(op in content for op in ['Γ', 'Γ·', '+', '-']):
num, den = content.split('/')
return f'\\frac{{{num}}}{{{den}}}'
return f'\\left({content}\\right)'
text = re.sub(r'\((.*?)\)', process_math, text)
return text |