fix(docreader): detect legacy doc payloads

This commit is contained in:
wizardchen
2026-07-11 12:03:43 +08:00
committed by lyingbug
parent ac8c5c5540
commit 083e9738f6
2 changed files with 85 additions and 6 deletions
+27 -6
View File
@@ -8,6 +8,28 @@ from docreader.parser.web_parser import WebParser
logger = logging.getLogger(__name__)
# OLE Compound File magic used by legacy binary Microsoft Office files.
# Some WPS/Word documents keep this payload while being renamed to .docx.
_OLE_COMPOUND_FILE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
def detect_effective_file_type(file_type: str, content: bytes) -> str:
"""Return the parser file type after checking trustworthy file magic.
OOXML ``.docx`` files are ZIP containers, while legacy ``.doc`` files
use the OLE Compound File format. Word and WPS tolerate a legacy file
renamed to ``.docx``, so route that well-known mismatch through the DOC
parser instead of feeding binary OLE data to the DOCX parser.
"""
normalized = file_type.lower().lstrip(".")
if normalized == "docx" and content.startswith(_OLE_COMPOUND_FILE_MAGIC):
logger.warning(
"Detected legacy DOC content with a DOCX extension; using DOC parser"
)
return "doc"
return normalized
class Parser:
"""Document parser facade (lightweight version).
@@ -40,15 +62,16 @@ class Parser:
engine or "builtin",
)
cls = self.registry.get_parser_class(engine, file_type)
effective_file_type = detect_effective_file_type(file_type, content)
cls = self.registry.get_parser_class(engine, effective_file_type)
logger.info(
"Creating %s parser instance for %s file",
cls.__name__,
file_type,
effective_file_type,
)
parser = cls(
file_name=file_name,
file_type=file_type,
file_type=effective_file_type,
**overrides,
)
@@ -57,9 +80,7 @@ class Parser:
if not result.content:
logger.warning("Parser returned empty content for file: %s", file_name)
logger.info(
"Parsed file %s, content length=%d", file_name, len(result.content)
)
logger.info("Parsed file %s, content length=%d", file_name, len(result.content))
return result
def parse_url(