服务: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 默认密钥已清空
145 lines
4.9 KiB
Python
145 lines
4.9 KiB
Python
"""
|
|
Input parser factory for auto-detecting and creating appropriate parsers.
|
|
|
|
This module provides centralized parser creation with auto-detection
|
|
support for determining the most appropriate parser based on input source.
|
|
"""
|
|
|
|
import os
|
|
from typing import Union, List
|
|
from ..core.interfaces import Parser
|
|
|
|
|
|
class InputParserFactory:
|
|
"""
|
|
Factory for creating input parsers based on source content.
|
|
|
|
This factory provides centralized parser creation with support for:
|
|
- Auto-detection based on file extension or content
|
|
- Explicit parser selection by type
|
|
- Clear error messages for unsupported formats
|
|
"""
|
|
|
|
@staticmethod
|
|
def create_parser(source: str, parser_type: Union[str, None] = None) -> Parser:
|
|
"""
|
|
Create an appropriate parser for the input source.
|
|
|
|
Args:
|
|
source: Input source (file path or content string)
|
|
parser_type: Optional explicit parser type
|
|
("docx", "omml", "mathml", or None for auto-detection)
|
|
|
|
Returns:
|
|
Parser instance appropriate for the source
|
|
|
|
Raises:
|
|
ValueError: If input format cannot be determined or is unsupported
|
|
|
|
Examples:
|
|
>>> factory = InputParserFactory()
|
|
>>> parser = factory.create_parser("equations.docx")
|
|
>>> isinstance(parser, DocxParser)
|
|
True
|
|
|
|
>>> parser = factory.create_parser("<math><mi>x</mi></math>")
|
|
>>> isinstance(parser, MathMLParser)
|
|
True
|
|
|
|
>>> parser = factory.create_parser(xml_content, parser_type="omml")
|
|
>>> isinstance(parser, OmmlParser)
|
|
True
|
|
"""
|
|
# Import here to avoid circular dependencies
|
|
from .docx_parser import DocxParser
|
|
from .omml_parser import OmmlParser
|
|
from .mathml_parser import MathMLParser
|
|
|
|
# Explicit parser type specified
|
|
if parser_type:
|
|
parser_type = parser_type.lower()
|
|
if parser_type == "docx":
|
|
return DocxParser()
|
|
elif parser_type == "omml":
|
|
return OmmlParser()
|
|
elif parser_type == "mathml":
|
|
return MathMLParser()
|
|
else:
|
|
raise ValueError(f"Unknown parser type: {parser_type}")
|
|
|
|
# Auto-detection based on source
|
|
# Check file extension first (most common case)
|
|
if source.endswith('.docx') or (os.path.exists(source) and source.lower().endswith('.docx')):
|
|
return DocxParser()
|
|
|
|
# Check content for XML markers
|
|
# Strip whitespace for reliable detection
|
|
content_start = source.strip()[:200] # Check first 200 chars
|
|
|
|
# Check for OMML namespace
|
|
if '<m:oMath' in content_start or '<m:oMathPara' in content_start:
|
|
return OmmlParser()
|
|
|
|
# Check for MathML namespace
|
|
if '<math' in content_start or '<mml:math' in content_start:
|
|
return MathMLParser()
|
|
|
|
# If it's a file path but not .docx, check file content
|
|
if os.path.exists(source):
|
|
try:
|
|
with open(source, 'r', encoding='utf-8') as f:
|
|
file_content = f.read(500) # Read first 500 chars
|
|
if '<m:oMath' in file_content:
|
|
return OmmlParser()
|
|
elif '<math' in file_content or '<mml:math' in file_content:
|
|
return MathMLParser()
|
|
except (UnicodeDecodeError, IOError):
|
|
# Binary file or read error - not a supported format
|
|
pass
|
|
|
|
# Unable to determine format
|
|
preview = source if len(source) <= 100 else source[:100] + "..."
|
|
raise ValueError(
|
|
f"Unable to determine input format for source: '{preview}'. "
|
|
f"Supported formats: .docx files, OMML XML (<m:oMath), MathML XML (<math)"
|
|
)
|
|
|
|
@staticmethod
|
|
def detect_parser_type(source: str) -> str:
|
|
"""
|
|
Detect the parser type needed for the input source.
|
|
|
|
Args:
|
|
source: Input source (file path or content string)
|
|
|
|
Returns:
|
|
Parser type string ("docx", "omml", or "mathml")
|
|
|
|
Raises:
|
|
ValueError: If input format cannot be determined
|
|
|
|
Examples:
|
|
>>> factory = InputParserFactory()
|
|
>>> factory.detect_parser_type("equations.docx")
|
|
'docx'
|
|
|
|
>>> factory.detect_parser_type("<math><mi>x</mi></math>")
|
|
'mathml'
|
|
"""
|
|
parser = InputParserFactory.create_parser(source)
|
|
return parser.parser_type
|
|
|
|
@staticmethod
|
|
def get_supported_formats() -> List[str]:
|
|
"""
|
|
Get list of supported input formats.
|
|
|
|
Returns:
|
|
List of format identifiers that can be parsed
|
|
"""
|
|
return ["docx", "omml", "mathml"]
|
|
|
|
def __repr__(self) -> str:
|
|
"""String representation for debugging."""
|
|
return "InputParserFactory(docx, omml, mathml)"
|