chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
Parser module for Academy document processing system.
|
||||
|
||||
This module provides document parsers for various file formats including:
|
||||
- Microsoft Word documents (.doc, .docx)
|
||||
- PDF documents
|
||||
- Markdown files
|
||||
- Plain text files
|
||||
- Images with text content
|
||||
- Web pages
|
||||
|
||||
The parsers extract content from documents and can split them into
|
||||
meaningful chunks for further processing and indexing.
|
||||
"""
|
||||
|
||||
from .doc_parser import DocParser
|
||||
from .docx2_parser import Docx2Parser
|
||||
from .excel_parser import ExcelParser
|
||||
from .html_parser import HTMLParser
|
||||
from .image_parser import ImageParser
|
||||
from .markdown_parser import MarkdownParser
|
||||
from .parser import Parser
|
||||
from .pdf_parser import PDFParser
|
||||
from .registry import ParserEngineRegistry, registry
|
||||
from .web_parser import WebParser
|
||||
|
||||
# Export public classes and modules
|
||||
__all__ = [
|
||||
"Docx2Parser",
|
||||
"DocParser",
|
||||
"PDFParser",
|
||||
"MarkdownParser",
|
||||
"ImageParser",
|
||||
"WebParser",
|
||||
"Parser",
|
||||
"ExcelParser",
|
||||
"HTMLParser",
|
||||
"ParserEngineRegistry",
|
||||
"registry",
|
||||
]
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
import os
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional
|
||||
|
||||
from docreader.models.document import Document
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
|
||||
class BaseParser(ABC):
|
||||
"""Base parser interface.
|
||||
|
||||
After the lightweight refactoring, BaseParser only extracts markdown text
|
||||
and raw image references from documents. Chunking, image storage, OCR,
|
||||
and VLM caption are handled by the Go App module.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
file_name: str = "",
|
||||
file_type: Optional[str] = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.file_name = file_name
|
||||
self.file_type = file_type or os.path.splitext(file_name)[1].lstrip(".")
|
||||
|
||||
logger.info(
|
||||
"Initializing parser for file=%s, type=%s",
|
||||
file_name,
|
||||
self.file_type,
|
||||
)
|
||||
|
||||
@abstractmethod
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse document content into markdown text.
|
||||
|
||||
Returns:
|
||||
Document with ``content`` (markdown string) and optional
|
||||
``images`` dict mapping storage-relative paths to base64 data.
|
||||
"""
|
||||
|
||||
def parse(self, content: bytes) -> Document:
|
||||
"""Parse document and return markdown + image references.
|
||||
|
||||
No chunking, no OCR, no VLM caption — those are done in Go.
|
||||
"""
|
||||
logger.info(
|
||||
"Parsing document with %s, bytes: %d",
|
||||
self.__class__.__name__,
|
||||
len(content),
|
||||
)
|
||||
document = self.parse_into_text(content)
|
||||
logger.info(
|
||||
"Extracted %d characters from %s",
|
||||
len(document.content),
|
||||
self.file_name,
|
||||
)
|
||||
return document
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
Chain Parser Module
|
||||
|
||||
This module provides two chain-of-responsibility pattern implementations for document parsing:
|
||||
1. FirstParser: Tries multiple parsers sequentially until one succeeds
|
||||
2. PipelineParser: Chains parsers where each parser processes the output of the previous one
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Dict, List, Tuple, Type
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.utils import endecode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
|
||||
class FirstParser(BaseParser):
|
||||
"""
|
||||
First-success parser that tries multiple parsers in sequence.
|
||||
|
||||
This parser attempts to parse content using each registered parser in order.
|
||||
It returns the result from the first parser that successfully produces a valid document.
|
||||
If all parsers fail, it returns an empty Document.
|
||||
|
||||
Usage:
|
||||
# Create a custom FirstParser with specific parser classes
|
||||
CustomParser = FirstParser.create(MarkdownParser, HTMLParser)
|
||||
parser = CustomParser()
|
||||
document = parser.parse_into_text(content_bytes)
|
||||
"""
|
||||
|
||||
# Tuple of parser classes to be instantiated
|
||||
_parser_cls: Tuple[Type["BaseParser"], ...] = ()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize FirstParser with configured parser classes."""
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Instantiate all parser classes into parser instances
|
||||
self._parsers: List[BaseParser] = []
|
||||
for parser_cls in self._parser_cls:
|
||||
parser = parser_cls(*args, **kwargs)
|
||||
self._parsers.append(parser)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse content using the first parser that succeeds.
|
||||
|
||||
Args:
|
||||
content: Raw bytes content to be parsed
|
||||
|
||||
Returns:
|
||||
Document: Parsed document from the first successful parser,
|
||||
or an empty Document if all parsers fail
|
||||
"""
|
||||
for p in self._parsers:
|
||||
logger.info(f"FirstParser: using parser {p.__class__.__name__}")
|
||||
try:
|
||||
document = p.parse_into_text(content)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"FirstParser: parser %s raised exception; trying next parser",
|
||||
p.__class__.__name__,
|
||||
)
|
||||
continue
|
||||
|
||||
if document.is_valid():
|
||||
logger.info(f"FirstParser: parser {p.__class__.__name__} succeeded")
|
||||
return document
|
||||
return Document()
|
||||
|
||||
@classmethod
|
||||
def create(cls, *parser_classes: Type["BaseParser"]) -> Type["FirstParser"]:
|
||||
"""Factory method to create a FirstParser subclass with specific parsers.
|
||||
|
||||
Args:
|
||||
*parser_classes: Variable number of BaseParser subclasses to try in order
|
||||
|
||||
Returns:
|
||||
Type[FirstParser]: A new FirstParser subclass configured with the given parsers
|
||||
|
||||
Example:
|
||||
CustomParser = FirstParser.create(MarkdownParser, HTMLParser)
|
||||
parser = CustomParser()
|
||||
"""
|
||||
# Generate a descriptive class name based on parser names
|
||||
names = "_".join([p.__name__ for p in parser_classes])
|
||||
# Dynamically create a new class with the parser configuration
|
||||
return type(f"FirstParser_{names}", (cls,), {"_parser_cls": parser_classes})
|
||||
|
||||
|
||||
class PipelineParser(BaseParser):
|
||||
"""
|
||||
Pipeline parser that chains multiple parsers sequentially.
|
||||
|
||||
This parser processes content through a series of parsers where each parser
|
||||
receives the output of the previous parser as input. Images from all parsers
|
||||
are accumulated and merged into the final document.
|
||||
|
||||
Usage:
|
||||
# Create a custom PipelineParser with specific parser classes
|
||||
CustomParser = PipelineParser.create(PreParser, MarkdownParser, PostParser)
|
||||
parser = CustomParser()
|
||||
document = parser.parse_into_text(content_bytes)
|
||||
"""
|
||||
|
||||
# Tuple of parser classes to be instantiated and chained
|
||||
_parser_cls: Tuple[Type["BaseParser"], ...] = ()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize PipelineParser with configured parser classes."""
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Instantiate all parser classes into parser instances
|
||||
self._parsers: List[BaseParser] = []
|
||||
for parser_cls in self._parser_cls:
|
||||
parser = parser_cls(*args, **kwargs)
|
||||
self._parsers.append(parser)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse content through a pipeline of parsers.
|
||||
|
||||
Each parser in the pipeline processes the output of the previous parser.
|
||||
Images from all parsers are accumulated and merged into the final document.
|
||||
|
||||
Args:
|
||||
content: Raw bytes content to be parsed
|
||||
|
||||
Returns:
|
||||
Document: Final document after processing through all parsers,
|
||||
with accumulated images from all stages
|
||||
"""
|
||||
# Accumulate images and metadata from all parsers
|
||||
images: Dict[str, str] = {}
|
||||
metadata: Dict = {}
|
||||
document = Document()
|
||||
for p in self._parsers:
|
||||
logger.info(f"PipelineParser: using parser {p.__class__.__name__}")
|
||||
# Parse content with current parser
|
||||
document = p.parse_into_text(content)
|
||||
# Convert document content back to bytes for next parser
|
||||
content = endecode.encode_bytes(document.content)
|
||||
# Accumulate images and metadata from this parser
|
||||
images.update(document.images)
|
||||
metadata.update(document.metadata)
|
||||
# Merge all accumulated images and metadata into final document
|
||||
document.images.update(images)
|
||||
document.metadata.update(metadata)
|
||||
return document
|
||||
|
||||
@classmethod
|
||||
def create(cls, *parser_classes: Type["BaseParser"]) -> Type["PipelineParser"]:
|
||||
"""Factory method to create a PipelineParser subclass with specific parsers.
|
||||
|
||||
Args:
|
||||
*parser_classes: Variable number of BaseParser subclasses to chain in order
|
||||
|
||||
Returns:
|
||||
Type[PipelineParser]: A new PipelineParser subclass configured with the given parsers
|
||||
|
||||
Example:
|
||||
CustomParser = PipelineParser.create(PreprocessParser, MarkdownParser)
|
||||
parser = CustomParser()
|
||||
"""
|
||||
# Generate a descriptive class name based on parser names
|
||||
names = "_".join([p.__name__ for p in parser_classes])
|
||||
# Dynamically create a new class with the parser configuration
|
||||
return type(f"PipelineParser_{names}", (cls,), {"_parser_cls": parser_classes})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
|
||||
# Example: Create and use a FirstParser with MarkdownParser
|
||||
FpCls = FirstParser.create(MarkdownParser)
|
||||
lparser = FpCls()
|
||||
print(lparser.parse_into_text(b"aaa"))
|
||||
@@ -0,0 +1,39 @@
|
||||
import logging
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from typing import Dict, Iterator
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_LIMITERS: Dict[str, threading.BoundedSemaphore] = {}
|
||||
_LIMITERS_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _get_limiter(name: str, max_workers: int) -> threading.BoundedSemaphore:
|
||||
with _LIMITERS_LOCK:
|
||||
limiter = _LIMITERS.get(name)
|
||||
if limiter is None:
|
||||
limiter = threading.BoundedSemaphore(max_workers)
|
||||
_LIMITERS[name] = limiter
|
||||
return limiter
|
||||
|
||||
|
||||
@contextmanager
|
||||
def parser_worker_limit(name: str, max_workers: int) -> Iterator[None]:
|
||||
"""Limit concurrent access to heavy, process-wide parser operations.
|
||||
|
||||
Set max_workers <= 0 to disable throttling for deployments that have enough
|
||||
CPU/GPU resources and know the parser backend is safe under concurrency.
|
||||
"""
|
||||
|
||||
if max_workers <= 0:
|
||||
yield
|
||||
return
|
||||
|
||||
limiter = _get_limiter(name, max_workers)
|
||||
logger.debug("Waiting for %s parser slot (max_workers=%d)", name, max_workers)
|
||||
limiter.acquire()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
limiter.release()
|
||||
@@ -0,0 +1,434 @@
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
import textract
|
||||
|
||||
from docreader.config import CONFIG
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.docx2_parser import Docx2Parser
|
||||
from docreader.utils.tempfile import TempDirContext, TempFileContext
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SandboxExecutor:
|
||||
"""Sandbox executor for running commands with proxy configuration"""
|
||||
|
||||
def __init__(self, proxy: Optional[str] = None, default_timeout: int = 60):
|
||||
"""Initialize sandbox executor with configuration
|
||||
|
||||
Args:
|
||||
proxy: Proxy URL to use for network access. If None, will use WEB_PROXY environment variable
|
||||
default_timeout: Default timeout in seconds for command execution
|
||||
"""
|
||||
# Get proxy from parameter, environment variable, or use default blocking proxy
|
||||
# Use 'or None' to convert empty string to None, then apply default value
|
||||
self.proxy = proxy or CONFIG.external_https_proxy or "http://128.0.0.1:1"
|
||||
self.default_timeout = default_timeout
|
||||
|
||||
def execute_in_sandbox(self, cmd: List[str]) -> tuple:
|
||||
"""Execute command in sandbox with proxy configuration
|
||||
|
||||
Args:
|
||||
cmd: Command to execute
|
||||
|
||||
Returns:
|
||||
Tuple of (stdout, stderr, returncode)
|
||||
"""
|
||||
# Try different sandbox methods in order of preference
|
||||
sandbox_methods = [
|
||||
self._execute_with_proxy,
|
||||
]
|
||||
|
||||
for method in sandbox_methods:
|
||||
try:
|
||||
return method(cmd)
|
||||
except Exception as e:
|
||||
logger.warning(f"Sandbox method {method.__name__} failed: {e}")
|
||||
continue
|
||||
|
||||
raise RuntimeError("All sandbox methods failed")
|
||||
|
||||
def _execute_with_proxy(self, cmd: List[str]) -> tuple:
|
||||
"""Execute command with proxy configuration
|
||||
|
||||
Args:
|
||||
cmd: Command to execute
|
||||
|
||||
Returns:
|
||||
Tuple of (stdout, stderr, returncode)
|
||||
"""
|
||||
# Set up environment with proxy configuration
|
||||
env = os.environ.copy()
|
||||
if self.proxy:
|
||||
env["http_proxy"] = self.proxy
|
||||
env["https_proxy"] = self.proxy
|
||||
env["HTTP_PROXY"] = self.proxy
|
||||
env["HTTPS_PROXY"] = self.proxy
|
||||
|
||||
logger.info(f"Executing command with proxy: {' '.join(cmd)}")
|
||||
if self.proxy:
|
||||
logger.info(f"Using proxy: {self.proxy}")
|
||||
|
||||
is_posix = os.name == "posix"
|
||||
process = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=env,
|
||||
# On POSIX, start a fresh group so a timed-out command can be
|
||||
# terminated together with children it spawned (e.g. soffice.bin).
|
||||
start_new_session=is_posix,
|
||||
)
|
||||
# On POSIX start_new_session makes the direct child the group leader, so
|
||||
# retain this ID even if the direct child exits before cleanup starts.
|
||||
process_group_id = process.pid if is_posix else None
|
||||
|
||||
try:
|
||||
stdout, stderr = process.communicate(timeout=self.default_timeout)
|
||||
return stdout, stderr, process.returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
# Terminate the POSIX process group (or the direct child elsewhere),
|
||||
# then reap with a bounded wait. Do not drain pipes here:
|
||||
# communicate() waits for EOF and can hang if a descendant left
|
||||
# the group (setsid) or otherwise kept a PIPE writer open.
|
||||
try:
|
||||
self._kill_timed_out_command(process, process_group_id)
|
||||
finally:
|
||||
self._reap_timed_out_process(process)
|
||||
raise RuntimeError(
|
||||
f"Command execution timeout after {self.default_timeout} seconds"
|
||||
)
|
||||
|
||||
def _kill_timed_out_command(
|
||||
self, process: subprocess.Popen, process_group_id: Optional[int]
|
||||
) -> None:
|
||||
if process_group_id is None:
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
|
||||
self._signal_process_group(process_group_id, signal.SIGTERM)
|
||||
grace_period = 0.5
|
||||
grace_deadline = time.monotonic() + grace_period
|
||||
try:
|
||||
process.wait(timeout=grace_period)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
remaining_grace_period = grace_deadline - time.monotonic()
|
||||
if remaining_grace_period > 0:
|
||||
time.sleep(remaining_grace_period)
|
||||
# The direct child can exit after SIGTERM while a descendant
|
||||
# ignores it. Always finish the grace period with SIGKILL.
|
||||
self._signal_process_group(process_group_id, signal.SIGKILL)
|
||||
|
||||
@staticmethod
|
||||
def _signal_process_group(process_group_id: int, sig: int) -> None:
|
||||
try:
|
||||
os.killpg(process_group_id, sig)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _reap_timed_out_process(
|
||||
process: subprocess.Popen, timeout: float = 1.0
|
||||
) -> None:
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning(
|
||||
"Timed-out command pid=%s did not exit after SIGKILL",
|
||||
process.pid,
|
||||
)
|
||||
finally:
|
||||
for pipe in (process.stdout, process.stderr):
|
||||
if pipe is not None:
|
||||
try:
|
||||
pipe.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DocParser(Docx2Parser):
|
||||
"""DOC document parser"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize DOC parser with sandbox executor"""
|
||||
super().__init__(*args, **kwargs)
|
||||
self.sandbox_executor = SandboxExecutor()
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
logger.info(f"Parsing DOC document, content size: {len(content)} bytes")
|
||||
|
||||
handle_chain = [
|
||||
# 1. Try to convert to docx format to extract images
|
||||
self._parse_with_docx,
|
||||
# 2. If image extraction is not needed or conversion failed,
|
||||
# try using antiword to extract text
|
||||
self._parse_with_antiword,
|
||||
# 3. If antiword extraction fails, use textract
|
||||
# NOTE: _parse_with_textract is disabled due to SSRF vulnerability
|
||||
# self._parse_with_textract,
|
||||
]
|
||||
|
||||
# Save byte content as a temporary file
|
||||
with TempFileContext(content, ".doc") as temp_file_path:
|
||||
for handle in handle_chain:
|
||||
try:
|
||||
document = handle(temp_file_path)
|
||||
if document:
|
||||
return document
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to parse DOC with {handle.__name__} {e}")
|
||||
|
||||
return Document(content="")
|
||||
|
||||
def _parse_with_docx(self, temp_file_path: str) -> Document:
|
||||
logger.info("Multimodal enabled, attempting to extract images from DOC")
|
||||
|
||||
docx_content = self._try_convert_doc_to_docx(temp_file_path)
|
||||
if not docx_content:
|
||||
raise RuntimeError("Failed to convert DOC to DOCX")
|
||||
|
||||
logger.info("Successfully converted DOC to DOCX, using DocxParser")
|
||||
# Use existing DocxParser to parse the converted docx
|
||||
document = super(Docx2Parser, self).parse_into_text(docx_content)
|
||||
logger.info(f"Extracted {len(document.content)} characters using DocxParser")
|
||||
return document
|
||||
|
||||
def _parse_with_antiword(self, temp_file_path: str) -> Document:
|
||||
logger.info("Attempting to parse DOC file with antiword")
|
||||
|
||||
# Check if antiword is installed
|
||||
antiword_path = self._try_find_antiword()
|
||||
if not antiword_path:
|
||||
raise RuntimeError("antiword not found in PATH")
|
||||
|
||||
# Use antiword to extract text directly in sandbox
|
||||
cmd = [antiword_path, temp_file_path]
|
||||
logger.info("Executing antiword in sandbox with proxy configuration")
|
||||
|
||||
stdout, stderr, returncode = self.sandbox_executor.execute_in_sandbox(cmd)
|
||||
|
||||
if returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"antiword extraction failed: {stderr.decode('utf-8', errors='ignore')}"
|
||||
)
|
||||
text = stdout.decode("utf-8", errors="ignore")
|
||||
logger.info(f"Successfully extracted {len(text)} characters using antiword")
|
||||
return Document(content=text)
|
||||
|
||||
def _parse_with_textract(self, temp_file_path: str) -> Document:
|
||||
logger.info(f"Parsing DOC file with textract: {temp_file_path}")
|
||||
text = textract.process(temp_file_path, method="antiword").decode("utf-8")
|
||||
logger.info(f"Successfully extracted {len(text)} bytes of DOC using textract")
|
||||
return Document(content=str(text))
|
||||
|
||||
def _try_convert_doc_to_docx(self, doc_path: str) -> Optional[bytes]:
|
||||
"""Convert DOC file to DOCX format
|
||||
|
||||
Uses LibreOffice/OpenOffice for conversion
|
||||
|
||||
Args:
|
||||
doc_path: DOC file path
|
||||
|
||||
Returns:
|
||||
Byte stream of DOCX file content, or None if conversion fails
|
||||
"""
|
||||
logger.info(f"Converting DOC to DOCX: {doc_path}")
|
||||
|
||||
# Check if LibreOffice or OpenOffice is installed
|
||||
soffice_path = self._try_find_soffice()
|
||||
if not soffice_path:
|
||||
return None
|
||||
|
||||
# Execute conversion command
|
||||
logger.info(f"Using {soffice_path} to convert DOC to DOCX")
|
||||
|
||||
# LibreOffice shares a single user profile by default, so concurrent
|
||||
# `soffice` invocations contend for the same profile lock and the loser
|
||||
# silently fails to convert. Give each attempt a dedicated profile dir
|
||||
# and retry a few times so concurrent requests don't fall back to the
|
||||
# lower-fidelity antiword path.
|
||||
max_attempts = 3
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
# Create a temporary directory to store the converted file
|
||||
with TempDirContext() as temp_dir, TempDirContext() as profile_dir:
|
||||
user_installation = Path(profile_dir).as_uri()
|
||||
cmd = [
|
||||
soffice_path,
|
||||
"--headless",
|
||||
f"-env:UserInstallation={user_installation}",
|
||||
"--convert-to",
|
||||
"docx",
|
||||
"--outdir",
|
||||
temp_dir,
|
||||
doc_path,
|
||||
]
|
||||
logger.info(
|
||||
f"Running command in sandbox (attempt {attempt}/{max_attempts}): "
|
||||
f"{' '.join(cmd)}"
|
||||
)
|
||||
|
||||
# Execute in sandbox with proxy configuration
|
||||
stdout, stderr, returncode = self.sandbox_executor.execute_in_sandbox(
|
||||
cmd
|
||||
)
|
||||
|
||||
if returncode != 0:
|
||||
logger.warning(
|
||||
f"Error converting DOC to DOCX (attempt {attempt}/"
|
||||
f"{max_attempts}): {stderr.decode('utf-8', errors='ignore')}"
|
||||
)
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.5 * attempt)
|
||||
continue
|
||||
return None
|
||||
|
||||
# Find the converted file
|
||||
docx_file = [
|
||||
file for file in os.listdir(temp_dir) if file.endswith(".docx")
|
||||
]
|
||||
logger.info(
|
||||
f"Found {len(docx_file)} DOCX file(s) in temporary directory"
|
||||
)
|
||||
for file in docx_file:
|
||||
converted_file = os.path.join(temp_dir, file)
|
||||
logger.info(f"Found converted file: {converted_file}")
|
||||
|
||||
# Read the converted file content
|
||||
with open(converted_file, "rb") as f:
|
||||
docx_content = f.read()
|
||||
logger.info(
|
||||
f"Successfully read DOCX file, size: {len(docx_content)}"
|
||||
)
|
||||
return docx_content
|
||||
|
||||
# Conversion reported success but produced no docx; retry.
|
||||
logger.warning(
|
||||
f"No DOCX produced despite success (attempt {attempt}/"
|
||||
f"{max_attempts})"
|
||||
)
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.5 * attempt)
|
||||
return None
|
||||
|
||||
def _try_find_executable_path(
|
||||
self,
|
||||
executable_name: str,
|
||||
possible_path: List[str] = [],
|
||||
environment_variable: List[str] = [],
|
||||
) -> Optional[str]:
|
||||
"""Find executable path
|
||||
Args:
|
||||
executable_name: Executable name
|
||||
possible_path: List of possible paths
|
||||
environment_variable: List of environment variables to check
|
||||
Returns:
|
||||
Executable path, or None if not found
|
||||
"""
|
||||
# Common executable paths
|
||||
paths: List[str] = []
|
||||
paths.extend(possible_path)
|
||||
paths.extend(os.environ.get(env_var, "") for env_var in environment_variable)
|
||||
paths = list(set(paths))
|
||||
|
||||
# Check if path is set in environment variable
|
||||
for path in paths:
|
||||
if os.path.exists(path):
|
||||
logger.info(f"Found {executable_name} at {path}")
|
||||
return path
|
||||
|
||||
# Try to find in PATH
|
||||
result = subprocess.run(
|
||||
["which", executable_name], capture_output=True, text=True
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
path = result.stdout.strip()
|
||||
logger.info(f"Found {executable_name} at {path}")
|
||||
return path
|
||||
|
||||
logger.warning(f"Failed to find {executable_name}")
|
||||
return None
|
||||
|
||||
def _try_find_soffice(self) -> Optional[str]:
|
||||
"""Find LibreOffice/OpenOffice executable path
|
||||
|
||||
Returns:
|
||||
Executable path, or None if not found
|
||||
"""
|
||||
# Common LibreOffice/OpenOffice executable paths
|
||||
possible_paths = [
|
||||
# Linux
|
||||
"/usr/bin/soffice",
|
||||
"/usr/lib/libreoffice/program/soffice",
|
||||
"/opt/libreoffice25.2/program/soffice",
|
||||
# macOS
|
||||
"/Applications/LibreOffice.app/Contents/MacOS/soffice",
|
||||
# Windows
|
||||
"C:\\Program Files\\LibreOffice\\program\\soffice.exe",
|
||||
"C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe",
|
||||
]
|
||||
return self._try_find_executable_path(
|
||||
executable_name="soffice",
|
||||
possible_path=possible_paths,
|
||||
environment_variable=["LIBREOFFICE_PATH"],
|
||||
)
|
||||
|
||||
def _try_find_antiword(self) -> Optional[str]:
|
||||
"""Find antiword executable path
|
||||
|
||||
Returns:
|
||||
Executable path, or None if not found
|
||||
"""
|
||||
# Common antiword executable paths
|
||||
possible_paths = [
|
||||
# Linux/macOS
|
||||
"/usr/bin/antiword",
|
||||
"/usr/local/bin/antiword",
|
||||
# Windows
|
||||
"C:\\Program Files\\Antiword\\antiword.exe",
|
||||
"C:\\Program Files (x86)\\Antiword\\antiword.exe",
|
||||
]
|
||||
return self._try_find_executable_path(
|
||||
executable_name="antiword",
|
||||
possible_path=possible_paths,
|
||||
environment_variable=["ANTIWORD_PATH"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
file_name = "/path/to/your/test.doc"
|
||||
logger.info(f"Processing file: {file_name}")
|
||||
doc_parser = DocParser(
|
||||
file_name=file_name,
|
||||
enable_multimodal=True,
|
||||
chunk_size=512,
|
||||
chunk_overlap=60,
|
||||
)
|
||||
with open(file_name, "rb") as f:
|
||||
content = f.read()
|
||||
|
||||
document = doc_parser.parse_into_text(content)
|
||||
logger.info(f"Processing complete, extracted text length: {len(document.content)}")
|
||||
logger.info(f"Sample text: {document.content[:200]}...")
|
||||
@@ -0,0 +1,28 @@
|
||||
import logging
|
||||
|
||||
from docreader.parser.chain_parser import FirstParser
|
||||
from docreader.parser.docx_parser import DocxParser
|
||||
from docreader.parser.markitdown_parser import MarkitdownParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Docx2Parser(FirstParser):
|
||||
_parser_cls = (MarkitdownParser, DocxParser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
your_file = "/path/to/your/file.docx"
|
||||
parser = Docx2Parser(separators=[".", "?", "!", "。", "?", "!"])
|
||||
with open(your_file, "rb") as f:
|
||||
content = f.read()
|
||||
|
||||
document = parser.parse(content)
|
||||
for cc in document.chunks:
|
||||
logger.info(f"chunk: {cc}")
|
||||
|
||||
# document = parser.parse_into_text(content)
|
||||
# logger.info(f"docx content: {document.content}")
|
||||
# logger.info(f"find images {document.images.keys()}")
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Expand vertically merged DOCX table cells before Markdown conversion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import io
|
||||
import logging
|
||||
import zipfile
|
||||
|
||||
from lxml import etree
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_WORD_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
||||
_W = f"{{{_WORD_NAMESPACE}}}"
|
||||
_TC_PR = f"{_W}tcPr"
|
||||
_VMERGE = f"{_W}vMerge"
|
||||
_GRID_SPAN = f"{_W}gridSpan"
|
||||
_TR_PR = f"{_W}trPr"
|
||||
_GRID_BEFORE = f"{_W}gridBefore"
|
||||
_VAL = f"{_W}val"
|
||||
|
||||
|
||||
def fill_vertical_merged_cells_docx(content: bytes) -> bytes:
|
||||
"""Repeat a vertical merge's master content in every covered table row.
|
||||
|
||||
DOCX stores vertical merges as a ``vMerge=restart`` cell followed by empty
|
||||
``vMerge=continue`` cells. Mammoth preserves that as an HTML ``rowspan``,
|
||||
but Markdown tables cannot represent row spans and the later rows lose the
|
||||
merged value. This rewrites only Word XML parts that contain ``vMerge``;
|
||||
all other package parts and documents without vertical merges pass through
|
||||
unchanged.
|
||||
"""
|
||||
source = io.BytesIO(content)
|
||||
if not zipfile.is_zipfile(source):
|
||||
return content
|
||||
|
||||
with zipfile.ZipFile(source, "r") as archive:
|
||||
normalized_names = {
|
||||
info.filename.replace("\\", "/") for info in archive.infolist()
|
||||
}
|
||||
if "word/document.xml" not in normalized_names:
|
||||
return content
|
||||
|
||||
rewritten_parts: dict[str, bytes] = {}
|
||||
filled_count = 0
|
||||
for info in archive.infolist():
|
||||
name = info.filename.replace("\\", "/")
|
||||
if not name.startswith("word/") or not name.endswith(".xml"):
|
||||
continue
|
||||
|
||||
data = archive.read(info.filename)
|
||||
if b"vMerge" not in data:
|
||||
continue
|
||||
rewritten, part_filled_count = _fill_vertical_merges_in_xml(data)
|
||||
if rewritten is not None:
|
||||
rewritten_parts[info.filename] = rewritten
|
||||
filled_count += part_filled_count
|
||||
|
||||
if not rewritten_parts:
|
||||
return content
|
||||
|
||||
output = io.BytesIO()
|
||||
with zipfile.ZipFile(output, "w") as rewritten_archive:
|
||||
for info in archive.infolist():
|
||||
data = rewritten_parts.get(info.filename)
|
||||
if data is None:
|
||||
data = archive.read(info.filename)
|
||||
rewritten_archive.writestr(info, data)
|
||||
|
||||
logger.info(
|
||||
"Expanded %d vertically merged DOCX continuation cells before parse",
|
||||
filled_count,
|
||||
)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def _fill_vertical_merges_in_xml(data: bytes) -> tuple[bytes | None, int]:
|
||||
parser = etree.XMLParser(resolve_entities=False, no_network=True)
|
||||
try:
|
||||
root = etree.fromstring(data, parser=parser)
|
||||
except etree.XMLSyntaxError:
|
||||
return None, 0
|
||||
|
||||
changed = False
|
||||
filled_count = 0
|
||||
# Process nested tables first so copied cell content is already normalized.
|
||||
for table in reversed(root.xpath(".//w:tbl", namespaces={"w": _WORD_NAMESPACE})):
|
||||
table_changed, table_filled_count = _fill_table_vertical_merges(table)
|
||||
changed = changed or table_changed
|
||||
filled_count += table_filled_count
|
||||
|
||||
if not changed:
|
||||
return None, 0
|
||||
return etree.tostring(root, xml_declaration=True, encoding="UTF-8"), filled_count
|
||||
|
||||
|
||||
def _fill_table_vertical_merges(table: etree._Element) -> tuple[bool, int]:
|
||||
active_merges: dict[int, tuple[etree._Element, ...]] = {}
|
||||
changed = False
|
||||
filled_count = 0
|
||||
|
||||
for row in table.findall(f"{_W}tr"):
|
||||
next_active_merges: dict[int, tuple[etree._Element, ...]] = {}
|
||||
column = _grid_before(row)
|
||||
|
||||
for cell in row.findall(f"{_W}tc"):
|
||||
cell_properties = cell.find(_TC_PR)
|
||||
span = _grid_span(cell_properties)
|
||||
occupied_columns = range(column, column + span)
|
||||
vertical_merge = (
|
||||
cell_properties.find(_VMERGE) if cell_properties is not None else None
|
||||
)
|
||||
|
||||
if vertical_merge is not None:
|
||||
merge_type = vertical_merge.get(_VAL, "continue")
|
||||
if merge_type == "restart":
|
||||
template = tuple(
|
||||
copy.deepcopy(child) for child in cell if child.tag != _TC_PR
|
||||
)
|
||||
for occupied_column in occupied_columns:
|
||||
next_active_merges[occupied_column] = template
|
||||
cell_properties.remove(vertical_merge)
|
||||
changed = True
|
||||
else:
|
||||
template = next(
|
||||
(
|
||||
active_merges[occupied_column]
|
||||
for occupied_column in occupied_columns
|
||||
if occupied_column in active_merges
|
||||
),
|
||||
None,
|
||||
)
|
||||
if template is not None:
|
||||
for child in list(cell):
|
||||
if child.tag != _TC_PR:
|
||||
cell.remove(child)
|
||||
for child in template:
|
||||
cell.append(copy.deepcopy(child))
|
||||
for occupied_column in occupied_columns:
|
||||
next_active_merges[occupied_column] = template
|
||||
cell_properties.remove(vertical_merge)
|
||||
changed = True
|
||||
filled_count += 1
|
||||
|
||||
column += span
|
||||
|
||||
active_merges = next_active_merges
|
||||
|
||||
return changed, filled_count
|
||||
|
||||
|
||||
def _grid_span(cell_properties: etree._Element | None) -> int:
|
||||
if cell_properties is None:
|
||||
return 1
|
||||
grid_span = cell_properties.find(_GRID_SPAN)
|
||||
if grid_span is None:
|
||||
return 1
|
||||
return _positive_int(grid_span.get(_VAL), default=1)
|
||||
|
||||
|
||||
def _grid_before(row: etree._Element) -> int:
|
||||
row_properties = row.find(_TR_PR)
|
||||
if row_properties is None:
|
||||
return 0
|
||||
grid_before = row_properties.find(_GRID_BEFORE)
|
||||
if grid_before is None:
|
||||
return 0
|
||||
return _positive_int(grid_before.get(_VAL), default=0)
|
||||
|
||||
|
||||
def _positive_int(value: str | None, default: int) -> int:
|
||||
try:
|
||||
parsed = int(value or "")
|
||||
except ValueError:
|
||||
return default
|
||||
return parsed if parsed >= 0 else default
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,347 @@
|
||||
"""EPUB parser.
|
||||
|
||||
Parses EPUB files into markdown text and optional embedded images.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import posixpath
|
||||
import tempfile
|
||||
from urllib.parse import unquote, urlsplit
|
||||
import uuid
|
||||
from typing import Dict
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
import ebooklib
|
||||
from ebooklib import epub
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.mhtml_parser import MHTMLParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EPUBParser(BaseParser):
|
||||
"""Parser for EPUB e-book files."""
|
||||
|
||||
def __init__(self, *args, extract_images: bool = True, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.extract_images = extract_images
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
logger.info(
|
||||
"Parsing EPUB file: %s, size: %d bytes", self.file_name, len(content)
|
||||
)
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=".epub", delete=False, mode="wb"
|
||||
) as epub_file:
|
||||
epub_file.write(content)
|
||||
epub_path = epub_file.name
|
||||
try:
|
||||
book = epub.read_epub(epub_path)
|
||||
metadata = self._extract_metadata(book)
|
||||
markdown_content, images = self._extract_content(book)
|
||||
|
||||
metadata["source_format"] = "epub"
|
||||
metadata["file_size"] = len(content)
|
||||
metadata["chapter_count"] = len(
|
||||
[part for part in markdown_content.split("\n## ") if part.strip()]
|
||||
)
|
||||
metadata["image_count"] = len(images)
|
||||
return Document(
|
||||
content=markdown_content, images=images, metadata=metadata
|
||||
)
|
||||
finally:
|
||||
if os.path.exists(epub_path):
|
||||
os.unlink(epub_path)
|
||||
except ImportError:
|
||||
logger.error("ebooklib not installed")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"ebooklib failed to parse EPUB: %s, trying ZIP fallback", str(e)
|
||||
)
|
||||
return self._parse_epub_fallback(content)
|
||||
|
||||
def _parse_epub_fallback(self, content: bytes) -> Document:
|
||||
"""Parse EPUB directly as a ZIP when ebooklib cannot read it."""
|
||||
import re
|
||||
import zipfile
|
||||
from io import BytesIO
|
||||
|
||||
metadata = {"source_format": "epub", "file_size": len(content)}
|
||||
images: Dict[str, str] = {}
|
||||
image_aliases: Dict[str, str] = {}
|
||||
markdown_parts = []
|
||||
|
||||
with zipfile.ZipFile(BytesIO(content), "r") as epub_zip:
|
||||
html_files = [
|
||||
f
|
||||
for f in epub_zip.namelist()
|
||||
if f.endswith((".html", ".xhtml", ".htm"))
|
||||
]
|
||||
|
||||
def chapter_num(filename: str) -> int:
|
||||
match = re.search(r"chapter(\d+)", filename, re.IGNORECASE)
|
||||
return int(match.group(1)) if match else 999999
|
||||
|
||||
html_files.sort(key=chapter_num)
|
||||
|
||||
if self.extract_images:
|
||||
img_exts = (".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg")
|
||||
for img_file in epub_zip.namelist():
|
||||
if img_file.lower().endswith(img_exts):
|
||||
try:
|
||||
img_data = epub_zip.read(img_file)
|
||||
ext = os.path.splitext(img_file)[1]
|
||||
img_path = f"images/{uuid.uuid4().hex}{ext}"
|
||||
images[img_path] = base64.b64encode(img_data).decode(
|
||||
"utf-8"
|
||||
)
|
||||
self._add_image_aliases(image_aliases, img_file, img_path)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"Failed to extract image %s: %s", img_file, e
|
||||
)
|
||||
|
||||
for html_file in html_files:
|
||||
try:
|
||||
html_content = epub_zip.read(html_file).decode(
|
||||
"utf-8", errors="ignore"
|
||||
)
|
||||
chapter_md = self._html_to_markdown(
|
||||
html_content,
|
||||
image_aliases=image_aliases,
|
||||
base_path=posixpath.dirname(html_file),
|
||||
)
|
||||
base = os.path.basename(html_file)
|
||||
title = base.replace(".html", "").replace(".xhtml", "")
|
||||
title = re.sub(
|
||||
r"chapter[_-]?", "Chapter ", title, flags=re.IGNORECASE
|
||||
)
|
||||
title = title.replace("_", " ").replace("-", " ").title()
|
||||
if chapter_md.strip():
|
||||
markdown_parts.append(f"## {title}\n\n{chapter_md}")
|
||||
except Exception as e:
|
||||
logger.warning("Failed to process %s: %s", html_file, e)
|
||||
|
||||
metadata["chapter_count"] = len(markdown_parts)
|
||||
metadata["image_count"] = len(images)
|
||||
return Document(
|
||||
content="\n\n".join(markdown_parts), images=images, metadata=metadata
|
||||
)
|
||||
|
||||
def _extract_metadata(self, book) -> Dict[str, str]:
|
||||
metadata: Dict[str, str] = {}
|
||||
mapping = {
|
||||
"title": "title",
|
||||
"creator": "author",
|
||||
"publisher": "publisher",
|
||||
"language": "language",
|
||||
"description": "description",
|
||||
"date": "date",
|
||||
"identifier": "isbn",
|
||||
}
|
||||
for dc_key, out_key in mapping.items():
|
||||
try:
|
||||
values = book.get_metadata("DC", dc_key)
|
||||
except Exception:
|
||||
values = None
|
||||
if values:
|
||||
if out_key == "author":
|
||||
metadata[out_key] = ", ".join(value[0] for value in values)
|
||||
else:
|
||||
metadata[out_key] = values[0][0]
|
||||
return metadata
|
||||
|
||||
def _extract_content(self, book) -> tuple[str, Dict[str, str]]:
|
||||
markdown_parts = []
|
||||
images: Dict[str, str] = {}
|
||||
image_aliases: Dict[str, str] = {}
|
||||
|
||||
if self.extract_images:
|
||||
for item in book.get_items():
|
||||
if item.get_type() == ebooklib.ITEM_IMAGE:
|
||||
img_data = item.get_content()
|
||||
ext = os.path.splitext(item.get_name())[1]
|
||||
img_path = f"images/{uuid.uuid4().hex}{ext}"
|
||||
images[img_path] = base64.b64encode(img_data).decode("utf-8")
|
||||
self._add_image_aliases(image_aliases, item.get_name(), img_path)
|
||||
|
||||
for item in self._documents_in_reading_order(book):
|
||||
markdown_parts.append(
|
||||
self._process_chapter(
|
||||
item,
|
||||
toc_index=len(markdown_parts),
|
||||
image_aliases=image_aliases,
|
||||
)
|
||||
)
|
||||
|
||||
return "\n\n".join(part for part in markdown_parts if part.strip()), images
|
||||
|
||||
@staticmethod
|
||||
def _documents_in_reading_order(book) -> list:
|
||||
"""Return the book's documents in spine order.
|
||||
|
||||
The spine is the reading order. ``get_items()`` follows the manifest,
|
||||
which can list files in any order: Standard Ebooks puts the title page
|
||||
after the last chapter there. Documents the spine leaves out follow, in
|
||||
manifest order.
|
||||
"""
|
||||
documents = [
|
||||
item
|
||||
for item in book.get_items()
|
||||
if item.get_type() == ebooklib.ITEM_DOCUMENT
|
||||
]
|
||||
ordered = []
|
||||
for idref, _linear in book.spine:
|
||||
item = book.get_item_with_id(idref)
|
||||
if item in documents and item not in ordered:
|
||||
ordered.append(item)
|
||||
ordered.extend(item for item in documents if item not in ordered)
|
||||
return ordered
|
||||
|
||||
def _process_chapter(
|
||||
self,
|
||||
html_item,
|
||||
toc_index: int = 0,
|
||||
image_aliases: Dict[str, str] | None = None,
|
||||
) -> str:
|
||||
try:
|
||||
html_content = html_item.get_content()
|
||||
soup = BeautifulSoup(html_content, "lxml")
|
||||
title_tag = soup.find(["h1", "h2"])
|
||||
if title_tag:
|
||||
chapter_title = title_tag.get_text().strip()
|
||||
title_tag.decompose()
|
||||
else:
|
||||
chapter_title = html_item.get_name().replace("/", "")
|
||||
chapter_title = chapter_title.replace(".xhtml", "")
|
||||
chapter_title = chapter_title.replace("-", " ").title()
|
||||
body_html = str(soup.body) if soup.body else str(html_content)
|
||||
chapter_md = self._html_to_markdown(
|
||||
body_html,
|
||||
image_aliases=image_aliases,
|
||||
base_path=posixpath.dirname(html_item.get_name()),
|
||||
)
|
||||
return f"## {chapter_title}\n\n{chapter_md}"
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"Failed to process chapter %s: %s", html_item.get_name(), e
|
||||
)
|
||||
return f"## Chapter {toc_index + 1}\n\n[Error processing chapter: {e}]"
|
||||
|
||||
def _html_to_markdown(
|
||||
self,
|
||||
html_content: str,
|
||||
image_aliases: Dict[str, str] | None = None,
|
||||
base_path: str = "",
|
||||
) -> str:
|
||||
try:
|
||||
from bs4 import Comment
|
||||
from markdownify import markdownify as md
|
||||
|
||||
soup = BeautifulSoup(html_content, "lxml")
|
||||
for element in soup(["script", "style"]):
|
||||
element.decompose()
|
||||
for comment in soup.find_all(
|
||||
string=lambda text: isinstance(text, Comment)
|
||||
):
|
||||
comment.extract()
|
||||
self._strip_internal_links(soup)
|
||||
if image_aliases:
|
||||
self._rewrite_image_sources(soup, image_aliases, base_path)
|
||||
markdown_text = md(str(soup), heading_style="ATX")
|
||||
# Keep the blank lines and indentation that delimit Markdown blocks
|
||||
# (paragraphs, quotes, lists, tables, fenced code) and only collapse
|
||||
# runs of blank lines, as the MHTML and static HTML parsers do.
|
||||
return MHTMLParser._normalize_markdown(markdown_text)
|
||||
except ImportError:
|
||||
logger.warning("markdownify not available, using HTML as-is")
|
||||
return f"```html\n{html_content}\n```"
|
||||
except Exception as e:
|
||||
logger.error("HTML to Markdown conversion failed: %s", e)
|
||||
return f"```html\n{html_content}\n```"
|
||||
|
||||
@staticmethod
|
||||
def _strip_internal_links(soup: BeautifulSoup) -> None:
|
||||
"""Unwrap links that don't point to an external resource.
|
||||
|
||||
EPUB internal links (other chapter files, ``#fragment`` anchors, TOC
|
||||
entries) become dead links after extraction. Keep only external links
|
||||
and replace everything else with its text.
|
||||
"""
|
||||
external = ("http://", "https://", "mailto:", "tel:")
|
||||
for link in soup.find_all("a"):
|
||||
href = (link.get("href") or "").strip().lower()
|
||||
if not href or not href.startswith(external):
|
||||
link.unwrap()
|
||||
|
||||
@staticmethod
|
||||
def _add_image_aliases(
|
||||
image_aliases: Dict[str, str],
|
||||
original_path: str,
|
||||
image_path: str,
|
||||
) -> None:
|
||||
normalized = EPUBParser._normalize_epub_path(original_path)
|
||||
aliases = {
|
||||
original_path,
|
||||
normalized,
|
||||
}
|
||||
for alias in aliases:
|
||||
if alias:
|
||||
image_aliases[alias] = image_path
|
||||
# A basename fallback must not overwrite a real archive-root path.
|
||||
image_aliases.setdefault(posixpath.basename(normalized), image_path)
|
||||
|
||||
@staticmethod
|
||||
def _rewrite_image_sources(
|
||||
soup: BeautifulSoup,
|
||||
image_aliases: Dict[str, str],
|
||||
base_path: str = "",
|
||||
) -> None:
|
||||
for img in soup.find_all("img"):
|
||||
src = (img.get("src") or "").strip()
|
||||
if not src:
|
||||
continue
|
||||
# Only archive-local references may use the basename fallback.
|
||||
# A remote image can share its filename with an unrelated ZIP entry.
|
||||
try:
|
||||
reference = urlsplit(src)
|
||||
except ValueError:
|
||||
continue
|
||||
if reference.scheme or reference.netloc:
|
||||
continue
|
||||
# Only src is a URI reference. Strip its URI suffixes before decoding
|
||||
# once; archive paths from EbookLib and ZIP already contain literal
|
||||
# characters, including #, ? and percent-encoded-looking names.
|
||||
raw_path = src.split("#", 1)[0].split("?", 1)[0].replace("\\", "/")
|
||||
src_path = unquote(raw_path).replace("\\", "/")
|
||||
normalized_src = EPUBParser._normalize_epub_path(src_path)
|
||||
# Some EPUBs reference literal percent-looking names verbatim.
|
||||
# Try the undecoded path after the decoded path at each location.
|
||||
raw_normalized = EPUBParser._normalize_epub_path(raw_path)
|
||||
candidates = [normalized_src, raw_normalized]
|
||||
if base_path:
|
||||
joined = EPUBParser._normalize_epub_path(
|
||||
posixpath.join(base_path, src_path)
|
||||
)
|
||||
raw_joined = EPUBParser._normalize_epub_path(
|
||||
posixpath.join(base_path, raw_path)
|
||||
)
|
||||
# Resolve relative to the chapter before trying ambiguous aliases.
|
||||
candidates[:0] = [joined, raw_joined]
|
||||
candidates.append(posixpath.basename(normalized_src))
|
||||
for candidate in candidates:
|
||||
if candidate in image_aliases:
|
||||
img["src"] = image_aliases[candidate]
|
||||
break
|
||||
|
||||
@staticmethod
|
||||
def _normalize_epub_path(path: str) -> str:
|
||||
"""Normalize a decoded archive path without interpreting it as a URI."""
|
||||
normalized = posixpath.normpath(path.replace("\\", "/"))
|
||||
return "" if normalized == "." else normalized.lstrip("/")
|
||||
@@ -0,0 +1,149 @@
|
||||
"""LibreOffice helpers for normalizing legacy or unusual Excel uploads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_XLS_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
||||
_ZIP_MAGIC = b"PK\x03\x04"
|
||||
|
||||
|
||||
def detect_excel_format(content: bytes) -> str | None:
|
||||
"""Return pandas/excel format id: xlsx, xls, xlsb, ods, or None."""
|
||||
if not content:
|
||||
return None
|
||||
|
||||
from pandas.io.excel._base import inspect_excel_format
|
||||
|
||||
ext = inspect_excel_format(content_or_path=content)
|
||||
if ext in ("xlsx", "xls", "xlsb", "ods"):
|
||||
return ext
|
||||
if ext == "zip":
|
||||
return "xlsx"
|
||||
|
||||
if content.startswith(_ZIP_MAGIC):
|
||||
return "xlsx"
|
||||
if len(content) >= len(_XLS_MAGIC) and content.startswith(_XLS_MAGIC):
|
||||
return "xls"
|
||||
return None
|
||||
|
||||
|
||||
def engine_for_format(ext: str | None) -> str:
|
||||
if ext == "xls":
|
||||
return "xlrd"
|
||||
if ext in ("xlsx", "xlsb"):
|
||||
return "openpyxl"
|
||||
if ext == "ods":
|
||||
return "odf"
|
||||
return "openpyxl"
|
||||
|
||||
|
||||
def convert_excel_to_xlsx_bytes(content: bytes, suffix: str = ".xlsx") -> bytes | None:
|
||||
"""Convert arbitrary spreadsheet bytes to XLSX using LibreOffice, if available."""
|
||||
soffice = find_soffice()
|
||||
if not soffice:
|
||||
return None
|
||||
|
||||
max_attempts = 3
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
with tempfile.TemporaryDirectory() as temp_dir, tempfile.TemporaryDirectory() as profile_dir:
|
||||
src = os.path.join(temp_dir, f"input{suffix}")
|
||||
with open(src, "wb") as handle:
|
||||
handle.write(content)
|
||||
|
||||
user_installation = Path(profile_dir).as_uri()
|
||||
cmd = [
|
||||
soffice,
|
||||
"--headless",
|
||||
f"-env:UserInstallation={user_installation}",
|
||||
"--convert-to",
|
||||
"xlsx",
|
||||
"--outdir",
|
||||
temp_dir,
|
||||
src,
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, timeout=120)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
logger.warning("LibreOffice convert failed to start: %s", exc)
|
||||
return None
|
||||
|
||||
if result.returncode != 0:
|
||||
stderr = result.stderr.decode("utf-8", errors="ignore")
|
||||
logger.warning(
|
||||
"LibreOffice convert failed (attempt %s/%s): %s",
|
||||
attempt,
|
||||
max_attempts,
|
||||
stderr,
|
||||
)
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.5 * attempt)
|
||||
continue
|
||||
return None
|
||||
|
||||
for name in os.listdir(temp_dir):
|
||||
if name.endswith(".xlsx"):
|
||||
with open(os.path.join(temp_dir, name), "rb") as handle:
|
||||
converted = handle.read()
|
||||
logger.info(
|
||||
"Converted spreadsheet via LibreOffice (%s -> xlsx, %d bytes)",
|
||||
suffix,
|
||||
len(converted),
|
||||
)
|
||||
return converted
|
||||
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.5 * attempt)
|
||||
return None
|
||||
|
||||
|
||||
def normalize_excel_bytes(content: bytes, file_type: str | None = None) -> bytes:
|
||||
"""Return bytes readable by pandas, converting via LibreOffice when needed."""
|
||||
ext = detect_excel_format(content)
|
||||
if ext is not None:
|
||||
return content
|
||||
|
||||
suffixes = []
|
||||
if file_type:
|
||||
suffixes.append(f".{file_type.lstrip('.')}")
|
||||
suffixes.extend([".xlsx", ".xls", ".et", ".csv"])
|
||||
seen: set[str] = set()
|
||||
for suffix in suffixes:
|
||||
if suffix in seen:
|
||||
continue
|
||||
seen.add(suffix)
|
||||
converted = convert_excel_to_xlsx_bytes(content, suffix=suffix)
|
||||
if converted and detect_excel_format(converted) is not None:
|
||||
return converted
|
||||
|
||||
raise ValueError(
|
||||
"Unrecognized Excel file format; the file may be corrupt, encrypted, "
|
||||
"or not a spreadsheet"
|
||||
)
|
||||
|
||||
|
||||
def find_soffice() -> Optional[str]:
|
||||
possible_paths = [
|
||||
"/usr/bin/soffice",
|
||||
"/usr/lib/libreoffice/program/soffice",
|
||||
"/opt/libreoffice25.2/program/soffice",
|
||||
"/Applications/LibreOffice.app/Contents/MacOS/soffice",
|
||||
"C:\\Program Files\\LibreOffice\\program\\soffice.exe",
|
||||
"C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe",
|
||||
]
|
||||
for path in possible_paths:
|
||||
if path and os.path.exists(path):
|
||||
return path
|
||||
|
||||
result = subprocess.run(["which", "soffice"], capture_output=True, text=True)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
return result.stdout.strip()
|
||||
return None
|
||||
@@ -0,0 +1,329 @@
|
||||
"""
|
||||
Excel Parser Module
|
||||
|
||||
This module provides functionality to parse Excel files (.xlsx, .xls) into
|
||||
structured Document objects with text content and chunks. It supports multiple
|
||||
sheets and handles various Excel formats using pandas.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from io import BytesIO
|
||||
from typing import Any, List
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from docreader.models.document import Chunk, Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.excel_convert import (
|
||||
convert_excel_to_xlsx_bytes,
|
||||
detect_excel_format,
|
||||
engine_for_format,
|
||||
normalize_excel_bytes,
|
||||
)
|
||||
from docreader.parser.xlsx_merge import fill_merged_cells_xlsx
|
||||
from docreader.parser.xlsx_repair import (
|
||||
repair_xlsx_bytes,
|
||||
sanitize_xlsx_styles,
|
||||
strip_unreadable_ranges_xlsx,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Pattern to detect Excel image function strings that should be excluded from
|
||||
# parsed text content. WPS uses =DISPIMG("ID",mode) to embed images in cells;
|
||||
# when opened by other tools the formula may appear as plain text prefixed with
|
||||
# "_xlfn." or "=". Office 365 uses =_xlfn.IMAGE(url, ...) similarly.
|
||||
# The _xlfn. prefix is optional — WPS may omit it (e.g. =DISPIMG("ID",1)).
|
||||
_IMAGE_FUNC_RE = re.compile(
|
||||
r"^=?(_xlfn\.)?(DISPIMG|IMAGE)\(", re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
def _is_image_function(value: object) -> bool:
|
||||
"""Return True if *value* looks like an embedded-image function string."""
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
return _IMAGE_FUNC_RE.match(value) is not None
|
||||
|
||||
|
||||
class ExcelParser(BaseParser):
|
||||
"""Parser for Excel files (.xlsx, .xls).
|
||||
|
||||
This parser extracts text content from Excel files by processing all sheets
|
||||
and converting each row into a structured text format. Each row becomes a
|
||||
separate chunk with key-value pairs.
|
||||
|
||||
Features:
|
||||
- Supports multiple sheets in a single Excel file
|
||||
- Automatically removes completely empty rows
|
||||
- Converts each row to "column: value" format
|
||||
- Creates individual chunks for each row for better granularity
|
||||
|
||||
Example:
|
||||
>>> parser = ExcelParser()
|
||||
>>> with open("data.xlsx", "rb") as f:
|
||||
... content = f.read()
|
||||
... document = parser.parse_into_text(content)
|
||||
>>> print(document.content)
|
||||
Name: John,Age: 30,City: NYC
|
||||
Name: Jane,Age: 25,City: LA
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
file_name: str = "",
|
||||
file_type: str | None = None,
|
||||
xlsx_first_row_as_header: Any = False,
|
||||
xlsx_percent_as_text: Any = None,
|
||||
**kwargs: Any,
|
||||
):
|
||||
super().__init__(file_name=file_name, file_type=file_type, **kwargs)
|
||||
self.xlsx_first_row_as_header = _parse_bool(xlsx_first_row_as_header)
|
||||
# Tri-state: None (or an empty value) keeps the deployment default from
|
||||
# DOCREADER_XLSX_PERCENT_AS_TEXT, an explicit value wins. Same
|
||||
# precedence as the pdf_force_scanned parser override.
|
||||
self.xlsx_percent_as_text = _parse_optional_bool(xlsx_percent_as_text)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse Excel file bytes into a Document object.
|
||||
|
||||
Args:
|
||||
content: Raw bytes of the Excel file
|
||||
|
||||
Returns:
|
||||
Document: Parsed document containing:
|
||||
- content: Full text with all rows from all sheets
|
||||
- chunks: List of Chunk objects, one per row
|
||||
|
||||
Note:
|
||||
- Empty rows (all NaN values) are automatically skipped
|
||||
- Each row is formatted as: "col1: val1,col2: val2,..."
|
||||
- Chunks maintain sequential ordering across all sheets
|
||||
"""
|
||||
chunks: List[Chunk] = []
|
||||
text: List[str] = []
|
||||
source_blocks: List[dict] = []
|
||||
start, end = 0, 0
|
||||
|
||||
excel_file = _open_excel_file(
|
||||
content,
|
||||
file_type=self.file_type,
|
||||
percent_as_text=self.xlsx_percent_as_text,
|
||||
)
|
||||
|
||||
# Process each sheet in the Excel file
|
||||
for excel_sheet_name in excel_file.sheet_names:
|
||||
df = _read_sheet_dataframe(
|
||||
excel_file,
|
||||
excel_sheet_name,
|
||||
xlsx_first_row_as_header=self.xlsx_first_row_as_header,
|
||||
)
|
||||
# Remove rows where all values are NaN (completely empty rows)
|
||||
df.dropna(how="all", inplace=True)
|
||||
|
||||
# Process each row in the DataFrame. The index is the 0-based
|
||||
# sheet row (rows are read from row 1 and dropped rows keep
|
||||
# their labels), so index + 1 is the row number users see.
|
||||
for row_index, row in df.iterrows():
|
||||
page_content = []
|
||||
# Build key-value pairs for non-null values
|
||||
for k, v in row.items():
|
||||
if pd.notna(v) and not _is_image_function(v):
|
||||
page_content.append(f"{k}: {v}")
|
||||
|
||||
# Skip rows with no valid content
|
||||
if not page_content:
|
||||
continue
|
||||
|
||||
# Format row as comma-separated key-value pairs
|
||||
content_row = ",".join(page_content) + "\n"
|
||||
end += len(content_row)
|
||||
text.append(content_row)
|
||||
|
||||
# Create a chunk for this row with position tracking
|
||||
chunks.append(
|
||||
Chunk(content=content_row, seq=len(chunks), start=start, end=end)
|
||||
)
|
||||
try:
|
||||
row_number = int(row_index) + 1
|
||||
except (TypeError, ValueError):
|
||||
row_number = 0
|
||||
if row_number > 0:
|
||||
source_blocks.append(
|
||||
{
|
||||
"start": start,
|
||||
"end": end,
|
||||
"locator": {
|
||||
"type": "sheet",
|
||||
"sheet": str(excel_sheet_name),
|
||||
"row_start": row_number,
|
||||
"row_end": row_number,
|
||||
},
|
||||
}
|
||||
)
|
||||
start = end
|
||||
|
||||
# Combine all text and return as Document
|
||||
return Document(
|
||||
content="".join(text), chunks=chunks, source_blocks=source_blocks
|
||||
)
|
||||
|
||||
|
||||
def _read_sheet_dataframe(
|
||||
excel_file: pd.ExcelFile,
|
||||
sheet_name: str,
|
||||
xlsx_first_row_as_header: bool = False,
|
||||
) -> pd.DataFrame:
|
||||
"""Read a worksheet into a DataFrame with stable column labels."""
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
# Keep row 1 as data by default for both XLSX and legacy XLS. Users can
|
||||
# explicitly restore the historical behavior where row 1 supplies semantic
|
||||
# labels for every row.
|
||||
df = excel_file.parse(sheet_name=sheet_name, header=None)
|
||||
if xlsx_first_row_as_header and len(df.index) >= 2:
|
||||
df.columns = _stable_header_labels(df.iloc[0].tolist())
|
||||
return df.iloc[1:].copy()
|
||||
|
||||
df.columns = [get_column_letter(idx + 1) for idx in range(len(df.columns))]
|
||||
return df
|
||||
|
||||
|
||||
def _stable_header_labels(values: List[object]) -> List[str]:
|
||||
"""Build non-empty, unique labels from an explicitly selected header row."""
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
labels: List[str] = []
|
||||
counts: dict[str, int] = {}
|
||||
for index, value in enumerate(values, start=1):
|
||||
label = ""
|
||||
if pd.notna(value) and not _is_image_function(value):
|
||||
label = str(value).strip()
|
||||
if not label:
|
||||
label = get_column_letter(index)
|
||||
|
||||
count = counts.get(label, 0) + 1
|
||||
counts[label] = count
|
||||
labels.append(label if count == 1 else f"{label}_{count}")
|
||||
return labels
|
||||
|
||||
|
||||
def _parse_bool(value: Any) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _parse_optional_bool(value: Any) -> bool | None:
|
||||
"""Parse a tri-state parser override; None keeps the deployment default."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
text = str(value).strip().lower()
|
||||
if not text:
|
||||
return None
|
||||
return text in {"1", "true", "yes", "y", "on"}
|
||||
|
||||
|
||||
def _prepare_xlsx_bytes(data: bytes, percent_as_text: bool | None = None) -> bytes:
|
||||
repaired = repair_xlsx_bytes(data)
|
||||
if repaired is not None:
|
||||
data = repaired
|
||||
readable = strip_unreadable_ranges_xlsx(data)
|
||||
if readable is not None:
|
||||
data = readable
|
||||
try:
|
||||
return fill_merged_cells_xlsx(data, percent_as_text=percent_as_text)
|
||||
except TypeError:
|
||||
# A non-conforming styles.xml (empty/malformed fills) makes openpyxl's
|
||||
# load_workbook raise before pandas ever sees the file (#3637).
|
||||
# sanitize_xlsx_styles returns None when the fills are clean, in which
|
||||
# case the TypeError has a different cause and must propagate.
|
||||
sanitized = sanitize_xlsx_styles(data)
|
||||
if sanitized is None:
|
||||
raise
|
||||
return fill_merged_cells_xlsx(sanitized, percent_as_text=percent_as_text)
|
||||
|
||||
|
||||
def _open_excel_file(
|
||||
content: bytes,
|
||||
file_type: str | None = None,
|
||||
percent_as_text: bool | None = None,
|
||||
) -> pd.ExcelFile:
|
||||
"""Open an Excel workbook with explicit engine selection and fallbacks."""
|
||||
data = content
|
||||
converted_via_soffice = False
|
||||
|
||||
while True:
|
||||
ext = detect_excel_format(data)
|
||||
if ext is None:
|
||||
if converted_via_soffice:
|
||||
raise ValueError(
|
||||
"Excel file format cannot be determined, you must specify an engine manually."
|
||||
)
|
||||
try:
|
||||
data = normalize_excel_bytes(data, file_type=file_type)
|
||||
except ValueError as exc:
|
||||
raise ValueError(
|
||||
"Excel file format cannot be determined, you must specify an engine manually."
|
||||
) from exc
|
||||
converted_via_soffice = True
|
||||
continue
|
||||
|
||||
if ext == "ods":
|
||||
converted = convert_excel_to_xlsx_bytes(data, suffix=".ods")
|
||||
if converted:
|
||||
data = converted
|
||||
continue
|
||||
|
||||
engine = engine_for_format(ext)
|
||||
if ext == "xlsx":
|
||||
data = _prepare_xlsx_bytes(data, percent_as_text=percent_as_text)
|
||||
engine = "openpyxl"
|
||||
try:
|
||||
return pd.ExcelFile(BytesIO(data), engine=engine)
|
||||
except ImportError as exc:
|
||||
raise ValueError(
|
||||
f"Excel engine {engine!r} is not available for .{ext} files"
|
||||
) from exc
|
||||
except KeyError as exc:
|
||||
if "sharedStrings.xml" not in str(exc) or engine != "openpyxl":
|
||||
raise
|
||||
repaired = repair_xlsx_bytes(data)
|
||||
if repaired is None:
|
||||
raise
|
||||
logger.info("Repaired XLSX sharedStrings packaging before parse")
|
||||
data = _prepare_xlsx_bytes(repaired, percent_as_text=percent_as_text)
|
||||
continue
|
||||
except ValueError as exc:
|
||||
if converted_via_soffice or "cannot be determined" not in str(exc):
|
||||
raise
|
||||
try:
|
||||
data = normalize_excel_bytes(content, file_type=file_type)
|
||||
except ValueError:
|
||||
raise
|
||||
converted_via_soffice = True
|
||||
continue
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage: Parse an Excel file and display results
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Specify the path to your Excel file
|
||||
your_file = "/path/to/your/file.xlsx"
|
||||
parser = ExcelParser()
|
||||
|
||||
# Read and parse the Excel file
|
||||
with open(your_file, "rb") as f:
|
||||
content = f.read()
|
||||
document = parser.parse_into_text(content)
|
||||
|
||||
# Display the full document content
|
||||
logger.error(document.content)
|
||||
|
||||
# Display the first chunk as an example
|
||||
for chunk in document.chunks:
|
||||
logger.error(chunk.content)
|
||||
break # Only show the first chunk
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Static HTML file parser."""
|
||||
|
||||
import logging
|
||||
from collections import Counter
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from trafilatura import extract
|
||||
|
||||
from docreader.config import CONFIG
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.chain_parser import PipelineParser
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
from docreader.parser.mhtml_parser import MHTMLParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# An uploaded HTML file is converted in full by default, so navigation,
|
||||
# sidebars and footers are indexed as if they were document body. Setting
|
||||
# DOCREADER_HTML_MAIN_CONTENT=true indexes only the main content instead, the
|
||||
# way the URL import path (web_parser.py) already does with trafilatura. It is
|
||||
# off by default on purpose, so upgrading never changes what a knowledge base
|
||||
# indexes for documents it already ingests.
|
||||
#
|
||||
# Main-content extraction can fail in two ways: the page has no clear article
|
||||
# body (a form page, a bare link list) or trafilatura misjudges it. Both
|
||||
# thresholds below keep the full conversion in that case, which is also the
|
||||
# upstream behavior.
|
||||
_MIN_EXTRACTED_CHARS = 250
|
||||
# trafilatura falls back to a plain-text rendering below its own
|
||||
# MIN_EXTRACTED_SIZE (250); that rendering drops heading levels, tables and
|
||||
# link targets, so a page that lands between the two thresholds would lose
|
||||
# structure instead of just losing its chrome. Bracketing at trafilatura's
|
||||
# own floor keeps the full conversion in charge there.
|
||||
_MIN_KEEP_RATIO = 0.15
|
||||
|
||||
|
||||
def extract_main_content(html: str) -> str:
|
||||
"""Extract the main content of a page with trafilatura.
|
||||
|
||||
Returns the extracted markdown, or an empty string when trafilatura finds
|
||||
nothing usable or raises; callers then keep the full conversion.
|
||||
"""
|
||||
try:
|
||||
extracted = extract(
|
||||
html,
|
||||
output_format="markdown",
|
||||
include_tables=True,
|
||||
include_links=True,
|
||||
include_formatting=True,
|
||||
# Keep references in Markdown; Go can only resolve/download body
|
||||
# images if their URLs survive this extraction step.
|
||||
include_images=True,
|
||||
)
|
||||
except Exception as exc: # never fail a parse the full conversion can serve
|
||||
logger.warning("HTML main-content extraction failed: %s", exc)
|
||||
return ""
|
||||
return (extracted or "").strip()
|
||||
|
||||
|
||||
class HTMLToMarkdownParser(BaseParser):
|
||||
"""Convert uploaded HTML bytes to Markdown without browser or network access."""
|
||||
|
||||
def _full_markdown(self, html: str) -> str:
|
||||
"""Convert the whole page, the way this parser always did."""
|
||||
return MHTMLParser(
|
||||
file_name=self.file_name,
|
||||
file_type=self.file_type,
|
||||
extract_images=False,
|
||||
).html_to_markdown(
|
||||
html,
|
||||
strip_internal_links=False,
|
||||
fallback_to_raw_html=False,
|
||||
) or ""
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
if not content.strip():
|
||||
return Document()
|
||||
|
||||
# Inspect the original bytes so BOMs and HTML charset declarations are
|
||||
# honored before the shared Markdown conversion runs.
|
||||
html = BeautifulSoup(content, "lxml").decode()
|
||||
|
||||
full = self._full_markdown(html)
|
||||
if not CONFIG.html_main_content:
|
||||
return Document(content=full)
|
||||
|
||||
extracted = extract_main_content(html)
|
||||
# Some short articles are repeated by trafilatura's fallback. Do not
|
||||
# index extra copies or let them inflate the length/retention guards.
|
||||
# Only reject repetitions absent from the full conversion: deliberate
|
||||
# repeated paragraphs in the source must remain valid.
|
||||
blocks = Counter(line.strip() for line in extracted.splitlines())
|
||||
for block, occurrences in blocks.items():
|
||||
if occurrences > 1 and len(block) >= 80 and 0 < full.count(block) < occurrences:
|
||||
logger.info(
|
||||
"HTML main-content extraction duplicated a body block; keeping the full conversion"
|
||||
)
|
||||
return Document(content=full)
|
||||
if len(extracted) < _MIN_EXTRACTED_CHARS:
|
||||
logger.info(
|
||||
"HTML main-content extraction returned %d chars (<%d); "
|
||||
"keeping the full conversion",
|
||||
len(extracted),
|
||||
_MIN_EXTRACTED_CHARS,
|
||||
)
|
||||
return Document(content=full)
|
||||
if full and len(extracted) < len(full) * _MIN_KEEP_RATIO:
|
||||
logger.info(
|
||||
"HTML main-content extraction kept only %d chars of %d; "
|
||||
"keeping the full conversion",
|
||||
len(extracted),
|
||||
len(full),
|
||||
)
|
||||
return Document(content=full)
|
||||
|
||||
logger.info(
|
||||
"HTML main-content extraction applied: kept %d chars, "
|
||||
"full conversion would be %d",
|
||||
len(extracted),
|
||||
len(full),
|
||||
)
|
||||
return Document(content=extracted)
|
||||
|
||||
|
||||
class HTMLParser(PipelineParser):
|
||||
"""Extract static HTML content and normalize the resulting Markdown."""
|
||||
|
||||
_parser_cls = (HTMLToMarkdownParser, MarkdownParser)
|
||||
@@ -0,0 +1,28 @@
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ImageParser(BaseParser):
|
||||
"""Parser for standalone image files.
|
||||
|
||||
Returns the image as a markdown reference with the raw image data
|
||||
in Document.images so that the Go-side ImageResolver (or main.py's
|
||||
_resolve_images) can handle storage upload.
|
||||
"""
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
logger.info("Parsing image file=%s, size=%d bytes", self.file_name, len(content))
|
||||
|
||||
ext = os.path.splitext(self.file_name)[1].lower() or ".png"
|
||||
ref_path = f"images/{self.file_name}"
|
||||
|
||||
text = f""
|
||||
images = {ref_path: base64.b64encode(content).decode()}
|
||||
|
||||
return Document(content=text, images=images)
|
||||
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Straighten and crop a photographed page before OCR reads it.
|
||||
|
||||
The working assumption is that the union of RapidOCR's text-line boxes is the
|
||||
page's content area, so a content-tight rectangle can be recovered from text
|
||||
geometry alone — no page detector and no model beyond the recogniser already in
|
||||
the image pipeline.
|
||||
|
||||
Per input image:
|
||||
|
||||
1. RapidOCR detects the text-line boxes, each with a rotation angle;
|
||||
2. filter them: score, angle consensus (within ANG_TOL of the dominant angle,
|
||||
which is what kills detections on background objects) and size (long edge
|
||||
at least SIZE_MIN of the median);
|
||||
3. align by the dominant text direction (two candidate signs, chosen by the
|
||||
smaller residual; a +/-90deg page is kept, never collapsed to 0);
|
||||
4. fit the content quad inside the ALIGNED coordinate system (outer supporting
|
||||
lines through the extreme point sets, intersected), then pad it by PAD;
|
||||
5. warpPerspective inside that same coordinate system, giving a rectangular
|
||||
content image with horizontal text;
|
||||
6. decide 0 vs 180 degrees by comparing the mean recognition score of the
|
||||
result with that of its 180deg rotation (with cls disabled, so the score
|
||||
is orientation-sensitive);
|
||||
7. compare against a content-level reference crop (aspect ratio, then by eye).
|
||||
|
||||
Every failure mode is a verdict rather than an exception — the caller keeps its
|
||||
own bytes — so a page that cannot be corrected is read as the original
|
||||
photograph instead of something worse.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from rapidocr import RapidOCR
|
||||
|
||||
from docreader.config import CONFIG
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# The thresholds, tuned on the 17-image benchmark (see the R22 handover
|
||||
# document). Each one can be overridden for a debugging run through the
|
||||
# environment — ACADEMY_PREPROCESS_<NAME> — because re-tuning a constant meant
|
||||
# rebuilding the image, which is a long way round to answer "what happens if
|
||||
# this page is scored a little differently".
|
||||
#
|
||||
# The default IS the tuned value; an override is validated against a range and
|
||||
# a bad one is refused rather than clamped, so a typo cannot quietly run the
|
||||
# pipeline at a value nobody chose. The set in force is named in the server's
|
||||
# startup log, so a run's output can be read back against the tuning that
|
||||
# produced it.
|
||||
DEFAULT_PAD = 0.015
|
||||
DEFAULT_MIN_SCORE = 0.5
|
||||
DEFAULT_ANG_TOL = 15.0
|
||||
DEFAULT_SIZE_MIN = 0.35
|
||||
DEFAULT_QUAD_TOL = -0.02
|
||||
|
||||
_ENV_PREFIX = "ACADEMY_PREPROCESS_"
|
||||
|
||||
# name -> (default, low, high). The range is what the value has to mean
|
||||
# something in, not a second tuning: PAD is a fraction of the page side,
|
||||
# MIN_SCORE and SIZE_MIN are fractions, ANG_TOL is an angle in degrees, and
|
||||
# QUAD_TOL is a negative allowance relative to the quad's longer side.
|
||||
_THRESHOLDS = {
|
||||
"PAD": (DEFAULT_PAD, 0.0, 0.2),
|
||||
"MIN_SCORE": (DEFAULT_MIN_SCORE, 0.0, 1.0),
|
||||
"ANG_TOL": (DEFAULT_ANG_TOL, 0.0, 90.0),
|
||||
"SIZE_MIN": (DEFAULT_SIZE_MIN, 0.0, 1.0),
|
||||
"QUAD_TOL": (DEFAULT_QUAD_TOL, -0.5, 0.0),
|
||||
}
|
||||
|
||||
|
||||
def resolve_threshold(name: str, raw: "str | None") -> float:
|
||||
"""The value one threshold takes for one raw environment string.
|
||||
|
||||
Unset or blank means the tuned default. Anything else has to parse as a
|
||||
number inside the threshold's range, or the default is used and the reason
|
||||
is logged — a refused override is louder than a silent one.
|
||||
"""
|
||||
default, low, high = _THRESHOLDS[name]
|
||||
if raw is None or raw.strip() == "":
|
||||
return default
|
||||
try:
|
||||
value = float(raw)
|
||||
except ValueError:
|
||||
logger.warning("%s%s=%r is not a number; using the default %g", _ENV_PREFIX, name, raw, default)
|
||||
return default
|
||||
if not low <= value <= high:
|
||||
logger.warning("%s%s=%g is outside [%g, %g]; using the default %g",
|
||||
_ENV_PREFIX, name, value, low, high, default)
|
||||
return default
|
||||
return value
|
||||
|
||||
|
||||
PAD = resolve_threshold("PAD", os.environ.get(_ENV_PREFIX + "PAD"))
|
||||
MIN_SCORE = resolve_threshold("MIN_SCORE", os.environ.get(_ENV_PREFIX + "MIN_SCORE"))
|
||||
ANG_TOL = resolve_threshold("ANG_TOL", os.environ.get(_ENV_PREFIX + "ANG_TOL"))
|
||||
SIZE_MIN = resolve_threshold("SIZE_MIN", os.environ.get(_ENV_PREFIX + "SIZE_MIN"))
|
||||
QUAD_TOL = resolve_threshold("QUAD_TOL", os.environ.get(_ENV_PREFIX + "QUAD_TOL"))
|
||||
|
||||
|
||||
def effective_thresholds() -> dict:
|
||||
"""The thresholds this process is running with, by name.
|
||||
|
||||
The server logs this once at startup (see docreader.main), so the output of
|
||||
a debugging run can be read back against the tuning that produced it. It is
|
||||
not logged from here: this module is imported before the log level is set.
|
||||
"""
|
||||
return {
|
||||
"PAD": PAD,
|
||||
"MIN_SCORE": MIN_SCORE,
|
||||
"ANG_TOL": ANG_TOL,
|
||||
"SIZE_MIN": SIZE_MIN,
|
||||
"QUAD_TOL": QUAD_TOL,
|
||||
}
|
||||
|
||||
# RapidOCR instances carry mutable state: parameters are written onto the
|
||||
# instance (update_params -> setattr), so calling ocr(img, use_cls=...) changes
|
||||
# what every later call sees. The gRPC server handles requests concurrently, so
|
||||
# one instance is shared per thread rather than globally.
|
||||
_ocr_local = threading.local()
|
||||
|
||||
|
||||
def _engine() -> "RapidOCR":
|
||||
engine = getattr(_ocr_local, "engine", None)
|
||||
if engine is None:
|
||||
engine = RapidOCR(params={
|
||||
"EngineConfig.onnxruntime.intra_op_num_threads": CONFIG.preprocess_threads,
|
||||
"EngineConfig.onnxruntime.inter_op_num_threads": 1,
|
||||
})
|
||||
_ocr_local.engine = engine
|
||||
return engine
|
||||
|
||||
|
||||
def box_angle(b):
|
||||
"""(angle of a box's long edge in degrees, length of that edge)."""
|
||||
d1 = float(np.linalg.norm(b[1] - b[0]))
|
||||
d2 = float(np.linalg.norm(b[2] - b[1]))
|
||||
v = (b[1] - b[0]) if d1 >= d2 else (b[2] - b[1])
|
||||
return float(np.degrees(np.arctan2(v[1], v[0]))), max(d1, d2)
|
||||
|
||||
|
||||
def wrap90(a):
|
||||
"""Fold an angle into (-90, 90], the period a text line really has."""
|
||||
return ((a + 90.0) % 180.0) - 90.0
|
||||
|
||||
|
||||
def detect(img):
|
||||
# use_cls MUST be passed explicitly: RapidOCR.__call__(use_cls=...) writes the
|
||||
# flag onto the instance (rapidocr.main.update_params -> setattr), so a later
|
||||
# rec_score(img, use_cls=False) would silently change the DETECTION result of
|
||||
# every subsequent call on the shared instance (measured on up180: 166 boxes
|
||||
# with cls on -> 147 with cls off, losing exactly the long text lines that
|
||||
# carry the dominant angle).
|
||||
res = _engine()(img, use_cls=True)
|
||||
return [(np.array(b, "float32"), float(s)) for b, s in zip(res.boxes, res.scores) if s >= MIN_SCORE]
|
||||
|
||||
|
||||
def dominant_angle(items):
|
||||
"""Length-weighted MODE of the text-line angle on the 180deg-periodic circle.
|
||||
|
||||
Must not be a plain median: near-vertical boxes land at BOTH ends of the
|
||||
(-90, 90] window, because the sign of the long edge's x component is pixel
|
||||
noise. Measured on the 90deg set, a 90deg-rotated page split into 46.9% at
|
||||
-89 and 37.1% at +89 -> a median landed at 0.0 and the page was "aligned"
|
||||
by 0deg (wrong). Working on angle mod 180 with a tolerance-width window
|
||||
merges those two halves and returns ~90.
|
||||
"""
|
||||
if not items:
|
||||
return 0.0
|
||||
ang = np.array([box_angle(b)[0] % 180.0 for b, _ in items])
|
||||
w = np.array([box_angle(b)[1] for b, _ in items])
|
||||
grid = np.arange(0.0, 180.0, 0.5)
|
||||
d = np.abs(((grid[:, None] - ang[None, :]) + 90.0) % 180.0 - 90.0)
|
||||
score = (w[None, :] * (d <= ANG_TOL)).sum(axis=1)
|
||||
peak = float(grid[int(np.argmax(score))])
|
||||
# The argmax sits at the EDGE of a plateau (any window covering the same
|
||||
# cluster scores identically), so refine: circular mean of the in-tolerance
|
||||
# boxes, weighted by length. Without this the output keeps a 5-15deg tilt.
|
||||
sel = np.abs(((peak - ang) + 90.0) % 180.0 - 90.0) <= ANG_TOL
|
||||
if sel.sum() < 3:
|
||||
return wrap90(peak)
|
||||
a2 = np.radians(2.0 * ang[sel])
|
||||
sw = w[sel]
|
||||
return wrap90(float(np.degrees(np.arctan2((sw * np.sin(a2)).sum(), (sw * np.cos(a2)).sum())) / 2.0))
|
||||
|
||||
|
||||
def filter_items(items, theta):
|
||||
"""Keep the boxes that agree with the dominant angle and are not too small.
|
||||
|
||||
A false detection on a background object (a keyboard, a phone) fails on both
|
||||
counts: its angle is unrelated to the text and its box is short.
|
||||
"""
|
||||
med = float(np.median([box_angle(b)[1] for b, _ in items])) if items else 0.0
|
||||
keep = []
|
||||
for b, s in items:
|
||||
a, L = box_angle(b)
|
||||
if abs(wrap90(a - theta)) <= ANG_TOL and L >= SIZE_MIN * med:
|
||||
keep.append((b, s))
|
||||
return keep
|
||||
|
||||
|
||||
def rotate_expand(img, ang):
|
||||
"""Rotate with an expanded canvas (PIL expand=True equivalent); return (img, M)."""
|
||||
h, w = img.shape[:2]
|
||||
M = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), ang, 1.0)
|
||||
cos, sin = abs(M[0, 0]), abs(M[0, 1])
|
||||
nW, nH = int(h * sin + w * cos), int(h * cos + w * sin)
|
||||
M[0, 2] += nW / 2.0 - w / 2.0
|
||||
M[1, 2] += nH / 2.0 - h / 2.0
|
||||
return cv2.warpAffine(img, M, (nW, nH), borderValue=(255, 255, 255)), M
|
||||
|
||||
|
||||
def align_residual(items, angle_deg):
|
||||
"""Median |residual| of box angles after rotating by `angle_deg` (cv2 convention)."""
|
||||
c, s = np.cos(np.radians(angle_deg)), np.sin(np.radians(angle_deg))
|
||||
Rm = np.array([[c, s], [-s, c]], "float32")
|
||||
res = []
|
||||
for b, _ in items:
|
||||
d1 = float(np.linalg.norm(b[1] - b[0]))
|
||||
d2 = float(np.linalg.norm(b[2] - b[1]))
|
||||
v = (b[1] - b[0]) if d1 >= d2 else (b[2] - b[1])
|
||||
w = Rm @ v
|
||||
res.append(wrap90(float(np.degrees(np.arctan2(w[1], w[0])))))
|
||||
return float(np.median(np.abs(res)))
|
||||
|
||||
|
||||
def choose_rotation(items, theta):
|
||||
"""The sign of theta that leaves the smaller residual: -theta or theta.
|
||||
|
||||
Both signs are real candidates because the dominant angle is only known
|
||||
modulo 180, and a page rotated by +90 and one rotated by -90 are different
|
||||
pictures even though their text lines share an angle.
|
||||
"""
|
||||
return -theta if align_residual(items, -theta) <= align_residual(items, theta) else theta
|
||||
|
||||
|
||||
def _tls(points, along):
|
||||
"""Fit `other = m*along + b` by least squares (bands are narrow -> TLS~LSQ)."""
|
||||
x, y = points[:, along], points[:, 1 - along]
|
||||
if len(x) < 2 or x.max() - x.min() < 1e-6:
|
||||
return None
|
||||
m = float(np.polyfit(x, y, 1)[0])
|
||||
return (m, float(np.mean(y) - m * np.mean(x)))
|
||||
|
||||
|
||||
def _boundary_line(pts, axis, side, frac=0.10, max_slope=0.12):
|
||||
"""Outer SUPPORTING line for one side: robust slope + outward shift.
|
||||
|
||||
Slope comes from the extreme band ONLY IF that band spans enough of the other
|
||||
axis (a small cluster extrapolated across the full width gives wild slopes).
|
||||
Otherwise the line is axis-aligned — legitimate here because the frame was
|
||||
already rotated so that text lines are horizontal / columns vertical.
|
||||
Then the line is shifted outward until it touches the outermost point, so the
|
||||
quad always ENCLOSES every detected box (the plain band fit cut 550px off).
|
||||
"""
|
||||
other = pts[:, 1 - axis]
|
||||
span = float(np.ptp(other))
|
||||
if span < 1e-6:
|
||||
return None
|
||||
# Select the outer band across the boundary, then measure its coverage
|
||||
# along the boundary. Using the same axis for both makes the 50% coverage
|
||||
# requirement impossible for a 10% band.
|
||||
coord = pts[:, axis]
|
||||
lo, hi = float(coord.min()), float(coord.max())
|
||||
band = (hi - lo) * frac
|
||||
sel = pts[coord <= lo + band] if side == "min" else pts[coord >= hi - band]
|
||||
m = 0.0
|
||||
if len(sel) >= 5 and np.ptp(sel[:, 1 - axis]) >= 0.5 * span:
|
||||
m = float(np.polyfit(sel[:, 1 - axis], sel[:, axis], 1)[0])
|
||||
if abs(m) > max_slope:
|
||||
m = 0.0
|
||||
b0 = float(np.mean(sel[:, axis]) - m * np.mean(sel[:, 1 - axis]))
|
||||
r = pts[:, axis] - (m * pts[:, 1 - axis] + b0)
|
||||
b = b0 + (float(r.min()) if side == "min" else float(r.max()))
|
||||
return (m, b) # coord_axis = m * coord_other + b
|
||||
|
||||
|
||||
def _intersect(line_h, line_v):
|
||||
"""line_h: y = m*x + b; line_v: x = m*y + b -> x = (m2*b1 + b2)/(1 - m1*m2)."""
|
||||
(m1, b1), (m2, b2) = line_h, line_v
|
||||
den = 1.0 - m1 * m2
|
||||
if abs(den) < 1e-9:
|
||||
return None
|
||||
x = (m2 * b1 + b2) / den
|
||||
return (x, m1 * x + b1)
|
||||
|
||||
|
||||
def order_pts(p):
|
||||
"""Order four corners as top-left, top-right, bottom-right, bottom-left."""
|
||||
p = np.asarray(p, "float32").reshape(4, 2)
|
||||
s, d = p.sum(1), np.diff(p, axis=1).ravel()
|
||||
return np.array([p[np.argmin(s)], p[np.argmin(d)], p[np.argmax(s)], p[np.argmax(d)]], "float32")
|
||||
|
||||
|
||||
def fit_quad(pts):
|
||||
"""Content quad = intersections of four OUTER supporting lines of the boxes.
|
||||
|
||||
The supporting lines enclose every point, so a first attempt can come back
|
||||
with a few outliers still inside the tolerance band; those are dropped and
|
||||
the quad is refitted, which is why the loop exists. `QUAD_TOL` is a negative
|
||||
allowance: a point is accepted while it is no further outside than that
|
||||
fraction of the quad's longer side.
|
||||
"""
|
||||
quad = None
|
||||
for _ in range(3):
|
||||
top = _boundary_line(pts, 1, "min") # y = m*x + b, above all points
|
||||
bot = _boundary_line(pts, 1, "max") # y = m*x + b, below all points
|
||||
lef = _boundary_line(pts, 0, "min") # x = m*y + b, left of all points
|
||||
rig = _boundary_line(pts, 0, "max") # x = m*y + b, right of all points
|
||||
if None in (top, bot, lef, rig):
|
||||
return None
|
||||
corners = [_intersect(top, lef), _intersect(top, rig),
|
||||
_intersect(bot, rig), _intersect(bot, lef)]
|
||||
if None in corners:
|
||||
return None
|
||||
quad = np.array(corners, "float32")
|
||||
xr = quad[:, 0].max() - quad[:, 0].min()
|
||||
yr = quad[:, 1].max() - quad[:, 1].min()
|
||||
tol = QUAD_TOL * max(xr, yr)
|
||||
inside = np.array([cv2.pointPolygonTest(quad, (float(p[0]), float(p[1])), True) >= tol
|
||||
for p in pts])
|
||||
if inside.all():
|
||||
return quad
|
||||
pts = pts[inside]
|
||||
if len(pts) < 8:
|
||||
return quad
|
||||
return quad
|
||||
|
||||
|
||||
def warp(img, quad, pad=PAD):
|
||||
"""Perspective-warp the padded quad into a rectangle; return (rect, quad)."""
|
||||
q = order_pts(quad)
|
||||
side = float(np.mean([np.linalg.norm(q[(i + 1) % 4] - q[i]) for i in range(4)]))
|
||||
d = pad * side
|
||||
q = q + np.array([[-d, -d], [d, -d], [d, d], [-d, d]], "float32")
|
||||
wA, wB = np.linalg.norm(q[1] - q[0]), np.linalg.norm(q[2] - q[3])
|
||||
hA, hB = np.linalg.norm(q[3] - q[0]), np.linalg.norm(q[2] - q[1])
|
||||
Wt, Ht = int(max(wA, wB)), int(max(hA, hB))
|
||||
dst = np.array([[0, 0], [Wt - 1, 0], [Wt - 1, Ht - 1], [0, Ht - 1]], "float32")
|
||||
rect = cv2.warpPerspective(img, cv2.getPerspectiveTransform(q, dst), (Wt, Ht),
|
||||
borderValue=(255, 255, 255))
|
||||
return rect, q
|
||||
|
||||
|
||||
def warp_ordered(img, quad, pad=0.0):
|
||||
"""Warp an ALREADY-ORDERED quad (TL, TR, BR, BL), with optional extra padding.
|
||||
|
||||
`preprocess`'s `quad_input` is already ordered and padded in the rotated
|
||||
frame, so it must NOT go through `order_pts` again: on a rotated page the
|
||||
sum/difference heuristic can pick a different corner and the crop comes back
|
||||
twisted. This lets a caller detect on a smaller probe and still crop the
|
||||
original bytes at their own resolution.
|
||||
"""
|
||||
q = np.asarray(quad, "float32").reshape(4, 2)
|
||||
if pad:
|
||||
side = float(np.mean([np.linalg.norm(q[(i + 1) % 4] - q[i]) for i in range(4)]))
|
||||
d = pad * side
|
||||
q = q + np.array([[-d, -d], [d, -d], [d, d], [-d, d]], "float32")
|
||||
wA, wB = np.linalg.norm(q[1] - q[0]), np.linalg.norm(q[2] - q[3])
|
||||
hA, hB = np.linalg.norm(q[3] - q[0]), np.linalg.norm(q[2] - q[1])
|
||||
Wt, Ht = int(max(wA, wB)), int(max(hA, hB))
|
||||
dst = np.array([[0, 0], [Wt - 1, 0], [Wt - 1, Ht - 1], [0, Ht - 1]], "float32")
|
||||
return cv2.warpPerspective(img, cv2.getPerspectiveTransform(q, dst), (Wt, Ht),
|
||||
borderValue=(255, 255, 255))
|
||||
|
||||
|
||||
def rec_score(img):
|
||||
"""Mean recognition score with cls DISABLED (orientation-sensitive)."""
|
||||
try:
|
||||
res = _engine()(img, use_cls=False)
|
||||
sc = np.asarray(res.scores if res.scores is not None else [], "float32").ravel()
|
||||
return (float(sc.mean()) if sc.size else 0.0), int(sc.size)
|
||||
except Exception as e:
|
||||
logger.warning("Recognition score unavailable, treating the image as unreadable: %s", e)
|
||||
return 0.0, 0
|
||||
|
||||
|
||||
def preprocess(bgr: "np.ndarray") -> dict:
|
||||
"""Straighten and crop one photographed page (R22 end to end).
|
||||
|
||||
Returns a dict: rect (corrected BGR image or None), quad_input (content quad
|
||||
in the INPUT image's coordinates), theta / ang / residual / flip / s0 / s180 /
|
||||
n_boxes / n_kept, and status = "ok" | "no_text" | "low_quality".
|
||||
|
||||
A non-"ok" status is a verdict, not an exception: the caller keeps its own
|
||||
original bytes. Callers must not treat it as an error to log.
|
||||
"""
|
||||
items = detect(bgr)
|
||||
if len(items) < 4:
|
||||
return {"rect": None, "status": "no_text", "n_boxes": len(items), "n_kept": 0}
|
||||
theta = dominant_angle(items)
|
||||
kept = filter_items(items, theta)
|
||||
if len(kept) < 4:
|
||||
return {"rect": None, "status": "no_text", "n_boxes": len(items), "n_kept": len(kept)}
|
||||
ang = choose_rotation(kept, theta)
|
||||
residual = align_residual(kept, ang)
|
||||
rot, M = rotate_expand(bgr, ang)
|
||||
pts = cv2.transform(np.concatenate([b for b, _ in kept]).reshape(-1, 1, 2), M).reshape(-1, 2)
|
||||
quad_r = fit_quad(pts)
|
||||
if quad_r is None:
|
||||
return {"rect": None, "status": "low_quality", "theta": float(theta), "ang": float(ang),
|
||||
"residual": float(residual), "n_boxes": len(items), "n_kept": len(kept)}
|
||||
rect, quad_pad = warp(rot, quad_r)
|
||||
s0, _ = rec_score(rect)
|
||||
s1, _ = rec_score(cv2.rotate(rect, cv2.ROTATE_180))
|
||||
flip = bool(s1 > s0)
|
||||
if flip:
|
||||
rect = cv2.rotate(rect, cv2.ROTATE_180)
|
||||
back = cv2.invertAffineTransform(M)
|
||||
quad_o = cv2.transform(quad_pad.reshape(-1, 1, 2), back).reshape(-1, 2)
|
||||
return {
|
||||
"rect": rect,
|
||||
"quad_input": quad_o.astype("float32"),
|
||||
"theta": float(theta),
|
||||
"ang": float(ang),
|
||||
"residual": float(residual),
|
||||
"flip": flip,
|
||||
"s0": float(s0),
|
||||
"s180": float(s1),
|
||||
"n_boxes": len(items),
|
||||
"n_kept": len(kept),
|
||||
"status": "ok",
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
"""
|
||||
Markdown Parser Module
|
||||
|
||||
This module provides comprehensive Markdown parsing functionality including:
|
||||
- Table formatting and standardization
|
||||
- Base64 image extraction and conversion
|
||||
- Image path replacement and URL generation
|
||||
- Pipeline-based parsing with multiple stages
|
||||
|
||||
The parser uses a pipeline approach to process Markdown content through
|
||||
multiple stages: table formatting -> image processing.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from typing import Dict, List, Match, Optional, Tuple
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.chain_parser import PipelineParser
|
||||
from docreader.utils import endecode
|
||||
|
||||
# Get logger object
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SEPARATOR_CELL = re.compile(r"^:?-{3,}:?$")
|
||||
# A backslash escape, or a bare pipe. Scanning both keeps an escaped pipe
|
||||
# (``\|``) out of the cell delimiters without a lookbehind, in linear time.
|
||||
_ESCAPE_OR_PIPE = re.compile(r"\\.|\|", re.DOTALL)
|
||||
# Cells of a GFM alignment row as matched by the previous ``align_pattern``.
|
||||
# Looser than ``_SEPARATOR_CELL``: any non-empty run of ``:``/``-`` qualifies.
|
||||
_ALIGNMENT_CELL = re.compile(r"^[:-]+$")
|
||||
|
||||
|
||||
class MarkdownTableUtil:
|
||||
"""Utility class for formatting Markdown tables.
|
||||
|
||||
This class standardizes Markdown table formatting by:
|
||||
- Normalizing column alignment markers (e.g., :---, :---:, ---:)
|
||||
- Adding consistent spacing around pipes (|)
|
||||
- Preserving indentation levels
|
||||
- Handling both header rows and data rows
|
||||
|
||||
Example:
|
||||
Input: |姓名|年龄|城市|
|
||||
|:---|---:|:---:|
|
||||
|张三|25|北京|
|
||||
|
||||
Output: | 姓名 | 年龄 | 城市 |
|
||||
| :--- | ---: | :---: |
|
||||
| 张三 | 25 | 北京 |
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _split_row_cells(row_line: str) -> List[str]:
|
||||
"""Split a markdown table row into cells, preserving empty cells.
|
||||
|
||||
As in GFM, a pipe escaped as ``\\|`` is text inside its cell rather
|
||||
than a cell delimiter.
|
||||
"""
|
||||
inner = row_line.strip()
|
||||
if not inner.startswith("|"):
|
||||
return []
|
||||
parts: List[str] = []
|
||||
start = 0
|
||||
for match in _ESCAPE_OR_PIPE.finditer(inner):
|
||||
if match.group() == "|":
|
||||
parts.append(inner[start:match.start()])
|
||||
start = match.end()
|
||||
parts.append(inner[start:])
|
||||
if parts and parts[0].strip() == "":
|
||||
parts = parts[1:]
|
||||
if parts and parts[-1].strip() == "":
|
||||
parts = parts[:-1]
|
||||
return [part.strip() for part in parts]
|
||||
|
||||
@staticmethod
|
||||
def _is_table_row(line: str) -> bool:
|
||||
stripped = line.strip()
|
||||
return stripped.startswith("|") and "|" in stripped[1:]
|
||||
|
||||
@classmethod
|
||||
def _is_separator_row(cls, line: str) -> bool:
|
||||
cells = cls._split_row_cells(line)
|
||||
return bool(cells) and all(_SEPARATOR_CELL.match(cell) for cell in cells)
|
||||
|
||||
@classmethod
|
||||
def _is_alignment_row(cls, line: str) -> bool:
|
||||
"""Detect a GFM alignment row, matching the previous ``align_pattern``.
|
||||
|
||||
Deliberately looser than :meth:`_is_separator_row` (which needs three
|
||||
or more dashes per cell) so formatting output is unchanged for rows
|
||||
like ``| - | - |``.
|
||||
"""
|
||||
cells = cls._split_row_cells(line)
|
||||
return bool(cells) and all(_ALIGNMENT_CELL.match(cell) for cell in cells)
|
||||
|
||||
@classmethod
|
||||
def _is_empty_row(cls, line: str) -> bool:
|
||||
cells = cls._split_row_cells(line)
|
||||
return bool(cells) and all(cell == "" for cell in cells)
|
||||
|
||||
@classmethod
|
||||
def _separator_row_for(cls, header_line: str) -> str:
|
||||
cells = cls._split_row_cells(header_line)
|
||||
return "| " + " | ".join("---" for _ in cells) + " |"
|
||||
|
||||
@classmethod
|
||||
def _normalize_table_block(cls, block: List[str]) -> List[str]:
|
||||
"""Fix MarkItDown-style tables: drop bogus prefix rows, ensure GFM delimiter."""
|
||||
while block and cls._is_empty_row(block[0]):
|
||||
block.pop(0)
|
||||
if block and cls._is_separator_row(block[0]):
|
||||
block.pop(0)
|
||||
# GFM/marked need "| --- |" after the first row. Headerless Word tables
|
||||
# only have data rows after we strip the fake empty+separator prefix.
|
||||
if len(block) >= 2 and not cls._is_separator_row(block[1]):
|
||||
sep = cls._separator_row_for(block[0])
|
||||
block = [block[0], sep] + block[1:]
|
||||
return block
|
||||
|
||||
def normalize_spurious_table_prefixes(self, content: str) -> str:
|
||||
"""Remove bogus empty/separator prefix rows from MarkItDown table output."""
|
||||
lines = content.split("\n")
|
||||
out: List[str] = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
if not self._is_table_row(line):
|
||||
out.append(line)
|
||||
i += 1
|
||||
continue
|
||||
block: List[str] = []
|
||||
while i < len(lines) and self._is_table_row(lines[i]):
|
||||
block.append(lines[i])
|
||||
i += 1
|
||||
out.extend(self._normalize_table_block(block))
|
||||
return "\n".join(out)
|
||||
|
||||
def format_table(self, content: str) -> str:
|
||||
"""Format all Markdown tables in the content.
|
||||
|
||||
Line-based and regex-free: only well-formed rows (leading *and*
|
||||
trailing ``|``, with at least one cell) are treated as tables, so a
|
||||
malformed row can never trigger the catastrophic backtracking
|
||||
described in https://github.com/Tencent/WeKnora/issues/2768.
|
||||
CRLF/CR input is normalized to LF before scanning.
|
||||
|
||||
Args:
|
||||
content: Raw Markdown text containing tables
|
||||
|
||||
Returns:
|
||||
Formatted Markdown text with standardized table formatting
|
||||
"""
|
||||
|
||||
def format_alignment_row(prefix: str, columns: List[str]) -> str:
|
||||
"""Standardize an alignment row, preserving ``:`` markers."""
|
||||
processed = []
|
||||
for col in columns:
|
||||
# Preserve left alignment marker (:---)
|
||||
left_colon = ":" if col.startswith(":") else ""
|
||||
# Preserve right alignment marker (---:)
|
||||
right_colon = ":" if col.endswith(":") else ""
|
||||
processed.append(left_colon + "---" + right_colon)
|
||||
return prefix + "| " + " | ".join(processed) + " |"
|
||||
|
||||
def format_data_row(prefix: str, columns: List[str]) -> str:
|
||||
"""Standardize a header or data row."""
|
||||
return prefix + "| " + " | ".join(columns) + " |"
|
||||
|
||||
# Unify CRLF/CR first so a trailing ``\r`` left by split("\n") cannot
|
||||
# be mistaken for "ends with |" via str.rstrip(), and so we do not
|
||||
# emit mixed line endings. Trailing newlines are preserved.
|
||||
unified = content.replace("\r\n", "\n").replace("\r", "\n")
|
||||
lines = unified.split("\n")
|
||||
out: List[str] = []
|
||||
for line in lines:
|
||||
stripped = line.lstrip(" \t")
|
||||
# A row must both begin and end with a pipe to be a table row;
|
||||
# anything else is passed through unchanged. This also keeps
|
||||
# unclosed rows (the old regex's exponential worst case) cheap.
|
||||
# rstrip only spaces/tabs (old ``\|[\t ]*$``), not all whitespace.
|
||||
if stripped.startswith("|") and line.rstrip(" \t").endswith("|"):
|
||||
prefix = line[: len(line) - len(stripped)]
|
||||
columns = self._split_row_cells(line)
|
||||
# Lone "|" is not a table row: the old line_pattern required
|
||||
# opening *and* closing pipes. Formatting it to "| |" would
|
||||
# let normalize_spurious_table_prefixes drop the line.
|
||||
if not columns:
|
||||
out.append(line)
|
||||
elif self._is_alignment_row(line):
|
||||
out.append(format_alignment_row(prefix, columns))
|
||||
else:
|
||||
out.append(format_data_row(prefix, columns))
|
||||
else:
|
||||
out.append(line)
|
||||
return self.normalize_spurious_table_prefixes("\n".join(out))
|
||||
|
||||
@staticmethod
|
||||
def _self_test():
|
||||
test_content = """
|
||||
# 测试表格
|
||||
普通文本---不会被匹配
|
||||
|
||||
## 表格1(无前置空格)
|
||||
|
||||
| 姓名 | 年龄 | 城市 |
|
||||
| :---------- | -------: | :------ |
|
||||
| 张三 | 25 | 北京 |
|
||||
|
||||
## 表格3(前置4个空格+首尾|)
|
||||
| 产品 | 价格 | 库存 |
|
||||
| :-------------: | ----------- | :-----------: |
|
||||
| 手机 | 5999 | 100 |
|
||||
"""
|
||||
util = MarkdownTableUtil()
|
||||
format_content = util.format_table(test_content)
|
||||
print(format_content)
|
||||
|
||||
|
||||
class MarkdownTableFormatter(BaseParser):
|
||||
"""Parser for formatting Markdown tables.
|
||||
|
||||
This parser standardizes the formatting of all Markdown tables in the
|
||||
document to ensure consistent spacing and alignment markers.
|
||||
|
||||
Example:
|
||||
>>> formatter = MarkdownTableFormatter()
|
||||
>>> content = b"|Name|Age|\n|---|---|\n|John|30|"
|
||||
>>> doc = formatter.parse_into_text(content)
|
||||
>>> print(doc.content)
|
||||
| Name | Age |
|
||||
| --- | --- |
|
||||
| John | 30 |
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.table_helper = MarkdownTableUtil()
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse and format Markdown tables.
|
||||
|
||||
Args:
|
||||
content: Raw Markdown content as bytes
|
||||
|
||||
Returns:
|
||||
Document with formatted table content
|
||||
"""
|
||||
# Decode bytes to string with automatic encoding detection
|
||||
text = endecode.decode_bytes(content)
|
||||
# Format all tables in the content
|
||||
text = self.table_helper.format_table(text)
|
||||
return Document(content=text)
|
||||
|
||||
|
||||
class MarkdownImageUtil:
|
||||
"""Utility class for handling images in Markdown.
|
||||
|
||||
This class provides functionality to:
|
||||
- Extract base64-encoded images from Markdown
|
||||
- Extract image paths from Markdown
|
||||
- Replace image paths with new URLs
|
||||
- Convert base64 images to binary format
|
||||
|
||||
Supported formats:
|
||||
- Base64 embedded images: 
|
||||
- Regular image links: 
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Pattern to match base64 embedded images
|
||||
# Captures: (1) alt text, (2) image format, (3) base64 data
|
||||
# Alt text uses .*? (non-greedy) to allow literal ] (e.g. Windows paths).
|
||||
# MIME subtype uses [^;]+ to handle types with hyphens like x-emf.
|
||||
self.b64_pattern = re.compile(
|
||||
r"!\[(.*?)\]\(data:image/([^;]+);base64,([^\)]+)\)"
|
||||
)
|
||||
# Pattern to match regular image syntax (alt text allows ])
|
||||
self.image_pattern = re.compile(r"!\[(.*?)\]\(([^)]+)\)")
|
||||
# Pattern for replacing image paths
|
||||
self.replace_pattern = re.compile(r"!\[(.*?)\]\(([^)]+)\)")
|
||||
|
||||
def extract_image(
|
||||
self,
|
||||
content: str,
|
||||
path_prefix: Optional[str] = None,
|
||||
replace: bool = True,
|
||||
) -> Tuple[str, List[str]]:
|
||||
"""Extract image paths from Markdown content.
|
||||
|
||||
Args:
|
||||
content: Markdown text containing images
|
||||
path_prefix: Optional prefix to add to image paths
|
||||
replace: Whether to replace image syntax in content
|
||||
|
||||
Returns:
|
||||
Tuple of (processed_text, list_of_image_paths)
|
||||
|
||||
Example:
|
||||
>>> util = MarkdownImageUtil()
|
||||
>>> text, images = util.extract_image("")
|
||||
>>> print(images)
|
||||
['img/logo.png']
|
||||
"""
|
||||
# List to store extracted image paths
|
||||
images: List[str] = []
|
||||
|
||||
def repl(match: Match[str]) -> str:
|
||||
"""Replacement function for each image match."""
|
||||
title = match.group(1) # Alt text
|
||||
image_path = match.group(2) # Image path
|
||||
|
||||
# Add prefix if specified
|
||||
if path_prefix:
|
||||
image_path = f"{path_prefix}/{image_path}"
|
||||
|
||||
images.append(image_path)
|
||||
|
||||
# Keep original if replace is False
|
||||
if not replace:
|
||||
return match.group(0)
|
||||
|
||||
# Replace image path with potentially prefixed path
|
||||
return f""
|
||||
|
||||
text = self.image_pattern.sub(repl, content)
|
||||
logger.debug(f"Extracted {len(images)} images from markdown")
|
||||
return text, images
|
||||
|
||||
def extract_base64(
|
||||
self,
|
||||
content: str,
|
||||
path_prefix: Optional[str] = None,
|
||||
replace: bool = True,
|
||||
) -> Tuple[str, Dict[str, bytes]]:
|
||||
"""Extract and decode base64 embedded images from Markdown.
|
||||
|
||||
This method finds all base64-encoded images in the Markdown content,
|
||||
decodes them to binary format, generates unique filenames, and
|
||||
optionally replaces them with file path references.
|
||||
|
||||
Args:
|
||||
content: Markdown text containing base64 images
|
||||
path_prefix: Optional directory prefix for generated paths
|
||||
replace: Whether to replace base64 syntax with file paths
|
||||
|
||||
Returns:
|
||||
Tuple of (processed_text, dict_of_path_to_bytes)
|
||||
|
||||
Example:
|
||||
>>> util = MarkdownImageUtil()
|
||||
>>> text = ""
|
||||
>>> new_text, images = util.extract_base64(text, "images")
|
||||
>>> print(new_text)
|
||||

|
||||
>>> print(len(images))
|
||||
1
|
||||
"""
|
||||
# Dictionary mapping generated file paths to binary image data
|
||||
images: Dict[str, bytes] = {}
|
||||
|
||||
def repl(match: Match[str]) -> str:
|
||||
"""Replacement function for each base64 image match."""
|
||||
title = match.group(1) # Alt text
|
||||
img_ext = match.group(2) # Image format (png, jpg, etc.)
|
||||
img_b64 = match.group(3) # Base64 encoded data
|
||||
|
||||
# Decode base64 string to bytes
|
||||
image_byte = endecode.encode_image(img_b64, errors="ignore")
|
||||
if not image_byte:
|
||||
logger.error(f"Failed to decode base64 image skip it: {img_b64}")
|
||||
return title # Return just the alt text if decode fails
|
||||
|
||||
# Generate unique filename with original extension
|
||||
image_path = f"{uuid.uuid4()}.{img_ext}"
|
||||
if path_prefix:
|
||||
image_path = f"{path_prefix}/{image_path}"
|
||||
images[image_path] = image_byte
|
||||
|
||||
# Keep original base64 if replace is False
|
||||
if not replace:
|
||||
return match.group(0)
|
||||
|
||||
# Replace base64 data with file path reference
|
||||
return f""
|
||||
|
||||
text = self.b64_pattern.sub(repl, content)
|
||||
logger.debug(f"Extracted {len(images)} base64 images from markdown")
|
||||
return text, images
|
||||
|
||||
def replace_path(self, content: str, images: Dict[str, str]) -> str:
|
||||
"""Replace image paths in Markdown with new URLs.
|
||||
|
||||
This method is typically used to replace local file paths with
|
||||
uploaded URLs after images have been stored.
|
||||
|
||||
Args:
|
||||
content: Markdown text with image references
|
||||
images: Mapping of old paths to new URLs
|
||||
|
||||
Returns:
|
||||
Markdown text with updated image URLs
|
||||
|
||||
Example:
|
||||
>>> util = MarkdownImageUtil()
|
||||
>>> content = ""
|
||||
>>> mapping = {"temp/img.png": "https://cdn.com/img.png"}
|
||||
>>> result = util.replace_path(content, mapping)
|
||||
>>> print(result)
|
||||

|
||||
"""
|
||||
# Track which paths were actually replaced
|
||||
content_replace: set = set()
|
||||
|
||||
def repl(match: Match[str]) -> str:
|
||||
"""Replacement function for each image match."""
|
||||
title = match.group(1) # Alt text
|
||||
image_path = match.group(2) # Current image path
|
||||
|
||||
# Only replace if path exists in mapping
|
||||
if image_path not in images:
|
||||
return match.group(0) # Keep original
|
||||
|
||||
content_replace.add(image_path)
|
||||
# Get new URL from mapping
|
||||
image_path = images[image_path]
|
||||
return f"" if image_path else title
|
||||
|
||||
text = self.replace_pattern.sub(repl, content)
|
||||
logger.debug(f"Replaced {len(content_replace)} images in markdown")
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def _self_test():
|
||||
your_content = "testtest"
|
||||
image_handle = MarkdownImageUtil()
|
||||
text, images = image_handle.extract_base64(your_content)
|
||||
print(text)
|
||||
|
||||
for image_url, image_byte in images.items():
|
||||
with open(image_url, "wb") as f:
|
||||
f.write(image_byte)
|
||||
|
||||
|
||||
class MarkdownImageBase64(BaseParser):
|
||||
"""Parser for extracting base64 images from Markdown.
|
||||
|
||||
Extracts base64-encoded images, replaces them with path references,
|
||||
and returns the raw image data in Document.images for the Go-side
|
||||
ImageResolver (or main.py _resolve_images) to handle storage.
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.image_helper = MarkdownImageUtil()
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
text = endecode.decode_bytes(content)
|
||||
text, img_b64 = self.image_helper.extract_base64(text, path_prefix="images")
|
||||
|
||||
images: Dict[str, str] = {}
|
||||
for ipath, raw_bytes in img_b64.items():
|
||||
images[ipath] = base64.b64encode(raw_bytes).decode()
|
||||
|
||||
logger.debug("Extracted %d base64 images from markdown", len(images))
|
||||
return Document(content=text, images=images)
|
||||
|
||||
|
||||
class MarkdownParser(PipelineParser):
|
||||
"""Complete Markdown parser using pipeline approach.
|
||||
|
||||
This parser processes Markdown content through multiple stages:
|
||||
1. MarkdownTableFormatter: Standardizes table formatting
|
||||
2. MarkdownImageBase64: Extracts and uploads base64 images
|
||||
|
||||
The pipeline ensures that content flows through each parser in sequence,
|
||||
with each stage's output becoming the next stage's input.
|
||||
"""
|
||||
|
||||
_parser_cls = (MarkdownTableFormatter, MarkdownImageBase64)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage and testing
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Test the complete MarkdownParser pipeline
|
||||
your_content = "testtest"
|
||||
parser = MarkdownParser()
|
||||
|
||||
# Parse content and display results
|
||||
document = parser.parse_into_text(your_content.encode())
|
||||
logger.info(document.content)
|
||||
logger.info(f"Images: {len(document.images)}, name: {document.images.keys()}")
|
||||
|
||||
# Run individual utility tests
|
||||
MarkdownImageUtil._self_test()
|
||||
MarkdownTableUtil._self_test()
|
||||
@@ -0,0 +1,100 @@
|
||||
import io
|
||||
import logging
|
||||
|
||||
from markitdown import MarkItDown
|
||||
|
||||
from docreader.config import CONFIG
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.chain_parser import PipelineParser
|
||||
from docreader.parser.concurrency import parser_worker_limit
|
||||
from docreader.parser.docx_merge import fill_vertical_merged_cells_docx
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
from docreader.parser.ppt_convert import normalize_ppt_bytes
|
||||
from docreader.parser.pptx_media import (
|
||||
attach_pptx_media_to_markdown,
|
||||
markdown_needs_pptx_media_attach,
|
||||
)
|
||||
from docreader.parser.xlsx_repair import (
|
||||
sanitize_xlsx_styles,
|
||||
strip_unreadable_ranges_xlsx,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StdMarkitdownParser(BaseParser):
|
||||
"""
|
||||
Standard MarkItDown Parser Wrapper
|
||||
|
||||
This parser uses the markitdown library to convert various document formats
|
||||
(docx, pptx, pdf, etc.) into text/markdown.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
# 这里的 super() 会调用 BaseParser 的初始化,确保 self.file_type 被正确赋值
|
||||
super().__init__(*args, **kwargs)
|
||||
self.markitdown = MarkItDown()
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""
|
||||
Parses content using MarkItDown.
|
||||
Uses self.file_type (inherited from BaseParser) to hint the stream format.
|
||||
"""
|
||||
ext = self.file_type
|
||||
ft = (ext or "").lstrip(".").lower()
|
||||
pptx_bytes: bytes | None = None
|
||||
if ft in ("ppt", "pptx"):
|
||||
content, ext = normalize_ppt_bytes(content, ft)
|
||||
pptx_bytes = content
|
||||
ft = "pptx"
|
||||
elif ft == "docx":
|
||||
content = fill_vertical_merged_cells_docx(content)
|
||||
elif ft in ("xlsx", "xlsm"):
|
||||
# MarkItDown reads spreadsheets through pandas/openpyxl, so the
|
||||
# ranges openpyxl cannot parse (#3599) and the non-conforming
|
||||
# styles.xml fills (#3637) that break the builtin ExcelParser break
|
||||
# this engine too. Strip the ranges first: the fill repair alone
|
||||
# would still leave the range TypeError. Both passes return None
|
||||
# for clean workbooks.
|
||||
readable = strip_unreadable_ranges_xlsx(content)
|
||||
if readable is not None:
|
||||
content = readable
|
||||
sanitized = sanitize_xlsx_styles(content)
|
||||
if sanitized is not None:
|
||||
content = sanitized
|
||||
if ext and not ext.startswith("."):
|
||||
ext = "." + ext
|
||||
|
||||
with parser_worker_limit("markitdown", CONFIG.markitdown_max_workers):
|
||||
result = self._convert_markitdown(content, ext, keep_data_uris=True)
|
||||
if result is None:
|
||||
logger.warning(
|
||||
"MarkItDown failed with embedded images for %s; retrying without data URIs",
|
||||
ft or ext,
|
||||
)
|
||||
result = self._convert_markitdown(content, ext, keep_data_uris=False)
|
||||
|
||||
text = result.text_content
|
||||
images: dict[str, str] = {}
|
||||
if pptx_bytes is not None and markdown_needs_pptx_media_attach(text):
|
||||
text, images = attach_pptx_media_to_markdown(text, pptx_bytes)
|
||||
return Document(content=text, images=images)
|
||||
|
||||
def _convert_markitdown(
|
||||
self, content: bytes, ext: str | None, *, keep_data_uris: bool
|
||||
):
|
||||
try:
|
||||
return self.markitdown.convert(
|
||||
io.BytesIO(content),
|
||||
file_extension=ext,
|
||||
keep_data_uris=keep_data_uris,
|
||||
)
|
||||
except Exception:
|
||||
if keep_data_uris:
|
||||
return None
|
||||
raise
|
||||
|
||||
|
||||
class MarkitdownParser(PipelineParser):
|
||||
_parser_cls = (StdMarkitdownParser, MarkdownParser)
|
||||
@@ -0,0 +1,441 @@
|
||||
"""MHTML parser.
|
||||
|
||||
Parses MIME HTML web archives into markdown text and optional embedded images.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import email
|
||||
import html
|
||||
import logging
|
||||
import os
|
||||
from email.header import decode_header
|
||||
from urllib.parse import unquote, urljoin, urlparse
|
||||
import uuid
|
||||
from typing import Dict
|
||||
|
||||
from bs4 import BeautifulSoup, NavigableString
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_AD_DOMAINS = (
|
||||
"googleads",
|
||||
"doubleclick",
|
||||
"googlesyndication",
|
||||
"facebook.com/tr",
|
||||
"analytics",
|
||||
"pixel",
|
||||
)
|
||||
|
||||
_UNKNOWN_8BIT = frozenset({"unknown-8bit", "unknown"})
|
||||
|
||||
# Inline elements that markdownify renders as "" when their text is only
|
||||
# whitespace, taking that whitespace with them.
|
||||
_WHITESPACE_DROPPING_INLINE_TAGS = (
|
||||
"a",
|
||||
"b",
|
||||
"code",
|
||||
"del",
|
||||
"em",
|
||||
"i",
|
||||
"kbd",
|
||||
"s",
|
||||
"samp",
|
||||
"strong",
|
||||
"sub",
|
||||
"sup",
|
||||
)
|
||||
|
||||
|
||||
def _header_str(value) -> str:
|
||||
"""Normalize a MIME header to str, recovering 8-bit UTF-8 bytes.
|
||||
|
||||
``email.message_from_bytes`` uses compat32 by default. Browser-saved
|
||||
``.mhtml`` files often store raw UTF-8 in headers such as Content-Location.
|
||||
Those values come back as ``email.header.Header`` with charset
|
||||
``unknown-8bit``: ``.strip()`` / ``.lower()`` raise AttributeError, and
|
||||
``str(Header)`` replaces the bytes with U+FFFD so image aliases no longer
|
||||
match the HTML body.
|
||||
"""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, bytes):
|
||||
return value.decode("utf-8", errors="replace")
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return value.encode("ascii", "surrogateescape").decode("utf-8")
|
||||
except UnicodeError:
|
||||
return value
|
||||
try:
|
||||
chunks = decode_header(value)
|
||||
except (TypeError, ValueError, LookupError, UnicodeError):
|
||||
return str(value)
|
||||
|
||||
parts: list[str] = []
|
||||
for chunk, charset in chunks:
|
||||
if isinstance(chunk, bytes):
|
||||
encoding = (charset or "utf-8").lower()
|
||||
if encoding in _UNKNOWN_8BIT:
|
||||
encoding = "utf-8"
|
||||
try:
|
||||
parts.append(chunk.decode(encoding, errors="replace"))
|
||||
except LookupError:
|
||||
parts.append(chunk.decode("utf-8", errors="replace"))
|
||||
elif chunk:
|
||||
try:
|
||||
parts.append(
|
||||
chunk.encode("ascii", "surrogateescape").decode("utf-8")
|
||||
)
|
||||
except UnicodeError:
|
||||
parts.append(chunk)
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
class MHTMLParser(BaseParser):
|
||||
"""Parser for MHTML web archives."""
|
||||
|
||||
def __init__(self, *args, extract_images: bool = True, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.extract_images = extract_images
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
logger.info(
|
||||
"Parsing MHTML file: %s, size: %d bytes", self.file_name, len(content)
|
||||
)
|
||||
msg = email.message_from_bytes(content)
|
||||
|
||||
html_parts = []
|
||||
images: Dict[str, str] = {}
|
||||
image_aliases: Dict[str, str] = {}
|
||||
metadata: Dict[str, object] = {}
|
||||
|
||||
for part in msg.walk():
|
||||
content_type = part.get_content_type()
|
||||
location = _header_str(part.get("Content-Location", ""))
|
||||
|
||||
if content_type == "text/html":
|
||||
payload = part.get_payload(decode=True)
|
||||
if not payload:
|
||||
continue
|
||||
charset = part.get_content_charset() or "utf-8"
|
||||
try:
|
||||
html_text = payload.decode(charset, errors="ignore")
|
||||
except LookupError:
|
||||
html_text = payload.decode("utf-8", errors="ignore")
|
||||
html_parts.append(
|
||||
{
|
||||
"content": html_text,
|
||||
"location": location,
|
||||
"size": len(html_text),
|
||||
}
|
||||
)
|
||||
elif content_type.startswith("image/") and self.extract_images:
|
||||
image_data = part.get_payload(decode=True)
|
||||
if image_data:
|
||||
image_path = self._image_path_for_part(part, content_type, images)
|
||||
images[image_path] = base64.b64encode(image_data).decode("utf-8")
|
||||
self._add_image_aliases(image_aliases, part, image_path)
|
||||
|
||||
main_html = self._select_main_html(html_parts)
|
||||
if not main_html:
|
||||
logger.warning("No HTML content found in MHTML file")
|
||||
return Document(
|
||||
content="", images=images, metadata={"source_format": "mhtml"}
|
||||
)
|
||||
html_content = main_html["content"]
|
||||
|
||||
try:
|
||||
markdown_text = self.html_to_markdown(
|
||||
html_content,
|
||||
image_aliases=image_aliases,
|
||||
base_location=main_html.get("location", ""),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Failed to convert HTML to Markdown: %s", e)
|
||||
markdown_text = f"```html\n{html_content}\n```"
|
||||
|
||||
metadata["source_format"] = "mhtml"
|
||||
metadata["file_size"] = len(content)
|
||||
metadata["image_count"] = len(images)
|
||||
return Document(content=markdown_text, images=images, metadata=metadata)
|
||||
|
||||
def _select_main_html(self, html_parts) -> dict:
|
||||
"""Pick the largest non-ad HTML part as the main document body."""
|
||||
if not html_parts:
|
||||
return {}
|
||||
|
||||
def is_ad(location: str) -> bool:
|
||||
loc = _header_str(location)
|
||||
if not loc:
|
||||
return False
|
||||
loc = loc.lower()
|
||||
return any(ad in loc for ad in _AD_DOMAINS)
|
||||
|
||||
non_ad = sorted(
|
||||
(part for part in html_parts if not is_ad(part.get("location", ""))),
|
||||
key=lambda part: part["size"],
|
||||
reverse=True,
|
||||
)
|
||||
if non_ad:
|
||||
logger.info("Selected main HTML: %d bytes", non_ad[0]["size"])
|
||||
return non_ad[0]
|
||||
|
||||
largest = max(html_parts, key=lambda part: part["size"])
|
||||
logger.warning(
|
||||
"Only ad content found, using largest: %d bytes", largest["size"]
|
||||
)
|
||||
return largest
|
||||
|
||||
@staticmethod
|
||||
def _add_image_aliases(
|
||||
image_aliases: Dict[str, str], part, image_path: str
|
||||
) -> None:
|
||||
"""Register the refs an MHTML document may use for an image part."""
|
||||
for raw in (
|
||||
part.get("Content-Location", ""),
|
||||
part.get("Content-ID", ""),
|
||||
part.get("X-Attachment-Id", ""),
|
||||
):
|
||||
raw = _header_str(raw).strip()
|
||||
if not raw:
|
||||
continue
|
||||
values = {raw, html.unescape(raw), unquote(html.unescape(raw))}
|
||||
cid = raw.strip("<>")
|
||||
if cid:
|
||||
values.add(f"cid:{cid}")
|
||||
values.add(f"cid:{unquote(cid)}")
|
||||
for value in values:
|
||||
if value:
|
||||
image_aliases[value] = image_path
|
||||
|
||||
@staticmethod
|
||||
def _image_extension(content_type: str) -> str:
|
||||
return {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
"image/bmp": ".bmp",
|
||||
"image/tiff": ".tiff",
|
||||
"image/x-icon": ".ico",
|
||||
}.get(content_type, ".png")
|
||||
|
||||
@classmethod
|
||||
def _image_path_for_part(
|
||||
cls, part, content_type: str, images: Dict[str, str]
|
||||
) -> str:
|
||||
"""Choose a stable image path when the MHTML part exposes a filename."""
|
||||
ext = cls._image_extension(content_type)
|
||||
location = _header_str(part.get("Content-Location", "")).strip()
|
||||
filename = cls._filename_from_content_location(location)
|
||||
if not filename:
|
||||
return f"images/{uuid.uuid4().hex}{ext}"
|
||||
|
||||
stem, location_ext = os.path.splitext(filename)
|
||||
if not location_ext:
|
||||
filename = f"{filename}{ext}"
|
||||
image_path = f"images/{filename}"
|
||||
if image_path not in images:
|
||||
return image_path
|
||||
|
||||
suffix = 2
|
||||
stem, location_ext = os.path.splitext(filename)
|
||||
while True:
|
||||
candidate = f"images/{stem}_{suffix}{location_ext}"
|
||||
if candidate not in images:
|
||||
return candidate
|
||||
suffix += 1
|
||||
|
||||
@staticmethod
|
||||
def _filename_from_content_location(location: str) -> str:
|
||||
decoded = unquote(html.unescape(_header_str(location).strip()))
|
||||
if not decoded or decoded.lower().startswith("cid:"):
|
||||
return ""
|
||||
path = urlparse(decoded).path or decoded
|
||||
filename = os.path.basename(path)
|
||||
if not filename or filename in {".", ".."}:
|
||||
return ""
|
||||
if "/" in filename or "\\" in filename:
|
||||
return ""
|
||||
return filename
|
||||
|
||||
def html_to_markdown(
|
||||
self,
|
||||
html_content: str,
|
||||
image_aliases: Dict[str, str] | None = None,
|
||||
base_location: str = "",
|
||||
*,
|
||||
strip_internal_links: bool = True,
|
||||
fallback_to_raw_html: bool = True,
|
||||
) -> str:
|
||||
"""Convert HTML to Markdown with explicit link and fallback policies."""
|
||||
|
||||
def raw_html_fallback() -> str:
|
||||
if not fallback_to_raw_html:
|
||||
return ""
|
||||
return f"```html\n{html_content[:50000]}\n```"
|
||||
|
||||
try:
|
||||
from markdownify import markdownify as md
|
||||
|
||||
soup = BeautifulSoup(html_content, "lxml")
|
||||
for tag in soup(["script", "style", "noscript", "iframe"]):
|
||||
tag.decompose()
|
||||
if strip_internal_links:
|
||||
self._strip_internal_links(soup)
|
||||
if image_aliases:
|
||||
self._rewrite_image_sources(soup, image_aliases, base_location)
|
||||
self._unwrap_whitespace_only_inline(soup)
|
||||
text_fallback = soup.get_text(separator="\n", strip=True)
|
||||
self._escape_table_cell_pipes(soup)
|
||||
markdown_text = md(str(soup), heading_style="ATX")
|
||||
result = self._normalize_markdown(markdown_text)
|
||||
if not result and text_fallback:
|
||||
logger.warning("Markdown empty, falling back to text extraction")
|
||||
return text_fallback
|
||||
if not result:
|
||||
return raw_html_fallback()
|
||||
return result
|
||||
except ImportError:
|
||||
logger.warning("markdownify not available, returning raw HTML")
|
||||
return raw_html_fallback()
|
||||
except Exception as e:
|
||||
logger.error("HTML to Markdown conversion failed: %s", e)
|
||||
return raw_html_fallback()
|
||||
|
||||
def _html_to_markdown(
|
||||
self,
|
||||
html_content: str,
|
||||
image_aliases: Dict[str, str] | None = None,
|
||||
base_location: str = "",
|
||||
) -> str:
|
||||
"""Backward-compatible wrapper for existing internal callers and tests."""
|
||||
return self.html_to_markdown(html_content, image_aliases, base_location)
|
||||
|
||||
@staticmethod
|
||||
def _unwrap_whitespace_only_inline(soup: BeautifulSoup) -> None:
|
||||
"""Keep the whitespace held by an otherwise empty inline element.
|
||||
|
||||
markdownify drops such an element together with its whitespace, so
|
||||
``further<strong> </strong>reference`` became ``furtherreference``.
|
||||
Unwrapping leaves the whitespace as plain text. Innermost elements go
|
||||
first, so ``<b><i> </i></b>`` is unwrapped completely.
|
||||
"""
|
||||
for tag in reversed(soup.find_all(_WHITESPACE_DROPPING_INLINE_TAGS)):
|
||||
if tag.find(True) is None and not tag.get_text().strip():
|
||||
tag.unwrap()
|
||||
|
||||
@staticmethod
|
||||
def _escape_table_cell_pipes(soup: BeautifulSoup) -> None:
|
||||
"""Escape the ``|`` in table cell text, which markdownify writes as is.
|
||||
|
||||
In the GFM table markdownify writes, a bare pipe in a cell's text ends
|
||||
the cell, so the row gains a column and every later cell shifts one
|
||||
column right.
|
||||
"""
|
||||
for cell in soup.find_all(["td", "th"]):
|
||||
for text in cell.find_all(string=True):
|
||||
# Comments and other special strings keep their own type
|
||||
if type(text) is NavigableString and "|" in text:
|
||||
text.replace_with(text.replace("|", "\\|"))
|
||||
|
||||
@staticmethod
|
||||
def _normalize_markdown(markdown_text: str) -> str:
|
||||
text = markdown_text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
output: list[str] = []
|
||||
pending_blank = False
|
||||
fence_char: str | None = None
|
||||
fence_len = 0
|
||||
|
||||
for line in text.split("\n"):
|
||||
if fence_char is not None:
|
||||
output.append(line)
|
||||
if MHTMLParser._is_closing_fence(line, fence_char, fence_len):
|
||||
fence_char = None
|
||||
fence_len = 0
|
||||
continue
|
||||
|
||||
opening = MHTMLParser._opening_fence(line)
|
||||
if opening is not None:
|
||||
if pending_blank and output:
|
||||
output.append("")
|
||||
pending_blank = False
|
||||
output.append(line)
|
||||
fence_char, fence_len = opening
|
||||
continue
|
||||
|
||||
if not line.strip(" \t"):
|
||||
pending_blank = True
|
||||
continue
|
||||
|
||||
if pending_blank and output:
|
||||
output.append("")
|
||||
pending_blank = False
|
||||
|
||||
trailing_spaces = len(line) - len(line.rstrip(" "))
|
||||
if trailing_spaces >= 2:
|
||||
line = line.rstrip(" \t") + " "
|
||||
else:
|
||||
line = line.rstrip(" \t")
|
||||
output.append(line)
|
||||
|
||||
return "\n".join(output).strip("\n")
|
||||
|
||||
@staticmethod
|
||||
def _opening_fence(line: str) -> tuple[str, int] | None:
|
||||
stripped = line.lstrip(" ")
|
||||
if len(line) - len(stripped) > 3 or not stripped:
|
||||
return None
|
||||
fence_char = stripped[0]
|
||||
if fence_char not in {"`", "~"}:
|
||||
return None
|
||||
fence_len = len(stripped) - len(stripped.lstrip(fence_char))
|
||||
if fence_len < 3:
|
||||
return None
|
||||
return fence_char, fence_len
|
||||
|
||||
@staticmethod
|
||||
def _is_closing_fence(line: str, fence_char: str, fence_len: int) -> bool:
|
||||
stripped = line.lstrip(" ")
|
||||
if len(line) - len(stripped) > 3:
|
||||
return False
|
||||
closing_len = len(stripped) - len(stripped.lstrip(fence_char))
|
||||
if closing_len < fence_len:
|
||||
return False
|
||||
return not stripped[closing_len:].strip(" \t")
|
||||
|
||||
@staticmethod
|
||||
def _strip_internal_links(soup: BeautifulSoup) -> None:
|
||||
"""Unwrap links that don't point to an external resource."""
|
||||
external = ("http://", "https://", "mailto:", "tel:")
|
||||
for link in soup.find_all("a"):
|
||||
href = (link.get("href") or "").strip().lower()
|
||||
if not href or not href.startswith(external):
|
||||
link.unwrap()
|
||||
|
||||
@staticmethod
|
||||
def _rewrite_image_sources(
|
||||
soup: BeautifulSoup,
|
||||
image_aliases: Dict[str, str],
|
||||
base_location: str = "",
|
||||
) -> None:
|
||||
for img in soup.find_all("img"):
|
||||
src = (img.get("src") or "").strip()
|
||||
if not src:
|
||||
continue
|
||||
candidates = [
|
||||
src,
|
||||
html.unescape(src),
|
||||
unquote(html.unescape(src)),
|
||||
]
|
||||
if base_location:
|
||||
candidates.append(urljoin(base_location, src))
|
||||
base_name = os.path.basename(unquote(html.unescape(src)))
|
||||
if base_name:
|
||||
candidates.append(base_name)
|
||||
for candidate in candidates:
|
||||
if candidate in image_aliases:
|
||||
img["src"] = image_aliases[candidate]
|
||||
break
|
||||
@@ -0,0 +1,378 @@
|
||||
"""PDF parser backed by OpenDataLoader PDF (Apache-2.0).
|
||||
|
||||
Requires Java 11+ on PATH and the ``opendataloader-pdf`` Python package.
|
||||
Each ``convert()`` spawns a JVM; concurrency is limited via
|
||||
``DOCREADER_ODL_MAX_WORKERS``.
|
||||
|
||||
Hybrid mode (``docling-fast``, etc.) needs a running
|
||||
``opendataloader-pdf-hybrid`` server — configure ``DOCREADER_ODL_HYBRID_URL``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Dict, Mapping, Optional, Tuple
|
||||
|
||||
from docreader.config import CONFIG
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.concurrency import parser_worker_limit
|
||||
from docreader.utils.ssrf import is_ssrf_safe_url
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MIN_CHARS_PER_PAGE = 20
|
||||
_IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp")
|
||||
_MD_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
|
||||
_IMAGE_FILE_NUM_RE = re.compile(r"^imageFile(\d+)\.", re.I)
|
||||
|
||||
|
||||
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
"""Health probes never need redirects; refusing them closes redirect SSRF."""
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def _override_str(overrides: Optional[Mapping[str, Any]], key: str, default: str = "") -> str:
|
||||
if overrides:
|
||||
v = overrides.get(key)
|
||||
if v is not None and str(v).strip() != "":
|
||||
return str(v).strip()
|
||||
return default
|
||||
|
||||
|
||||
def _override_bool(overrides: Optional[Mapping[str, Any]], key: str, default: bool) -> bool:
|
||||
if overrides:
|
||||
v = overrides.get(key)
|
||||
if v is not None and str(v).strip() != "":
|
||||
return str(v).strip().lower() in {"1", "true", "yes", "y", "on"}
|
||||
return default
|
||||
|
||||
|
||||
def _java_available() -> Tuple[bool, str]:
|
||||
if not shutil.which("java"):
|
||||
return False, "需要 Java 11+(JRE),请安装并在 PATH 中配置 java"
|
||||
return True, ""
|
||||
|
||||
|
||||
def _package_available() -> Tuple[bool, str]:
|
||||
try:
|
||||
import opendataloader_pdf # noqa: F401
|
||||
except ImportError as e:
|
||||
return False, f"opendataloader-pdf 未安装: {e}"
|
||||
return True, ""
|
||||
|
||||
|
||||
def _ping_hybrid(
|
||||
url: str,
|
||||
*,
|
||||
timeout_sec: float = 5.0,
|
||||
retries: int = 3,
|
||||
retry_delay_sec: float = 2.0,
|
||||
) -> Tuple[bool, str]:
|
||||
import time
|
||||
|
||||
base = url.rstrip("/")
|
||||
health_url = f"{base}/health"
|
||||
safe, reason = is_ssrf_safe_url(health_url)
|
||||
if not safe:
|
||||
return False, f"OpenDataLoader hybrid URL 被 SSRF 防护拦截: {reason}"
|
||||
|
||||
opener = urllib.request.build_opener(_NoRedirectHandler())
|
||||
last_err = ""
|
||||
for attempt in range(max(1, retries)):
|
||||
try:
|
||||
req = urllib.request.Request(health_url, method="GET")
|
||||
with opener.open(req, timeout=timeout_sec) as resp:
|
||||
if 200 <= resp.status < 300:
|
||||
return True, ""
|
||||
last_err = f"hybrid 健康检查 HTTP {resp.status}: {health_url}"
|
||||
except urllib.error.URLError as e:
|
||||
last_err = f"无法连接 OpenDataLoader hybrid 服务 ({health_url}): {e}"
|
||||
except Exception as e:
|
||||
last_err = f"hybrid 健康检查失败: {e}"
|
||||
if attempt + 1 < retries:
|
||||
time.sleep(retry_delay_sec)
|
||||
hint = (
|
||||
";若刚执行 make dev-start --odl-hybrid,请等待镜像构建/服务就绪"
|
||||
"(docker logs Academy-odl-hybrid)"
|
||||
)
|
||||
return False, last_err + hint
|
||||
|
||||
|
||||
def opendataloader_available(
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
quick: bool = False,
|
||||
) -> Tuple[bool, str]:
|
||||
"""Registry / ListEngines availability probe.
|
||||
|
||||
When ``quick`` is set the hybrid health check uses a single short-timeout
|
||||
attempt with no retries, so it can be used for fast status listing without
|
||||
blocking on long retry/backoff loops. Parsing keeps the patient retry
|
||||
behavior to tolerate a hybrid service that is still starting up.
|
||||
"""
|
||||
ok, msg = _java_available()
|
||||
if not ok:
|
||||
return False, msg
|
||||
ok, msg = _package_available()
|
||||
if not ok:
|
||||
return False, msg
|
||||
|
||||
hybrid = _resolve_hybrid(overrides)
|
||||
if hybrid and hybrid.lower() not in ("off", ""):
|
||||
url = _resolve_hybrid_url(overrides)
|
||||
if url:
|
||||
if quick:
|
||||
return _ping_hybrid(url, retries=1, timeout_sec=2.0)
|
||||
return _ping_hybrid(url, retries=6, retry_delay_sec=5.0, timeout_sec=5.0)
|
||||
return True, ""
|
||||
|
||||
|
||||
def _resolve_hybrid(overrides: Optional[Mapping[str, Any]] = None) -> str:
|
||||
return _override_str(overrides, "odl_hybrid", CONFIG.odl_hybrid)
|
||||
|
||||
|
||||
def _resolve_hybrid_url(overrides: Optional[Mapping[str, Any]] = None) -> str:
|
||||
return _override_str(overrides, "odl_hybrid_url", CONFIG.odl_hybrid_url)
|
||||
|
||||
|
||||
def _find_markdown_file(output_dir: str, pdf_stem: str) -> str:
|
||||
candidates = []
|
||||
for root, _, files in os.walk(output_dir):
|
||||
for name in files:
|
||||
if name.lower().endswith(".md"):
|
||||
path = os.path.join(root, name)
|
||||
candidates.append(path)
|
||||
if not candidates:
|
||||
raise FileNotFoundError(f"OpenDataLoader 未在 {output_dir} 生成 markdown 文件")
|
||||
for path in candidates:
|
||||
base = os.path.splitext(os.path.basename(path))[0]
|
||||
if base == pdf_stem or base.startswith(pdf_stem):
|
||||
return path
|
||||
candidates.sort(key=lambda p: os.path.getmtime(p), reverse=True)
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _normalize_odl_image_url(raw: str) -> str:
|
||||
"""OpenDataLoader wraps paths as ``<images/foo.png>``; storage may HTML-escape them."""
|
||||
s = html.unescape((raw or "").strip())
|
||||
s = s.replace("<", "<").replace(">", ">").replace("&", "&")
|
||||
s = s.strip().strip("<>").strip().strip('"').strip("'")
|
||||
if s.startswith("./"):
|
||||
s = s[2:]
|
||||
return s.replace("\\", "/")
|
||||
|
||||
|
||||
def _canonical_image_ref(abs_path: str, output_dir: str) -> str:
|
||||
"""Use ``images/<file>`` keys to match OpenDataLoader markdown conventions."""
|
||||
rel = os.path.relpath(abs_path, output_dir).replace("\\", "/")
|
||||
name = os.path.basename(abs_path)
|
||||
if rel.startswith("images/"):
|
||||
return rel
|
||||
return f"images/{name}"
|
||||
|
||||
|
||||
def _collect_images_under_output(output_dir: str) -> Dict[str, str]:
|
||||
"""Collect every extracted image under the convert output tree."""
|
||||
images: Dict[str, str] = {}
|
||||
for root, _, files in os.walk(output_dir):
|
||||
for name in files:
|
||||
if not name.lower().endswith(_IMAGE_SUFFIXES):
|
||||
continue
|
||||
abs_path = os.path.join(root, name)
|
||||
ref = _canonical_image_ref(abs_path, output_dir)
|
||||
if ref in images:
|
||||
continue
|
||||
with open(abs_path, "rb") as f:
|
||||
images[ref] = base64.b64encode(f.read()).decode("utf-8")
|
||||
return images
|
||||
|
||||
|
||||
def _register_image_alias(aliases: Dict[str, str], alias: str, canonical: str) -> None:
|
||||
key = _normalize_odl_image_url(alias)
|
||||
if key:
|
||||
aliases[key] = canonical
|
||||
|
||||
|
||||
def _build_path_alias_map(images: Dict[str, str]) -> Dict[str, str]:
|
||||
"""Map ODL markdown spellings (angle brackets, entities, basenames) to dict keys."""
|
||||
aliases: Dict[str, str] = {}
|
||||
for ref in images:
|
||||
base = os.path.basename(ref)
|
||||
variants = [
|
||||
ref,
|
||||
base,
|
||||
f"images/{base}",
|
||||
f"<{ref}>",
|
||||
f"<images/{base}>",
|
||||
f"<{ref}>",
|
||||
f"<images/{base}>",
|
||||
]
|
||||
for variant in variants:
|
||||
_register_image_alias(aliases, variant, ref)
|
||||
return aliases
|
||||
|
||||
|
||||
def _resolve_image_ref(url: str, aliases: Dict[str, str]) -> Optional[str]:
|
||||
key = _normalize_odl_image_url(url)
|
||||
if not key or key.startswith("data:"):
|
||||
return None
|
||||
if key in aliases:
|
||||
return aliases[key]
|
||||
base = os.path.basename(key)
|
||||
for candidate in (base, f"images/{base}"):
|
||||
if candidate in aliases:
|
||||
return aliases[candidate]
|
||||
m = _IMAGE_FILE_NUM_RE.match(base)
|
||||
if m:
|
||||
num = int(m.group(1))
|
||||
numbered = []
|
||||
for ref in {aliases[k] for k in aliases}:
|
||||
bm = _IMAGE_FILE_NUM_RE.match(os.path.basename(ref))
|
||||
if bm:
|
||||
numbered.append((int(bm.group(1)), ref))
|
||||
numbered.sort(key=lambda x: x[0])
|
||||
for n, ref in numbered:
|
||||
if n == num:
|
||||
return ref
|
||||
if numbered and 1 <= num <= len(numbered):
|
||||
return numbered[num - 1][1]
|
||||
return None
|
||||
|
||||
|
||||
def _rewrite_markdown_image_refs(
|
||||
markdown: str, images: Dict[str, str]
|
||||
) -> str:
|
||||
if not images:
|
||||
return markdown
|
||||
aliases = _build_path_alias_map(images)
|
||||
|
||||
def repl(match: re.Match[str]) -> str:
|
||||
alt, raw_url = match.group(1), match.group(2)
|
||||
url = raw_url.strip().split()[0] if raw_url else ""
|
||||
canonical = _resolve_image_ref(url, aliases)
|
||||
if canonical is None:
|
||||
return match.group(0)
|
||||
return f""
|
||||
|
||||
return _MD_IMAGE_RE.sub(repl, markdown)
|
||||
|
||||
|
||||
def _run_convert(
|
||||
pdf_path: str,
|
||||
output_dir: str,
|
||||
image_dir: str,
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> None:
|
||||
import opendataloader_pdf
|
||||
|
||||
kwargs: Dict[str, Any] = {
|
||||
"input_path": pdf_path,
|
||||
"output_dir": output_dir,
|
||||
"format": "markdown",
|
||||
"image_output": "external",
|
||||
"image_dir": image_dir,
|
||||
"quiet": True,
|
||||
"markdown_with_html": _override_bool(
|
||||
overrides, "odl_markdown_with_html", CONFIG.odl_markdown_with_html
|
||||
),
|
||||
}
|
||||
hybrid = _resolve_hybrid(overrides)
|
||||
if hybrid and hybrid.lower() not in ("off", ""):
|
||||
kwargs["hybrid"] = hybrid
|
||||
hybrid_url = _resolve_hybrid_url(overrides)
|
||||
if hybrid_url:
|
||||
safe, reason = is_ssrf_safe_url(hybrid_url)
|
||||
if not safe:
|
||||
raise RuntimeError(
|
||||
f"OpenDataLoader hybrid URL 被 SSRF 防护拦截: {reason}"
|
||||
)
|
||||
kwargs["hybrid_url"] = hybrid_url
|
||||
hybrid_mode = _override_str(overrides, "odl_hybrid_mode", CONFIG.odl_hybrid_mode)
|
||||
if hybrid_mode:
|
||||
kwargs["hybrid_mode"] = hybrid_mode
|
||||
if _override_bool(overrides, "odl_hybrid_fallback", CONFIG.odl_hybrid_fallback):
|
||||
kwargs["hybrid_fallback"] = True
|
||||
|
||||
opendataloader_pdf.convert(**kwargs)
|
||||
|
||||
|
||||
class OpenDataLoaderParser(BaseParser):
|
||||
"""Parse PDFs with OpenDataLoader (layout-aware markdown + external images)."""
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any):
|
||||
self._engine_overrides: Dict[str, Any] = {
|
||||
k: v
|
||||
for k, v in kwargs.items()
|
||||
if k.startswith("odl_") or k in ("mineru_endpoint", "mineru_api_key")
|
||||
}
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
ok, msg = opendataloader_available(self._engine_overrides)
|
||||
if not ok:
|
||||
raise RuntimeError(msg)
|
||||
|
||||
safe_name = os.path.basename(self.file_name) or "document.pdf"
|
||||
if not safe_name.lower().endswith(".pdf"):
|
||||
safe_name = f"{os.path.splitext(safe_name)[0] or 'document'}.pdf"
|
||||
pdf_stem = os.path.splitext(safe_name)[0]
|
||||
|
||||
max_workers = CONFIG.odl_max_workers
|
||||
with parser_worker_limit("opendataloader", max_workers):
|
||||
with tempfile.TemporaryDirectory(prefix="academy-odl-") as tmp_dir:
|
||||
pdf_path = os.path.join(tmp_dir, safe_name)
|
||||
with open(pdf_path, "wb") as f:
|
||||
f.write(content)
|
||||
image_dir = os.path.join(tmp_dir, "images")
|
||||
os.makedirs(image_dir, exist_ok=True)
|
||||
|
||||
_run_convert(
|
||||
pdf_path,
|
||||
tmp_dir,
|
||||
image_dir,
|
||||
overrides=self._engine_overrides,
|
||||
)
|
||||
|
||||
md_path = _find_markdown_file(tmp_dir, pdf_stem)
|
||||
with open(md_path, encoding="utf-8", errors="replace") as f:
|
||||
text = f.read()
|
||||
|
||||
images = _collect_images_under_output(tmp_dir)
|
||||
text = _rewrite_markdown_image_refs(text, images)
|
||||
|
||||
if len(text.strip()) < _MIN_CHARS_PER_PAGE:
|
||||
logger.info(
|
||||
"OpenDataLoaderParser: %s yielded little text; "
|
||||
"falling back to builtin scanned renderer",
|
||||
self.file_name,
|
||||
)
|
||||
from docreader.parser.pdf_parser import PDFScannedParser
|
||||
|
||||
return PDFScannedParser(
|
||||
file_name=self.file_name, file_type=self.file_type
|
||||
).parse_into_text(content)
|
||||
|
||||
logger.info(
|
||||
"OpenDataLoaderParser: %s -> content_len=%d images=%d",
|
||||
self.file_name,
|
||||
len(text),
|
||||
len(images),
|
||||
)
|
||||
return Document(
|
||||
content=text,
|
||||
images=images,
|
||||
metadata={
|
||||
"parser_engine": "opendataloader",
|
||||
"odl_hybrid": _resolve_hybrid(self._engine_overrides) or "off",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.registry import registry
|
||||
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).
|
||||
|
||||
Converts files/URLs to markdown + image references.
|
||||
No chunking, no storage, no OCR, no VLM.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.registry = registry
|
||||
logger.info(
|
||||
"Parser initialized with engines: %s",
|
||||
", ".join(self.registry.get_engine_names()),
|
||||
)
|
||||
|
||||
def parse_file(
|
||||
self,
|
||||
file_name: str,
|
||||
file_type: str,
|
||||
content: bytes,
|
||||
parser_engine: Optional[str] = None,
|
||||
engine_overrides: Optional[dict[str, Any]] = None,
|
||||
) -> Document:
|
||||
"""Parse file content to markdown."""
|
||||
engine = parser_engine or ""
|
||||
overrides = engine_overrides or {}
|
||||
logger.info(
|
||||
"Parsing file: %s, type: %s, engine: %s",
|
||||
file_name,
|
||||
file_type,
|
||||
engine or "builtin",
|
||||
)
|
||||
|
||||
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__,
|
||||
effective_file_type,
|
||||
)
|
||||
parser = cls(
|
||||
file_name=file_name,
|
||||
file_type=effective_file_type,
|
||||
**overrides,
|
||||
)
|
||||
|
||||
logger.info("Starting to parse file content, size: %d bytes", len(content))
|
||||
result = parser.parse(content)
|
||||
|
||||
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))
|
||||
return result
|
||||
|
||||
def parse_url(
|
||||
self,
|
||||
url: str,
|
||||
title: str,
|
||||
parser_engine: Optional[str] = None,
|
||||
engine_overrides: Optional[dict[str, Any]] = None,
|
||||
) -> Document:
|
||||
"""Parse content from a URL to markdown."""
|
||||
logger.info("Parsing URL: %s, title: %s", url, title)
|
||||
|
||||
parser = WebParser(title=title)
|
||||
logger.info("Starting to parse URL content")
|
||||
result = parser.parse(url.encode())
|
||||
|
||||
if not result.content:
|
||||
logger.warning("Parser returned empty content for url: %s", url)
|
||||
logger.info("Parsed url %s, content length=%d", url, len(result.content))
|
||||
return result
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,116 @@
|
||||
"""LibreOffice helpers for legacy binary PowerPoint (.ppt) uploads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from docreader.parser.excel_convert import find_soffice
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
||||
_ZIP_MAGIC = b"PK\x03\x04"
|
||||
|
||||
|
||||
def is_ole_compound(content: bytes) -> bool:
|
||||
return len(content) >= len(_OLE_MAGIC) and content.startswith(_OLE_MAGIC)
|
||||
|
||||
|
||||
def is_zip_openxml(content: bytes) -> bool:
|
||||
return len(content) >= len(_ZIP_MAGIC) and content.startswith(_ZIP_MAGIC)
|
||||
|
||||
|
||||
def needs_ppt_to_pptx_conversion(content: bytes, file_type: str | None) -> bool:
|
||||
"""True when content is legacy .ppt (OLE), not modern .pptx (ZIP)."""
|
||||
ext = (file_type or "").lstrip(".").lower()
|
||||
if ext == "pptx" or is_zip_openxml(content):
|
||||
return False
|
||||
if ext == "ppt" or is_ole_compound(content):
|
||||
return is_ole_compound(content) or ext == "ppt"
|
||||
return False
|
||||
|
||||
|
||||
def convert_ppt_to_pptx_bytes(content: bytes, suffix: str = ".ppt") -> bytes | None:
|
||||
"""Convert legacy PowerPoint bytes to PPTX using LibreOffice, if available."""
|
||||
soffice = find_soffice()
|
||||
if not soffice:
|
||||
return None
|
||||
|
||||
max_attempts = 3
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
with tempfile.TemporaryDirectory() as temp_dir, tempfile.TemporaryDirectory() as profile_dir:
|
||||
src = os.path.join(temp_dir, f"input{suffix}")
|
||||
with open(src, "wb") as handle:
|
||||
handle.write(content)
|
||||
|
||||
user_installation = Path(profile_dir).as_uri()
|
||||
cmd = [
|
||||
soffice,
|
||||
"--headless",
|
||||
f"-env:UserInstallation={user_installation}",
|
||||
"--convert-to",
|
||||
"pptx",
|
||||
"--outdir",
|
||||
temp_dir,
|
||||
src,
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, timeout=120)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
logger.warning("LibreOffice PPT convert failed to start: %s", exc)
|
||||
return None
|
||||
|
||||
if result.returncode != 0:
|
||||
stderr = result.stderr.decode("utf-8", errors="ignore")
|
||||
logger.warning(
|
||||
"LibreOffice PPT convert failed (attempt %s/%s): %s",
|
||||
attempt,
|
||||
max_attempts,
|
||||
stderr,
|
||||
)
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.5 * attempt)
|
||||
continue
|
||||
return None
|
||||
|
||||
for name in os.listdir(temp_dir):
|
||||
if name.endswith(".pptx"):
|
||||
with open(os.path.join(temp_dir, name), "rb") as handle:
|
||||
converted = handle.read()
|
||||
logger.info(
|
||||
"Converted presentation via LibreOffice (%s -> pptx, %d bytes)",
|
||||
suffix,
|
||||
len(converted),
|
||||
)
|
||||
return converted
|
||||
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.5 * attempt)
|
||||
return None
|
||||
|
||||
|
||||
def normalize_ppt_bytes(content: bytes, file_type: str | None) -> tuple[bytes, str]:
|
||||
"""Return (bytes, extension) suitable for MarkItDown (pptx when converted)."""
|
||||
ext = (file_type or "").lstrip(".").lower()
|
||||
|
||||
if is_zip_openxml(content):
|
||||
return content, ".pptx"
|
||||
|
||||
if not needs_ppt_to_pptx_conversion(content, ext):
|
||||
dotted = f".{ext}" if ext else ".pptx"
|
||||
return content, dotted
|
||||
|
||||
suffix = ".ppt" if ext in ("", "ppt") else f".{ext}"
|
||||
converted = convert_ppt_to_pptx_bytes(content, suffix=suffix)
|
||||
if converted:
|
||||
return converted, ".pptx"
|
||||
|
||||
raise ValueError(
|
||||
"Legacy PowerPoint (.ppt) is not supported by MarkItDown directly; "
|
||||
"LibreOffice is required to convert it to .pptx. Install LibreOffice "
|
||||
"(soffice) in the docreader environment or upload .pptx instead."
|
||||
)
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Extract and rasterize images embedded in PPTX (e.g. WMF) when MarkItDown cannot inline them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
import zipfile
|
||||
from collections import deque
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MARKDOWN_IMAGE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
|
||||
_RASTER_EXT = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
|
||||
_VECTOR_EXT = {".wmf", ".emf", ".svg"}
|
||||
|
||||
|
||||
def _find_convert() -> str | None:
|
||||
for path in ("/usr/bin/convert", "/usr/local/bin/convert"):
|
||||
if os.path.isfile(path):
|
||||
return path
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["which", "convert"], capture_output=True, text=True, check=False
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
return result.stdout.strip()
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _rasterize_with_imagemagick(data: bytes, suffix: str) -> bytes | None:
|
||||
convert = _find_convert()
|
||||
if not convert:
|
||||
return None
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
src = os.path.join(temp_dir, f"input{suffix}")
|
||||
dst = os.path.join(temp_dir, "output.png")
|
||||
with open(src, "wb") as handle:
|
||||
handle.write(data)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[convert, src, dst],
|
||||
capture_output=True,
|
||||
timeout=60,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
logger.warning("ImageMagick convert failed: %s", exc)
|
||||
return None
|
||||
if result.returncode != 0 or not os.path.isfile(dst):
|
||||
stderr = (result.stderr or b"").decode("utf-8", errors="ignore")
|
||||
logger.warning("ImageMagick convert exit %s: %s", result.returncode, stderr)
|
||||
return None
|
||||
with open(dst, "rb") as handle:
|
||||
return handle.read()
|
||||
|
||||
|
||||
def _rasterize_with_pillow(data: bytes) -> bytes | None:
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
return None
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
# These PNG-compatible modes retain alpha channels or palette transparency.
|
||||
if img.mode not in ("RGB", "RGBA", "L", "LA", "P"):
|
||||
img = img.convert("RGB")
|
||||
out = io.BytesIO()
|
||||
img.save(out, format="PNG")
|
||||
return out.getvalue()
|
||||
except Exception as exc:
|
||||
logger.debug("Pillow could not open media bytes: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def rasterize_media_bytes(name: str, data: bytes) -> bytes | None:
|
||||
ext = os.path.splitext(name)[1].lower()
|
||||
if ext in _RASTER_EXT:
|
||||
png = _rasterize_with_pillow(data)
|
||||
if png:
|
||||
return png
|
||||
if ext in _VECTOR_EXT or ext in _RASTER_EXT:
|
||||
return _rasterize_with_imagemagick(data, ext or ".bin")
|
||||
return _rasterize_with_imagemagick(data, ext or ".bin")
|
||||
|
||||
|
||||
def list_pptx_media(pptx_bytes: bytes) -> List[Tuple[str, bytes]]:
|
||||
"""Return (zip path, raw bytes) for each file under ppt/media/, in archive order."""
|
||||
items: List[Tuple[str, bytes]] = []
|
||||
with zipfile.ZipFile(io.BytesIO(pptx_bytes)) as archive:
|
||||
for name in archive.namelist():
|
||||
if not name.startswith("ppt/media/"):
|
||||
continue
|
||||
base = os.path.basename(name)
|
||||
if not base or base.startswith("."):
|
||||
continue
|
||||
items.append((name, archive.read(name)))
|
||||
return items
|
||||
|
||||
|
||||
def extract_pptx_media_rasterized(pptx_bytes: bytes) -> List[bytes]:
|
||||
"""Rasterize all ppt/media assets to PNG bytes, skipping failures."""
|
||||
rasterized: List[bytes] = []
|
||||
for path, raw in list_pptx_media(pptx_bytes):
|
||||
png = rasterize_media_bytes(os.path.basename(path), raw)
|
||||
if png:
|
||||
rasterized.append(png)
|
||||
logger.info(
|
||||
"Rasterized pptx media %s (%d -> %d bytes)", path, len(raw), len(png)
|
||||
)
|
||||
else:
|
||||
logger.warning("Failed to rasterize pptx media %s", path)
|
||||
return rasterized
|
||||
|
||||
|
||||
def _is_unresolved_image_ref(url: str) -> bool:
|
||||
if not url or url.startswith("data:") or url.startswith("images/"):
|
||||
return False
|
||||
if url.startswith(("http://", "https://")):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _picture_sources(pptx_bytes: bytes) -> dict[str, deque[tuple[str, bytes] | None]]:
|
||||
"""Resolve MarkItDown picture placeholders in slide/shape order."""
|
||||
from pptx import Presentation
|
||||
from pptx.enum.shapes import MSO_SHAPE_TYPE
|
||||
from pptx.exc import PythonPptxError
|
||||
|
||||
sources: dict[str, deque[tuple[str, bytes] | None]] = {}
|
||||
|
||||
def visit(shapes) -> None:
|
||||
# Match MarkItDown, which emits shapes (and group members) sorted by
|
||||
# position rather than in z-order.
|
||||
for shape in sorted(
|
||||
shapes,
|
||||
key=lambda x: (
|
||||
float("-inf") if not x.top else x.top,
|
||||
float("-inf") if not x.left else x.left,
|
||||
),
|
||||
):
|
||||
if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
|
||||
visit(shape.shapes)
|
||||
continue
|
||||
is_picture = shape.shape_type == MSO_SHAPE_TYPE.PICTURE or (
|
||||
shape.shape_type == MSO_SHAPE_TYPE.PLACEHOLDER
|
||||
and hasattr(shape, "image")
|
||||
)
|
||||
if not is_picture:
|
||||
continue
|
||||
|
||||
# MarkItDown's no-data-URI mode uses the shape name, not the media
|
||||
# part name. Names may repeat across slides or normalize equally.
|
||||
placeholder = re.sub(r"\W", "", shape.name) + ".jpg"
|
||||
source = None
|
||||
try:
|
||||
blip = shape._element.blipFill.blip
|
||||
relationship = blip.rEmbed if blip is not None else None
|
||||
if relationship:
|
||||
part = shape.part.related_part(relationship)
|
||||
# Read the part directly: shape.image.content_type can
|
||||
# require a decoder for the same vector format that
|
||||
# triggered fallback.
|
||||
source = (str(part.partname), part.blob)
|
||||
except (AttributeError, KeyError, ValueError, PythonPptxError) as exc:
|
||||
# A missing blipFill or blip, a dangling or external r:embed,
|
||||
# or a media part dropped at load time must only lose this
|
||||
# picture, not the whole document. None keeps the queue
|
||||
# position.
|
||||
logger.warning(
|
||||
"Skipping unresolvable pptx picture %s: %s", shape.name, exc
|
||||
)
|
||||
sources.setdefault(placeholder, deque()).append(source)
|
||||
|
||||
presentation = Presentation(io.BytesIO(pptx_bytes))
|
||||
for slide in presentation.slides:
|
||||
visit(slide.shapes)
|
||||
return sources
|
||||
|
||||
|
||||
def attach_pptx_media_to_markdown(
|
||||
markdown: str, pptx_bytes: bytes
|
||||
) -> Tuple[str, Dict[str, str]]:
|
||||
"""Attach the media referenced by MarkItDown's fallback picture placeholders."""
|
||||
sources = _picture_sources(pptx_bytes)
|
||||
if not sources:
|
||||
return markdown, {}
|
||||
|
||||
images: Dict[str, str] = {}
|
||||
converted: dict[str, bytes | None] = {}
|
||||
|
||||
def repl(match: re.Match[str]) -> str:
|
||||
alt, url = match.group(1), match.group(2)
|
||||
if not _is_unresolved_image_ref(url):
|
||||
return match.group(0)
|
||||
pending = sources.get(url)
|
||||
if not pending:
|
||||
return match.group(0)
|
||||
source = pending.popleft()
|
||||
if source is None:
|
||||
return match.group(0)
|
||||
name, raw = source
|
||||
if name not in converted:
|
||||
converted[name] = rasterize_media_bytes(name, raw)
|
||||
if converted[name] is None:
|
||||
logger.warning("Failed to rasterize pptx media %s", name)
|
||||
png = converted[name]
|
||||
if not png:
|
||||
return match.group(0)
|
||||
ref = f"images/{uuid.uuid4()}.png"
|
||||
images[ref] = base64.b64encode(png).decode()
|
||||
return f""
|
||||
|
||||
return _MARKDOWN_IMAGE.sub(repl, markdown), images
|
||||
|
||||
|
||||
def markdown_needs_pptx_media_attach(markdown: str) -> bool:
|
||||
return any(
|
||||
_is_unresolved_image_ref(m.group(2)) for m in _MARKDOWN_IMAGE.finditer(markdown)
|
||||
)
|
||||
@@ -0,0 +1,216 @@
|
||||
import logging
|
||||
from typing import Callable, Dict, List, Optional, Tuple, Type
|
||||
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.doc_parser import DocParser
|
||||
from docreader.parser.docx2_parser import Docx2Parser
|
||||
from docreader.parser.epub_parser import EPUBParser
|
||||
from docreader.parser.excel_parser import ExcelParser
|
||||
from docreader.parser.html_parser import HTMLParser
|
||||
from docreader.parser.image_parser import ImageParser
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
from docreader.parser.markitdown_parser import MarkitdownParser
|
||||
from docreader.parser.mhtml_parser import MHTMLParser
|
||||
from docreader.parser.opendataloader_parser import (
|
||||
OpenDataLoaderParser,
|
||||
opendataloader_available,
|
||||
)
|
||||
from docreader.parser.pdf_parser import PDFParser
|
||||
from docreader.parser.xmind_parser import XMindParser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BUILTIN_ENGINE = "builtin"
|
||||
|
||||
# File types that builtin does not implement natively. When the requested
|
||||
# engine (including empty / builtin) cannot parse them, route to this engine
|
||||
# instead of raising ValueError — PPT/PPTX/CSV are markitdown-only.
|
||||
_DEFAULT_ENGINE_BY_TYPE = {
|
||||
"ppt": "markitdown",
|
||||
"pptx": "markitdown",
|
||||
"csv": "markitdown",
|
||||
}
|
||||
|
||||
|
||||
class ParserEngineRegistry:
|
||||
"""Registry for parser engines.
|
||||
|
||||
Each engine maps file extensions to parser classes.
|
||||
When a requested engine doesn't support a file type, the registry
|
||||
tries a type-level default engine, then builtin.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._engines: Dict[str, Dict[str, Type[BaseParser]]] = {}
|
||||
self._descriptions: Dict[str, str] = {}
|
||||
self._check_available: Dict[str, Callable[..., Tuple[bool, str]]] = {}
|
||||
self._unavailable_hint: Dict[str, str] = {}
|
||||
|
||||
def register(
|
||||
self,
|
||||
name: str,
|
||||
file_types: Dict[str, Type[BaseParser]],
|
||||
description: str = "",
|
||||
check_available: Callable[..., Tuple[bool, str]] | None = None,
|
||||
unavailable_hint: str = "",
|
||||
):
|
||||
self._engines[name] = file_types
|
||||
self._descriptions[name] = description
|
||||
if check_available is not None:
|
||||
self._check_available[name] = check_available
|
||||
self._unavailable_hint[name] = unavailable_hint
|
||||
logger.info(
|
||||
"Registered parser engine '%s' with file types: %s",
|
||||
name,
|
||||
", ".join(file_types.keys()),
|
||||
)
|
||||
|
||||
def get_parser_class(self, engine: str, file_type: str) -> Type[BaseParser]:
|
||||
"""Resolve parser class for the given engine and file type.
|
||||
|
||||
Fallback order when the requested engine is empty or does not
|
||||
support the type: type-level default (e.g. ppt → markitdown),
|
||||
then builtin. Raises an actionable error listing engines that
|
||||
do support the type.
|
||||
"""
|
||||
ft = file_type.lower().lstrip(".")
|
||||
|
||||
if engine and engine in self._engines:
|
||||
cls = self._engines[engine].get(ft)
|
||||
if cls:
|
||||
logger.info("Using engine '%s' for file type '%s'", engine, ft)
|
||||
return cls
|
||||
logger.info(
|
||||
"Engine '%s' does not support '%s', falling back",
|
||||
engine,
|
||||
ft,
|
||||
)
|
||||
|
||||
default_engine = _DEFAULT_ENGINE_BY_TYPE.get(ft)
|
||||
if default_engine:
|
||||
cls = self._engines.get(default_engine, {}).get(ft)
|
||||
if cls:
|
||||
logger.info(
|
||||
"Using default engine '%s' for file type '%s'",
|
||||
default_engine,
|
||||
ft,
|
||||
)
|
||||
return cls
|
||||
|
||||
builtin = self._engines.get(BUILTIN_ENGINE, {})
|
||||
cls = builtin.get(ft)
|
||||
if cls:
|
||||
return cls
|
||||
|
||||
supported = sorted(
|
||||
name for name, parsers in self._engines.items() if ft in parsers
|
||||
)
|
||||
engine_label = engine or BUILTIN_ENGINE
|
||||
if supported:
|
||||
raise ValueError(
|
||||
f"Unsupported file type {file_type!r} for engine {engine_label!r}. "
|
||||
f"Configure one of: {', '.join(supported)}"
|
||||
)
|
||||
raise ValueError(f"Unsupported file type: {file_type}")
|
||||
|
||||
def list_engines(self, overrides: Optional[Dict[str, str]] = None) -> List[Dict]:
|
||||
"""Return metadata for all registered engines, including availability.
|
||||
|
||||
Args:
|
||||
overrides: tenant-level config overrides (e.g. mineru_endpoint, mineru_api_key)
|
||||
forwarded to each engine's check_available function.
|
||||
"""
|
||||
result = []
|
||||
for name, parsers in self._engines.items():
|
||||
available = True
|
||||
unavailable_reason = ""
|
||||
check = self._check_available.get(name)
|
||||
if check is not None:
|
||||
try:
|
||||
available, unavailable_reason = check(overrides)
|
||||
except Exception as e:
|
||||
available = False
|
||||
unavailable_reason = str(e) or self._unavailable_hint.get(name, "")
|
||||
if not available and not unavailable_reason:
|
||||
unavailable_reason = self._unavailable_hint.get(name, "不可用")
|
||||
result.append(
|
||||
{
|
||||
"name": name,
|
||||
"description": self._descriptions.get(name, ""),
|
||||
"file_types": sorted(parsers.keys()),
|
||||
"available": available,
|
||||
"unavailable_reason": unavailable_reason,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
def get_engine_names(self) -> List[str]:
|
||||
return list(self._engines.keys())
|
||||
|
||||
|
||||
def _build_default_registry() -> ParserEngineRegistry:
|
||||
"""Create and populate the default registry with all known engines."""
|
||||
reg = ParserEngineRegistry()
|
||||
|
||||
_image_types = {
|
||||
ext: ImageParser for ext in ("jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp")
|
||||
}
|
||||
|
||||
reg.register(
|
||||
BUILTIN_ENGINE,
|
||||
{
|
||||
"docx": Docx2Parser,
|
||||
"doc": DocParser,
|
||||
"pdf": PDFParser,
|
||||
"md": MarkdownParser,
|
||||
"markdown": MarkdownParser,
|
||||
"xlsx": ExcelParser,
|
||||
"xls": ExcelParser,
|
||||
"pptx": MarkitdownParser,
|
||||
"ppt": MarkitdownParser,
|
||||
"epub": EPUBParser,
|
||||
"html": HTMLParser,
|
||||
"htm": HTMLParser,
|
||||
"mhtml": MHTMLParser,
|
||||
"xmind": XMindParser,
|
||||
**_image_types,
|
||||
},
|
||||
description="内置解析引擎",
|
||||
)
|
||||
|
||||
reg.register(
|
||||
"markitdown",
|
||||
{
|
||||
"md": MarkitdownParser,
|
||||
"markdown": MarkitdownParser,
|
||||
"pdf": MarkitdownParser,
|
||||
"docx": MarkitdownParser,
|
||||
"doc": MarkitdownParser,
|
||||
"pptx": MarkitdownParser,
|
||||
"ppt": MarkitdownParser,
|
||||
"xlsx": MarkitdownParser,
|
||||
"xls": MarkitdownParser,
|
||||
"csv": MarkitdownParser,
|
||||
},
|
||||
description="MarkItDown 解析引擎(微软 MarkItDown 库)",
|
||||
)
|
||||
|
||||
reg.register(
|
||||
"opendataloader",
|
||||
{"pdf": OpenDataLoaderParser},
|
||||
description="OpenDataLoader PDF(版面分析,需 Java 11+)",
|
||||
check_available=lambda overrides: opendataloader_available(
|
||||
overrides, quick=True
|
||||
),
|
||||
unavailable_hint="请安装 opendataloader-pdf 与 Java 11+",
|
||||
)
|
||||
|
||||
# NOTE: Engine listing is managed by Go-side engine registry
|
||||
# (docparser.ListAllEngines). The Python list_engines method is kept for
|
||||
# backward compatibility with the gRPC ListEngines RPC but the Go app
|
||||
# no longer calls it. MinerU engines are handled natively by Go.
|
||||
|
||||
return reg
|
||||
|
||||
|
||||
registry = _build_default_registry()
|
||||
@@ -0,0 +1,344 @@
|
||||
"""Source locators: map ranges of parsed markdown back to the original file.
|
||||
|
||||
A source block is ``{"start": int, "end": int, "locator": {...}}`` where
|
||||
``start``/``end`` are code point offsets into the document content (end
|
||||
exclusive) and the locator says where that text sits in the original file.
|
||||
For PDFs the locator is ``{"type": "pdf", "page": n}`` plus an optional
|
||||
``"bbox": [x0, y0, x1, y1]`` given as fractions of the displayed page with
|
||||
the origin at its top-left corner, so viewers can draw it at any zoom.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
import statistics
|
||||
import unicodedata
|
||||
from typing import Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
# How far past the cursor a line is searched for, in normalized characters.
|
||||
_SEARCH_WINDOW = 6000
|
||||
# Lines shorter than this (normalized) are too ambiguous to place.
|
||||
_MIN_KEY_CHARS = 2
|
||||
# Lines shorter than this are placed only when their text is unique on the
|
||||
# page: labels inside figures ("LLM", "EBAE") otherwise steal body offsets.
|
||||
# Wide (CJK) characters count as four, since each carries about a word.
|
||||
_SHORT_KEY_WEIGHT = 16
|
||||
|
||||
_LIST_START_RE = re.compile(
|
||||
r"^\s*(?:"
|
||||
r"\d{1,3}(?:\.\d{1,3}){0,4}[\.、.))]?\s" # 1 1. 8.14.11 2)
|
||||
r"|[((]\d{1,3}[))]" # (1) (1)
|
||||
r"|[一二三四五六七八九十百]+[、..]" # 一、
|
||||
r"|[•·●○■□◆◇▪\-–*]\s" # bullets
|
||||
r"|第[一二三四五六七八九十百零\d]+[章节条款部分篇]" # 第三章
|
||||
r")"
|
||||
)
|
||||
_SENTENCE_END = tuple("。..!?!?::;;」』”))")
|
||||
|
||||
|
||||
def _fold(ch: str) -> str:
|
||||
"""Letters and digits only, lower-cased, full-width folded."""
|
||||
if not ch.isalnum():
|
||||
return ""
|
||||
return unicodedata.normalize("NFKC", ch).lower()
|
||||
|
||||
|
||||
def normalize_with_positions(text: str) -> Tuple[str, List[int]]:
|
||||
"""Project text onto letters and digits.
|
||||
|
||||
Returns the projection and, for each of its characters, the offset in
|
||||
``text`` of the character it came from.
|
||||
"""
|
||||
out: List[str] = []
|
||||
pos: List[int] = []
|
||||
for i, ch in enumerate(text):
|
||||
value = unicodedata.normalize("NFKC", ch)
|
||||
folded = _fold(ch)
|
||||
if value in ".,:/+−-%‰<>=≤≥≠":
|
||||
before, after = i - 1, i + 1
|
||||
while before >= 0 and text[before] in " \t":
|
||||
before -= 1
|
||||
while after < len(text) and text[after] in " \t":
|
||||
after += 1
|
||||
prev = before >= 0 and text[before].isdigit()
|
||||
next_digit = after < len(text) and text[after].isdigit()
|
||||
semantic = ((value in ".,/:" and prev and next_digit)
|
||||
or (value in "+-−" and next_digit)
|
||||
or (value in "%‰" and prev)
|
||||
or value in "<>=≤≥≠")
|
||||
if semantic:
|
||||
folded = value.replace("−", "-")
|
||||
for f in folded:
|
||||
out.append(f)
|
||||
pos.append(i)
|
||||
return "".join(out), pos
|
||||
|
||||
|
||||
def normalize(text: str) -> str:
|
||||
return normalize_with_positions(text)[0]
|
||||
|
||||
|
||||
def _key_weight(key: str) -> int:
|
||||
return sum(4 if unicodedata.east_asian_width(ch) in ("W", "F") else 1 for ch in key)
|
||||
|
||||
|
||||
def _column_cursor(boxes, idx: int, ends: List[Optional[int]]) -> Optional[int]:
|
||||
"""End of the nearest placed line above ``boxes[idx]`` in the same column."""
|
||||
x0, y0, x1, _ = boxes[idx]
|
||||
for j in range(idx - 1, max(-1, idx - 80), -1):
|
||||
if ends[j] is None:
|
||||
continue
|
||||
px0, py0, px1, _ = boxes[j]
|
||||
if px0 < x1 and x0 < px1 and py0 > y0:
|
||||
return ends[j]
|
||||
return None
|
||||
|
||||
|
||||
def _numeric_safe_matches(text: str, key: str) -> List[int]:
|
||||
out = []
|
||||
if not key:
|
||||
return out
|
||||
start = 0
|
||||
while (at := text.find(key, start)) >= 0:
|
||||
before = text[at - 1] if at else ""
|
||||
end = at + len(key)
|
||||
after = text[end] if end < len(text) else ""
|
||||
left = key[0].isdigit() and bool(before) and (before.isdigit() or before in ".,:/+−-")
|
||||
right = key[-1].isdigit() and bool(after) and (after.isdigit() or after in ".,:/%‰")
|
||||
if not left and not right:
|
||||
out.append(at)
|
||||
start = at + 1
|
||||
return out
|
||||
|
||||
|
||||
def locate_lines(
|
||||
page_text: str,
|
||||
line_texts: Sequence[str],
|
||||
boxes: Optional[Sequence[Tuple[float, float, float, float]]] = None,
|
||||
) -> List[Optional[int]]:
|
||||
"""Find where each visual line starts in the page text.
|
||||
|
||||
Lines are searched in order after the previous hit so repeated phrases
|
||||
resolve to the right occurrence. With ``boxes`` (PDF points, bottom-left
|
||||
origin) the search first continues from the line above in the same
|
||||
column, since glyph lines of side-by-side columns arrive interleaved. A
|
||||
line not found after either cursor is searched from the start of the page,
|
||||
which tolerates text extractors that order columns differently from the
|
||||
glyph grouping. Returns one offset (or None) per line.
|
||||
"""
|
||||
norm, pos = normalize_with_positions(page_text)
|
||||
hits: List[Optional[int]] = []
|
||||
ends: List[Optional[int]] = []
|
||||
cursor = 0
|
||||
counts = Counter(normalize(line) for line in line_texts)
|
||||
occurrences = {key: _numeric_safe_matches(norm, key) for key in counts}
|
||||
for idx, line in enumerate(line_texts):
|
||||
key = normalize(line)
|
||||
if len(key) < _MIN_KEY_CHARS or len(occurrences[key]) != counts[key] or (
|
||||
_key_weight(key) < _SHORT_KEY_WEIGHT and len(occurrences[key]) > 1
|
||||
):
|
||||
hits.append(None)
|
||||
ends.append(None)
|
||||
continue
|
||||
cursors = [cursor]
|
||||
if boxes is not None:
|
||||
column = _column_cursor(boxes, idx, ends)
|
||||
if column is not None:
|
||||
cursors.insert(0, column)
|
||||
at = -1
|
||||
for start_at in cursors:
|
||||
at = next((hit for hit in occurrences[key] if start_at <= hit <= start_at + _SEARCH_WINDOW), -1)
|
||||
if at >= 0:
|
||||
break
|
||||
if at < 0:
|
||||
at = occurrences[key][0] if len(occurrences[key]) == 1 else -1
|
||||
if at < 0:
|
||||
hits.append(None)
|
||||
ends.append(None)
|
||||
continue
|
||||
else:
|
||||
cursor = at + len(key)
|
||||
ends.append(at + len(key))
|
||||
start = pos[at]
|
||||
# Pull in leading punctuation or markup on the same text line
|
||||
# (brackets, "## ", list bullets) that normalization skipped.
|
||||
while start > 0 and page_text[start - 1] != "\n" and not page_text[start - 1].isalnum():
|
||||
start -= 1
|
||||
hits.append(start)
|
||||
return hits
|
||||
|
||||
|
||||
class PageGeometry:
|
||||
"""Converts PDF user-space points to fractions of the displayed page."""
|
||||
|
||||
def __init__(self, cropbox: Tuple[float, float, float, float], rotation: int = 0):
|
||||
left, bottom, right, top = cropbox
|
||||
self.left, self.bottom = min(left, right), min(bottom, top)
|
||||
self.width = abs(right - left) or 1.0
|
||||
self.height = abs(top - bottom) or 1.0
|
||||
self.rotation = int(rotation or 0) % 360
|
||||
|
||||
def bbox(self, box: Tuple[float, float, float, float]) -> List[float]:
|
||||
x0, y0, x1, y1 = box
|
||||
# Unrotated, top-left origin.
|
||||
ux0 = (x0 - self.left) / self.width
|
||||
ux1 = (x1 - self.left) / self.width
|
||||
uy0 = 1.0 - (y1 - self.bottom) / self.height
|
||||
uy1 = 1.0 - (y0 - self.bottom) / self.height
|
||||
corners = [self._rotate(ux0, uy0), self._rotate(ux1, uy1)]
|
||||
xs = [c[0] for c in corners]
|
||||
ys = [c[1] for c in corners]
|
||||
return [
|
||||
round(_clamp(min(xs)), 4),
|
||||
round(_clamp(min(ys)), 4),
|
||||
round(_clamp(max(xs)), 4),
|
||||
round(_clamp(max(ys)), 4),
|
||||
]
|
||||
|
||||
def _rotate(self, x: float, y: float) -> Tuple[float, float]:
|
||||
# Viewers display /Rotate clockwise.
|
||||
if self.rotation == 90:
|
||||
return 1.0 - y, x
|
||||
if self.rotation == 180:
|
||||
return 1.0 - x, 1.0 - y
|
||||
if self.rotation == 270:
|
||||
return y, 1.0 - x
|
||||
return x, y
|
||||
|
||||
|
||||
def _clamp(v: float) -> float:
|
||||
return 0.0 if v < 0 else 1.0 if v > 1 else v
|
||||
|
||||
|
||||
def _union(boxes: Iterable[Tuple[float, float, float, float]]):
|
||||
boxes = list(boxes)
|
||||
return (
|
||||
min(b[0] for b in boxes),
|
||||
min(b[1] for b in boxes),
|
||||
max(b[2] for b in boxes),
|
||||
max(b[3] for b in boxes),
|
||||
)
|
||||
|
||||
|
||||
def _line_gap(prev: dict, cur: dict) -> Optional[float]:
|
||||
"""Vertical gap from ``prev`` down to ``cur`` when they share a column."""
|
||||
px0, py0, px1, _ = prev["bbox"]
|
||||
cx0, _, cx1, cy1 = cur["bbox"]
|
||||
if cx1 < px0 or cx0 > px1 or cy1 > py0:
|
||||
return None
|
||||
return py0 - cy1
|
||||
|
||||
|
||||
def _starts_paragraph(
|
||||
prev: dict, cur: dict, line_h: float, usual_gap: float, col_right: float
|
||||
) -> bool:
|
||||
"""Whether ``cur`` opens a new visual paragraph after ``prev``.
|
||||
|
||||
Boxes are PDF points with a bottom-left origin, so reading downwards means
|
||||
decreasing y. ``usual_gap`` is the page's typical gap between consecutive
|
||||
lines of a paragraph, which absorbs double-spaced layouts.
|
||||
"""
|
||||
px0, py0, px1, _ = prev["bbox"]
|
||||
cx0, _, cx1, cy1 = cur["bbox"]
|
||||
if cx1 < px0 or cx0 > px1:
|
||||
return True # moved to another column
|
||||
if cy1 > py0 + line_h * 0.5:
|
||||
return True # went back up the page: a new column or region
|
||||
if py0 - cy1 > usual_gap * 1.5 + line_h * 0.3:
|
||||
return True # vertical gap wider than the usual line spacing
|
||||
if _LIST_START_RE.match(cur["text"]):
|
||||
return True
|
||||
ends_sentence = prev["text"].rstrip().endswith(_SENTENCE_END)
|
||||
short = col_right - px1 > line_h * 2
|
||||
return ends_sentence and short
|
||||
|
||||
|
||||
def page_blocks(
|
||||
page_text: str,
|
||||
offset: int,
|
||||
page_number: int,
|
||||
lines: Sequence[dict],
|
||||
geometry: Optional[PageGeometry],
|
||||
) -> List[dict]:
|
||||
"""Source blocks for one text page placed at ``offset`` in the document.
|
||||
|
||||
``lines`` are visual lines ``{"text", "bbox"}`` (bbox in PDF points). Lines
|
||||
are placed in ``page_text``, grouped into paragraphs by geometry, and each
|
||||
paragraph becomes a block spanning only its matched lines, boxed by their
|
||||
union. Unmatched gaps keep page-only provenance and never inherit the
|
||||
previous paragraph's geometry.
|
||||
"""
|
||||
end = offset + len(page_text)
|
||||
page_only = {"type": "pdf", "page": page_number, "mapping": "exact"}
|
||||
if not page_text:
|
||||
return []
|
||||
placed = []
|
||||
if lines and geometry is not None:
|
||||
starts = locate_lines(
|
||||
page_text, [ln["text"] for ln in lines], [ln["bbox"] for ln in lines]
|
||||
)
|
||||
placed = sorted(
|
||||
(
|
||||
(at, ln)
|
||||
for at, ln in zip(starts, lines)
|
||||
if at is not None
|
||||
),
|
||||
key=lambda item: item[0],
|
||||
)
|
||||
if not placed:
|
||||
return [{"start": offset, "end": end, "locator": dict(page_only)}]
|
||||
|
||||
heights = [ln["bbox"][3] - ln["bbox"][1] for _, ln in placed if ln["bbox"][3] > ln["bbox"][1]]
|
||||
line_h = statistics.median(heights) if heights else 10.0
|
||||
gaps = [
|
||||
g
|
||||
for g in (_line_gap(a[1], b[1]) for a, b in zip(placed, placed[1:]))
|
||||
if g is not None and g >= 0
|
||||
]
|
||||
usual_gap = min(statistics.median(gaps), line_h * 1.5) if gaps else line_h * 0.5
|
||||
|
||||
norm, positions = normalize_with_positions(page_text)
|
||||
def line_end(at, line):
|
||||
key = normalize(line["text"])
|
||||
norm_start = next((i for i, p in enumerate(positions) if p >= at), len(norm))
|
||||
hit = norm.find(key, norm_start)
|
||||
if hit < 0:
|
||||
return at
|
||||
end_at = positions[hit + len(key) - 1] + 1
|
||||
while end_at < len(page_text) and not page_text[end_at].isalnum():
|
||||
if page_text[end_at] == "\n":
|
||||
return end_at + 1
|
||||
end_at += 1
|
||||
return end_at
|
||||
|
||||
paragraphs: List[Tuple[int, List[dict]]] = []
|
||||
for at, ln in placed:
|
||||
ln = {**ln, "_source_end": line_end(at, ln)}
|
||||
if paragraphs:
|
||||
prev = paragraphs[-1][1][-1]
|
||||
col_right = max(p["bbox"][2] for p in paragraphs[-1][1])
|
||||
col_right = max(col_right, ln["bbox"][2])
|
||||
previous_end = prev["_source_end"]
|
||||
gap_is_empty = not normalize(page_text[previous_end:at])
|
||||
if gap_is_empty and not _starts_paragraph(prev, ln, line_h, usual_gap, col_right):
|
||||
paragraphs[-1][1].append(ln)
|
||||
continue
|
||||
paragraphs.append((at, [ln]))
|
||||
|
||||
blocks: List[dict] = []
|
||||
cursor = 0
|
||||
for at, members in paragraphs:
|
||||
stop = members[-1]["_source_end"]
|
||||
if stop <= at:
|
||||
continue
|
||||
if at > cursor and page_text[cursor:at].strip():
|
||||
blocks.append({"start": offset + cursor, "end": offset + at, "locator": dict(page_only)})
|
||||
locator = dict(page_only)
|
||||
locator["bbox"] = geometry.bbox(_union(m["bbox"] for m in members))
|
||||
locator["source_id"] = f"pdf:{page_number}:{at}:{stop}"
|
||||
blocks.append({"start": offset + at, "end": offset + stop, "locator": locator})
|
||||
cursor = stop
|
||||
if cursor < len(page_text) and page_text[cursor:].strip():
|
||||
blocks.append({"start": offset + cursor, "end": end, "locator": dict(page_only)})
|
||||
return blocks
|
||||
@@ -0,0 +1,351 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from lxml.etree import XPath
|
||||
from playwright.async_api import Page, async_playwright
|
||||
from trafilatura import extract, utils, xpaths
|
||||
|
||||
from docreader.config import CONFIG
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.chain_parser import PipelineParser
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
from docreader.utils import endecode
|
||||
from docreader.utils.ssrf import is_ssrf_safe_url
|
||||
from docreader.utils.ssrf_proxy import SSRFProxy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class WebParseError(RuntimeError):
|
||||
"""Raised when a URL cannot be scraped or has no extractable content.
|
||||
|
||||
This must propagate as a parse failure. Returning the error string as
|
||||
document body would index it as knowledge.
|
||||
"""
|
||||
|
||||
|
||||
_GOTO_TIMEOUT_MS = 30_000
|
||||
_NETWORK_IDLE_TIMEOUT_MS = 10_000
|
||||
_SPA_WAIT_TIMEOUT_MS = 15_000
|
||||
# Minimum visible characters before treating an SPA shell as "rendered".
|
||||
_SPA_MIN_TEXT_LEN = 80
|
||||
# Minimum visible characters for Playwright text fallback when trafilatura fails.
|
||||
_MIN_FALLBACK_TEXT_LEN = 50
|
||||
|
||||
# Monkey-patch trafilatura internals to better support WeChat Official Account
|
||||
# articles, whose images live on `mmbiz.qpic.cn` without a standard file
|
||||
# extension and whose main content sits inside `#js_content` /
|
||||
# `.rich_media_content`. Trafilatura's `utils.IMAGE_EXTENSION` and
|
||||
# `xpaths.BODY_XPATH` are internal APIs, so we guard the patch and skip
|
||||
# silently if they are renamed/removed in a future release.
|
||||
try:
|
||||
_WECHAT_IMAGE_EXTENSION = re.compile(
|
||||
r"[^\s]+\.(avif|bmp|gif|hei[cf]|jpe?g|png|webp)(\b|$)|" # Standard extensions
|
||||
r"mmbiz\.qpic\.cn/[^\s]*wx_fmt=(jpeg|jpg|png|gif|webp)" # WeChat query format
|
||||
)
|
||||
utils.IMAGE_EXTENSION = _WECHAT_IMAGE_EXTENSION
|
||||
|
||||
_WECHAT_BODY_XPATH = XPath(
|
||||
'(.//*[@id="js_content" or contains(@class, "rich_media_content")])[1]'
|
||||
)
|
||||
_wechat_xpath_str = str(_WECHAT_BODY_XPATH)
|
||||
if not any(str(x) == _wechat_xpath_str for x in xpaths.BODY_XPATH):
|
||||
xpaths.BODY_XPATH.insert(0, _WECHAT_BODY_XPATH)
|
||||
except (AttributeError, ImportError) as e:
|
||||
logger.warning(
|
||||
"Failed to patch trafilatura internals for WeChat support: %s", e
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _ScrapeResult:
|
||||
html: str
|
||||
visible_text: str
|
||||
page_title: str
|
||||
error: str = ""
|
||||
|
||||
|
||||
def extract_markdown_from_html(html: str) -> Optional[str]:
|
||||
"""Run trafilatura on HTML; return markdown or None if nothing extracted."""
|
||||
if not html or not html.strip():
|
||||
return None
|
||||
md_text = extract(
|
||||
html,
|
||||
output_format="markdown",
|
||||
with_metadata=True,
|
||||
include_images=True,
|
||||
include_tables=True,
|
||||
include_links=True,
|
||||
)
|
||||
if not md_text or not md_text.strip():
|
||||
return None
|
||||
return md_text
|
||||
|
||||
|
||||
def build_visible_text_fallback(visible_text: str, page_title: str = "") -> Optional[str]:
|
||||
"""Build markdown from Playwright-visible text when trafilatura finds no article body."""
|
||||
text = (visible_text or "").strip()
|
||||
if len(text) < _MIN_FALLBACK_TEXT_LEN:
|
||||
return None
|
||||
title = (page_title or "").strip()
|
||||
if title and not text.startswith(title):
|
||||
return f"# {title}\n\n{text}"
|
||||
return text
|
||||
|
||||
|
||||
async def wait_for_rendered_content(page: Page) -> None:
|
||||
"""Wait for SPA/JS pages beyond the initial HTML shell."""
|
||||
try:
|
||||
await page.wait_for_load_state("networkidle", timeout=_NETWORK_IDLE_TIMEOUT_MS)
|
||||
logger.info("Network idle after navigation")
|
||||
except Exception:
|
||||
logger.info("Network idle wait timed out, continuing")
|
||||
|
||||
try:
|
||||
await page.wait_for_function(
|
||||
"""(minLen) => {
|
||||
const root = document.querySelector('#app')
|
||||
|| document.querySelector('main')
|
||||
|| document.body;
|
||||
return ((root?.innerText || '').trim().length >= minLen);
|
||||
}""",
|
||||
arg=_SPA_MIN_TEXT_LEN,
|
||||
timeout=_SPA_WAIT_TIMEOUT_MS,
|
||||
)
|
||||
logger.info("SPA/root visible text reached minimum length")
|
||||
except Exception:
|
||||
logger.info("SPA text wait timed out, using current DOM")
|
||||
|
||||
|
||||
async def read_visible_text(page: Page) -> str:
|
||||
"""Prefer #app/main innerText, then fall back to body."""
|
||||
return await page.evaluate(
|
||||
"""() => {
|
||||
const root = document.querySelector('#app')
|
||||
|| document.querySelector('main')
|
||||
|| document.querySelector('[role="main"]')
|
||||
|| document.body;
|
||||
return (root?.innerText || '').trim();
|
||||
}"""
|
||||
)
|
||||
|
||||
|
||||
async def install_ssrf_route_guard(page: Page) -> None:
|
||||
"""Reject initial URLs early; SSRFProxy enforces every actual connection."""
|
||||
|
||||
async def handle_route(route) -> None:
|
||||
safe, reason = is_ssrf_safe_url(route.request.url)
|
||||
if not safe:
|
||||
logger.warning(
|
||||
"SSRF guard blocked request to %s: %s", route.request.url, reason
|
||||
)
|
||||
await route.abort("blockedbyclient")
|
||||
return
|
||||
await route.continue_()
|
||||
|
||||
await page.route("**/*", handle_route)
|
||||
|
||||
|
||||
class StdWebParser(BaseParser):
|
||||
"""Standard web page parser using Playwright and Trafilatura.
|
||||
|
||||
This parser scrapes web pages using Playwright's WebKit browser and extracts
|
||||
clean content using Trafilatura library. It supports proxy configuration and
|
||||
converts HTML content to markdown format.
|
||||
"""
|
||||
|
||||
def __init__(self, title: str, **kwargs):
|
||||
"""Initialize the web parser.
|
||||
|
||||
Args:
|
||||
title: Title of the web page to be used as file name
|
||||
**kwargs: Additional arguments passed to BaseParser
|
||||
"""
|
||||
self.title = title
|
||||
# Get proxy configuration from config if available
|
||||
self.proxy = CONFIG.external_https_proxy
|
||||
super().__init__(file_name=title, **kwargs)
|
||||
logger.info(f"Initialized WebParser with title: {title}")
|
||||
|
||||
async def scrape(self, url: str) -> _ScrapeResult:
|
||||
"""Scrape web page content using Playwright.
|
||||
|
||||
Args:
|
||||
url: The URL of the web page to scrape
|
||||
|
||||
Returns:
|
||||
HTML, visible text, and document title. On hard failure the
|
||||
content fields are empty and ``error`` explains why.
|
||||
"""
|
||||
logger.info(f"Starting web page scraping for URL: {url}")
|
||||
safe, reason = is_ssrf_safe_url(url)
|
||||
if not safe:
|
||||
logger.error("URL blocked by SSRF guard before navigation: %s", reason)
|
||||
return _ScrapeResult(
|
||||
html="", visible_text="", page_title="",
|
||||
error=f"URL blocked by SSRF guard: {reason}",
|
||||
)
|
||||
try:
|
||||
async with SSRFProxy(self.proxy) as proxy, async_playwright() as p:
|
||||
kwargs = {"proxy": {"server": proxy.url, "bypass": ""}}
|
||||
logger.info("Launching WebKit browser")
|
||||
browser = await p.webkit.launch(**kwargs)
|
||||
page = await browser.new_page(service_workers="block")
|
||||
await install_ssrf_route_guard(page)
|
||||
|
||||
logger.info(f"Navigating to URL: {url}")
|
||||
try:
|
||||
await page.goto(
|
||||
url,
|
||||
timeout=_GOTO_TIMEOUT_MS,
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
logger.info("Initial page load complete")
|
||||
except Exception as e:
|
||||
logger.error(f"Error navigating to URL: {str(e)}")
|
||||
await browser.close()
|
||||
return _ScrapeResult(
|
||||
html="", visible_text="", page_title="",
|
||||
error=f"navigation failed: {e}",
|
||||
)
|
||||
|
||||
await wait_for_rendered_content(page)
|
||||
|
||||
page_title = await page.title()
|
||||
visible_text = await read_visible_text(page)
|
||||
content = await page.content()
|
||||
logger.info(
|
||||
"Retrieved %d bytes HTML, %d chars visible text, title=%r",
|
||||
len(content),
|
||||
len(visible_text),
|
||||
page_title[:80] if page_title else "",
|
||||
)
|
||||
|
||||
await browser.close()
|
||||
logger.info("Browser closed")
|
||||
|
||||
logger.info("Successfully retrieved HTML content")
|
||||
return _ScrapeResult(
|
||||
html=content,
|
||||
visible_text=visible_text,
|
||||
page_title=page_title or "",
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to scrape web page: {str(e)}")
|
||||
return _ScrapeResult(
|
||||
html="", visible_text="", page_title="",
|
||||
error=f"scrape failed: {e}",
|
||||
)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse web page content into a Document object.
|
||||
|
||||
Args:
|
||||
content: URL encoded as bytes
|
||||
|
||||
Returns:
|
||||
Document object containing the parsed markdown content
|
||||
|
||||
Raises:
|
||||
WebParseError: If scraping fails or the page has no extractable
|
||||
content. Callers must surface this as a parse failure rather
|
||||
than indexing the error string as document body.
|
||||
"""
|
||||
url = endecode.decode_bytes(content)
|
||||
|
||||
logger.info(f"Scraping web page: {url}")
|
||||
scrape_result = asyncio.run(self.scrape(url))
|
||||
if scrape_result.error or (
|
||||
not scrape_result.html and not scrape_result.visible_text
|
||||
):
|
||||
detail = scrape_result.error or "no HTML or visible text"
|
||||
logger.error("Failed to scrape web page %s: %s", url, detail)
|
||||
raise WebParseError(f"Failed to scrape web page: {url} ({detail})")
|
||||
|
||||
md_text = extract_markdown_from_html(scrape_result.html)
|
||||
if not md_text:
|
||||
md_text = build_visible_text_fallback(
|
||||
scrape_result.visible_text,
|
||||
scrape_result.page_title,
|
||||
)
|
||||
if md_text:
|
||||
logger.info(
|
||||
"Trafilatura empty; using Playwright visible-text fallback (%d chars)",
|
||||
len(md_text),
|
||||
)
|
||||
|
||||
if not md_text:
|
||||
logger.error("Failed to parse web page: %s", url)
|
||||
raise WebParseError(f"Failed to parse web page: {url}")
|
||||
|
||||
metadata = {}
|
||||
title_match = re.search(r"^title:\s*(.+)", md_text, re.MULTILINE)
|
||||
if title_match:
|
||||
extracted_title = title_match.group(1).strip()
|
||||
if extracted_title:
|
||||
metadata["title"] = extracted_title
|
||||
logger.info(
|
||||
f"Extracted article title from trafilatura: {extracted_title}"
|
||||
)
|
||||
elif scrape_result.page_title:
|
||||
metadata["title"] = scrape_result.page_title.strip()
|
||||
logger.info(
|
||||
"Using page title from Playwright: %s", metadata["title"]
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"No title found in trafilatura output, first 200 chars: %r",
|
||||
md_text[:200],
|
||||
)
|
||||
return Document(content=md_text, metadata=metadata)
|
||||
|
||||
|
||||
class WebParser(PipelineParser):
|
||||
"""Web parser using pipeline pattern.
|
||||
|
||||
This parser chains StdWebParser (for web scraping and HTML to markdown conversion)
|
||||
with MarkdownParser (for markdown processing). The pipeline processes content
|
||||
sequentially through both parsers.
|
||||
"""
|
||||
|
||||
# Parser classes to be executed in sequence
|
||||
_parser_cls = (StdWebParser, MarkdownParser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
|
||||
url = sys.argv[1] if len(sys.argv) > 1 else "https://cloud.tencent.com/document/product/457/6759"
|
||||
print(f"\n{'='*60}")
|
||||
print(f"URL: {url}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
parser = WebParser(title="")
|
||||
doc = parser.parse_into_text(url.encode())
|
||||
|
||||
print(f"--- metadata ---")
|
||||
for k, v in doc.metadata.items():
|
||||
print(f" {k}: {v}")
|
||||
|
||||
print(f"\n--- images ({len(doc.images)}) ---")
|
||||
for path in list(doc.images.keys())[:10]:
|
||||
print(f" {path} ({len(doc.images[path])} chars base64)")
|
||||
|
||||
print(f"\n--- content ({len(doc.content)} chars) ---")
|
||||
print(doc.content[:300000])
|
||||
if len(doc.content) > 300000:
|
||||
print(f"\n... (truncated, total {len(doc.content)} chars)")
|
||||
|
||||
print(f"\n--- chunks ({len(doc.chunks)}) ---")
|
||||
for i, chunk in enumerate(doc.chunks[:5]):
|
||||
print(f" [{i}] seq={chunk.seq} range=[{chunk.start}:{chunk.end}] len={len(chunk.content)}")
|
||||
print(f" {chunk.content[:120]}{'...' if len(chunk.content) > 120 else ''}")
|
||||
if len(doc.chunks) > 5:
|
||||
print(f" ... ({len(doc.chunks) - 5} more chunks)")
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Fill merged cell values before pandas reads an XLSX workbook."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
from io import BytesIO
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --- Percentage number formats (opt-in) --------------------------------------
|
||||
# Excel keeps a percentage as the stored fraction plus a display format: the
|
||||
# cell holds 0.61123366 and "0.00%" renders it as 61.12%. openpyxl and pandas
|
||||
# read only the fraction, so a value the user sees as 61.12% reaches the
|
||||
# pipeline as 0.6112 — a 100x error that a model will copy verbatim into a
|
||||
# report. When this switch is on, percentage cells are materialized as the
|
||||
# literal text the spreadsheet shows ("61.12%") instead.
|
||||
#
|
||||
# It is off by default on purpose: the cell changes from a number into a
|
||||
# string, so anything that sorts, aggregates or computes with it sees different
|
||||
# input. With it off, every workbook is read exactly as before. A single upload
|
||||
# can override it through parser_engine_overrides.xlsx_percent_as_text.
|
||||
PERCENT_AS_TEXT_ENV = "DOCREADER_XLSX_PERCENT_AS_TEXT"
|
||||
|
||||
# Only percentages are materialized. Currency and thousands separators change
|
||||
# how a number is displayed, not what it means ("1,234,567" and 1234567 are the
|
||||
# same number), so rewriting them would churn cells for no semantic gain, and
|
||||
# date formats are already converted to datetimes by openpyxl.
|
||||
|
||||
# --- Same-row hint fallback (opt-in, off by default) -------------------------
|
||||
# Workbooks occasionally leave one cell of a percentage row without a
|
||||
# percentage format (a real financial statement had 折旧率 0.0592 formatted as
|
||||
# "0.00_ ;[Red]\-0.00\ "). When a row carries at least this many explicitly
|
||||
# percentage-formatted cells, an unformatted 0 < |value| < 1 number in that row
|
||||
# is treated as a percentage too. Only consulted while percent materialization
|
||||
# is on; 0 disables the fallback.
|
||||
ROW_HINT_MIN_ENV = "DOCREADER_XLSX_PCT_ROW_HINT_MIN"
|
||||
_DEFAULT_ROW_HINT_MIN = 0
|
||||
|
||||
# Only materialize a known numeric percentage pattern. Excel literals, conditions,
|
||||
# scaling and arbitrary decorations require a full format renderer; leave those
|
||||
# values untouched rather than guessing that every '%' means multiply by 100.
|
||||
_PERCENT_PATTERN = re.compile(
|
||||
r"(?P<sign>-?)(?P<open>\()?(?P<group>#,##)?0"
|
||||
r"(?:\.(?P<decimals>0+))?%(?P<close>\))?"
|
||||
)
|
||||
_FORMAT_COLOR = re.compile(
|
||||
r"\[(?:Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color[0-9]+)\]", re.I
|
||||
)
|
||||
|
||||
|
||||
def _env_bool(name: str, default: bool) -> bool:
|
||||
value = os.environ.get(name)
|
||||
if value is None or not str(value).strip():
|
||||
return default
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
try:
|
||||
return int(str(os.environ.get(name, default)).strip())
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def percent_as_text_default() -> bool:
|
||||
"""Deployment-wide default for materializing percentage formats.
|
||||
|
||||
Read per call (not at import time) so the value can be flipped without a
|
||||
module reload; a per-upload override still wins over it.
|
||||
"""
|
||||
return _env_bool(PERCENT_AS_TEXT_ENV, False)
|
||||
|
||||
|
||||
def _format_percentage(value, number_format: str):
|
||||
"""Render supported Excel percentage formats, leaving other formats intact."""
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
if not number_format or "%" not in number_format:
|
||||
return None
|
||||
# Quoted/escaped percentages are literal text, not percentage operators.
|
||||
# Reject unsupported conditions across all sections before selecting one.
|
||||
cleaned = _FORMAT_COLOR.sub("", number_format)
|
||||
if any(char in cleaned for char in ('"', "\\", "_", "*", "[", "]")):
|
||||
return None
|
||||
sections = cleaned.split(";")
|
||||
if len(sections) > 4:
|
||||
return None
|
||||
section_index = 1 if value < 0 and len(sections) >= 2 else 0
|
||||
if value == 0 and len(sections) >= 3:
|
||||
section_index = 2
|
||||
match = _PERCENT_PATTERN.fullmatch(sections[section_index].strip())
|
||||
if not match or bool(match["open"]) != bool(match["close"]):
|
||||
return None
|
||||
decimals = len(match["decimals"] or "")
|
||||
# Excel's negative section formats the magnitude; a single section instead
|
||||
# supplies the minus sign automatically.
|
||||
amount = abs(value) if section_index == 1 else value
|
||||
grouping = "," if match["group"] else ""
|
||||
try:
|
||||
number = f"{float(amount) * 100:{grouping}.{decimals}f}"
|
||||
return f"{match['sign']}{match['open'] or ''}{number}%{match['close'] or ''}"
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def _materialize_percentage_cells(ws, row_hint_min: int) -> tuple[int, int]:
|
||||
"""Rewrite the percentage-formatted numbers of *ws* as their display text.
|
||||
|
||||
Must run before merged ranges are filled: only the master cell of a merge
|
||||
carries a number_format while the covered cells are General, so filling
|
||||
first would copy a bare fraction into rows 2..n and leave it unconverted —
|
||||
the same row would then show both "0.55%" and 0.005509433890047721.
|
||||
|
||||
Returns ``(materialized, hinted)`` cell counts.
|
||||
"""
|
||||
row_hints: dict = {}
|
||||
if row_hint_min > 0:
|
||||
# Count the explicit percentage formats before converting anything:
|
||||
# the conversion below resets number_format to General.
|
||||
for row in ws.iter_rows():
|
||||
count = sum(
|
||||
1
|
||||
for cell in row
|
||||
if type(cell.value) in (int, float) # noqa: E721 - excludes bool
|
||||
and _format_percentage(cell.value, cell.number_format) is not None
|
||||
)
|
||||
if count:
|
||||
row_hints[row[0].row] = count
|
||||
|
||||
materialized = 0
|
||||
hinted = 0
|
||||
for row in ws.iter_rows():
|
||||
hint = row_hints.get(row[0].row, 0)
|
||||
for cell in row:
|
||||
if type(cell.value) not in (int, float): # noqa: E721 - excludes bool
|
||||
continue
|
||||
text = _format_percentage(cell.value, cell.number_format)
|
||||
if (
|
||||
text is None
|
||||
and "%" not in str(cell.number_format or "")
|
||||
and hint >= row_hint_min > 0
|
||||
and 0 < abs(cell.value) < 1
|
||||
):
|
||||
# Fallback for a cell that lost its percentage format while its
|
||||
# row kept one. Logged because it rewrites an unformatted value.
|
||||
text = f"{float(cell.value) * 100:.2f}%"
|
||||
hinted += 1
|
||||
logger.info(
|
||||
"XLSX pre-parse: %s!%s%d has no percentage format but its row "
|
||||
"does; reading it as %.2f%% (stored value %r)",
|
||||
ws.title,
|
||||
cell.column_letter,
|
||||
cell.row,
|
||||
float(cell.value) * 100,
|
||||
cell.value,
|
||||
)
|
||||
if text is None:
|
||||
continue
|
||||
cell.value = text
|
||||
cell.number_format = "General"
|
||||
materialized += 1
|
||||
return materialized, hinted
|
||||
|
||||
|
||||
def fill_merged_cells_xlsx(
|
||||
content: bytes, percent_as_text: bool | None = None
|
||||
) -> bytes:
|
||||
"""Unmerge ranges and copy the master cell value into every covered cell.
|
||||
|
||||
openpyxl only stores values on the top-left cell of a merge; pandas then
|
||||
sees NaN in the rest. Filling makes row-wise RAG chunks retain context.
|
||||
|
||||
``percent_as_text`` also materializes percentage-formatted numbers as the
|
||||
text the spreadsheet displays ("0.6112" -> "61.12%"), because the stored
|
||||
fraction is 100x off from what a reader sees. ``None`` (the default) uses
|
||||
the ``DOCREADER_XLSX_PERCENT_AS_TEXT`` deployment default, which is off, so
|
||||
the default path is unchanged.
|
||||
"""
|
||||
if percent_as_text is None:
|
||||
percent_as_text = percent_as_text_default()
|
||||
|
||||
if not zipfile.is_zipfile(BytesIO(content)):
|
||||
return content
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
wb = load_workbook(BytesIO(content), data_only=True)
|
||||
changed = False
|
||||
materialized_cells = 0
|
||||
hinted_cells = 0
|
||||
row_hint_min = (
|
||||
_env_int(ROW_HINT_MIN_ENV, _DEFAULT_ROW_HINT_MIN) if percent_as_text else 0
|
||||
)
|
||||
|
||||
for ws in wb.worksheets:
|
||||
if percent_as_text:
|
||||
# Before the merge fill below — see _materialize_percentage_cells.
|
||||
materialized, hinted = _materialize_percentage_cells(ws, row_hint_min)
|
||||
materialized_cells += materialized
|
||||
hinted_cells += hinted
|
||||
if materialized:
|
||||
changed = True
|
||||
|
||||
if not ws.merged_cells.ranges:
|
||||
continue
|
||||
for merge_range in list(ws.merged_cells.ranges):
|
||||
master_value = ws.cell(merge_range.min_row, merge_range.min_col).value
|
||||
ws.unmerge_cells(str(merge_range))
|
||||
for row in range(merge_range.min_row, merge_range.max_row + 1):
|
||||
for col in range(merge_range.min_col, merge_range.max_col + 1):
|
||||
ws.cell(row, col).value = master_value
|
||||
changed = True
|
||||
|
||||
if not changed:
|
||||
return content
|
||||
|
||||
# Charts are not part of the cell text extracted by DocReader. Remove
|
||||
# dedicated chart sheets through the public workbook API, then clear
|
||||
# embedded worksheet charts (openpyxl has no public removal API for them)
|
||||
# before saving this temporary workbook.
|
||||
active_sheet = wb.active
|
||||
for chart_sheet in list(wb.chartsheets):
|
||||
wb.remove(chart_sheet)
|
||||
if active_sheet in wb.worksheets:
|
||||
wb.active = active_sheet
|
||||
elif wb.worksheets:
|
||||
wb.active = wb.worksheets[0]
|
||||
for ws in wb.worksheets:
|
||||
ws._charts.clear()
|
||||
|
||||
out = BytesIO()
|
||||
wb.save(out)
|
||||
if materialized_cells:
|
||||
logger.info(
|
||||
"Materialized %d percentage cell(s) in XLSX before parse "
|
||||
"(%d recovered by the same-row hint fallback, threshold=%d)",
|
||||
materialized_cells,
|
||||
hinted_cells,
|
||||
row_hint_min,
|
||||
)
|
||||
logger.info("Filled merged cells in XLSX before parse")
|
||||
return out.getvalue()
|
||||
@@ -0,0 +1,282 @@
|
||||
"""Repair common XLSX packaging issues before openpyxl/pandas read."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import zipfile
|
||||
from typing import Callable, Dict, Iterable, Set
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SST_PART = "xl/sharedStrings.xml"
|
||||
_SST_OVERRIDE_RE = re.compile(
|
||||
r'<Override[^>]*PartName="[^"]*sharedStrings\.xml"[^>]*/>',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_SST_REL_RE = re.compile(
|
||||
r'<Relationship[^>]*Type="[^"]*sharedStrings"[^>]*/>',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def repair_xlsx_bytes(content: bytes) -> bytes | None:
|
||||
"""Return repaired XLSX bytes, or None if no repair was applied.
|
||||
|
||||
Handles workbooks that reference ``xl/sharedStrings.xml`` in package
|
||||
metadata but omit the part (common with some exporters). When worksheets
|
||||
only use inline strings, manifest references are stripped so openpyxl can
|
||||
read the file.
|
||||
"""
|
||||
if not zipfile.is_zipfile(io.BytesIO(content)):
|
||||
return None
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(content), "r") as zin:
|
||||
names = _normalized_names(zin.namelist())
|
||||
sst_path = _find_shared_strings_path(names)
|
||||
if sst_path:
|
||||
if sst_path == SST_PART:
|
||||
return None
|
||||
return _rewrite_zip(
|
||||
zin, lambda files: _rename_shared_strings_part(files, sst_path)
|
||||
)
|
||||
if not _package_references_shared_strings(zin, names):
|
||||
return None
|
||||
if _worksheets_use_shared_string_cells(zin, names):
|
||||
return None
|
||||
return _rewrite_zip(zin, _strip_shared_strings_manifest)
|
||||
|
||||
|
||||
# A data validation, or a scenario list, whose ``sqref`` openpyxl cannot parse
|
||||
# aborts the whole workbook: openpyxl reads that attribute through a converter that
|
||||
# turns the underlying range-parse ValueError into
|
||||
# "TypeError: expected <class 'MultiCellRange'>" (#3599). Measured on openpyxl
|
||||
# 3.1.5, a whole column (``C:C``), a whole row (``1:1``), a comma-separated
|
||||
# list, ``#REF!`` and an out-of-bounds range all do it, in load_workbook and in
|
||||
# pandas alike. Conditional formatting goes through the same converter, but
|
||||
# openpyxl already catches it there and drops the rule with a warning, so it
|
||||
# is not touched here. For scenarios the range sits on the ``<scenarios>``
|
||||
# container, not on each ``<scenario>``, so the container is what goes.
|
||||
_SQREF_ELEMENT_RE = re.compile(
|
||||
r"<(?P<tag>(?:\w+:)?(?:dataValidation|scenarios))\b[^>]*?(?:/>|>.*?</(?P=tag)>)",
|
||||
re.DOTALL,
|
||||
)
|
||||
_SQREF_ATTR_RE = re.compile(r'\bsqref="([^"]*)"')
|
||||
|
||||
|
||||
def strip_unreadable_ranges_xlsx(content: bytes) -> bytes | None:
|
||||
"""Drop data validations and scenario lists whose range openpyxl cannot parse.
|
||||
|
||||
Returns the rewritten bytes, or None when every such range is readable, in
|
||||
which case the file is left exactly as it was. Neither element changes what
|
||||
a cell contains — a validation constrains input, a scenario holds what-if
|
||||
values that are not the displayed ones — so removing one costs text
|
||||
extraction nothing, while keeping it costs the whole document.
|
||||
"""
|
||||
if not zipfile.is_zipfile(io.BytesIO(content)):
|
||||
return None
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(content), "r") as zin:
|
||||
sheets = sorted(
|
||||
name
|
||||
for name in _normalized_names(zin.namelist())
|
||||
if name.startswith("xl/worksheets/") and name.endswith(".xml")
|
||||
)
|
||||
dropped: Dict[str, int] = {}
|
||||
for name in sheets:
|
||||
sheet = zin.read(name).decode("utf-8", errors="replace")
|
||||
count = sum(1 for m in _SQREF_ELEMENT_RE.finditer(sheet) if _unreadable(m.group(0)))
|
||||
if count:
|
||||
dropped[name] = count
|
||||
if not dropped:
|
||||
return None
|
||||
logger.warning(
|
||||
"Dropping %d data validation/scenario range(s) openpyxl cannot parse: %s",
|
||||
sum(dropped.values()),
|
||||
", ".join(f"{name} ({n})" for name, n in dropped.items()),
|
||||
)
|
||||
return _rewrite_zip(zin, lambda files: _strip_unreadable_ranges(files, dropped))
|
||||
|
||||
|
||||
def _unreadable(element: str) -> bool:
|
||||
"""True when openpyxl would fail to build this element's range."""
|
||||
from openpyxl.worksheet.cell_range import MultiCellRange
|
||||
|
||||
match = _SQREF_ATTR_RE.search(element)
|
||||
if match is None:
|
||||
return False
|
||||
try:
|
||||
MultiCellRange(match.group(1))
|
||||
except Exception: # noqa: BLE001 - mirrors openpyxl's own bare except
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _strip_unreadable_ranges(files: Dict[str, bytes], sheets: Dict[str, int]) -> Dict[str, bytes]:
|
||||
updated = dict(files)
|
||||
for name in sheets:
|
||||
sheet = updated[name].decode("utf-8")
|
||||
sheet = _SQREF_ELEMENT_RE.sub(
|
||||
lambda m: "" if _unreadable(m.group(0)) else m.group(0), sheet
|
||||
)
|
||||
updated[name] = sheet.encode("utf-8")
|
||||
return updated
|
||||
|
||||
def _normalized_names(namelist: Iterable[str]) -> Set[str]:
|
||||
return {name.replace("\\", "/") for name in namelist}
|
||||
|
||||
|
||||
def _find_shared_strings_path(names: Set[str]) -> str | None:
|
||||
for name in names:
|
||||
if name.lower().endswith("sharedstrings.xml"):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _package_references_shared_strings(
|
||||
zin: zipfile.ZipFile, names: Set[str]
|
||||
) -> bool:
|
||||
content_types = "[Content_Types].xml"
|
||||
if content_types in names:
|
||||
ct = zin.read(content_types).decode("utf-8", errors="replace")
|
||||
if "sharedstrings.xml" in ct.lower():
|
||||
return True
|
||||
|
||||
rels_path = "xl/_rels/workbook.xml.rels"
|
||||
if rels_path in names:
|
||||
rels = zin.read(rels_path).decode("utf-8", errors="replace")
|
||||
if "sharedstrings" in rels.lower():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _worksheets_use_shared_string_cells(
|
||||
zin: zipfile.ZipFile, names: Set[str]
|
||||
) -> bool:
|
||||
for name in names:
|
||||
if not name.startswith("xl/worksheets/") or not name.endswith(".xml"):
|
||||
continue
|
||||
sheet = zin.read(name).decode("utf-8", errors="replace")
|
||||
if re.search(r'\bt="s"', sheet):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _rename_shared_strings_part(
|
||||
files: Dict[str, bytes], source_path: str
|
||||
) -> Dict[str, bytes]:
|
||||
updated = dict(files)
|
||||
updated[SST_PART] = updated.pop(source_path)
|
||||
return updated
|
||||
|
||||
|
||||
def _strip_shared_strings_manifest(files: Dict[str, bytes]) -> Dict[str, bytes]:
|
||||
updated = dict(files)
|
||||
ct_path = "[Content_Types].xml"
|
||||
if ct_path in updated:
|
||||
ct = updated[ct_path].decode("utf-8")
|
||||
ct = _SST_OVERRIDE_RE.sub("", ct)
|
||||
updated[ct_path] = ct.encode("utf-8")
|
||||
|
||||
rels_path = "xl/_rels/workbook.xml.rels"
|
||||
if rels_path in updated:
|
||||
rels = updated[rels_path].decode("utf-8")
|
||||
rels = _SST_REL_RE.sub("", rels)
|
||||
updated[rels_path] = rels.encode("utf-8")
|
||||
return updated
|
||||
|
||||
|
||||
def _rewrite_zip(
|
||||
zin: zipfile.ZipFile,
|
||||
transform: Callable[[Dict[str, bytes]], Dict[str, bytes]],
|
||||
) -> bytes:
|
||||
files: Dict[str, bytes] = {}
|
||||
for info in zin.infolist():
|
||||
name = info.filename.replace("\\", "/")
|
||||
files[name] = zin.read(info.filename)
|
||||
files = transform(files)
|
||||
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zout:
|
||||
for name, data in files.items():
|
||||
zout.writestr(name, data)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
# The one stylesheet openpyxl reads (openpyxl.xml.constants.ARC_STYLE). Match
|
||||
# it exactly: a suffix match also hits xl/richData/richStyles.xml (Excel 365
|
||||
# in-cell images / data types), which carries no fills.
|
||||
STYLES_PART = "xl/styles.xml"
|
||||
_REPLACEMENT_FILL = b'<fill><patternFill patternType="none"/></fill>'
|
||||
_FILLS_BLOCK_RE = re.compile(rb"<fills\b[^>]*>.*?</fills>", re.S)
|
||||
# Case-insensitive so wrong-case <Fill>…</Fill> entries are caught too.
|
||||
_FILL_ELEMENT_RE = re.compile(rb"<fill\s*/>|<fill\s*>.*?</fill\s*>", re.S | re.I)
|
||||
# A fill openpyxl can deserialize starts (case-sensitively) with a
|
||||
# patternFill or gradientFill child — everything else, including the
|
||||
# self-closing <fill/>, is rejected by its sequence descriptor.
|
||||
_WELL_FORMED_FILL_RE = re.compile(rb"<fill\s*>\s*<(?:patternFill|gradientFill)[\s/>]")
|
||||
|
||||
|
||||
def sanitize_xlsx_styles(content: bytes) -> bytes | None:
|
||||
"""Rewrite styles.xml fills that openpyxl cannot deserialize.
|
||||
|
||||
Some exporters (cloud-doc systems, LabView, Acumatica ERP) write ``<fill>``
|
||||
elements with no child, or a child that is neither patternFill nor
|
||||
gradientFill. openpyxl's strict sequence descriptor raises
|
||||
``TypeError: expected <class 'openpyxl.styles.fills.Fill'>`` on them and
|
||||
treats the workbook as non-conformant, so both parse engines die on a
|
||||
file Excel itself opens fine (#3637). Replacing each malformed fill in
|
||||
place with a no-op patternFill keeps the fill list length — and therefore
|
||||
every cellXf fillId reference — stable. Returns None when nothing needs
|
||||
fixing, so callers pay one styles.xml scan on the happy path.
|
||||
|
||||
Never raises: on any internal failure the original bytes flow on
|
||||
unchanged, so a caller recovering from its own error keeps that error's
|
||||
cause instead of trading it for a sanitizer failure.
|
||||
"""
|
||||
try:
|
||||
return _sanitize_xlsx_styles(content)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"XLSX styles sanitize failed; passing original bytes through",
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _sanitize_xlsx_styles(content: bytes) -> bytes | None:
|
||||
if not zipfile.is_zipfile(io.BytesIO(content)):
|
||||
return None
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(content)) as zin:
|
||||
if STYLES_PART not in zin.namelist():
|
||||
return None
|
||||
styles = zin.read(STYLES_PART)
|
||||
|
||||
block = _FILLS_BLOCK_RE.search(styles)
|
||||
if block is None:
|
||||
return None
|
||||
|
||||
fixed_count = 0
|
||||
|
||||
def _fix(match: "re.Match[bytes]") -> bytes:
|
||||
nonlocal fixed_count
|
||||
if _WELL_FORMED_FILL_RE.match(match.group(0)):
|
||||
return match.group(0)
|
||||
fixed_count += 1
|
||||
return _REPLACEMENT_FILL
|
||||
|
||||
patched_block = _FILL_ELEMENT_RE.sub(_fix, block.group(0))
|
||||
if fixed_count == 0:
|
||||
return None
|
||||
|
||||
# Doubles as the recurrence meter for #3637: how often real uploads
|
||||
# carry non-conforming fills, and how many per file.
|
||||
logger.info(
|
||||
"Sanitized %d non-conforming fill(s) in XLSX styles.xml before parse",
|
||||
fixed_count,
|
||||
)
|
||||
|
||||
patched = styles[: block.start()] + patched_block + styles[block.end():]
|
||||
return _rewrite_zip(zin, lambda files: {**files, STYLES_PART: patched})
|
||||
@@ -0,0 +1,246 @@
|
||||
"""Parse XMind archives into Markdown outlines."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from dataclasses import dataclass, field
|
||||
from xml.etree import ElementTree
|
||||
from xml.etree.ElementTree import Element
|
||||
|
||||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
|
||||
|
||||
MAX_CONTENT_BYTES = 32 * 1024 * 1024
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Topic:
|
||||
title: str = ""
|
||||
note: str = ""
|
||||
children: list["_Topic"] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Sheet:
|
||||
title: str = ""
|
||||
root_topic: _Topic | None = None
|
||||
|
||||
|
||||
def _clean_text(value: object) -> str:
|
||||
return value.strip() if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def _topic_from_json(value: object) -> _Topic | None:
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
|
||||
note = ""
|
||||
notes = value.get("notes")
|
||||
if isinstance(notes, dict):
|
||||
plain = notes.get("plain")
|
||||
if isinstance(plain, dict):
|
||||
note = _clean_text(plain.get("content"))
|
||||
|
||||
topics: list[_Topic] = []
|
||||
children = value.get("children")
|
||||
if isinstance(children, dict):
|
||||
attached = children.get("attached")
|
||||
if isinstance(attached, list):
|
||||
for child in attached:
|
||||
topic = _topic_from_json(child)
|
||||
if topic is not None:
|
||||
topics.append(topic)
|
||||
|
||||
return _Topic(
|
||||
title=_clean_text(value.get("title")),
|
||||
note=note,
|
||||
children=topics,
|
||||
)
|
||||
|
||||
|
||||
def _parse_json_sheets(payload: bytes) -> list[_Sheet]:
|
||||
values = json.loads(payload)
|
||||
if not isinstance(values, list):
|
||||
raise ValueError("invalid XMind content.json: expected a sheet list")
|
||||
|
||||
sheets: list[_Sheet] = []
|
||||
for value in values:
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
sheets.append(
|
||||
_Sheet(
|
||||
title=_clean_text(value.get("title")),
|
||||
root_topic=_topic_from_json(value.get("rootTopic")),
|
||||
)
|
||||
)
|
||||
return sheets
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
return tag.rsplit("}", 1)[-1].split(":", 1)[-1]
|
||||
|
||||
|
||||
def _direct_children(element: Element, name: str) -> list[Element]:
|
||||
return [child for child in element if _local_name(child.tag) == name]
|
||||
|
||||
|
||||
def _first_child(element: Element, name: str) -> Element | None:
|
||||
children = _direct_children(element, name)
|
||||
return children[0] if children else None
|
||||
|
||||
|
||||
def _element_text(element: Element | None) -> str:
|
||||
if element is None:
|
||||
return ""
|
||||
return "".join(element.itertext()).strip()
|
||||
|
||||
|
||||
def _topic_from_xml(element: Element) -> _Topic:
|
||||
notes = _first_child(element, "notes")
|
||||
plain = _first_child(notes, "plain") if notes is not None else None
|
||||
|
||||
topics: list[_Topic] = []
|
||||
for children in _direct_children(element, "children"):
|
||||
for topic_group in _direct_children(children, "topics"):
|
||||
topics.extend(
|
||||
_topic_from_xml(topic)
|
||||
for topic in _direct_children(topic_group, "topic")
|
||||
)
|
||||
|
||||
return _Topic(
|
||||
title=_element_text(_first_child(element, "title")),
|
||||
note=_element_text(plain),
|
||||
children=topics,
|
||||
)
|
||||
|
||||
|
||||
def _parse_xml_sheets(payload: bytes) -> list[_Sheet]:
|
||||
try:
|
||||
root = ElementTree.fromstring(payload)
|
||||
except ElementTree.ParseError as exc:
|
||||
raise ValueError("invalid XMind content.xml") from exc
|
||||
|
||||
sheets: list[_Sheet] = []
|
||||
for sheet in _direct_children(root, "sheet"):
|
||||
root_topic = _first_child(sheet, "topic")
|
||||
sheets.append(
|
||||
_Sheet(
|
||||
title=_element_text(_first_child(sheet, "title")),
|
||||
root_topic=(
|
||||
_topic_from_xml(root_topic) if root_topic is not None else None
|
||||
),
|
||||
)
|
||||
)
|
||||
return sheets
|
||||
|
||||
|
||||
def _read_content_entry(content: bytes) -> tuple[str, bytes]:
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(content)) as archive:
|
||||
try:
|
||||
info = archive.getinfo("content.json")
|
||||
content_format = "json"
|
||||
except KeyError:
|
||||
try:
|
||||
info = archive.getinfo("content.xml")
|
||||
except KeyError as exc:
|
||||
raise ValueError(
|
||||
"XMind archive is missing content.json or content.xml"
|
||||
) from exc
|
||||
content_format = "xml"
|
||||
|
||||
if info.flag_bits & 0x1:
|
||||
raise ValueError("encrypted XMind content is not supported")
|
||||
if info.file_size > MAX_CONTENT_BYTES:
|
||||
raise ValueError("XMind content entry exceeds the 32 MiB limit")
|
||||
|
||||
with archive.open(info) as entry:
|
||||
payload = entry.read(MAX_CONTENT_BYTES + 1)
|
||||
if len(payload) > MAX_CONTENT_BYTES:
|
||||
raise ValueError("XMind content entry exceeds the 32 MiB limit")
|
||||
return content_format, payload
|
||||
except zipfile.BadZipFile as exc:
|
||||
raise ValueError("invalid XMind archive") from exc
|
||||
|
||||
|
||||
def _render_topic(topic: _Topic, depth: int) -> tuple[list[str], int, int]:
|
||||
lines: list[str] = []
|
||||
topic_count = 0
|
||||
note_count = 0
|
||||
child_depth = depth
|
||||
|
||||
if topic.title:
|
||||
lines.append(f"{' ' * depth}- {topic.title}")
|
||||
topic_count = 1
|
||||
child_depth += 1
|
||||
if topic.note:
|
||||
for note_line in topic.note.splitlines():
|
||||
normalized = note_line.strip()
|
||||
quote = f"> {normalized}" if normalized else ">"
|
||||
lines.append(f"{' ' * child_depth}{quote}")
|
||||
note_count = 1
|
||||
|
||||
for child in topic.children:
|
||||
child_lines, child_topics, child_notes = _render_topic(child, child_depth)
|
||||
lines.extend(child_lines)
|
||||
topic_count += child_topics
|
||||
note_count += child_notes
|
||||
|
||||
return lines, topic_count, note_count
|
||||
|
||||
|
||||
def _render_sheets(sheets: list[_Sheet]) -> tuple[str, int, int, int]:
|
||||
rendered_sheets: list[str] = []
|
||||
topic_count = 0
|
||||
note_count = 0
|
||||
|
||||
for index, sheet in enumerate(sheets, start=1):
|
||||
if sheet.root_topic is None:
|
||||
continue
|
||||
lines, sheet_topics, sheet_notes = _render_topic(sheet.root_topic, 0)
|
||||
if not lines:
|
||||
continue
|
||||
title = sheet.title or f"Sheet {index}"
|
||||
rendered_sheets.append(f"# {title}\n\n" + "\n".join(lines))
|
||||
topic_count += sheet_topics
|
||||
note_count += sheet_notes
|
||||
|
||||
return (
|
||||
"\n\n---\n\n".join(rendered_sheets),
|
||||
len(rendered_sheets),
|
||||
topic_count,
|
||||
note_count,
|
||||
)
|
||||
|
||||
|
||||
class XMindParser(BaseParser):
|
||||
"""Extract topic hierarchy and plain-text notes from XMind files."""
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
content_format, payload = _read_content_entry(content)
|
||||
|
||||
if content_format == "json":
|
||||
try:
|
||||
sheets = _parse_json_sheets(payload)
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
|
||||
raise ValueError("invalid XMind content.json") from exc
|
||||
else:
|
||||
sheets = _parse_xml_sheets(payload)
|
||||
|
||||
markdown, sheet_count, topic_count, note_count = _render_sheets(
|
||||
sheets
|
||||
)
|
||||
if not markdown:
|
||||
raise ValueError("XMind archive contains no renderable topics")
|
||||
return Document(
|
||||
content=markdown,
|
||||
metadata={
|
||||
"source_format": "xmind",
|
||||
"xmind_content_format": content_format,
|
||||
"file_size": len(content),
|
||||
"sheet_count": sheet_count,
|
||||
"topic_count": topic_count,
|
||||
"note_count": note_count,
|
||||
},
|
||||
)
|
||||
Reference in new issue
Block a user