MisConceptTutor / latex_formatter.py
Jintonic92's picture
Create latex_formatter.py
565499c verified
raw
history blame
3.24 kB
# 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