服务:Spring Boot 3.2 + docx4j 8.3.9,POST /api/v3/server_office_file/file/parse
接受 .docx,返回 HTML(公式 → LaTeX,图片 → RustFS 外链)
公式支持三类来源:
- OMML(Word 2007+ 公式) → Python omml_mathml2latex
- MathType OLE 对象 → Ruby mathtype2mathml → MathML → LaTeX
- Word EQ 域(老教辅主力) → EqToLatexUtil(本次新增)
本次改动:
1. 新增 java-svc/.../core/EqToLatexUtil.java:
移植自 jby backend-services office-core,EQ 语法 → LaTeX
(\f→\dfrac、\r→\sqrt、\i→\int/\sum/\prod、\s→^{}/_{}、\b→\left\right、
\a→array、\x→\boxed/\overline、\o\al 堆叠、圈码、化学符号、极限、连等式)
品牌标记 JBYU* → WPU*,与采集端一致
2. CtoMathFinder:接上 EQ 分支(原为 not-ported 桩),域代码经
EqToLatexUtil.convert 转 LaTeX 写入 eqLatexMap(WPEQNUM 占位符)
3. WordParseUtil.dealPlaceholder:EQ 的 LaTeX 同样加 \( \) 包裹
(原先因 WPEQNUM 例外不加包裹,前端/MathJax 不渲染)
修前症状:教辅 Word 里分式/方程组/上下标整段丢失(如 {−1/3, 1} 变成 {-,1})
修后实测:46 份教辅 2908 处 EQ 域全部还原,公式总数 2954 处、零未包裹残留
安全:application.yml(含 RustFS 密钥)不入库,提供 application.yml.example;
OssService 的 @Value 默认密钥已清空
302 lines
11 KiB
Python
302 lines
11 KiB
Python
r"""
|
|
Visitor for <mstyle> (style attributes) MathML elements.
|
|
|
|
The <mstyle> element is a wrapper that applies style attributes to its children:
|
|
- mathvariant: Font variants (bold, italic, script, fraktur, etc.)
|
|
- mathcolor: Text color
|
|
- displaystyle: Display vs inline math mode
|
|
|
|
This visitor is a transparent container that wraps converted children with
|
|
appropriate LaTeX style commands.
|
|
"""
|
|
|
|
from lxml import etree as ET
|
|
from ..core.interfaces import Visitor, Strategy
|
|
from ..utils import local_name as _local
|
|
|
|
|
|
class MstyleVisitor(Visitor):
|
|
r"""
|
|
Handles <mstyle> (style attributes) MathML elements.
|
|
|
|
Applies style attributes to child content through LaTeX wrappers.
|
|
|
|
Examples:
|
|
Bold text:
|
|
<mstyle mathvariant="bold"><mi>x</mi></mstyle>
|
|
→ \mathbf{x}
|
|
|
|
Colored text:
|
|
<mstyle mathcolor="red"><mi>f</mi></mstyle>
|
|
→ \textcolor{red}{f}
|
|
|
|
Script font:
|
|
<mstyle mathvariant="script"><mi>L</mi></mstyle>
|
|
→ \mathscr{L}
|
|
|
|
Fraktur font:
|
|
<mstyle mathvariant="fraktur"><mi>g</mi></mstyle>
|
|
→ \mathfrak{g}
|
|
|
|
Double-struck (blackboard bold):
|
|
<mstyle mathvariant="double-struck"><mi>R</mi></mstyle>
|
|
→ \mathbb{R}
|
|
|
|
Normal (upright) text:
|
|
<mstyle mathvariant="normal"><mi>x</mi></mstyle>
|
|
→ \mathrm{x}
|
|
|
|
Display style (affects fractions):
|
|
<mstyle displaystyle="true"><mfrac>...</mfrac></mstyle>
|
|
→ (context passed to children)
|
|
"""
|
|
|
|
def __init__(self, strategy: Strategy):
|
|
"""Initialize the Mstyle visitor."""
|
|
super().__init__(strategy)
|
|
self._converter_context = None
|
|
|
|
def set_converter_context(self, converter):
|
|
"""Set converter context for color suppression checking."""
|
|
self._converter_context = converter
|
|
|
|
def visit(self, node: ET.Element) -> str:
|
|
r"""
|
|
Convert <mstyle> element to LaTeX.
|
|
|
|
Args:
|
|
node: The <mstyle> element to convert
|
|
|
|
Returns:
|
|
LaTeX string with style wrappers applied to children
|
|
|
|
Raises:
|
|
ValueError: If node is not an <mstyle> element
|
|
"""
|
|
if not self.can_handle(node):
|
|
raise ValueError(f"MstyleVisitor cannot handle element '{node.tag}'")
|
|
|
|
# Get style attributes
|
|
mathvariant = node.get("mathvariant", "")
|
|
displaystyle = node.get("displaystyle", "")
|
|
mathcolor = node.get("mathcolor", "")
|
|
|
|
# Convert all children
|
|
content = self._convert_children(node)
|
|
|
|
# Apply font variants
|
|
content = self._apply_mathvariant(content, mathvariant)
|
|
|
|
# Apply color (if not black, which is default)
|
|
content = self._apply_color(content, mathcolor)
|
|
|
|
# Display style is contextual and doesn't produce direct LaTeX output
|
|
# It would be handled by context/strategy if needed
|
|
# (In the original implementation, it affects fraction rendering)
|
|
|
|
return content
|
|
|
|
def _convert_children(self, node: ET.Element) -> str:
|
|
"""
|
|
Convert all child elements to LaTeX.
|
|
|
|
Args:
|
|
node: The <mstyle> element
|
|
|
|
Returns:
|
|
LaTeX string with all children converted
|
|
"""
|
|
parts = []
|
|
for child in node:
|
|
parts.append(self._convert_child(child))
|
|
return ' '.join(parts).strip()
|
|
|
|
def _convert_child(self, child: ET.Element) -> str:
|
|
"""Convert a child element to LaTeX."""
|
|
tag = _local(child.tag)
|
|
|
|
# Import visitors as needed to avoid circular imports
|
|
if tag == 'mi':
|
|
from .mi_visitor import MiVisitor
|
|
return MiVisitor(self.strategy).visit(child)
|
|
elif tag == 'mo':
|
|
from .mo_visitor import MoVisitor
|
|
return MoVisitor(self.strategy).visit(child)
|
|
elif tag == 'mn':
|
|
from .mn_visitor import MnVisitor
|
|
return MnVisitor(self.strategy).visit(child)
|
|
elif tag == 'mfrac':
|
|
from .mfrac_visitor import MfracVisitor
|
|
return MfracVisitor(self.strategy).visit(child)
|
|
elif tag == 'msup':
|
|
from .msup_visitor import MsupVisitor
|
|
return MsupVisitor(self.strategy).visit(child)
|
|
elif tag == 'msub':
|
|
from .msub_visitor import MsubVisitor
|
|
return MsubVisitor(self.strategy).visit(child)
|
|
elif tag == 'mrow':
|
|
from .mrow_visitor import MrowVisitor
|
|
return MrowVisitor(self.strategy).visit(child)
|
|
elif tag == 'msqrt':
|
|
from .msqrt_visitor import MsqrtVisitor
|
|
return MsqrtVisitor(self.strategy).visit(child)
|
|
elif tag == 'mroot':
|
|
from .mroot_visitor import MrootVisitor
|
|
return MrootVisitor(self.strategy).visit(child)
|
|
elif tag == 'msubsup':
|
|
from .msubsup_visitor import MsubsupVisitor
|
|
return MsubsupVisitor(self.strategy).visit(child)
|
|
elif tag == 'munder':
|
|
from .munder_visitor import MunderVisitor
|
|
return MunderVisitor(self.strategy).visit(child)
|
|
elif tag == 'mover':
|
|
from .mover_visitor import MoverVisitor
|
|
return MoverVisitor(self.strategy).visit(child)
|
|
elif tag == 'munderover':
|
|
from .munderover_visitor import MunderoverVisitor
|
|
return MunderoverVisitor(self.strategy).visit(child)
|
|
elif tag == 'mfenced':
|
|
from .mfenced_visitor import MfencedVisitor
|
|
return MfencedVisitor(self.strategy).visit(child)
|
|
elif tag == 'mtable':
|
|
from .mtable_visitor import MtableVisitor
|
|
return MtableVisitor(self.strategy).visit(child)
|
|
elif tag == 'mtext':
|
|
from .mtext_visitor import MtextVisitor
|
|
return MtextVisitor(self.strategy).visit(child)
|
|
elif tag == 'mstyle':
|
|
from .mstyle_visitor import MstyleVisitor
|
|
return MstyleVisitor(self.strategy).visit(child)
|
|
elif tag == 'mspace':
|
|
from .mspace_visitor import MspaceVisitor
|
|
return MspaceVisitor(self.strategy).visit(child)
|
|
elif tag == 'menclose':
|
|
from .menclose_visitor import MencloseVisitor
|
|
return MencloseVisitor(self.strategy).visit(child)
|
|
elif tag == 'mmultiscripts':
|
|
from .mmultiscripts_visitor import MmultiscriptsVisitor
|
|
return MmultiscriptsVisitor(self.strategy).visit(child)
|
|
elif tag == 'maction':
|
|
from .maction_visitor import MactionVisitor
|
|
return MactionVisitor(self.strategy).visit(child)
|
|
elif tag == 'merror':
|
|
from .merror_visitor import MerrorVisitor
|
|
return MerrorVisitor(self.strategy).visit(child)
|
|
elif tag == 'mpadded':
|
|
from .mpadded_visitor import MpaddedVisitor
|
|
return MpaddedVisitor(self.strategy).visit(child)
|
|
elif tag == 'mphantom':
|
|
from .mphantom_visitor import MphantomVisitor
|
|
return MphantomVisitor(self.strategy).visit(child)
|
|
elif tag == 'ms':
|
|
from .ms_visitor import MsVisitor
|
|
return MsVisitor(self.strategy).visit(child)
|
|
elif tag == 'mglyph':
|
|
from .mglyph_visitor import MglyphVisitor
|
|
return MglyphVisitor(self.strategy).visit(child)
|
|
elif tag == 'maligngroup':
|
|
from .maligngroup_visitor import MaligngroupVisitor
|
|
return MaligngroupVisitor(self.strategy).visit(child)
|
|
elif tag == 'malignmark':
|
|
from .malignmark_visitor import MalignmarkVisitor
|
|
return MalignmarkVisitor(self.strategy).visit(child)
|
|
elif tag == 'mlabeledtr':
|
|
from .mlabeledtr_visitor import MlabeledtrVisitor
|
|
return MlabeledtrVisitor(self.strategy).visit(child)
|
|
else:
|
|
# Fallback: return text content for unknown elements
|
|
import sys
|
|
print(f"[WARNING] Unknown element <{tag}> in mstyle, using text fallback", file=sys.stderr)
|
|
return _text_content(child)
|
|
|
|
def _apply_mathvariant(self, content: str, mathvariant: str) -> str:
|
|
"""
|
|
Apply mathvariant font styling to content.
|
|
|
|
Args:
|
|
content: The LaTeX content to wrap
|
|
mathvariant: The mathvariant attribute value
|
|
|
|
Returns:
|
|
LaTeX content with font variant wrapper
|
|
"""
|
|
if not mathvariant or not content:
|
|
return content
|
|
|
|
# Map mathvariant values to LaTeX commands
|
|
variant_map = {
|
|
"bold": "\\mathbf",
|
|
"bold-italic": "\\boldsymbol", # Bold italic
|
|
"italic": None, # Italic is default in math mode
|
|
"normal": "\\mathrm", # Upright/roman text
|
|
"script": "\\mathscr",
|
|
"fraktur": "\\mathfrak",
|
|
"double-struck": "\\mathbb", # Blackboard bold
|
|
"monospace": "\\mathtt",
|
|
"sans-serif": "\\mathsf",
|
|
}
|
|
|
|
latex_cmd = variant_map.get(mathvariant)
|
|
if latex_cmd:
|
|
return f"{latex_cmd}{{{content}}}"
|
|
else:
|
|
# Italic (default) or unknown variant - no wrapper needed
|
|
return content
|
|
|
|
def _apply_color(self, content: str, mathcolor: str) -> str:
|
|
"""
|
|
Apply color styling to content.
|
|
|
|
Args:
|
|
content: The LaTeX content to wrap
|
|
mathcolor: The mathcolor attribute value
|
|
|
|
Returns:
|
|
LaTeX content with color wrapper
|
|
"""
|
|
# Use centralized color handling with RGB support and suppression
|
|
from ..utils.color_helpers import hex_to_latex_color
|
|
from ..utils import is_default_color
|
|
|
|
if not mathcolor or not content:
|
|
return content
|
|
|
|
# Check if suppression is active (uniform color optimization)
|
|
# Get context from visitor or strategy (strategy is shared across all visitors)
|
|
context = getattr(self, '_converter_context', None)
|
|
if context is None and hasattr(self.strategy, '_converter_context'):
|
|
context = self.strategy._converter_context
|
|
|
|
if context and getattr(context, '_suppress_leaf_colors', False):
|
|
return content
|
|
|
|
# Skip default black color
|
|
if is_default_color(mathcolor):
|
|
return content
|
|
|
|
# Convert hex color to LaTeX format (with RGB mode support)
|
|
color_model, color_spec = hex_to_latex_color(mathcolor)
|
|
|
|
# Skip if conversion resulted in black
|
|
if color_spec == 'black':
|
|
return content
|
|
|
|
# Wrap with appropriate format
|
|
if color_model:
|
|
return f"\\textcolor{color_model}{{{color_spec}}}{{{content}}}"
|
|
else:
|
|
return f"\\textcolor{{{color_spec}}}{{{content}}}"
|
|
|
|
def can_handle(self, node: ET.Element) -> bool:
|
|
"""Check if this visitor can handle the given node."""
|
|
return _local(node.tag) == 'mstyle'
|
|
|
|
@property
|
|
def element_name(self) -> str:
|
|
"""Get the element name this visitor handles."""
|
|
return 'mstyle'
|
|
|
|
def __repr__(self) -> str:
|
|
"""String representation for debugging."""
|
|
return f"MstyleVisitor(strategy={self.strategy.name})"
|