chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
"""Generate the real DOCX regression fixture for GitHub issue #2634."""
from pathlib import Path
from docx import Document
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
OUTPUT = Path(__file__).with_name("issue_2634_vertical_merge.docx")
def main() -> None:
document = Document()
document.add_heading("遗传病检测项目表", level=1)
document.add_paragraph(
"回归场景:检测方法纵向合并,但每条检测项目在转换后都必须保留该方法。"
)
rows = [
("Q0101", "遗传性乳腺癌", "BRCA1", "15个工作日"),
("Q0102", "遗传性卵巢癌", "BRCA2", "15个工作日"),
("Q0103", "林奇综合征", "MLH1", "15个工作日"),
("Q0104", "家族性腺瘤性息肉病", "APC", "15个工作日"),
]
method = (
"检测方法:提取外周血基因组 DNA,采用高通量测序,并对候选位点进行"
"Sanger 测序验证;检测结果需结合临床表现综合判断。"
)
table = document.add_table(rows=len(rows) + 1, cols=5)
table.style = "Table Grid"
headers = ("项目编号", "检测项目", "相关基因", "周期", "检测方法")
for column, value in enumerate(headers):
table.cell(0, column).text = value
for row_index, row in enumerate(rows, start=1):
for column, value in enumerate(row):
table.cell(row_index, column).text = value
merged_method = table.cell(1, 4).merge(table.cell(len(rows), 4))
merged_method.text = method
merged_method.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
document.add_paragraph("非合并对照表:相邻单元格内容允许相同,但不应被当作合并。")
control = document.add_table(rows=2, cols=3)
control.style = "Table Grid"
for column, value in enumerate(("列A", "列B", "列C")):
control.cell(0, column).text = value
for column, value in enumerate(("相同值", "相同值", "独立值")):
control.cell(1, column).text = value
document.save(OUTPUT)
print(f"generated={OUTPUT}")
print(f"size={OUTPUT.stat().st_size}")
if __name__ == "__main__":
main()
Binary file not shown.
@@ -0,0 +1,41 @@
"""Regenerate browser fixtures with the actual builtin PDF parser.
Run from the repository root:
docreader/.venv/bin/python -m docreader.tests.generate_source_location_browser_fixtures
"""
import base64
import json
from pathlib import Path
from unittest.mock import patch
from docreader.parser.pdf_parser import PDFParser
from docreader.tests.test_source_locator_pdf import pdf_fixture
def main():
cases = [{"name": "PDFium lower paragraph with decimal evidence", "page": 2,
"needle": "Second page lower evidence", "pages": [
{"lines": [("First page has independent original evidence.", 60, 700)]},
{"lines": [("Second page upper paragraph is unrelated.", 60, 700),
("Second page lower evidence: the limit is 1.5 mm.", 60, 400)]}]}]
for rotation in (0, 90, 180, 270):
cases.append({"name": f"PDFium CropBox and rotation {rotation}", "page": 1,
"needle": "Cropped and rotated", "pages": [
{"rotation": rotation, "crop": "/CropBox [100 100 500 700]",
"lines": [("Cropped and rotated source evidence.", 150, 600)]}]})
output = []
for case in cases:
data = pdf_fixture(case["pages"])
with patch("docreader.parser.pdf_parser.SOURCE_BOXES", True):
doc = PDFParser(file_name="fixture.pdf", pdf_force_scanned=False).parse_into_text(data)
at = doc.content.index(case["needle"])
block = next(b for b in doc.source_blocks if b["start"] <= at < b["end"])
locator = {**block["locator"], "quote": doc.content[block["start"]:block["end"]].strip()}
assert locator.get("bbox"), case["name"]
output.append({"name": case["name"], "page": case["page"], "pdf": base64.b64encode(data).decode(), "locator": locator})
target = Path(__file__).resolve().parents[2] / "frontend/tests/source-locate/parsedFixtures.json"
target.write_text(json.dumps(output, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
@@ -0,0 +1,60 @@
"""Real subprocess protocol fixture: no OCR models or network needed."""
import json
import os
from pathlib import Path
import socket
import struct
import sys
import time
from docreader.preprocess import PreprocessLimits, _Channel
from docreader.proto.docreader_pb2 import PreprocessImageResponse
def main():
connection = _Channel(socket.socket(fileno=int(sys.argv[1])))
connection.send_bytes(b"ready")
try:
if os.environ.get("PREPROCESS_FIXTURE_STALL_INPUT"):
Path(os.environ["PREPROCESS_FIXTURE_STALL_INPUT"]).write_text(str(os.getpid()))
while True:
time.sleep(1)
while True:
command = json.loads(connection.recv_bytes())
if command.get("started"):
Path(command["started"]).write_text(str(os.getpid()))
if command.get("crash"):
os._exit(7)
if command.get("partial_reply"):
# A readable socket can contain only the length header. The
# parent must still enforce its deadline while awaiting data.
connection.socket.send(struct.pack("!I", 100))
if command.get("check_address_limit"):
import resource
from docreader.preprocess_worker import apply_process_limits
limits = PreprocessLimits(**json.loads(sys.argv[2]))
apply_process_limits(limits, int(sys.argv[3]))
cap = resource.getrlimit(resource.RLIMIT_AS)
connection.send_bytes(PreprocessImageResponse(
image=json.dumps(cap).encode(), status="ok").SerializeToString())
continue
if command.get("memory"):
allocation = bytearray(command["memory"])
# Touch the pages so RSS supervision sees them on every OS.
for offset in range(0, len(allocation), 4096):
allocation[offset] = 1
if command.get("release"):
while not Path(command["release"]).exists():
time.sleep(0.01)
response = PreprocessImageResponse(image=str(os.getpid()).encode(), status="ok")
connection.send_bytes(response.SerializeToString())
except (EOFError, BrokenPipeError):
pass
finally:
connection.close()
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
import os
import unittest
from unittest.mock import patch
from docreader import config
class DocReaderConfigTest(unittest.TestCase):
def test_parser_concurrency_defaults_are_conservative(self):
with patch.dict(os.environ, {}, clear=True):
cfg = config.load_config()
self.assertEqual(cfg.markitdown_max_workers, 1)
self.assertEqual(cfg.pdf_render_max_workers, 1)
self.assertEqual(cfg.pdf_render_dpi, 200)
self.assertEqual(cfg.pdf_jpeg_quality, 85)
def test_loads_parser_concurrency_env(self):
env = {
"DOCREADER_MARKITDOWN_MAX_WORKERS": "3",
"DOCREADER_PDF_RENDER_MAX_WORKERS": "2",
"DOCREADER_PDF_RENDER_DPI": "180",
"DOCREADER_PDF_JPEG_QUALITY": "85",
}
with patch.dict(os.environ, env):
cfg = config.load_config()
self.assertEqual(cfg.markitdown_max_workers, 3)
self.assertEqual(cfg.pdf_render_max_workers, 2)
self.assertEqual(cfg.pdf_render_dpi, 180)
self.assertEqual(cfg.pdf_jpeg_quality, 85)
def test_dump_config_includes_parser_limits(self):
dumped = config.dump_config()
self.assertIn("DOCREADER_MARKITDOWN_MAX_WORKERS", dumped)
self.assertIn("DOCREADER_PDF_RENDER_MAX_WORKERS", dumped)
self.assertIn("DOCREADER_PDF_RENDER_DPI", dumped)
self.assertIn("DOCREADER_PDF_JPEG_QUALITY", dumped)
def test_html_main_content_is_off_by_default(self):
with patch.dict(os.environ, {}, clear=True):
cfg = config.load_config()
self.assertFalse(cfg.html_main_content)
def test_loads_html_main_content_env(self):
with patch.dict(os.environ, {"DOCREADER_HTML_MAIN_CONTENT": "true"}):
cfg = config.load_config()
self.assertTrue(cfg.html_main_content)
def test_dump_config_includes_html_main_content(self):
dumped = config.dump_config()
self.assertIn("DOCREADER_HTML_MAIN_CONTENT", dumped)
def test_preprocess_limits_are_independent_and_bounded(self):
with patch.dict(os.environ, {"DOCREADER_GRPC_MAX_WORKERS": "8"}, clear=True):
cfg = config.load_config()
self.assertEqual(cfg.preprocess_max_workers, 1)
self.assertEqual(cfg.preprocess_threads, 2)
self.assertEqual(cfg.preprocess_timeout_seconds, 30)
self.assertEqual(cfg.preprocess_memory_mb, 2048)
self.assertEqual(cfg.preprocess_max_pixels, 16_000_000)
self.assertEqual(cfg.preprocess_max_edge, 2000)
self.assertEqual(cfg.preprocess_probe_edge, 2000)
def test_preprocess_limits_cannot_be_disabled_by_invalid_values(self):
for name in ("MAX_WORKERS", "THREADS", "TIMEOUT_SECONDS", "MEMORY_MB", "MAX_PIXELS", "MAX_EDGE", "PROBE_EDGE"):
key = f"DOCREADER_PREPROCESS_{name}"
for value in ("0", "-1", "invalid"):
with self.subTest(key=key, value=value), patch.dict(os.environ, {key: value}, clear=True):
cfg = config.load_config()
self.assertGreater(getattr(cfg, f"preprocess_{name.lower()}"), 0)
with self.subTest(key=key), patch.dict(os.environ, {key: "7"}, clear=True):
self.assertEqual(getattr(config.load_config(), f"preprocess_{name.lower()}"), 7)
self.assertIn(key, config.dump_config())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,64 @@
import os
import signal
import subprocess
import unittest
from unittest.mock import patch
from docreader.container_entrypoint import runtime_environment
class ContainerEntrypointTest(unittest.TestCase):
def setUp(self):
env = patch.dict(os.environ, {"PATH": "/app/.venv/bin"}, clear=True)
env.start()
self.addCleanup(env.stop)
machine = patch("docreader.container_entrypoint.platform.machine", return_value="aarch64")
machine.start()
self.addCleanup(machine.stop)
@patch("docreader.container_entrypoint.subprocess.run")
def test_healthy_arm_keeps_acceleration(self, run):
run.return_value = subprocess.CompletedProcess([], 0, b"", b"")
self.assertNotIn("OPENSSL_armcap", runtime_environment())
self.assertEqual(run.call_count, 1)
@patch("docreader.container_entrypoint.subprocess.run")
def test_sigill_retries_and_verifies_portable_crypto(self, run):
run.side_effect = [subprocess.CompletedProcess([], -signal.SIGILL, b"", b""), subprocess.CompletedProcess([], 0, b"", b"")]
self.assertEqual(runtime_environment()["OPENSSL_armcap"], "0")
self.assertEqual(run.call_count, 2)
self.assertNotIn("OPENSSL_armcap", os.environ)
@patch("docreader.container_entrypoint.subprocess.run")
def test_other_failure_is_not_masked(self, run):
run.return_value = subprocess.CompletedProcess([], 1, b"", b"missing dependency")
with self.assertRaisesRegex(RuntimeError, "missing dependency"):
runtime_environment()
self.assertEqual(run.call_count, 1)
@patch("docreader.container_entrypoint.subprocess.run")
def test_failed_portable_probe_stays_fatal(self, run):
run.side_effect = [subprocess.CompletedProcess([], -signal.SIGILL, b"", b""), subprocess.CompletedProcess([], 1, b"", b"encryption failed")]
with self.assertRaisesRegex(RuntimeError, "encryption failed"):
runtime_environment()
@patch("docreader.container_entrypoint.subprocess.run")
def test_operator_override_is_preserved(self, run):
os.environ["OPENSSL_armcap"] = "0x1"
self.assertEqual(runtime_environment()["OPENSSL_armcap"], "0x1")
run.assert_not_called()
@patch("docreader.container_entrypoint.platform.machine", return_value="x86_64")
@patch("docreader.container_entrypoint.subprocess.run")
def test_other_architectures_are_unchanged(self, run, machine):
self.assertNotIn("OPENSSL_armcap", runtime_environment())
run.assert_not_called()
@patch("docreader.container_entrypoint.subprocess.run", side_effect=subprocess.TimeoutExpired("probe", 30))
def test_probe_has_bounded_startup(self, run):
with self.assertRaises(subprocess.TimeoutExpired):
runtime_environment()
if __name__ == "__main__":
unittest.main()
+206
View File
@@ -0,0 +1,206 @@
"""Linux regression: large PDF requests release their buffers while idle."""
import ctypes
import gc
import io
import logging
import multiprocessing
import os
import sys
import time
import unittest
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import patch
import grpc
from PIL import Image
from docreader.proto import docreader_pb2 as pb
from docreader.proto import docreader_pb2_grpc as rpc
def _anonymous_bytes():
with open("/proc/self/status") as status:
return next(
int(line.split()[1]) * 1024
for line in status
if line.startswith("RssAnon:")
)
def _serve(control):
os.environ["DOCREADER_PDF_RENDER_PARALLELISM"] = "1"
os.environ["GRPC_AUTH_TOKEN"] = ""
os.environ["GRPC_TLS_ENABLED"] = "false"
from docreader import main
logging.disable(logging.CRITICAL)
real_server = grpc.server
def create_server(pool, **kwargs):
kwargs["options"] = [("grpc.max_receive_message_length", 80 * 1024 * 1024)]
server = real_server(pool, **kwargs)
add_port = server.add_insecure_port
port = None
def bind(_address):
nonlocal port
port = add_port("127.0.0.1:0")
return port
def wait():
# No auto-GC while idle: the completed request must reclaim itself.
gc.collect()
gc.disable()
control.send(port)
try:
while control.recv() == "memory":
control.send(_anonymous_bytes())
finally:
server.stop(0).wait()
pool.shutdown()
control.close()
server.add_insecure_port = bind
server.wait_for_termination = wait
return server
with patch.object(main.grpc, "server", create_server):
with patch.object(main.config, "print_config"):
main.main()
def _scanned_pdf(padding_bytes=0):
image = io.BytesIO()
with Image.new("RGB", (64, 64), "black") as page:
page.save(image, format="JPEG")
jpeg = image.getvalue()
drawing = b"q 200 0 0 200 0 0 cm /Im0 Do Q"
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] "
b"/Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>",
b"<< /Type /XObject /Subtype /Image /Width 64 /Height 64 "
b"/ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length "
+ str(len(jpeg)).encode() + b" >>\nstream\n" + jpeg + b"\nendstream",
b"<< /Length " + str(len(drawing)).encode()
+ b" >>\nstream\n" + drawing + b"\nendstream",
]
# An unreferenced stream gives the request a large payload without making
# rendering slow or requiring a checked-in binary fixture.
output = io.BytesIO()
output.write(b"%PDF-1.7\n")
offsets = []
for number, obj in enumerate(objects, 1):
offsets.append(output.tell())
output.write(f"{number} 0 obj\n".encode() + obj + b"\nendobj\n")
offsets.append(output.tell())
output.write(f"6 0 obj\n<< /Length {padding_bytes} >>\nstream\n".encode())
output.write(b"A" * padding_bytes)
output.write(b"\nendstream\nendobj\n")
xref = output.tell()
output.write(b"xref\n0 7\n0000000000 65535 f \n")
for offset in offsets:
output.write(f"{offset:010d} 00000 n \n".encode())
output.write(
f"trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()
)
return output.getvalue()
@unittest.skipUnless(
sys.platform.startswith("linux") and hasattr(ctypes.CDLL(None), "malloc_trim"),
"anonymous-memory regression requires Linux and glibc",
)
class DocReaderMemoryTest(unittest.TestCase):
def test_large_pdf_buffers_are_released_after_rpc(self):
ctx = multiprocessing.get_context("spawn")
control, child_control = ctx.Pipe()
process = ctx.Process(target=_serve, args=(child_control,))
process.start()
child_control.close()
channel = None
try:
self.assertTrue(control.poll(30), "docreader did not start")
port = control.recv()
channel = grpc.insecure_channel(
f"127.0.0.1:{port}",
options=[("grpc.max_send_message_length", 80 * 1024 * 1024)],
)
grpc.channel_ready_future(channel).result(timeout=10)
stub = rpc.DocReaderStub(channel)
small = pb.ReadRequest(
file_content=_scanned_pdf(), file_name="scan.pdf", file_type="pdf"
)
self.assertEqual(len(list(stub.ReadStream(small, timeout=10))), 2)
def memory():
control.send("memory")
self.assertTrue(control.poll(5), "memory probe did not respond")
return control.recv()
baseline = memory()
def assert_reclaimed(label):
# EOF can arrive before the worker finishes its cleanup.
deadline = time.monotonic() + 5
current = memory()
while current - baseline > 32 * 1024 * 1024 and time.monotonic() < deadline:
time.sleep(0.02)
current = memory()
print(
f"{label}: idle delta={(current-baseline)/1048576:.1f} MiB "
"after a 64 MiB request", flush=True,
)
self.assertLess(current - baseline, 32 * 1024 * 1024)
large = pb.ReadRequest(
file_content=_scanned_pdf(64 * 1024 * 1024),
file_name="scan.pdf",
file_type="pdf",
)
for method in ("ReadStream", "Read", "ReadStream", "invalid PDF"):
with self.subTest(method=method):
if method == "Read":
result = stub.Read(large, timeout=20)
self.assertFalse(result.error)
self.assertEqual(len(result.image_refs), 1)
else:
request = large
if method == "invalid PDF":
request = pb.ReadRequest(
file_content=b"not a PDF" + b"A" * (64 * 1024 * 1024),
file_name="broken.pdf", file_type="pdf",
)
frames = list(stub.ReadStream(request, timeout=20))
if method == "invalid PDF":
self.assertTrue(frames[0].meta.error)
else:
self.assertEqual(len(frames), 2)
self.assertEqual(frames[0].meta.image_count, 1)
self.assertTrue(frames[1].image.image_data.startswith(b"\xff\xd8"))
assert_reclaimed(method)
with ThreadPoolExecutor(max_workers=2) as clients:
calls = [
clients.submit(lambda: list(stub.ReadStream(large, timeout=20)))
for _ in range(2)
]
for call in calls:
self.assertEqual(len(call.result()), 2)
assert_reclaimed("concurrent ReadStream")
self.assertEqual(len(list(stub.ReadStream(small, timeout=10))), 2)
finally:
if channel is not None:
channel.close()
if process.is_alive():
control.send("stop")
process.join(timeout=5)
if process.is_alive():
process.terminate()
process.join(timeout=5)
control.close()
if __name__ == "__main__":
unittest.main()
+187
View File
@@ -0,0 +1,187 @@
import io
import unittest
import zipfile
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from docx import Document as WordDocument
from lxml import etree
from docreader.parser.docx2_parser import Docx2Parser
from docreader.parser.docx_merge import fill_vertical_merged_cells_docx
from docreader.parser.markitdown_parser import StdMarkitdownParser
FIXTURE = Path(__file__).with_name("fixtures") / "issue_2634_vertical_merge.docx"
METHOD_PREFIX = "检测方法:提取外周血基因组 DNA"
PROJECT_CODES = ("Q0101", "Q0102", "Q0103", "Q0104")
WORD_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
class DocxVerticalMergeFillTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.fixture_bytes = FIXTURE.read_bytes()
def test_fixture_is_a_real_docx_with_vertical_merge(self):
self.assertTrue(zipfile.is_zipfile(io.BytesIO(self.fixture_bytes)))
with zipfile.ZipFile(io.BytesIO(self.fixture_bytes)) as archive:
self.assertIsNone(archive.testzip())
root = etree.fromstring(archive.read("word/document.xml"))
vertical_merges = root.xpath(
".//w:tbl[1]//w:vMerge", namespaces={"w": WORD_NAMESPACE}
)
merge_values = [
node.get(f"{{{WORD_NAMESPACE}}}val", "continue") for node in vertical_merges
]
self.assertEqual(
merge_values,
["restart", "continue", "continue", "continue"],
)
def test_fill_repeats_master_content_in_every_covered_row(self):
filled = fill_vertical_merged_cells_docx(self.fixture_bytes)
document = WordDocument(io.BytesIO(filled))
table = document.tables[0]
for row_index, project_code in enumerate(PROJECT_CODES, start=1):
self.assertEqual(table.cell(row_index, 0).text, project_code)
self.assertIn(METHOD_PREFIX, table.cell(row_index, 4).text)
with zipfile.ZipFile(io.BytesIO(filled)) as archive:
root = etree.fromstring(archive.read("word/document.xml"))
self.assertEqual(
root.xpath("count(.//w:vMerge)", namespaces={"w": WORD_NAMESPACE}),
0.0,
)
def test_non_merged_equal_cells_are_not_collapsed(self):
filled = fill_vertical_merged_cells_docx(self.fixture_bytes)
document = WordDocument(io.BytesIO(filled))
control_row = document.tables[1].rows[1]
self.assertEqual(len(control_row.cells), 3)
self.assertEqual(
[cell.text for cell in control_row.cells],
["相同值", "相同值", "独立值"],
)
def test_non_docx_bytes_pass_through_unchanged(self):
content = b"not a docx package"
self.assertIs(fill_vertical_merged_cells_docx(content), content)
def test_docx_without_vertical_merges_passes_through_unchanged(self):
document = WordDocument()
table = document.add_table(rows=1, cols=2)
table.cell(0, 0).text = "left"
table.cell(0, 1).text = "right"
output = io.BytesIO()
document.save(output)
content = output.getvalue()
self.assertIs(fill_vertical_merged_cells_docx(content), content)
def test_horizontal_merge_only_passes_through_unchanged(self):
document = WordDocument()
table = document.add_table(rows=1, cols=3)
table.cell(0, 0).merge(table.cell(0, 1)).text = "horizontal merge"
table.cell(0, 2).text = "independent"
output = io.BytesIO()
document.save(output)
content = output.getvalue()
self.assertIs(fill_vertical_merged_cells_docx(content), content)
def test_separate_merge_groups_keep_distinct_values_and_other_columns(self):
document = WordDocument()
table = document.add_table(rows=6, cols=2)
table.cell(0, 0).text = "group"
table.cell(0, 1).text = "item"
for row_index in range(1, 6):
table.cell(row_index, 1).text = f"item-{row_index}"
table.cell(1, 0).merge(table.cell(2, 0)).text = "group-a"
table.cell(3, 0).text = "standalone"
table.cell(4, 0).merge(table.cell(5, 0)).text = "group-b"
output = io.BytesIO()
document.save(output)
filled = fill_vertical_merged_cells_docx(output.getvalue())
parsed_table = WordDocument(io.BytesIO(filled)).tables[0]
self.assertEqual(
[parsed_table.cell(row_index, 0).text for row_index in range(1, 6)],
["group-a", "group-a", "standalone", "group-b", "group-b"],
)
self.assertEqual(
[parsed_table.cell(row_index, 1).text for row_index in range(1, 6)],
[f"item-{row_index}" for row_index in range(1, 6)],
)
class DocxMarkitdownDispatchTest(unittest.TestCase):
def test_non_docx_types_do_not_run_docx_preprocessor(self):
for file_type in ("doc", "txt", "md"):
with self.subTest(file_type=file_type):
parser = StdMarkitdownParser(file_type=file_type)
result = SimpleNamespace(text_content="parsed")
with (
patch(
"docreader.parser.markitdown_parser.fill_vertical_merged_cells_docx"
) as preprocess,
patch.object(parser, "_convert_markitdown", return_value=result),
):
document = parser.parse_into_text(b"payload")
self.assertEqual(document.content, "parsed")
preprocess.assert_not_called()
def test_uppercase_docx_type_runs_docx_preprocessor(self):
parser = StdMarkitdownParser(file_type=".DOCX")
result = SimpleNamespace(text_content="parsed")
with (
patch(
"docreader.parser.markitdown_parser.fill_vertical_merged_cells_docx",
return_value=b"preprocessed",
) as preprocess,
patch.object(parser, "_convert_markitdown", return_value=result) as convert,
):
document = parser.parse_into_text(b"payload")
self.assertEqual(document.content, "parsed")
preprocess.assert_called_once_with(b"payload")
convert.assert_called_once_with(b"preprocessed", ".DOCX", keep_data_uris=True)
class Issue2634ParserRegressionTest(unittest.TestCase):
def test_markitdown_output_repeats_merged_value_for_every_data_row(self):
document = StdMarkitdownParser(
file_name=FIXTURE.name, file_type="docx"
).parse_into_text(FIXTURE.read_bytes())
data_lines = {
project_code: next(
line for line in document.content.splitlines() if project_code in line
)
for project_code in PROJECT_CODES
}
for line in data_lines.values():
self.assertIn(METHOD_PREFIX, line)
self.assertEqual(document.content.count(METHOD_PREFIX), len(PROJECT_CODES))
self.assertIn("| 相同值 | 相同值 | 独立值 |", document.content)
def test_full_docx_entry_keeps_context_on_all_four_rows(self):
document = Docx2Parser(
file_name=FIXTURE.name, file_type="docx"
).parse_into_text(FIXTURE.read_bytes())
for project_code in PROJECT_CODES:
data_line = next(
line for line in document.content.splitlines() if project_code in line
)
self.assertIn(METHOD_PREFIX, data_line)
self.assertEqual(document.content.count(METHOD_PREFIX), len(PROJECT_CODES))
if __name__ == "__main__":
unittest.main()
+216
View File
@@ -0,0 +1,216 @@
import importlib.util
import io
import sys
import types
import unittest
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest.mock import patch
from docx import Document as WordDocument
@patch.dict(sys.modules)
def _load_docx_parser():
"""Load docx_parser without triggering the heavy package __init__.
``docreader/parser/__init__.py`` imports doc_parser -> textract, a heavy
dependency unrelated to DOCX parsing. Registering the packages as bare
namespaces lets us import only the modules docx_parser actually needs.
Restore the module registry afterwards: later integration tests need the
real parser package, including its public Parser export.
"""
root = Path(__file__).resolve().parents[2]
docreader_pkg = types.ModuleType("docreader")
docreader_pkg.__path__ = [str(root / "docreader")]
sys.modules.setdefault("docreader", docreader_pkg)
parser_pkg = types.ModuleType("docreader.parser")
parser_pkg.__path__ = [str(root / "docreader" / "parser")]
sys.modules["docreader.parser"] = parser_pkg
spec = importlib.util.spec_from_file_location(
"docreader.parser.docx_parser", root / "docreader" / "parser" / "docx_parser.py"
)
module = importlib.util.module_from_spec(spec)
sys.modules["docreader.parser.docx_parser"] = module
spec.loader.exec_module(module)
return module
docx_parser = _load_docx_parser()
DocxParser = docx_parser.DocxParser
table_to_gfm_markdown = docx_parser.table_to_gfm_markdown
def _parse(content):
"""Parse a DOCX through the real Docx processor.
The production path uses a ProcessPoolExecutor backed by a multiprocessing
Manager. Some CI sandboxes forbid POSIX semaphores, so run the same page
task pool on threads and swap the manager for a plain list - parse
behavior is identical, only the execution backend changes.
"""
class _FakeManager:
def __enter__(self):
self._items = []
return self
def __exit__(self, *exc):
return False
def list(self):
return self._items
with patch.object(docx_parser, "Manager", _FakeManager), patch.object(
docx_parser, "ProcessPoolExecutor", ThreadPoolExecutor
):
return DocxParser(max_pages=100).parse_into_text(content)
def _docx_bytes(build):
doc = WordDocument()
build(doc)
buf = io.BytesIO()
doc.save(buf)
return buf.getvalue()
class DocxTableContentTest(unittest.TestCase):
"""Regression test: DOCX tables must be kept in the parsed text.
Docx.__call__ used to return tables separately from the text lines, and
parse_into_text dropped them, silently losing all table content.
"""
def _docx_with_table(self, cells):
def build(doc):
doc.add_paragraph("Introduction paragraph")
table = doc.add_table(rows=len(cells), cols=len(cells[0]))
for r, row in enumerate(cells):
for c, value in enumerate(row):
table.cell(r, c).text = value
return _docx_bytes(build)
def test_table_content_is_kept_in_parsed_text(self):
content = self._docx_with_table(
[["City", "Population"], ["Beijing", "21.5M"]]
)
document = _parse(content)
self.assertIn("Introduction paragraph", document.content)
for cell in ("City", "Population", "Beijing", "21.5M"):
self.assertIn(cell, document.content)
self.assertIn("| City | Population |", document.content)
self.assertIn("| --- | --- |", document.content)
def test_table_only_document_is_not_empty(self):
def build(doc):
table = doc.add_table(rows=2, cols=1)
table.cell(0, 0).text = "Header"
table.cell(1, 0).text = "Value"
document = _parse(_docx_bytes(build))
self.assertIn("Header", document.content)
self.assertIn("Value", document.content)
def test_pipe_in_cell_does_not_break_table(self):
def build(doc):
table = doc.add_table(rows=2, cols=1)
table.cell(0, 0).text = "A|B"
table.cell(1, 0).text = "C"
document = _parse(_docx_bytes(build))
self.assertIn(r"A\|B", document.content)
def test_empty_adjacent_cells_keep_columns(self):
def build(doc):
table = doc.add_table(rows=2, cols=3)
table.cell(0, 0).text = "A"
table.cell(0, 1).text = "B"
table.cell(0, 2).text = "C"
table.cell(1, 0).text = "1"
table.cell(1, 1).text = ""
table.cell(1, 2).text = ""
document = _parse(_docx_bytes(build))
self.assertIn("| A | B | C |", document.content)
self.assertIn("| 1 | | |", document.content)
def test_equal_adjacent_cells_are_not_collapsed(self):
"""Adjacent independent cells with the same text must stay separate.
Regression for the #2634 control row: ``相同值 | 相同值 | 独立值``.
"""
def build(doc):
table = doc.add_table(rows=2, cols=3)
table.cell(0, 0).text = "相同值"
table.cell(0, 1).text = "相同值"
table.cell(0, 2).text = "独立值"
table.cell(1, 0).text = "x"
table.cell(1, 1).text = "y"
table.cell(1, 2).text = "z"
document = _parse(_docx_bytes(build))
self.assertIn("| 相同值 | 相同值 | 独立值 |", document.content)
self.assertIn("| x | y | z |", document.content)
def test_horizontal_merge_keeps_grid_width(self):
def build(doc):
table = doc.add_table(rows=2, cols=3)
table.cell(0, 0).merge(table.cell(0, 1)).text = "merged"
table.cell(0, 2).text = "right"
table.cell(1, 0).text = "a"
table.cell(1, 1).text = "b"
table.cell(1, 2).text = "c"
document = _parse(_docx_bytes(build))
self.assertIn("| merged | merged | right |", document.content)
self.assertIn("| a | b | c |", document.content)
def test_table_stays_between_paragraphs(self):
def build(doc):
doc.add_paragraph("before table")
table = doc.add_table(rows=2, cols=1)
table.cell(0, 0).text = "H"
table.cell(1, 0).text = "V"
doc.add_paragraph("after table")
document = _parse(_docx_bytes(build))
before = document.content.index("before table")
header = document.content.index("| H |")
after = document.content.index("after table")
self.assertLess(before, header)
self.assertLess(header, after)
def test_html_like_cell_text_is_literal(self):
def build(doc):
table = doc.add_table(rows=1, cols=2)
table.cell(0, 0).text = "a < b"
table.cell(0, 1).text = "</td><td>injected"
document = _parse(_docx_bytes(build))
self.assertIn("| a < b | </td><td>injected |", document.content)
def test_table_to_gfm_markdown_helper(self):
doc = WordDocument()
table = doc.add_table(rows=2, cols=2)
table.cell(0, 0).text = "A"
table.cell(0, 1).text = "B"
table.cell(1, 0).text = "C"
table.cell(1, 1).text = "D"
self.assertEqual(
table_to_gfm_markdown(table),
"| A | B |\n| --- | --- |\n| C | D |",
)
def test_table_to_gfm_markdown_skips_empty(self):
class _Empty:
rows = []
self.assertEqual(table_to_gfm_markdown(_Empty()), "")
if __name__ == "__main__":
unittest.main()
+60
View File
@@ -0,0 +1,60 @@
import base64
import binascii
import re
import unittest
from docreader.utils.endecode import encode_image
# One valid PNG signature, the shortest payload that proves a decode happened.
PNG_SIGNATURE = bytes.fromhex("89504e470d0a1a0a")
VALID_B64 = base64.b64encode(PNG_SIGNATURE).decode()
class TestEncodeImage(unittest.TestCase):
def test_valid_base64_round_trips(self):
self.assertEqual(encode_image(VALID_B64), PNG_SIGNATURE)
def test_ignore_swallows_bad_padding(self):
"""A truncated payload raises binascii.Error, which 'ignore' absorbs."""
self.assertEqual(encode_image(VALID_B64[:-3], errors="ignore"), b"")
def test_ignore_swallows_non_ascii(self):
"""Non-ASCII input is a decoding error too, so 'ignore' must absorb it.
base64.b64decode rejects a non-ASCII str with a plain ValueError rather
than binascii.Error, so catching only binascii.Error lets it escape a
call that asked not to raise.
"""
self.assertEqual(encode_image(VALID_B64 + ' "图片"', errors="ignore"), b"")
def test_strict_still_raises_on_non_ascii(self):
with self.assertRaises(ValueError):
encode_image(VALID_B64 + ' "图片"')
def test_strict_still_raises_on_bad_padding(self):
with self.assertRaises(binascii.Error):
encode_image(VALID_B64[:-3])
class TestMarkdownBase64Reachability(unittest.TestCase):
"""The payload group of the markdown data-URI pattern is not ASCII-only.
Pinned here rather than in the parser tests because importing
docreader.parser pulls in the whole parser dependency set; the pattern
itself is what decides whether encode_image can ever see non-ASCII.
"""
# docreader/parser/markdown_parser.py
B64_PATTERN = re.compile(r"!\[(.*?)\]\(data:image/([^;]+);base64,([^\)]+)\)")
def test_markdown_title_lands_in_the_payload_group(self):
markdown = '![x](data:image/png;base64,%s "图片")' % VALID_B64
match = self.B64_PATTERN.search(markdown)
self.assertIsNotNone(match)
self.assertIn("图片", match.group(3))
# What the parser then hands to encode_image(errors="ignore").
self.assertEqual(encode_image(match.group(3), errors="ignore"), b"")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,87 @@
import base64
from html import escape
from io import BytesIO
import unittest
from unittest.mock import patch
from ebooklib import epub
from docreader.parser.epub_parser import EPUBParser
_LOCAL_PNG = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a"
"c1kAAAAASUVORK5CYII="
)
def _epub_with_external_image(src: str) -> bytes:
book = epub.EpubBook()
book.set_identifier("external-image-collision")
book.set_title("External and local images")
book.set_language("en")
chapter = epub.EpubHtml(title="Images", file_name="text/chapter.xhtml", lang="en")
chapter.properties.append("remote-resources")
chapter.content = (
"<html><body><h1>Images</h1><p>Different image sources.</p>"
f'<img alt="external" src="{escape(src, quote=True)}"/>'
'<img alt="local" src="../images/pic.png"/>'
"</body></html>"
)
book.add_item(chapter)
book.add_item(
epub.EpubItem(
uid="local-image",
file_name="images/pic.png",
media_type="image/png",
content=_LOCAL_PNG,
)
)
book.spine = [chapter]
book.toc = [chapter]
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
output = BytesIO()
epub.write_epub(output, book)
return output.getvalue()
class EPUBExternalImageTest(unittest.TestCase):
def assert_external_images_preserved(self, *, fallback: bool):
sources = (
"https://example.com/pic.png",
"HTTP://example.com/pic.png?size=large#image",
"//example.com/pic.png",
"https://example.com/images/pic.png",
"https://[malformed/pic.png",
"data:image/png;base64," + base64.b64encode(_LOCAL_PNG).decode(),
)
for src in sources:
with self.subTest(src=src, fallback=fallback):
parser = EPUBParser(file_name="images.epub", file_type="epub")
content = _epub_with_external_image(src)
if fallback:
with patch(
"docreader.parser.epub_parser.epub.read_epub",
side_effect=ValueError("exercise ZIP fallback"),
):
document = parser.parse(content)
else:
with patch.object(parser, "_parse_epub_fallback") as unexpected:
document = parser.parse(content)
unexpected.assert_not_called()
self.assertIn(f"![external]({src})", document.content)
self.assertEqual(len(document.images), 1)
local_ref, encoded = next(iter(document.images.items()))
self.assertEqual(base64.b64decode(encoded), _LOCAL_PNG)
self.assertIn(f"![local]({local_ref})", document.content)
def test_external_images_are_not_replaced_by_local_basename(self):
self.assert_external_images_preserved(fallback=False)
def test_zip_fallback_keeps_external_images_distinct(self):
self.assert_external_images_preserved(fallback=True)
if __name__ == "__main__":
unittest.main()
+457
View File
@@ -0,0 +1,457 @@
import base64
from html import escape
from io import BytesIO
import os
import tempfile
import unittest
from unittest.mock import patch
from urllib.parse import quote
import zipfile
from ebooklib import epub
from PIL import Image
from docreader.parser.epub_parser import EPUBParser
from docreader.parser.registry import registry
def _minimal_epub_bytes() -> bytes:
book = epub.EpubBook()
book.set_identifier("test-epub")
book.set_title("Tiny EPUB")
book.set_language("en")
book.add_author("Academy")
chapter = epub.EpubHtml(
title="Chapter One", file_name="text/chapter_01.xhtml", lang="en"
)
chapter.content = (
"<html><body><h1>Chapter One</h1>"
"<p>Hello EPUB world.</p>"
'<p><a href="chapter_02.xhtml#sec2">Chapter 2</a> '
'<a href="#footnote1">note</a> '
'<a href="https://example.com">the site</a></p>'
'<img alt="cover" src="../images/pic.png">'
"</body></html>"
)
book.add_item(chapter)
book.add_item(
epub.EpubItem(
uid="pic",
file_name="images/pic.png",
media_type="image/png",
content=b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR",
)
)
book.toc = (epub.Link("text/chapter_01.xhtml", "Chapter One", "chapter-one"),)
book.spine = ["nav", chapter]
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
with tempfile.NamedTemporaryFile(suffix=".epub", delete=False) as handle:
path = handle.name
try:
epub.write_epub(path, book)
with open(path, "rb") as handle:
return handle.read()
finally:
if os.path.exists(path):
os.unlink(path)
def _epub_with_colliding_image_names(
image_src: str, *, root_image_first: bool = False
) -> tuple[bytes, dict[str, bytes]]:
book = epub.EpubBook()
book.set_identifier("colliding-images")
book.set_title("Images in separate directories")
book.set_language("en")
image_data = {}
chapters = []
directories = (
("root", "first", "second")
if root_image_first
else ("first", "second", "root")
)
for directory in directories:
index = ("first", "second", "root").index(directory)
image = BytesIO()
Image.new("RGB", (1, 1), (index * 100, 0, 0)).save(image, format="PNG")
image_data[directory] = image.getvalue()
book.add_item(
epub.EpubItem(
uid=f"{directory}-image",
file_name="pic.png" if directory == "root" else f"{directory}/pic.png",
media_type="image/png",
content=image_data[directory],
)
)
chapter_path = (
"root.xhtml" if directory == "root" else f"{directory}/chapter.xhtml"
)
chapter = epub.EpubHtml(
title=directory, file_name=chapter_path, lang="en"
)
src = (
"pic.png" if directory == "root" else image_src.format(directory=directory)
)
chapter.content = (
f'<html><body><h1>{directory}</h1>'
f'<img alt="{directory}" src="{src}">'
"</body></html>"
)
book.add_item(chapter)
chapters.append(chapter)
# The root-level pic.png also collides with chapter-relative references.
book.toc = tuple(chapters)
book.spine = chapters
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
output = BytesIO()
epub.write_epub(output, book)
return output.getvalue(), image_data
def _epub_with_literal_path_characters(
chapter_path: str, image_src: str, image_path: str, decoy_path: str
) -> tuple[bytes, bytes]:
"""URI-encode manifest hrefs while preserving literal ZIP entry names."""
container = (
'<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container"'
' version="1.0"><rootfiles><rootfile full-path="EPUB/package.opf"'
' media-type="application/oebps-package+xml"/></rootfiles></container>'
)
package = (
'<package xmlns="http://www.idpf.org/2007/opf" version="3.0"'
' unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/">'
'<dc:identifier id="id">literal-paths</dc:identifier>'
'<dc:title>Literal paths</dc:title><dc:language>en</dc:language>'
'<meta property="dcterms:modified">2026-01-01T00:00:00Z</meta>'
'</metadata><manifest>'
f'<item id="chapter" href="{quote(chapter_path)}"'
' media-type="application/xhtml+xml"/>'
f'<item id="expected" href="{quote(image_path)}" media-type="image/png"/>'
f'<item id="decoy" href="{quote(decoy_path)}" media-type="image/png"/>'
'<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml"'
' properties="nav"/></manifest><spine><itemref idref="chapter"/>'
'</spine></package>'
)
chapter = (
'<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter</title>'
'</head><body><h1>Chapter</h1>'
f'<img alt="expected" src="{escape(image_src, quote=True)}"/>'
'</body></html>'
)
nav = (
'<html xmlns="http://www.w3.org/1999/xhtml"'
' xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title>'
'</head><body><nav epub:type="toc"><ol><li>'
f'<a href="{quote(chapter_path)}">Chapter</a>'
'</li></ol></nav></body></html>'
)
expected = BytesIO()
decoy = BytesIO()
Image.new("RGB", (1, 1), "red").save(expected, format="PNG")
Image.new("RGB", (1, 1), "blue").save(decoy, format="PNG")
output = BytesIO()
with zipfile.ZipFile(output, "w") as archive:
archive.writestr("mimetype", "application/epub+zip")
archive.writestr("META-INF/container.xml", container)
archive.writestr("EPUB/package.opf", package)
archive.writestr(f"EPUB/{chapter_path}", chapter)
archive.writestr(f"EPUB/{image_path}", expected.getvalue())
archive.writestr(f"EPUB/{decoy_path}", decoy.getvalue())
archive.writestr("EPUB/nav.xhtml", nav)
return output.getvalue(), expected.getvalue()
class EPUBParserTest(unittest.TestCase):
def assert_literal_path_image_bytes(self, *, use_fallback: bool):
cases = (
("Text#1/chapter.xhtml", "../images/pic.png",
"images/pic.png", "Text#1/cover.png"),
("Text?1/chapter.xhtml", "../images/pic.png",
"images/pic.png", "Text?1/cover.png"),
("Text%231/chapter.xhtml", "pic.png",
"Text%231/pic.png", "Text#1/pic.png"),
("Text/chapter.xhtml", "../images/pic%231.png?version=1#image",
"images/pic#1.png", "images/pic#2.png"),
("Text/chapter.xhtml", "../images/pic%3F1.png?version=1#image",
"images/pic?1.png", "images/pic?2.png"),
("Text/chapter.xhtml", "../images/pic%25231.png",
"images/pic%231.png", "images/pic#1.png"),
("Text/chapter.xhtml", "../images/pic%231.png",
"images/pic#1.png", "images/pic%231.png"),
# Verbatim percent-looking names must beat decoded basename aliases.
("chapter.xhtml", "images/my%20pic.png",
"images/my%20pic.png", "my pic.png"),
("Text/chapter.xhtml", "../images/my%20pic.png?version=1#image",
"images/my%20pic.png", "my pic.png"),
# A literal chapter-relative path also beats a decoded root path.
("Text/chapter.xhtml", "images/my%20pic.png",
"Text/images/my%20pic.png", "images/my pic.png"),
# When both exact paths exist, URI decoding still takes precedence.
("Text/chapter.xhtml", "../images/my%20pic.png",
"images/my pic.png", "images/my%20pic.png"),
# Normalize encoded separators before joining to the chapter path.
("Text/chapter.xhtml", "%5Cimages/pic.png",
"images/pic.png", "Text/images/pic.png"),
)
for chapter_path, image_src, image_path, decoy_path in cases:
with self.subTest(chapter_path=chapter_path, image_src=image_src):
content, expected = _epub_with_literal_path_characters(
chapter_path, image_src, image_path, decoy_path
)
parser = EPUBParser(file_name="literal-paths.epub", file_type="epub")
if use_fallback:
with patch(
"docreader.parser.epub_parser.epub.read_epub",
side_effect=ValueError("exercise ZIP fallback"),
):
document = parser.parse(content)
else:
with patch.object(parser, "_parse_epub_fallback") as fallback:
document = parser.parse(content)
fallback.assert_not_called()
self.assertEqual(len(document.images), 2)
image_ref = next(
ref for ref, encoded in document.images.items()
if base64.b64decode(encoded) == expected
)
self.assertIn(f"![expected]({image_ref})", document.content)
def test_literal_path_characters_are_preserved(self):
self.assert_literal_path_image_bytes(use_fallback=False)
def test_zip_fallback_preserves_literal_path_characters(self):
self.assert_literal_path_image_bytes(use_fallback=True)
def assert_chapter_image_bytes(self, document, image_data):
self.assertEqual(len(document.images), 3)
for directory, expected_data in image_data.items():
image_ref = next(
ref
for ref, encoded in document.images.items()
if base64.b64decode(encoded) == expected_data
)
self.assertIn(f"![{directory}]({image_ref})", document.content)
def test_chapter_relative_images_win_over_colliding_aliases(self):
for image_src in (
"pic.png",
"../{directory}/pic.png",
"./pic%2Epng?version=1#image",
):
with self.subTest(image_src=image_src):
content, image_data = _epub_with_colliding_image_names(image_src)
parser = EPUBParser(file_name="colliding.epub", file_type="epub")
with patch.object(parser, "_parse_epub_fallback") as fallback:
document = parser.parse(content)
fallback.assert_not_called()
self.assert_chapter_image_bytes(document, image_data)
def test_zip_fallback_resolves_colliding_chapter_relative_images(self):
for root_image_first in (False, True):
with self.subTest(root_image_first=root_image_first):
content, image_data = _epub_with_colliding_image_names(
"pic.png", root_image_first=root_image_first
)
with patch(
"docreader.parser.epub_parser.epub.read_epub",
side_effect=ValueError("exercise ZIP fallback"),
):
document = EPUBParser(
file_name="colliding.epub", file_type="epub"
).parse(content)
self.assert_chapter_image_bytes(document, image_data)
def test_root_image_alias_is_not_overwritten_by_nested_image_basenames(self):
content, image_data = _epub_with_colliding_image_names(
"pic.png", root_image_first=True
)
parser = EPUBParser(file_name="colliding.epub", file_type="epub")
with patch.object(parser, "_parse_epub_fallback") as fallback:
document = parser.parse(content)
fallback.assert_not_called()
self.assert_chapter_image_bytes(document, image_data)
def test_parse_minimal_epub(self):
document = EPUBParser(
file_name="tiny.epub", file_type="epub"
).parse_into_text(_minimal_epub_bytes())
self.assertIn("Hello EPUB world", document.content)
self.assertEqual(document.metadata["source_format"], "epub")
self.assertEqual(len(document.images), 1)
image_ref = next(iter(document.images))
self.assertTrue(image_ref.startswith("images/"))
self.assertIn(image_ref, document.content)
self.assertNotIn("../images/pic.png", document.content)
def test_internal_links_are_unwrapped_but_external_links_remain(self):
document = EPUBParser(
file_name="tiny.epub", file_type="epub"
).parse_into_text(_minimal_epub_bytes())
self.assertIn("Chapter 2", document.content)
self.assertIn("note", document.content)
self.assertNotIn("chapter_02.xhtml#sec2", document.content)
self.assertNotIn("#footnote1", document.content)
self.assertIn("[the site](https://example.com)", document.content)
def test_parse_without_images(self):
document = EPUBParser(
file_name="tiny.epub", file_type="epub", extract_images=False
).parse_into_text(_minimal_epub_bytes())
self.assertEqual(document.images, {})
def test_registry_resolves_epub(self):
self.assertIs(registry.get_parser_class("", "epub"), EPUBParser)
def test_chapters_follow_the_spine_not_the_manifest(self):
document = EPUBParser(
file_name="ordered.epub", file_type="epub"
).parse_into_text(
_ordered_epub_bytes(
manifest=["three", "title", "one", "two"],
spine=["title", "one", "two", "three"],
svg_cover_in_spine=True,
)
)
positions = [
document.content.index(f"Body of {name}.")
for name in ("title", "one", "two", "three")
]
self.assertEqual(positions, sorted(positions))
# An SVG in the spine is not a document and stays out, as before.
self.assertNotIn("COVER ART", document.content)
def test_documents_outside_the_spine_follow_it(self):
document = EPUBParser(
file_name="ordered.epub", file_type="epub"
).parse_into_text(
_ordered_epub_bytes(
manifest=["appendix", "two", "one"],
spine=["one", "two"],
)
)
positions = [
document.content.index(f"Body of {name}.")
for name in ("one", "two", "appendix")
]
self.assertEqual(positions, sorted(positions))
def test_a_document_listed_twice_in_the_spine_is_read_once(self):
document = EPUBParser(
file_name="ordered.epub", file_type="epub"
).parse_into_text(
_ordered_epub_bytes(manifest=["one", "two"], spine=["one", "two", "one"])
)
self.assertEqual(document.content.count("Body of one."), 1)
def test_chapter_markdown_keeps_block_structure(self):
content = _epub_with_chapter_body(
"<p>It was night.</p><hr/><p>Morning came.</p>"
"<blockquote><p>A quoted line.</p></blockquote><p>After the quote.</p>"
"<ul><li>parent<ul><li>child</li></ul></li></ul>"
"<pre>def total(items):\n\n return sum(items)\n</pre>"
"<table><tr><th>Name</th><th>Qty</th></tr>"
"<tr><td>Apple</td><td>3</td></tr></table>"
"<p>After the table.</p>"
)
for use_fallback in (False, True):
with self.subTest(use_fallback=use_fallback):
parser = EPUBParser(file_name="structured.epub", file_type="epub")
if use_fallback:
with patch(
"docreader.parser.epub_parser.epub.read_epub",
side_effect=ValueError("exercise ZIP fallback"),
):
document = parser.parse(content)
else:
with patch.object(parser, "_parse_epub_fallback") as fallback:
document = parser.parse(content)
fallback.assert_not_called()
# Directly above "---", a paragraph becomes a setext heading.
self.assertIn("It was night.\n\n---\n\nMorning came.", document.content)
# Directly below a quote, a paragraph joins the quote.
self.assertIn("> A quoted line.\n\nAfter the quote.", document.content)
self.assertIn("* parent\n + child", document.content)
self.assertIn(
"```\ndef total(items):\n\n return sum(items)\n```",
document.content,
)
# Directly below a table, GFM reads a line as another row.
self.assertIn("| Apple | 3 |\n\nAfter the table.", document.content)
def _epub_with_chapter_body(body: str) -> bytes:
"""Write an EPUB with a single chapter whose body is ``body``."""
book = epub.EpubBook()
book.set_identifier("structured-epub")
book.set_title("Structured EPUB")
book.set_language("en")
chapter = epub.EpubHtml(title="Chapter", file_name="text/chapter.xhtml", lang="en")
chapter.content = f"<html><body><h1>Chapter</h1>{body}</body></html>"
book.add_item(chapter)
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
book.spine = ["nav", chapter]
output = BytesIO()
epub.write_epub(output, book)
return output.getvalue()
def _ordered_epub_bytes(
manifest: list[str], spine: list[str], svg_cover_in_spine: bool = False
) -> bytes:
"""Write an EPUB whose manifest lists the documents in ``manifest`` order
and whose spine reads them in ``spine`` order."""
book = epub.EpubBook()
book.set_identifier("ordered-epub")
book.set_title("Ordered EPUB")
book.set_language("en")
chapters = {}
for name in manifest:
chapter = epub.EpubHtml(title=name, file_name=f"text/{name}.xhtml", lang="en")
chapter.content = f"<html><body><p>Body of {name}.</p></body></html>"
book.add_item(chapter)
chapters[name] = chapter
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
book.spine = ["nav"] + [chapters[name] for name in spine]
if svg_cover_in_spine:
cover = epub.EpubItem(
uid="cover-svg",
file_name="images/cover.svg",
media_type="image/svg+xml",
content=(
b'<svg xmlns="http://www.w3.org/2000/svg">'
b"<text>COVER ART</text></svg>"
),
)
book.add_item(cover)
book.spine.insert(1, cover)
with tempfile.NamedTemporaryFile(suffix=".epub", delete=False) as handle:
path = handle.name
try:
epub.write_epub(path, book)
with open(path, "rb") as handle:
return handle.read()
finally:
if os.path.exists(path):
os.unlink(path)
if __name__ == "__main__":
unittest.main()
+645
View File
@@ -0,0 +1,645 @@
import io
import os
import shutil
import subprocess
import tempfile
import unittest
import zipfile
from unittest.mock import patch
import openpyxl
import pandas as pd
from openpyxl.chart import BarChart, Reference
from docreader.parser.excel_convert import detect_excel_format, engine_for_format
from docreader.parser.excel_parser import ExcelParser
from docreader.parser.markitdown_parser import StdMarkitdownParser
from docreader.parser.xlsx_merge import fill_merged_cells_xlsx
from docreader.parser.xlsx_repair import repair_xlsx_bytes, strip_unreadable_ranges_xlsx
def _xlsx_with_phantom_shared_strings() -> bytes:
"""Workbook with inline strings but a dangling sharedStrings manifest entry."""
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "hello"
ws["B1"] = 42
bio = io.BytesIO()
wb.save(bio)
with tempfile.TemporaryDirectory() as tmpdir:
with zipfile.ZipFile(io.BytesIO(bio.getvalue()), "r") as zin:
zin.extractall(tmpdir)
ct_path = f"{tmpdir}/[Content_Types].xml"
with open(ct_path, encoding="utf-8") as f:
ct = f.read()
override = (
'<Override PartName="/xl/sharedStrings.xml" '
'ContentType="application/vnd.openxmlformats-officedocument.'
'spreadsheetml.sharedStrings+xml"/>'
)
with open(ct_path, "w", encoding="utf-8") as f:
f.write(ct.replace("</Types>", override + "</Types>"))
out = io.BytesIO()
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zout:
for root, _, files in os.walk(tmpdir):
for name in files:
path = os.path.join(root, name)
arc = os.path.relpath(path, tmpdir)
zout.write(path, arc)
return out.getvalue()
def _xlsx_with_sheet_fragment(fragment: str) -> bytes:
"""A two-row workbook with ``fragment`` spliced into sheet1 before pageMargins,
which is where OOXML puts data validations and scenarios."""
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"], ws["B1"] = "name", "qty"
ws["A2"], ws["B2"] = "apple", 3
bio = io.BytesIO()
wb.save(bio)
out = io.BytesIO()
with zipfile.ZipFile(io.BytesIO(bio.getvalue()), "r") as zin, zipfile.ZipFile(
out, "w", zipfile.ZIP_DEFLATED
) as zout:
for info in zin.infolist():
data = zin.read(info.filename)
if info.filename == "xl/worksheets/sheet1.xml":
sheet = data.decode("utf-8")
at = sheet.index("<pageMargins")
data = (sheet[:at] + fragment + sheet[at:]).encode("utf-8")
zout.writestr(info, data)
return out.getvalue()
def _validation(sqref: str, formula: str = '"a,b"') -> str:
return (
f'<dataValidation type="list" allowBlank="1" sqref="{sqref}">'
f"<formula1>{formula}</formula1></dataValidation>"
)
class ExcelFormatDetectionTest(unittest.TestCase):
def test_detect_xlsx_and_engine(self):
wb = openpyxl.Workbook()
bio = io.BytesIO()
wb.save(bio)
content = bio.getvalue()
self.assertEqual(detect_excel_format(content), "xlsx")
self.assertEqual(engine_for_format("xlsx"), "openpyxl")
def test_detect_xls_magic(self):
content = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + b"\x00" * 512
self.assertEqual(detect_excel_format(content), "xls")
self.assertEqual(engine_for_format("xls"), "xlrd")
def test_open_legacy_xls_bytes_with_xlsx_extension(self):
if not shutil.which("soffice"):
self.skipTest("LibreOffice not available")
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "legacy"
xlsx_bio = io.BytesIO()
wb.save(xlsx_bio)
with tempfile.TemporaryDirectory() as tmpdir:
src = os.path.join(tmpdir, "sheet.xlsx")
with open(src, "wb") as handle:
handle.write(xlsx_bio.getvalue())
subprocess.run(
[
"soffice",
"--headless",
"--convert-to",
"xls",
"--outdir",
tmpdir,
src,
],
check=True,
capture_output=True,
)
xls_path = os.path.join(tmpdir, "sheet.xls")
with open(xls_path, "rb") as handle:
xls_bytes = handle.read()
document = ExcelParser(file_name="fake.xlsx", file_type="xlsx").parse_into_text(
xls_bytes
)
self.assertIn("legacy", document.content)
class XlsxUnreadableRangesTest(unittest.TestCase):
"""#3599: a range openpyxl cannot parse must not cost the whole document."""
def test_whole_column_validation_aborts_openpyxl_without_the_fix(self):
broken = _xlsx_with_sheet_fragment(
f'<dataValidations count="1">{_validation("C:C")}</dataValidations>'
)
with self.assertRaisesRegex(TypeError, "MultiCellRange"):
openpyxl.load_workbook(io.BytesIO(broken), data_only=True)
with self.assertRaisesRegex(TypeError, "MultiCellRange"):
pd.read_excel(io.BytesIO(broken), engine="openpyxl")
def test_drops_each_range_spelling_openpyxl_rejects(self):
# Measured on openpyxl 3.1.5; every one of these raised the reported
# TypeError before the fix.
for sqref in ("C:C", "1:1", "A1:B2,C3", "#REF!", "A1:XFD1048577"):
with self.subTest(sqref=sqref):
broken = _xlsx_with_sheet_fragment(
f'<dataValidations count="1">{_validation(sqref)}</dataValidations>'
)
fixed = strip_unreadable_ranges_xlsx(broken)
self.assertIsNotNone(fixed)
df = pd.read_excel(io.BytesIO(fixed), header=None, engine="openpyxl")
self.assertEqual(df.values.tolist(), [["name", "qty"], ["apple", 3]])
def test_drops_a_scenario_list_with_an_unreadable_range(self):
broken = _xlsx_with_sheet_fragment(
# The range belongs to the list, not to each scenario.
'<scenarios sqref="A:A"><scenario name="s" count="1">'
'<inputCells r="A1" val="1"/></scenario></scenarios>'
)
with self.assertRaisesRegex(TypeError, "MultiCellRange"):
openpyxl.load_workbook(io.BytesIO(broken), data_only=True)
fixed = strip_unreadable_ranges_xlsx(broken)
self.assertIsNotNone(fixed)
openpyxl.load_workbook(io.BytesIO(fixed), data_only=True)
def test_keeps_a_readable_validation_next_to_an_unreadable_one(self):
broken = _xlsx_with_sheet_fragment(
'<dataValidations count="2">'
f'{_validation("C:C")}{_validation("D2:D10", chr(34) + "keep" + chr(34))}'
"</dataValidations>"
)
fixed = strip_unreadable_ranges_xlsx(broken)
self.assertIsNotNone(fixed)
ws = openpyxl.load_workbook(io.BytesIO(fixed)).active
self.assertEqual(
[str(dv.sqref) for dv in ws.data_validations.dataValidation], ["D2:D10"]
)
def test_leaves_a_readable_workbook_untouched(self):
fine = _xlsx_with_sheet_fragment(
f'<dataValidations count="1">{_validation("C2:C10")}</dataValidations>'
)
self.assertIsNone(strip_unreadable_ranges_xlsx(fine))
self.assertIsNone(strip_unreadable_ranges_xlsx(b"not a zip"))
def test_excel_parser_reads_a_workbook_with_a_whole_column_validation(self):
broken = _xlsx_with_sheet_fragment(
f'<dataValidations count="1">{_validation("C:C")}</dataValidations>'
)
document = ExcelParser(file_name="feishu.xlsx", file_type="xlsx").parse_into_text(
broken
)
self.assertIn("apple", document.content)
def test_markitdown_parser_reads_a_workbook_with_a_whole_column_validation(self):
broken = _xlsx_with_sheet_fragment(
f'<dataValidations count="1">{_validation("C:C")}</dataValidations>'
)
document = StdMarkitdownParser(
file_name="feishu.xlsx", file_type="xlsx"
).parse_into_text(broken)
self.assertIn("apple", document.content)
class XlsxRepairTest(unittest.TestCase):
def test_repair_removes_phantom_shared_strings_reference(self):
broken = _xlsx_with_phantom_shared_strings()
with self.assertRaises(KeyError):
pd.read_excel(io.BytesIO(broken))
repaired = repair_xlsx_bytes(broken)
self.assertIsNotNone(repaired)
df = pd.read_excel(io.BytesIO(repaired), header=None)
self.assertEqual(df.values.tolist(), [["hello", 42]])
def test_repair_skips_when_shared_string_cells_need_table(self):
import xlsxwriter
bio = io.BytesIO()
wb = xlsxwriter.Workbook(bio, {"in_memory": True})
ws = wb.add_worksheet()
ws.write(0, 0, "hello")
wb.close()
with tempfile.TemporaryDirectory() as tmpdir:
with zipfile.ZipFile(io.BytesIO(bio.getvalue()), "r") as zin:
zin.extractall(tmpdir)
os.remove(f"{tmpdir}/xl/sharedStrings.xml")
out = io.BytesIO()
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zout:
for root, _, files in os.walk(tmpdir):
for name in files:
path = os.path.join(root, name)
arc = os.path.relpath(path, tmpdir)
zout.write(path, arc)
broken = out.getvalue()
self.assertIsNone(repair_xlsx_bytes(broken))
class XlsxMergeFillTest(unittest.TestCase):
@staticmethod
def _workbook_with_merged_cells_and_chart() -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "title"
ws.merge_cells("A1:B1")
ws.append(["category", "value"])
ws.append(["one", 1])
ws.append(["two", 2])
chart = BarChart()
chart.add_data(
Reference(ws, min_col=2, min_row=2, max_row=4),
titles_from_data=True,
)
chart.set_categories(Reference(ws, min_col=1, min_row=3, max_row=4))
ws.add_chart(chart, "D2")
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def test_fill_merged_cells_propagates_master_value(self):
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "title"
ws.merge_cells("A1:B1")
ws["A2"] = "left"
ws["B2"] = "right"
ws.merge_cells("A2:A3")
ws["B3"] = "only-b"
bio = io.BytesIO()
wb.save(bio)
filled = fill_merged_cells_xlsx(bio.getvalue())
out_wb = openpyxl.load_workbook(io.BytesIO(filled), data_only=True)
out_ws = out_wb.active
self.assertEqual(out_ws["B1"].value, "title")
self.assertEqual(out_ws["A3"].value, "left")
self.assertEqual(out_ws["B3"].value, "only-b")
def test_fill_merged_cells_does_not_serialize_charts(self):
content = self._workbook_with_merged_cells_and_chart()
with patch(
"openpyxl.chart._chart.ChartBase._write",
side_effect=AttributeError("'Typed' object has no attribute 'to_tree'"),
):
filled = fill_merged_cells_xlsx(content)
out_wb = openpyxl.load_workbook(io.BytesIO(filled), data_only=True)
out_ws = out_wb.active
self.assertEqual(out_ws["B1"].value, "title")
self.assertEqual(out_ws["A3"].value, "one")
self.assertEqual(out_ws["B4"].value, 2)
self.assertEqual(out_ws._charts, [])
def test_excel_parser_reads_merged_workbook_with_chart(self):
document = ExcelParser().parse_into_text(
self._workbook_with_merged_cells_and_chart()
)
self.assertIn("A: title,B: title", document.content)
self.assertIn("A: one,B: 1", document.content)
self.assertIn("A: two,B: 2", document.content)
def test_chart_workbook_without_merges_passes_through_unchanged(self):
content = self._workbook_with_merged_cells_and_chart()
wb = openpyxl.load_workbook(io.BytesIO(content))
wb.active.unmerge_cells("A1:B1")
bio = io.BytesIO()
wb.save(bio)
content = bio.getvalue()
self.assertEqual(fill_merged_cells_xlsx(content), content)
def test_fill_does_not_serialize_dedicated_chart_sheets(self):
content = self._workbook_with_merged_cells_and_chart()
wb = openpyxl.load_workbook(io.BytesIO(content))
ws = wb.active
chart = BarChart()
chart.add_data(
Reference(ws, min_col=2, min_row=2, max_row=4),
titles_from_data=True,
)
chart.set_categories(Reference(ws, min_col=1, min_row=3, max_row=4))
chart_sheet = wb.create_chartsheet("Summary")
chart_sheet.add_chart(chart)
wb.active = chart_sheet
bio = io.BytesIO()
wb.save(bio)
with patch(
"openpyxl.chart._chart.ChartBase._write",
side_effect=AttributeError("'Typed' object has no attribute 'to_tree'"),
):
filled = fill_merged_cells_xlsx(bio.getvalue())
out_wb = openpyxl.load_workbook(io.BytesIO(filled), data_only=True)
self.assertEqual(out_wb.active._charts, [])
self.assertEqual(out_wb.active.title, "Sheet")
self.assertEqual(out_wb.chartsheets, [])
def test_fill_keeps_active_worksheet_after_removing_earlier_chart_sheet(self):
content = self._workbook_with_merged_cells_and_chart()
wb = openpyxl.load_workbook(io.BytesIO(content))
data_sheet = wb.active
chart = BarChart()
chart.add_data(
Reference(data_sheet, min_col=2, min_row=2, max_row=4),
titles_from_data=True,
)
chart_sheet = wb.create_chartsheet("Summary", 0)
chart_sheet.add_chart(chart)
wb.active = data_sheet
bio = io.BytesIO()
wb.save(bio)
filled = fill_merged_cells_xlsx(bio.getvalue())
out_wb = openpyxl.load_workbook(io.BytesIO(filled), data_only=True)
self.assertEqual(out_wb.active.title, "Sheet")
self.assertEqual(out_wb.chartsheets, [])
def test_parse_en_mergecell_workbook(self):
path = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"testdata",
"rag_test",
"xlsx",
"en_mergecell.xlsx",
)
if not os.path.isfile(path):
self.skipTest("en_mergecell.xlsx fixture not available")
with open(path, "rb") as handle:
document = ExcelParser().parse_into_text(handle.read())
chunks = [chunk.content.strip() for chunk in document.chunks]
self.assertEqual(len(chunks), 12)
self.assertIn("A: A1", chunks[0])
self.assertIn("A: A2", chunks[1])
self.assertIn("B: B3", chunks[2])
self.assertNotIn("Unnamed:", document.content)
self.assertIn("A: A7", chunks[6])
self.assertIn("A: A7", chunks[7])
self.assertIn("D: D10", chunks[9])
class ExcelImageFilterTest(unittest.TestCase):
"""Tests for filtering embedded image function strings (#1779)."""
def _xlsx_with_image_functions(self) -> bytes:
"""Create an XLSX where image functions are stored as text values.
WPS embeds images using =DISPIMG("ID",1) which may appear as plain
text (not a formula) in some export scenarios.
"""
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "Name"
ws["B1"] = "Photo"
ws["A2"] = "Alice"
ws["B2"] = '_xlfn.DISPIMG("ID_ABCDEF123",1)'
ws["A3"] = "Bob"
ws["B3"] = '_xlfn.DISPIMG("ID_GHIJKL456",1)'
ws["A4"] = "Charlie"
ws["B4"] = "real data"
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def test_dispimg_text_values_are_excluded(self):
"""Image function strings stored as text must not appear in output."""
document = ExcelParser().parse_into_text(self._xlsx_with_image_functions())
self.assertNotIn("DISPIMG", document.content)
self.assertNotIn("_xlfn", document.content)
# Real data must still be present
self.assertIn("Alice", document.content)
self.assertIn("Bob", document.content)
self.assertIn("Charlie", document.content)
self.assertIn("real data", document.content)
def test_dispimg_with_equals_prefix(self):
"""=_xlfn.DISPIMG(...) as text (not formula) should also be filtered."""
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "Name"
ws["B1"] = "Photo"
ws["A2"] = "Alice"
# Stored as text with = prefix (some exporters do this)
ws["B2"] = '=_xlfn.DISPIMG("ID_123",1)'
bio = io.BytesIO()
wb.save(bio)
# Note: openpyxl treats strings starting with = as formulas,
# so data_only=True in fill_merged_cells_xlsx will turn them to None.
# This test verifies the formula path also works correctly.
document = ExcelParser().parse_into_text(bio.getvalue())
self.assertNotIn("DISPIMG", document.content)
self.assertIn("Alice", document.content)
def test_image_function_variations(self):
"""Various image function patterns should all be filtered."""
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = '_xlfn.DISPIMG("ID_001",1)'
ws["A2"] = 'DISPIMG("ID_002",1)' # no prefix at all
ws["A3"] = '_xlfn.IMAGE("https://example.com/img.png")'
ws["A4"] = 'IMAGE("https://example.com/img.png",1)'
ws["A5"] = "Normal text"
bio = io.BytesIO()
wb.save(bio)
document = ExcelParser().parse_into_text(bio.getvalue())
self.assertNotIn("DISPIMG", document.content)
self.assertNotIn("IMAGE(", document.content)
self.assertIn("Normal text", document.content)
def test_real_world_wps_dispimg(self):
"""Exact pattern from issue #1779 screenshot: =DISPIMG("ID_...",1)."""
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "Product"
ws["B1"] = "Image"
ws["C1"] = "Price"
ws["A2"] = "Basic"
# This is the exact format shown in the issue screenshot
ws["B2"] = 'DISPIMG("ID_5A60F9ED501E48A38EBEE5D326E18235",1)'
ws["C2"] = "39.9"
ws["A3"] = "Pro"
ws["B3"] = 'DISPIMG("ID_AABBCCDD",1)'
ws["C3"] = "99.9"
bio = io.BytesIO()
wb.save(bio)
document = ExcelParser().parse_into_text(bio.getvalue())
self.assertNotIn("DISPIMG", document.content)
self.assertNotIn("ID_5A60F9ED", document.content)
self.assertIn("Basic", document.content)
self.assertIn("39.9", document.content)
self.assertIn("Pro", document.content)
self.assertIn("99.9", document.content)
class ExcelParserTest(unittest.TestCase):
@staticmethod
def _workbook_bytes(rows):
wb = openpyxl.Workbook()
ws = wb.active
for row in rows:
ws.append(row)
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def test_xlsx_first_row_header_mode_repeats_column_context(self):
content = self._workbook_bytes(
[
["Name", "Age", "City"],
["Alice", 30, "Shenzhen"],
["Bob", 28, "Shanghai"],
]
)
document = ExcelParser(
file_name="people.xlsx",
file_type="xlsx",
xlsx_first_row_as_header="true",
).parse_into_text(content)
chunks = [chunk.content.strip() for chunk in document.chunks]
self.assertEqual(
chunks,
[
"Name: Alice,Age: 30,City: Shenzhen",
"Name: Bob,Age: 28,City: Shanghai",
],
)
self.assertNotIn("A: Name", document.content)
def test_xlsx_keeps_first_row_as_data_by_default(self):
content = self._workbook_bytes(
[
["Name", "City"],
["Alice", "Shenzhen"],
]
)
document = ExcelParser(file_name="people.xlsx", file_type="xlsx").parse_into_text(
content
)
chunks = [chunk.content.strip() for chunk in document.chunks]
self.assertEqual(len(chunks), 2)
self.assertEqual(chunks[0], "A: Name,B: City")
self.assertEqual(chunks[1], "A: Alice,B: Shenzhen")
def test_single_row_xlsx_is_not_consumed_in_header_mode(self):
content = self._workbook_bytes([["Name", "Age", "City"]])
document = ExcelParser(
file_name="single.xlsx",
file_type="xlsx",
xlsx_first_row_as_header=True,
).parse_into_text(content)
self.assertEqual(
[chunk.content.strip() for chunk in document.chunks],
["A: Name,B: Age,C: City"],
)
def test_header_mode_generates_stable_labels_for_duplicate_and_empty_cells(self):
content = self._workbook_bytes(
[
["Name", "Name", None],
["Alice", "Alias", "Shenzhen"],
]
)
document = ExcelParser(
file_name="people.xlsx",
file_type="xlsx",
xlsx_first_row_as_header="yes",
).parse_into_text(content)
self.assertEqual(
[chunk.content.strip() for chunk in document.chunks],
["Name: Alice,Name_2: Alias,C: Shenzhen"],
)
def test_xlsx_explicit_false_override_keeps_first_row_as_data(self):
content = self._workbook_bytes(
[
["Name", "Age"],
["Alice", 30],
]
)
document = ExcelParser(
file_name="people.xlsx",
file_type="xlsx",
xlsx_first_row_as_header="false",
).parse_into_text(content)
chunks = [chunk.content.strip() for chunk in document.chunks]
self.assertEqual(chunks[0], "A: Name,B: Age")
self.assertEqual(chunks[1], "A: Alice,B: 30")
def test_parse_phantom_shared_strings_workbook(self):
document = ExcelParser().parse_into_text(_xlsx_with_phantom_shared_strings())
self.assertIn("hello", document.content)
self.assertIn("42", document.content)
self.assertGreater(len(document.chunks), 0)
def test_parse_en_calcchain_shared_strings_case(self):
path = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"testdata",
"rag_test",
"xlsx",
"en_calcchain.xlsx",
)
if not os.path.isfile(path):
self.skipTest("en_calcchain.xlsx fixture not available")
with open(path, "rb") as f:
document = ExcelParser().parse_into_text(f.read())
self.assertGreater(len(document.content), 0)
self.assertGreater(len(document.chunks), 0)
if __name__ == "__main__":
unittest.main()
class ExcelSourceBlocksTest(unittest.TestCase):
def test_rows_carry_sheet_and_row_number(self):
import io
import openpyxl
from docreader.parser.excel_parser import ExcelParser
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "明细"
ws["B3"] = "螺栓"
ws["A5"] = "合计"
buf = io.BytesIO()
wb.save(buf)
doc = ExcelParser(file_name="a.xlsx", file_type="xlsx").parse_into_text(buf.getvalue())
rows = [(b["locator"]["sheet"], b["locator"]["row_start"]) for b in doc.source_blocks]
self.assertEqual(rows, [("明细", 3), ("明细", 5)])
first = doc.source_blocks[0]
self.assertEqual(doc.content[first["start"]:first["end"]], "B: 螺栓\n")
+212
View File
@@ -0,0 +1,212 @@
import unittest
from dataclasses import replace
from pathlib import Path
from unittest.mock import patch
import docreader.parser.html_parser as html_parser
from docreader.config import CONFIG
from docreader.parser.html_parser import (
_MIN_EXTRACTED_CHARS,
_MIN_KEEP_RATIO,
HTMLParser,
extract_main_content,
)
from docreader.parser.registry import BUILTIN_ENGINE, registry
REPO_ROOT = Path(__file__).resolve().parents[2]
MAIN_CONTENT_FIXTURES = REPO_ROOT / "docreader" / "testdata" / "html_main_content"
def _parse_bytes(
content: bytes, *, main_content: bool, file_name: str = "page.html"
) -> str:
"""Parse HTML through the upload path with the switch forced."""
with patch.object(
html_parser, "CONFIG", replace(CONFIG, html_main_content=main_content)
):
return HTMLParser(file_name=file_name, file_type="html").parse(content).content
def _parse_uploaded_html(name: str, *, main_content: bool) -> str:
"""Parse a fixture through the upload path with the switch forced."""
return _parse_bytes(
(MAIN_CONTENT_FIXTURES / name).read_bytes(),
main_content=main_content,
file_name=name,
)
class HTMLParserTest(unittest.TestCase):
def test_parse_static_html_fixture_into_markdown(self):
content = (REPO_ROOT / "docreader" / "testdata" / "test.html").read_bytes()
document = HTMLParser(file_name="test.html", file_type="html").parse(content)
self.assertIn("# 测试 HTML 文档", document.content)
self.assertIn("[测试链接](https://example.com)", document.content)
self.assertIn("| 表头1 | 表头2 |", document.content)
self.assertIn("内容4", document.content)
def test_parse_empty_html_returns_empty_document(self):
document = HTMLParser(file_name="empty.htm", file_type="htm").parse(b"")
self.assertEqual("", document.content)
def test_parse_honors_declared_windows_1252_charset(self):
html = (
'<meta charset="windows-1252">'
"<h1>R\u00e9sum\u00e9 \u201cquoted\u201d \u20ac</h1>"
).encode("windows-1252")
document = HTMLParser(file_name="legacy.html", file_type="html").parse(html)
self.assertIn("# R\u00e9sum\u00e9 \u201cquoted\u201d \u20ac", document.content)
def test_parse_honors_utf16_bom(self):
html = "<html><body><h1>UTF-16 title</h1></body></html>".encode("utf-16")
document = HTMLParser(file_name="utf16.html", file_type="html").parse(html)
self.assertIn("# UTF-16 title", document.content)
self.assertNotIn("\x00", document.content)
def test_parse_script_only_html_returns_empty_document(self):
html = (
b"<html><body><script>alert('x')</script><style>p{}</style></body></html>"
)
document = HTMLParser(file_name="script.html", file_type="html").parse(html)
self.assertEqual("", document.content)
def test_parse_preserves_relative_and_fragment_links(self):
html = b'<a href="./guide.html">Guide</a><a href="#section">Section</a>'
document = HTMLParser(file_name="links.html", file_type="html").parse(html)
self.assertIn("[Guide](./guide.html)", document.content)
self.assertIn("[Section](#section)", document.content)
def test_parse_keeps_space_held_by_whitespace_only_inline_element(self):
html = b"<p>further<strong> </strong>reference</p>"
document = HTMLParser(file_name="space.html", file_type="html").parse(html)
self.assertEqual("further reference", document.content)
def test_registry_routes_html_extensions_to_html_parser(self):
self.assertIs(registry.get_parser_class("", "html"), HTMLParser)
self.assertIs(registry.get_parser_class("", "htm"), HTMLParser)
builtin_types = registry._engines[BUILTIN_ENGINE]
self.assertIn("html", builtin_types)
self.assertIn("htm", builtin_types)
class HTMLMainContentTest(unittest.TestCase):
"""DOCREADER_HTML_MAIN_CONTENT: opt-in main-content extraction on upload."""
def test_upload_indexes_the_whole_page_by_default(self):
content = _parse_uploaded_html("article_page.html", main_content=False)
# Header nav, sidebar and footer all reach the index, as they always did.
self.assertIn("产品定价", content)
self.assertIn("订阅我们的新闻邮件", content)
self.assertIn("京ICP备00000000号-1", content)
self.assertIn("混合检索", content)
def test_enabled_extraction_drops_page_chrome_and_keeps_the_article(self):
full = _parse_uploaded_html("article_page.html", main_content=False)
content = _parse_uploaded_html("article_page.html", main_content=True)
self.assertNotIn("产品定价", content) # header nav
self.assertNotIn("订阅我们的新闻邮件", content) # sidebar
self.assertNotIn("京ICP备00000000号-1", content) # footer
# The article body survives in full, table and links included.
self.assertIn("# 深入理解 RAG 的召回策略", content)
self.assertIn("混合检索把 BM25 的稀疏信号与向量召回融合在一起", content)
self.assertIn("重排模型只对前 N 条候选打分", content)
self.assertIn("| 策略 | 优点 | 代价 |", content)
self.assertIn("两路互补,召回率最高", content)
self.assertIn("[分块器的实现细节](/blog/99)", content)
self.assertLess(len(content), len(full))
def test_enabled_extraction_preserves_body_image_references(self):
html = (MAIN_CONTENT_FIXTURES / "article_page.html").read_text(encoding="utf-8")
html = html.replace(
"</article>",
'<figure><img src="https://example.com/chart.png" alt="Recall comparison" /></figure>'
'<figure><img src="images/local-chart.png" alt="Local comparison" /></figure>'
'</article>',
)
self.assertIn("https://example.com/chart.png", html)
content = _parse_bytes(html.encode(), main_content=True)
self.assertNotIn("产品定价", content)
self.assertIn("https://example.com/chart.png", content)
self.assertIn("images/local-chart.png", content)
self.assertIn("混合检索", content)
def test_short_article_does_not_index_duplicate_body_text(self):
body = "正文说明知识库如何解析上传文件,以及如何把检索到的内容交给模型生成答案。" * 9
html = f"<html><body><article><h1>知识库解析说明</h1><p>{body}</p></article></body></html>".encode()
content = _parse_bytes(html, main_content=True)
self.assertEqual(content.count(body), 1)
def test_extractor_introduced_repetition_falls_back_but_source_repetition_does_not(self):
body = "A long paragraph about retrieval, citations and document parsing. " * 5
html = f"<article><p>{body}</p></article>".encode()
full = _parse_bytes(html, main_content=False)
repeated = body.strip() + "\n\n" + body.strip()
with patch.object(html_parser, "extract_main_content", return_value=repeated):
self.assertEqual(_parse_bytes(html, main_content=True), full)
original_repeated = f"<article><p>{body}</p><p>{body}</p></article>".encode()
content = _parse_bytes(original_repeated, main_content=True)
self.assertEqual(content.count(body.strip()), 2)
def test_falls_back_to_full_conversion_without_an_article_body(self):
for name, expected in (
("form_page.html", "忘记密码?"),
("link_list_page.html", "第六章 常见问题"),
):
with self.subTest(fixture=name):
full = _parse_uploaded_html(name, main_content=False)
content = _parse_uploaded_html(name, main_content=True)
self.assertEqual(content, full)
self.assertIn(expected, content)
def test_falls_back_when_extraction_keeps_too_little_of_a_long_page(self):
full = _parse_uploaded_html("chrome_heavy_page.html", main_content=False)
content = _parse_uploaded_html("chrome_heavy_page.html", main_content=True)
# The length floor is passed here: what keeps the full conversion is the
# ratio guard against "trafilatura kept only a fragment of a long page".
html = (MAIN_CONTENT_FIXTURES / "chrome_heavy_page.html").read_text(
encoding="utf-8"
)
extracted = extract_main_content(html)
self.assertGreaterEqual(len(extracted), _MIN_EXTRACTED_CHARS)
self.assertLess(len(extracted), len(full) * _MIN_KEEP_RATIO)
self.assertEqual(content, full)
self.assertIn("批量导入任务在遇到空文件时不再中断整个批次", content)
self.assertIn("京ICP备00000000号-1", content)
def test_short_page_is_not_reduced_to_nothing(self):
full = _parse_uploaded_html("short_notice.html", main_content=False)
content = _parse_uploaded_html("short_notice.html", main_content=True)
self.assertEqual(content, full)
self.assertIn(
"本服务将于 10 月 1 日 02:00 至 04:00 维护,期间暂停文档上传与检索。",
content,
)
def test_empty_html_stays_empty(self):
content = _parse_bytes(b"", main_content=True, file_name="empty.html")
self.assertEqual("", content)
if __name__ == "__main__":
unittest.main()
+438
View File
@@ -0,0 +1,438 @@
"""Unit tests for the page-straightening geometry in parser/image_preprocess.
Geometry tests build their own boxes and points. Engine isolation is exercised
with a mutable recognizer double, so these tests never load RapidOCR models.
The values that matter most are the ones a wrong answer would hide:
* dominant_angle must fold the 180-degree period, because a near-vertical page
lands at BOTH ends of the (-90, 90] window and a median would call it 0;
* filter_items must keep the box that sits exactly on a threshold, so a change
from <= to < is visible rather than a silent one-box difference;
* fit_quad must enclose every box it was given — a quad that cuts a line off
is the failure the padding and the supporting lines exist to prevent.
"""
from concurrent.futures import ThreadPoolExecutor
import threading
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import cv2
import numpy as np
from docreader.parser import image_preprocess
from docreader.parser.image_preprocess import (
ANG_TOL,
DEFAULT_PAD,
MIN_SCORE,
PAD,
QUAD_TOL,
SIZE_MIN,
_THRESHOLDS as THRESHOLDS,
_boundary_line,
_intersect,
_tls,
align_residual,
box_angle,
choose_rotation,
dominant_angle,
effective_thresholds,
filter_items,
fit_quad,
order_pts,
resolve_threshold,
warp,
wrap90,
)
def box(cx, cy, w, h, angle_deg=0.0):
"""One text-line box: four corners, long edge first, as RapidOCR returns them."""
t = np.radians(angle_deg)
ux, uy = np.cos(t), np.sin(t)
vx, vy = -np.sin(t), np.cos(t)
corners = [
(cx - w / 2 * ux - h / 2 * vx, cy - w / 2 * uy - h / 2 * vy),
(cx + w / 2 * ux - h / 2 * vx, cy + w / 2 * uy - h / 2 * vy),
(cx + w / 2 * ux + h / 2 * vx, cy + w / 2 * uy + h / 2 * vy),
(cx - w / 2 * ux + h / 2 * vx, cy - w / 2 * uy + h / 2 * vy),
]
return np.array(corners, "float32")
def line(cx, cy, length, angle_deg=0.0, height=8.0, score=0.9):
"""A detected line: the box plus the score detect() would have attached."""
return (box(cx, cy, length, height, angle_deg), score)
def grid(xs, ys):
"""The point set a box list turns into after the alignment transform."""
return np.array([(float(x), float(y)) for x in xs for y in ys], "float32")
class EngineIsolationTest(unittest.TestCase):
def test_concurrent_detection_cannot_enable_recognition_classification(self):
scoring_started = threading.Event()
detection_finished = threading.Event()
class MutableRecognizer:
def __init__(self, **kwargs):
pass
def __call__(self, img, *, use_cls):
self.use_cls = use_cls
if not use_cls:
scoring_started.set()
if not detection_finished.wait(timeout=5):
raise TimeoutError("concurrent detection did not finish")
# Classification would make the recognition score insensitive
# to orientation. Expose another call changing this flag.
score = 0.9 if use_cls or not self.use_cls else 0.1
return SimpleNamespace(boxes=[box(50, 50, 100, 10)], scores=[score])
img = np.zeros((10, 10, 3), "uint8")
def score_page():
engine = image_preprocess._engine()
score, count = image_preprocess.rec_score(img)
return engine, image_preprocess._engine(), score, count
def detect_page():
try:
return image_preprocess._engine(), image_preprocess.detect(img)
finally:
detection_finished.set()
with patch.object(image_preprocess, "RapidOCR", side_effect=MutableRecognizer):
with ThreadPoolExecutor(max_workers=2) as pool:
scoring = pool.submit(score_page)
try:
self.assertTrue(scoring_started.wait(timeout=5))
detecting = pool.submit(detect_page)
detection_engine, boxes = detecting.result(timeout=5)
score_engine, reused_engine, score, count = scoring.result(timeout=5)
finally:
detection_finished.set()
self.assertAlmostEqual(score, 0.9, places=6)
self.assertEqual(count, 1)
self.assertEqual(len(boxes), 1)
self.assertIs(score_engine, reused_engine, "one worker should reuse its engine")
self.assertIsNot(score_engine, detection_engine, "workers must not share mutable OCR state")
def test_engine_limits_native_threads(self):
def create():
return image_preprocess._engine()
with patch.object(image_preprocess, "RapidOCR") as factory:
with ThreadPoolExecutor(max_workers=1) as pool:
pool.submit(create).result(timeout=5)
params = factory.call_args.kwargs["params"]
self.assertEqual(params["EngineConfig.onnxruntime.intra_op_num_threads"],
image_preprocess.CONFIG.preprocess_threads)
self.assertEqual(params["EngineConfig.onnxruntime.inter_op_num_threads"], 1)
class BoxAngleTest(unittest.TestCase):
def test_long_edge_sets_the_angle(self):
angle, length = box_angle(box(50, 50, 100, 10, 30))
self.assertAlmostEqual(angle, 30.0, places=3)
self.assertAlmostEqual(length, 100.0, places=3)
def test_a_tall_box_reports_its_long_edge_not_its_first(self):
# w < h: the first edge is the short one, so the long edge decides.
angle, length = box_angle(box(50, 50, 10, 100, 0))
self.assertAlmostEqual(abs(angle), 90.0, places=3)
self.assertAlmostEqual(length, 100.0, places=3)
def test_a_vertical_box_reports_the_sign_of_its_long_edge(self):
positive, _ = box_angle(box(50, 50, 100, 10, 45))
negative, _ = box_angle(box(50, 50, 100, 10, -45))
self.assertGreater(positive, 0)
self.assertLess(negative, 0)
class Wrap90Test(unittest.TestCase):
def test_folds_onto_the_period_a_line_really_has(self):
for given, want in (
(0.0, 0.0),
(89.0, 89.0),
(-89.0, -89.0),
(90.0, -90.0),
(-90.0, -90.0),
(91.0, -89.0),
(180.0, 0.0),
(270.0, -90.0),
):
with self.subTest(angle=given):
self.assertAlmostEqual(wrap90(given), want, places=6)
class DominantAngleTest(unittest.TestCase):
def test_no_boxes_is_no_angle(self):
self.assertEqual(dominant_angle([]), 0.0)
def test_a_flat_page_reads_zero(self):
items = [line(10 * i, 50, 100, 0) for i in range(1, 6)]
self.assertAlmostEqual(dominant_angle(items), 0.0, places=1)
def test_a_tilted_page_reads_its_tilt(self):
items = [line(10 * i, 50, 100, 30) for i in range(1, 6)]
self.assertAlmostEqual(dominant_angle(items), 30.0, places=1)
def test_a_quarter_turned_page_is_not_called_flat(self):
# The load-bearing test of this file. A near-vertical page lands at BOTH
# ends of the (-90, 90] window, because the sign of the long edge's x
# component is pixel noise: the measured case split ~47% at -89 and ~37%
# at +89. Here the short boxes near 0 are numerous enough to BE the
# median of the raw angles, so an implementation that took one would
# answer 0 and "align" the page by nothing; the length-weighted mode
# answers the vertical direction the page actually has.
items = [line(10 * i, 300, 10, 0) for i in range(1, 21)]
items += [line(10 * i, 50, 100, -89) for i in range(1, 5)]
items += [line(10 * i, 200, 100, 89) for i in range(1, 5)]
angle = dominant_angle(items)
self.assertAlmostEqual(abs(angle), 90.0, delta=0.5)
def test_too_few_boxes_leave_the_angle_approximate(self):
# Below three in-tolerance boxes the circular mean is not worth
# trusting, so the answer is the window's own peak — the edge of a
# plateau that can sit up to ANG_TOL away from the true angle. Two boxes
# is not a page, so the bound is what this pins.
items = [line(10, 50, 100, 20), line(200, 50, 100, 20)]
self.assertAlmostEqual(dominant_angle(items), 20.0, delta=ANG_TOL)
class FilterItemsTest(unittest.TestCase):
def test_keeps_what_agrees_and_drops_the_rest(self):
items = [line(10 * i, 50, 100, 0) for i in range(1, 4)]
items.append(line(500, 50, 100, 45)) # a background object's edge
items.append(line(600, 50, 10, 0)) # a speck, far below the median
kept = filter_items(items, 0.0)
self.assertEqual(len(kept), 3)
def test_a_box_just_inside_the_angle_threshold_is_kept(self):
# Just inside and just outside rather than exactly on it: the angle
# comes back through float32, so "exactly on it" is not a value the
# arithmetic can be asked to produce. This still pins the threshold and
# the direction of the comparison.
items = [line(10 * i, 50, 100, 0) for i in range(1, 4)]
items.append(line(500, 50, 100, ANG_TOL - 0.01))
self.assertEqual(len(filter_items(items, 0.0)), 4)
items[-1] = line(500, 50, 100, ANG_TOL + 0.01)
self.assertEqual(len(filter_items(items, 0.0)), 3)
def test_a_box_exactly_on_the_size_threshold_is_kept(self):
items = [line(10 * i, 50, 100, 0) for i in range(1, 4)]
items.append(line(500, 50, SIZE_MIN * 100, 0))
self.assertEqual(len(filter_items(items, 0.0)), 4)
items[-1] = line(500, 50, SIZE_MIN * 100 - 0.5, 0)
self.assertEqual(len(filter_items(items, 0.0)), 3)
def test_no_boxes_filters_to_nothing(self):
self.assertEqual(filter_items([], 0.0), [])
class RotationTest(unittest.TestCase):
def test_residual_is_smallest_at_the_alignment_that_matches(self):
items = [line(10 * i, 50, 100, 30) for i in range(1, 6)]
self.assertAlmostEqual(align_residual(items, 30), 0.0, places=1)
self.assertAlmostEqual(align_residual(items, -30), 60.0, places=1)
def test_rotation_is_chosen_by_the_smaller_residual(self):
tilted_up = [line(10 * i, 50, 100, 30) for i in range(1, 6)]
tilted_down = [line(10 * i, 50, 100, -30) for i in range(1, 6)]
self.assertAlmostEqual(choose_rotation(tilted_up, 30), 30.0, places=6)
self.assertAlmostEqual(choose_rotation(tilted_down, -30), -30.0, places=6)
class LeastSquaresTest(unittest.TestCase):
def test_fits_a_line_through_points_on_one(self):
pts = np.array([(x, 2.0 * x + 1.0) for x in range(10)], "float32")
slope, intercept = _tls(pts, 0)
self.assertAlmostEqual(slope, 2.0, places=3)
self.assertAlmostEqual(intercept, 1.0, places=3)
def test_needs_two_points_across_the_axis(self):
self.assertIsNone(_tls(np.array([(5.0, 5.0)], "float32"), 0))
self.assertIsNone(_tls(np.array([(5.0, 1.0), (5.0, 9.0)], "float32"), 0))
class BoundaryLineTest(unittest.TestCase):
def test_sloped_sides_are_fitted_across_both_axes(self):
# A perspective-distorted page narrows from 100 to 60 pixels. Its side
# slopes are within the accepted range and span the full page height.
pts = np.array([(x, y) for y in range(0, 201, 5)
for x in (0.1 * y, 100 - 0.1 * y)], "float32")
for axis, points in ((0, pts), (1, pts[:, ::-1])):
for side, expected_slope, expected_intercept in (("min", 0.1, 0), ("max", -0.1, 100)):
with self.subTest(axis=axis, side=side):
slope, intercept = _boundary_line(points, axis, side)
self.assertAlmostEqual(slope, expected_slope, places=5)
self.assertAlmostEqual(intercept, expected_intercept, places=4)
residual = points[:, axis] - (slope * points[:, 1 - axis] + intercept)
if side == "min":
self.assertGreaterEqual(float(residual.min()), -1e-4)
else:
self.assertLessEqual(float(residual.max()), 1e-4)
def test_a_short_extreme_band_does_not_extrapolate_its_slope(self):
pts = np.array([(0.1 * y, y) for y in range(10)] + [(100, 100)], "float32")
slope, intercept = _boundary_line(pts, 0, "min")
self.assertEqual(slope, 0.0)
self.assertEqual(intercept, 0.0)
def test_the_min_side_encloses_every_point(self):
pts = grid((0, 50, 100), (0, 40, 80))
slope, intercept = _boundary_line(pts, 1, "min")
residual = pts[:, 1] - (slope * pts[:, 0] + intercept)
self.assertGreaterEqual(float(residual.min()), -1e-4)
self.assertAlmostEqual(float(residual.min()), 0.0, places=3)
def test_the_max_side_encloses_every_point(self):
pts = grid((0, 50, 100), (0, 40, 80))
slope, intercept = _boundary_line(pts, 1, "max")
residual = pts[:, 1] - (slope * pts[:, 0] + intercept)
self.assertLessEqual(float(residual.max()), 1e-4)
self.assertAlmostEqual(float(residual.max()), 0.0, places=3)
def test_a_flat_band_has_no_line(self):
# Every point shares the coordinate this side is measured along, so
# there is no outer edge to find.
pts = np.array([(0.0, 5.0), (10.0, 5.0), (20.0, 5.0)], "float32")
self.assertIsNone(_boundary_line(pts, 0, "min"))
class IntersectTest(unittest.TestCase):
def test_two_lines_meet_where_they_should(self):
# y = 0*x + 1 and x = 0*y + 2 meet at (2, 1).
self.assertEqual(_intersect((0.0, 1.0), (0.0, 2.0)), (2.0, 1.0))
def test_parallel_lines_do_not_meet(self):
# m1 * m2 == 1: the two lines are parallel, so the intersection is at
# infinity and there is no corner.
self.assertIsNone(_intersect((2.0, 1.0), (0.5, 3.0)))
class OrderPointsTest(unittest.TestCase):
def test_corners_come_back_in_a_known_order(self):
corners = np.array([(100.0, 80.0), (0.0, 0.0), (0.0, 80.0), (100.0, 0.0)], "float32")
ordered = order_pts(corners)
self.assertEqual([tuple(p) for p in ordered], [(0.0, 0.0), (100.0, 0.0), (100.0, 80.0), (0.0, 80.0)])
class FitQuadTest(unittest.TestCase):
def test_perspective_edges_produce_a_trapezoid_instead_of_a_bounding_box(self):
pts = np.array([(x, y) for y in range(0, 201, 5)
for x in (0.1 * y, 100 - 0.1 * y)], "float32")
quad = fit_quad(pts)
self.assertIsNotNone(quad)
np.testing.assert_allclose(quad, [[0, 0], [100, 0], [80, 200], [20, 200]], atol=1e-4)
for x, y in pts:
self.assertGreaterEqual(cv2.pointPolygonTest(quad, (float(x), float(y)), True), -1e-4)
def test_the_quad_encloses_every_point_it_was_given(self):
pts = grid(range(0, 101, 10), range(0, 81, 10))
quad = fit_quad(pts)
self.assertIsNotNone(quad)
for x, y in pts:
# pointPolygonTest returns the distance to the nearest edge, signed:
# negative means the point is outside.
distance = cv2.pointPolygonTest(quad, (float(x), float(y)), True)
self.assertGreaterEqual(distance, -1e-3, f"point ({x}, {y}) fell outside the quad")
def test_the_quad_is_tight_around_the_points(self):
pts = grid(range(0, 101, 10), range(0, 81, 10))
quad = fit_quad(pts)
self.assertAlmostEqual(float(quad[:, 0].min()), 0.0, delta=1.0)
self.assertAlmostEqual(float(quad[:, 0].max()), 100.0, delta=1.0)
self.assertAlmostEqual(float(quad[:, 1].min()), 0.0, delta=1.0)
self.assertAlmostEqual(float(quad[:, 1].max()), 80.0, delta=1.0)
def test_points_on_one_line_have_no_quad(self):
# Nothing spans the other axis, so two of the four supporting lines do
# not exist and there is no content area to speak of.
pts = np.array([(float(x), 5.0) for x in range(0, 101, 10)], "float32")
self.assertIsNone(fit_quad(pts))
class WarpTest(unittest.TestCase):
def test_fitted_perspective_edges_become_straight_after_warp(self):
pts = np.array([(x + 50, y + 50) for y in range(0, 201, 5)
for x in (0.1 * y, 100 - 0.1 * y)], "float32")
img = np.zeros((300, 200, 3), "uint8")
cv2.fillConvexPoly(img, np.array([[50, 50], [150, 50], [130, 250], [70, 250]]), (255, 255, 255))
rect, _ = warp(img, fit_quad(pts), pad=0)
# A bounding-box crop retains black wedges beside the narrower end.
# Rectification must fill both sides throughout the page height.
self.assertGreater(float(rect[5:-5, 5:10].mean()), 250)
self.assertGreater(float(rect[5:-5, -10:-5].mean()), 250)
def test_the_result_is_the_quad_plus_its_padding(self):
img = np.full((300, 300, 3), 255, "uint8")
quad = np.array([(50.0, 50.0), (150.0, 50.0), (150.0, 100.0), (50.0, 100.0)], "float32")
rect, padded = warp(img, quad)
side = float(np.mean([np.linalg.norm(padded[(i + 1) % 4] - padded[i]) for i in range(4)]))
grown = 2 * PAD * side
self.assertAlmostEqual(rect.shape[1], 100 + grown, delta=2.0)
self.assertAlmostEqual(rect.shape[0], 50 + grown, delta=2.0)
def test_the_padding_grows_the_quad_outward(self):
img = np.full((300, 300, 3), 255, "uint8")
quad = np.array([(50.0, 50.0), (150.0, 50.0), (150.0, 100.0), (50.0, 100.0)], "float32")
_, padded = warp(img, quad)
self.assertLess(float(padded[:, 0].min()), 50.0)
self.assertGreater(float(padded[:, 1].max()), 100.0)
class ThresholdsTest(unittest.TestCase):
"""The thresholds are env-overridable, so the override has to be trustworthy.
The defaults are the tuned values; an override has to parse as a number in
the threshold's range, and anything else is refused with the default left in
place rather than clamped into range — a typo must not quietly run the
pipeline at a value nobody chose.
"""
def test_an_unset_override_leaves_the_tuned_default(self):
for name, (default, _, _) in THRESHOLDS.items():
with self.subTest(threshold=name):
self.assertEqual(resolve_threshold(name, None), default)
self.assertEqual(resolve_threshold(name, " "), default)
def test_a_valid_override_is_taken(self):
self.assertEqual(resolve_threshold("ANG_TOL", "25"), 25.0)
self.assertEqual(resolve_threshold("QUAD_TOL", "-0.05"), -0.05)
self.assertEqual(resolve_threshold("PAD", "0.02"), 0.02)
def test_the_ends_of_the_range_are_inside_it(self):
for name, (_, low, high) in THRESHOLDS.items():
with self.subTest(threshold=name):
self.assertEqual(resolve_threshold(name, repr(low)), low)
self.assertEqual(resolve_threshold(name, repr(high)), high)
def test_a_value_outside_the_range_is_refused(self):
for name, (default, low, high) in THRESHOLDS.items():
for bad in (low - 1.0, high + 1.0):
with self.subTest(threshold=name, value=bad):
self.assertEqual(resolve_threshold(name, repr(bad)), default)
def test_a_value_that_is_not_a_number_is_refused(self):
for raw in ("wide", "0.015x", "1,5", "nan-ish"):
with self.subTest(raw=raw):
self.assertEqual(resolve_threshold("PAD", raw), DEFAULT_PAD)
def test_the_effective_set_is_what_the_module_uses(self):
# The log line printed at import reads this, so it has to agree with the
# names the functions actually close over.
effective = effective_thresholds()
self.assertEqual(effective["PAD"], PAD)
self.assertEqual(effective["MIN_SCORE"], MIN_SCORE)
self.assertEqual(effective["ANG_TOL"], ANG_TOL)
self.assertEqual(effective["SIZE_MIN"], SIZE_MIN)
self.assertEqual(effective["QUAD_TOL"], QUAD_TOL)
if __name__ == "__main__":
unittest.main()
+109
View File
@@ -0,0 +1,109 @@
import io
import unittest
from pathlib import Path
from markitdown import MarkItDown
from docreader.parser.markdown_parser import MarkdownTableUtil
class TestMarkdownTableUtil(unittest.TestCase):
def test_preserves_empty_cells(self):
"""Interior empty cells must not be dropped during formatting."""
raw = "| a | | c |\n| --- | --- | --- |\n| 1 | 2 | 3 |"
formatted = MarkdownTableUtil().format_table(raw)
self.assertIn("| a | | c |", formatted)
self.assertEqual(formatted.count("|"), raw.count("|"))
def test_format_nonempty_table(self):
raw = "|Name|Age|\n|---|---|\n|John|30|"
formatted = MarkdownTableUtil().format_table(raw)
self.assertIn("| Name | Age |", formatted)
self.assertIn("| --- | --- |", formatted)
self.assertIn("| John | 30 |", formatted)
def test_normalize_markitdown_en_tables(self):
docx = (
Path(__file__).resolve().parents[2]
/ "testdata"
/ "rag_test"
/ "docx"
/ "en_tables.docx"
)
if not docx.is_file():
docx = Path(__file__).resolve().parents[2].parent / "testdata/rag_test/docx/en_tables.docx"
if not docx.is_file():
self.skipTest("en_tables.docx fixture not available")
raw = MarkItDown().convert(io.BytesIO(docx.read_bytes()), file_extension=".docx").text_content
normalized = MarkdownTableUtil().format_table(raw)
self.assertNotIn("| | | | |", normalized)
self.assertIn("| Name | Game | Fame | Blame |", normalized)
idx_name = normalized.index("| Name | Game | Fame | Blame |")
idx_sep = normalized.index("| --- | --- | --- | --- |", idx_name)
self.assertLess(idx_name, idx_sep)
self.assertIn("| Lebron James | Basketball |", normalized)
# Headerless 2-row tables: delimiter inserted so GFM renderers show a table
self.assertIn(
"| Sinple | Table |\n| --- | --- |\n| Without | Header |", normalized
)
self.assertIn(
"| Simple Multiparagraph | Table Full |\n| --- | --- |\n"
"| Of Paragraphs | In each Cell. |",
normalized,
)
def test_malformed_unclosed_row_is_passthrough(self):
"""An unclosed ``|``-prefixed row must not hang the process.
Regression for Tencent/WeKnora#2768: the old line_pattern explored an
exponential number of backtracking paths on such rows and stalled the
single-threaded docreader event loop.
"""
line = "| " + " | ".join(f"col{i}" for i in range(100)) + " unclosed"
formatted = MarkdownTableUtil().format_table(line)
self.assertEqual(formatted, line)
def test_long_valid_table_formats(self):
"""A long, well-formed table still formats in linear time."""
header = "| " + " | ".join(f"c{i}" for i in range(200)) + " |"
sep = "| " + " | ".join("---" for _ in range(200)) + " |"
row = "| " + " | ".join(f"v{i}" for i in range(200)) + " |"
formatted = MarkdownTableUtil().format_table("\n".join([header, sep, row]))
self.assertIn("| c0 | c1 |", formatted)
self.assertIn("| c199 |", formatted)
self.assertIn("| --- |", formatted)
self.assertIn("| v0 | v1 |", formatted)
self.assertIn("| v199 |", formatted)
def test_lone_pipe_is_passthrough(self):
"""A single-pipe line is not a table row and must not be deleted."""
self.assertEqual(MarkdownTableUtil().format_table("|"), "|")
self.assertEqual(MarkdownTableUtil().format_table(" | "), " | ")
def test_lone_pipe_above_table_is_kept(self):
raw = "|\n| a | b |\n| --- | --- |\n| 1 | 2 |"
formatted = MarkdownTableUtil().format_table(raw)
self.assertEqual(formatted.split("\n")[0], "|")
self.assertIn("| a | b |", formatted)
self.assertIn("| 1 | 2 |", formatted)
def test_alignment_colons_preserved(self):
raw = "| a | b | c |\n| :---------- | -------: | :------: |\n| 1 | 2 | 3 |"
formatted = MarkdownTableUtil().format_table(raw)
self.assertIn("| :--- | ---: | :---: |", formatted)
def test_crlf_table_formats_without_mixed_endings(self):
raw = "# Title\r\n\r\n|Name|Age|\r\n|---|---|\r\n|John|30|\r\n\r\nparagraph\r\n"
formatted = MarkdownTableUtil().format_table(raw)
self.assertIn("| Name | Age |", formatted)
self.assertIn("| --- | --- |", formatted)
self.assertIn("| John | 30 |", formatted)
self.assertIn("paragraph", formatted)
self.assertNotIn("\r", formatted)
self.assertTrue(formatted.endswith("\n"))
if __name__ == "__main__":
unittest.main()
+355
View File
@@ -0,0 +1,355 @@
import base64
import email
import json
import unittest
from email.header import Header
from email.message import EmailMessage
from pathlib import Path
from docreader.parser.mhtml_parser import MHTMLParser, _header_str
from docreader.parser.registry import registry
REPO_ROOT = Path(__file__).resolve().parents[2]
def _minimal_mhtml_bytes() -> bytes:
root = EmailMessage()
root["Subject"] = "Tiny MHTML"
root.make_related()
main = EmailMessage()
main.set_content(
"<html><body><h1>Main Article</h1>"
"<p>Hello MHTML world.</p>"
'<p><a href="chapter03.xhtml#sec2">Chapter 3</a> '
'<a href="#footnote1">note</a> '
'<a href="https://example.com">the site</a></p>'
'<img alt="tiny" src="cid:tiny-image">'
"<script>window.noise = true</script>"
"</body></html>",
subtype="html",
)
main["Content-Location"] = "https://example.com/article"
root.attach(main)
ad = EmailMessage()
ad.set_content(
"<html><body><h1>Advertisement</h1>"
"<p>Buy this unrelated thing.</p></body></html>",
subtype="html",
)
ad["Content-Location"] = "https://googleads.example/frame.html"
root.attach(ad)
image = EmailMessage()
image.set_content(
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR",
maintype="image",
subtype="png",
)
image["Content-Location"] = "cid:tiny-image"
root.attach(image)
return root.as_bytes()
def _mhtml_with_table_image_and_caption() -> bytes:
root = EmailMessage()
root["Subject"] = "MHTML with table image"
root.make_related()
main = EmailMessage()
main.set_content(
"<html><body>"
"<table>"
"<tr><th>体验方向</th><th>代表内容</th></tr>"
"<tr><td>赛季制建立</td><td>BP、Rank</td></tr>"
"</table>"
'<img src="cid:test-image" alt="图片" title="图片">'
"<p>高机动性身法与独特枪械反馈</p>"
"</body></html>",
subtype="html",
)
main["Content-Location"] = "https://example.com/article"
root.attach(main)
image = EmailMessage()
image.set_content(
b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff,\x00\x00"
b"\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;",
maintype="image",
subtype="gif",
)
image["Content-ID"] = "<test-image>"
root.attach(image)
return root.as_bytes()
def _mhtml_with_8bit_utf8_headers() -> bytes:
"""Browser-style MHTML: raw UTF-8 bytes in MIME headers, not RFC 2047."""
html_loc = "https://example.com/测试页面.html".encode("utf-8")
ad_loc = "https://googleads.example/广告.html".encode("utf-8")
image_loc = "https://example.com/图片.png".encode("utf-8")
content_id = "<图片@local>".encode("utf-8")
attachment_id = "图片".encode("utf-8")
main_html = (
"<html><body><h1>中文主文</h1>"
'<img alt="绝对" src="https://example.com/图片.png">'
'<img alt="相对" src="图片.png">'
'<img alt="cid" src="cid:图片@local">'
"</body></html>"
).encode("utf-8")
ad_html = "<html><body><h1>广告正文</h1></body></html>".encode("utf-8")
png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
return b"".join(
[
b"MIME-Version: 1.0\r\n",
b'Content-Type: multipart/related; boundary="----=_Next"\r\n',
b"\r\n",
b"------=_Next\r\n",
b'Content-Type: text/html; charset="utf-8"\r\n',
b"Content-Transfer-Encoding: 8bit\r\n",
b"Content-Location: ",
html_loc,
b"\r\n\r\n",
main_html,
b"\r\n",
b"------=_Next\r\n",
b'Content-Type: text/html; charset="utf-8"\r\n',
b"Content-Transfer-Encoding: 8bit\r\n",
b"Content-Location: ",
ad_loc,
b"\r\n\r\n",
ad_html,
b"\r\n",
b"------=_Next\r\n",
b"Content-Type: image/png\r\n",
b"Content-Transfer-Encoding: base64\r\n",
b"Content-Location: ",
image_loc,
b"\r\nContent-ID: ",
content_id,
b"\r\nX-Attachment-Id: ",
attachment_id,
b"\r\n\r\n",
base64.b64encode(png),
b"\r\n",
b"------=_Next--\r\n",
]
)
class MHTMLParserTest(unittest.TestCase):
def test_parse_selects_main_html_and_filters_noise(self):
document = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
).parse_into_text(_minimal_mhtml_bytes())
self.assertIn("Main Article", document.content)
self.assertIn("Hello MHTML world", document.content)
self.assertNotIn("Advertisement", document.content)
self.assertNotIn("window.noise", document.content)
self.assertEqual(document.metadata["source_format"], "mhtml")
def test_internal_links_are_unwrapped_but_external_links_remain(self):
document = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
).parse_into_text(_minimal_mhtml_bytes())
self.assertIn("Chapter 3", document.content)
self.assertIn("note", document.content)
self.assertNotIn("chapter03.xhtml#sec2", document.content)
self.assertNotIn("#footnote1", document.content)
self.assertIn("[the site](https://example.com)", document.content)
def test_image_extraction_toggle(self):
with_images = MHTMLParser(
file_name="article.mhtml", file_type="mhtml", extract_images=True
).parse_into_text(_minimal_mhtml_bytes())
without_images = MHTMLParser(
file_name="article.mhtml", file_type="mhtml", extract_images=False
).parse_into_text(_minimal_mhtml_bytes())
self.assertEqual(len(with_images.images), 1)
image_ref = next(iter(with_images.images))
self.assertTrue(image_ref.startswith("images/"))
self.assertIn(image_ref, with_images.content)
self.assertNotIn("cid:tiny-image", with_images.content)
self.assertEqual(without_images.images, {})
def test_table_image_and_caption_keep_markdown_block_boundaries(self):
document = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
).parse_into_text(_mhtml_with_table_image_and_caption())
self.assertEqual(len(document.images), 1)
image_ref = next(iter(document.images))
self.assertIn(f'![图片]({image_ref} "图片")', document.content)
self.assertIn(
f"| 赛季制建立 | BP、Rank |\n\n![图片]({image_ref} \"图片\")",
document.content,
)
self.assertIn(
f'![图片]({image_ref} "图片")\n\n高机动性身法与独特枪械反馈',
document.content,
)
def test_html_to_markdown_preserves_indentation_and_code_block_blanks(self):
markdown = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
)._html_to_markdown(
"<ul><li>parent<ul><li>child</li></ul></li></ul>"
"<blockquote><p>quoted</p></blockquote>"
"<pre><code>line1\n\n indented\n</code></pre>"
)
self.assertIn("* parent\n + child", markdown)
self.assertIn("\n\n> quoted\n\n", markdown)
self.assertIn("```\nline1\n\n indented\n```", markdown)
def test_html_to_markdown_preserves_nested_list_indentation(self):
markdown = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
)._html_to_markdown("<ul><li>parent<ul><li>child</li></ul></li></ul>")
self.assertIn("* parent\n + child", markdown)
def test_html_to_markdown_preserves_blockquote_boundaries(self):
markdown = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
)._html_to_markdown("<p>before</p><blockquote><p>quoted</p></blockquote><p>after</p>")
self.assertIn("before\n\n> quoted\n\nafter", markdown)
def test_html_to_markdown_preserves_fenced_code_blank_lines(self):
markdown = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
)._html_to_markdown("<pre><code>line1\n\n\nline2\n</code></pre>")
self.assertIn("```\nline1\n\n\nline2\n```", markdown)
def test_html_to_markdown_collapses_excess_blank_lines_outside_code(self):
markdown = MHTMLParser._normalize_markdown("alpha\n\n \n\t\n\nbeta")
self.assertEqual(markdown, "alpha\n\nbeta")
self.assertNotIn("\n\n\n", markdown)
def test_html_to_markdown_preserves_hard_break_spaces(self):
markdown = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
)._html_to_markdown("<p>alpha<br>beta</p>")
self.assertEqual(markdown, "alpha \nbeta")
def test_html_to_markdown_keeps_whitespace_of_whitespace_only_inline_elements(self):
parser = MHTMLParser(file_name="article.mhtml", file_type="mhtml")
cases = {
"<p>further<strong> </strong>reference</p>": "further reference",
"<p><b>First</b><b> </b><b>Last</b></p>": "**First** **Last**",
"<p>Hello<code> </code>world</p>": "Hello world",
"<p>one<em>&#160;</em>two</p>": "one\xa0two",
'<p>see<a href="https://example.com"> </a>here</p>': "see here",
"<p>a<b><i> </i></b>b</p>": "a b",
"<p>x<sub> </sub>y<sup> </sup>z<kbd> </kbd>w</p>": "x y z w",
"<p>v<del> </del>w<s> </s>x<samp> </samp>y</p>": "v w x y",
}
for html_content, expected in cases.items():
with self.subTest(html=html_content):
self.assertEqual(parser._html_to_markdown(html_content), expected)
def test_html_to_markdown_still_converts_inline_elements_with_content(self):
markdown = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
)._html_to_markdown(
"<p><strong>bold</strong> <code>code</code> <em>em</em> "
'<del>gone</del> <a href="https://example.com">link</a> '
"keep<b></b>empty "
'<a href="https://example.com"><img alt="pic" src="https://example.com/a.png"></a></p>'
)
self.assertEqual(
markdown,
"**bold** `code` *em* ~~gone~~ [link](https://example.com) keepempty "
"[![pic](https://example.com/a.png)](https://example.com)",
)
def test_normalize_markdown_preserves_two_space_hard_break(self):
markdown = MHTMLParser._normalize_markdown("alpha \nbeta")
self.assertEqual(markdown, "alpha \nbeta")
def test_html_to_markdown_normalizes_crlf(self):
markdown = MHTMLParser._normalize_markdown("alpha\r\n\r\nbeta\rgamma")
self.assertEqual(markdown, "alpha\n\nbeta\ngamma")
def test_html_to_markdown_does_not_strip_leading_indentation_at_document_start(self):
markdown = MHTMLParser._normalize_markdown(" indented start\n")
self.assertEqual(markdown, " indented start")
def test_mhtml_shared_contract_fixture(self):
fixture = REPO_ROOT / "testdata" / "mhtml" / "titled-image.mhtml"
contract_path = REPO_ROOT / "testdata" / "mhtml" / "titled-image-contract.json"
contract = json.loads(contract_path.read_text(encoding="utf-8"))
document = MHTMLParser(
file_name="titled-image.mhtml", file_type="mhtml"
).parse_into_text(fixture.read_bytes())
self.assertEqual(document.content, contract["markdown_content"])
self.assertEqual(len(document.images), 1)
image_contract = contract["images"][0]
self.assertIn(image_contract["original_ref"], document.images)
self.assertEqual(
base64.b64decode(document.images[image_contract["original_ref"]]),
base64.b64decode(image_contract["image_data_base64"]),
)
self.assertIn(
'| 赛季制建立 | BP、Rank |\n\n![图片](images/第 1 页 (测试).gif "阶段 1) 图片")',
document.content,
)
self.assertIn(
'![图片](images/第 1 页 (测试).gif "阶段 1) 图片")\n\n高机动性身法与独特枪械反馈',
document.content,
)
self.assertNotIn("\n\n\n", document.content.split("```", 1)[0])
self.assertIn("```\nline1\n\n\nline2\n```", document.content)
self.assertIn("* parent\n + child", document.content)
self.assertIn("alpha \nbeta", document.content)
def test_header_str_recovers_unknown_8bit_utf8(self):
raw = (
b"Content-Type: text/plain\r\n"
b"Content-Location: https://example.com/"
+ "图片.png".encode("utf-8")
+ b"\r\n\r\nbody\r\n"
)
value = email.message_from_bytes(raw).get("Content-Location")
self.assertIsInstance(value, Header)
self.assertEqual(_header_str(value), "https://example.com/图片.png")
self.assertEqual(_header_str(None), "")
self.assertEqual(_header_str("ascii-location"), "ascii-location")
self.assertEqual(_header_str("已是unicode"), "已是unicode")
def test_parse_8bit_utf8_headers_rewrites_images_without_crashing(self):
document = MHTMLParser(
file_name="article.mhtml", file_type="mhtml"
).parse_into_text(_mhtml_with_8bit_utf8_headers())
self.assertIn("中文主文", document.content)
self.assertNotIn("广告正文", document.content)
self.assertIn("images/图片.png", document.images)
self.assertIn("images/图片.png", document.content)
self.assertEqual(document.content.count("images/图片.png"), 3)
self.assertNotIn("cid:图片@local", document.content)
self.assertNotIn("\ufffd", document.content)
self.assertTrue(all("\ufffd" not in key for key in document.images))
def test_registry_resolves_mhtml(self):
self.assertIs(registry.get_parser_class("", "mhtml"), MHTMLParser)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,133 @@
"""Unit tests for OpenDataLoader parser helpers (no JVM required)."""
import os
import sys
import tempfile
import unittest
from unittest import mock
from docreader.parser.opendataloader_parser import (
OpenDataLoaderParser,
_collect_images_under_output,
_find_markdown_file,
_normalize_odl_image_url,
_ping_hybrid,
_run_convert,
_rewrite_markdown_image_refs,
opendataloader_available,
)
class OpenDataLoaderHelpersTest(unittest.TestCase):
def test_hybrid_health_probe_blocks_private_url_before_request(self):
with mock.patch(
"docreader.parser.opendataloader_parser.is_ssrf_safe_url",
return_value=(False, "restricted test address"),
), mock.patch("urllib.request.build_opener") as build_opener:
ok, msg = _ping_hybrid("http://127.0.0.1:8080", retries=1)
self.assertFalse(ok)
self.assertIn("SSRF", msg)
build_opener.assert_not_called()
def test_convert_blocks_private_hybrid_url_at_final_sink(self):
fake_module = mock.Mock()
with mock.patch.dict(sys.modules, {"opendataloader_pdf": fake_module}):
with self.assertRaisesRegex(RuntimeError, "SSRF"):
_run_convert(
"/tmp/input.pdf",
"/tmp/output",
"/tmp/output/images",
overrides={
"odl_hybrid": "docling-fast",
"odl_hybrid_url": "http://169.254.169.254/latest/meta-data",
},
)
fake_module.convert.assert_not_called()
def test_find_markdown_prefers_stem_match(self):
with tempfile.TemporaryDirectory() as d:
other = os.path.join(d, "other.md")
target = os.path.join(d, "paper.md")
with open(other, "w") as f:
f.write("x")
with open(target, "w") as f:
f.write("# Title")
self.assertEqual(_find_markdown_file(d, "paper"), target)
def test_collect_and_rewrite_images(self):
with tempfile.TemporaryDirectory() as d:
img_dir = os.path.join(d, "images")
os.makedirs(img_dir)
png = os.path.join(img_dir, "fig1.png")
with open(png, "wb") as f:
f.write(b"\x89PNG\r\n\x1a\n")
images = _collect_images_under_output(d)
self.assertIn("images/fig1.png", images)
md = "See ![fig](images/fig1.png) and ![alt](./fig1.png)."
out = _rewrite_markdown_image_refs(md, images)
self.assertIn("![fig](images/fig1.png)", out)
self.assertIn("![alt](images/fig1.png)", out)
def test_rewrite_odl_angle_bracket_and_entity_urls(self):
images = {"images/imageFile1.png": "e30="}
for md_in in (
"![image 1](<images/imageFile1.png>)",
"![image 1](&lt;images/imageFile1.png&gt;)",
):
out = _rewrite_markdown_image_refs(md_in, images)
self.assertEqual("![image 1](images/imageFile1.png)", out)
def test_normalize_odl_image_url(self):
self.assertEqual(
_normalize_odl_image_url("&lt;images/imageFile2.png&gt;"),
"images/imageFile2.png",
)
self.assertEqual(
_normalize_odl_image_url("<images/imageFile2.png>"),
"images/imageFile2.png",
)
def test_rewrite_skips_data_uris(self):
md = "![x](data:image/png;base64,abc)"
self.assertEqual(_rewrite_markdown_image_refs(md, {"images/a.png": "e30="}), md)
class OpenDataLoaderParserTest(unittest.TestCase):
@mock.patch("docreader.parser.opendataloader_parser.opendataloader_available")
@mock.patch("docreader.parser.opendataloader_parser._run_convert")
def test_parse_reads_markdown_and_images(self, mock_convert, mock_avail):
mock_avail.return_value = (True, "")
def fake_convert(pdf_path, output_dir, image_dir, overrides=None):
stem = os.path.splitext(os.path.basename(pdf_path))[0]
md_path = os.path.join(output_dir, f"{stem}.md")
with open(md_path, "w") as f:
f.write("# Hello\n\n![pic](images/pic.png)\n")
os.makedirs(image_dir, exist_ok=True)
with open(os.path.join(image_dir, "pic.png"), "wb") as f:
f.write(b"png")
mock_convert.side_effect = fake_convert
parser = OpenDataLoaderParser(file_name="doc.pdf", file_type="pdf")
doc = parser.parse_into_text(b"%PDF-1.4 fake")
self.assertIn("# Hello", doc.content)
self.assertIn("images/pic.png", doc.content)
self.assertIn("images/pic.png", doc.images)
self.assertEqual(doc.metadata.get("parser_engine"), "opendataloader")
@mock.patch("docreader.parser.opendataloader_parser.shutil.which", return_value=None)
def test_availability_requires_java(self, _which):
with mock.patch(
"docreader.parser.opendataloader_parser._package_available",
return_value=(True, ""),
):
ok, msg = opendataloader_available()
self.assertFalse(ok)
self.assertIn("Java", msg)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,88 @@
import base64
import io
import threading
import time
import unittest
import uuid
from PIL import Image
from docreader.parser.concurrency import parser_worker_limit
from docreader.parser.pdf_parser import PDFScannedParser, _normalize_image_quality
class ParserConcurrencyTest(unittest.TestCase):
def test_parser_worker_limit_serializes_work(self):
limiter_name = f"test-{uuid.uuid4()}"
active_workers = 0
max_active_workers = 0
state_lock = threading.Lock()
start = threading.Barrier(3)
def worker():
nonlocal active_workers, max_active_workers
start.wait()
with parser_worker_limit(limiter_name, 1):
with state_lock:
active_workers += 1
max_active_workers = max(max_active_workers, active_workers)
time.sleep(0.02)
with state_lock:
active_workers -= 1
threads = [threading.Thread(target=worker) for _ in range(2)]
for thread in threads:
thread.start()
start.wait()
for thread in threads:
thread.join()
self.assertEqual(max_active_workers, 1)
def test_scanned_pdf_parser_outputs_jpeg_images(self):
pdf_bytes = io.BytesIO()
pages = [
Image.new("RGB", (64, 64), "white"),
Image.new("RGB", (64, 64), "black"),
]
pages[0].save(
pdf_bytes,
format="PDF",
save_all=True,
append_images=pages[1:],
)
document = PDFScannedParser(file_name="scan.pdf").parse_into_text(
pdf_bytes.getvalue()
)
image_ref = "images/scan_page_1.jpg"
self.assertIn(f"![scan_page_1.jpg]({image_ref})", document.content)
self.assertIn(image_ref, document.images)
self.assertEqual(document.metadata["image_source_type"], "scanned_pdf")
self.assertEqual(document.metadata["page_count"], 2)
self.assertEqual(len(document.images), 2)
self.assertIn("images/scan_page_2.jpg", document.images)
image_bytes = base64.b64decode(document.images[image_ref])
self.assertTrue(image_bytes.startswith(b"\xff\xd8"))
def test_scanned_pdf_parser_logs_malformed_pdf_without_format_error(self):
parser = PDFScannedParser(file_name="broken.pdf")
with self.assertLogs("docreader.parser.pdf_parser", level="ERROR") as logs:
with self.assertRaises(Exception):
parser.parse_into_text(b"not a pdf")
self.assertTrue(
any("PDFScannedParser failed to parse PDF:" in line for line in logs.output)
)
def test_normalize_image_quality_bounds_jpeg_quality(self):
self.assertEqual(_normalize_image_quality(-1), 1)
self.assertEqual(_normalize_image_quality(90), 90)
self.assertEqual(_normalize_image_quality(120), 95)
if __name__ == "__main__":
unittest.main()
+105
View File
@@ -0,0 +1,105 @@
import unittest
from docreader.models.document import Document
from docreader.parser.base_parser import BaseParser
from docreader.parser.parser import Parser, detect_effective_file_type
from docreader.parser.markitdown_parser import MarkitdownParser
from docreader.parser.pdf_parser import PDFParser
from docreader.parser.registry import BUILTIN_ENGINE, ParserEngineRegistry, registry
from docreader.parser.xmind_parser import XMindParser
OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
class _RecordingParser(BaseParser):
last_file_type = ""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
type(self).last_file_type = self.file_type
def parse_into_text(self, content: bytes) -> Document:
return Document(content="parsed")
class _RecordingRegistry:
def __init__(self):
self.requested_file_type = ""
def get_parser_class(self, engine: str, file_type: str):
self.requested_file_type = file_type
return _RecordingParser
class ParserRoutingTest(unittest.TestCase):
def test_builtin_registry_routes_xmind_to_xmind_parser(self):
parser_class = registry.get_parser_class(BUILTIN_ENGINE, "xmind")
self.assertIs(parser_class, XMindParser)
def test_legacy_doc_payload_renamed_to_docx_uses_doc_parser(self):
registry = _RecordingRegistry()
parser = Parser()
parser.registry = registry
result = parser.parse_file(
"legacy.docx",
"docx",
OLE_MAGIC + b"legacy-word-payload",
)
self.assertEqual("parsed", result.content)
self.assertEqual("doc", registry.requested_file_type)
self.assertEqual("doc", _RecordingParser.last_file_type)
def test_real_docx_payload_keeps_docx_parser_route(self):
self.assertEqual(
"docx",
detect_effective_file_type(".DOCX", b"PK\x03\x04ooxml-payload"),
)
def test_unrelated_ole_type_is_not_reclassified(self):
self.assertEqual("xls", detect_effective_file_type("xls", OLE_MAGIC))
def test_empty_engine_routes_pptx_to_markitdown(self):
self.assertIs(registry.get_parser_class("", "pptx"), MarkitdownParser)
self.assertIs(registry.get_parser_class("", "ppt"), MarkitdownParser)
self.assertIs(registry.get_parser_class("", ".PPTX"), MarkitdownParser)
def test_builtin_engine_still_parses_pptx(self):
self.assertIs(registry.get_parser_class(BUILTIN_ENGINE, "pptx"), MarkitdownParser)
def test_type_default_when_builtin_lacks_pptx(self):
isolated = ParserEngineRegistry()
isolated.register(BUILTIN_ENGINE, {"pdf": PDFParser})
isolated.register(
"markitdown",
{"pptx": MarkitdownParser, "ppt": MarkitdownParser, "csv": MarkitdownParser},
)
self.assertIs(isolated.get_parser_class("", "pptx"), MarkitdownParser)
self.assertIs(isolated.get_parser_class(BUILTIN_ENGINE, "pptx"), MarkitdownParser)
self.assertIs(isolated.get_parser_class("", "csv"), MarkitdownParser)
self.assertIs(isolated.get_parser_class(BUILTIN_ENGINE, "csv"), MarkitdownParser)
self.assertIs(isolated.get_parser_class(BUILTIN_ENGINE, "pdf"), PDFParser)
self.assertIs(isolated.get_parser_class("", "pdf"), PDFParser)
with self.assertRaises(ValueError) as ctx:
isolated.get_parser_class("", "xyz")
self.assertIn("Unsupported file type: xyz", str(ctx.exception))
def test_actionable_error_lists_supporting_engines(self):
isolated = ParserEngineRegistry()
isolated.register(BUILTIN_ENGINE, {"pdf": PDFParser})
isolated.register("opendataloader", {"xmind": XMindParser})
with self.assertRaises(ValueError) as ctx:
isolated.get_parser_class(BUILTIN_ENGINE, "xmind")
message = str(ctx.exception)
self.assertIn("Configure one of:", message)
self.assertIn("opendataloader", message)
if __name__ == "__main__":
unittest.main()
+258
View File
@@ -0,0 +1,258 @@
"""Embedded-figure extraction from native PDF pages.
Focus: images whose visible content lives in a /SMask (soft transparency
mask) while the base RGB plane is black. ``get_bitmap()`` alone decodes only
the base plane, producing an all-black JPEG; the decode path must render the
mask in and composite over white. Reproduces the all-black figures extracted
from a production PDF exported by a plotting tool.
"""
import base64
import gc
import io
import unittest
from unittest.mock import patch
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_raw
from PIL import Image
from docreader.parser.pdf_parser import (
_decode_embedded_image_pil,
_extract_embedded_images,
)
PAGE_W, PAGE_H = 612, 792
IMG_W, IMG_H = 120, 90
def _pdf_from_objects(objects: list) -> bytes:
out = bytearray(b"%PDF-1.7\n")
offsets = []
for i, body in enumerate(objects, start=1):
offsets.append(len(out))
out += b"%d 0 obj\n" % i + body + b"\nendobj\n"
xref_pos = len(out)
out += b"xref\n0 %d\n" % (len(objects) + 1)
out += b"0000000000 65535 f \n"
for off in offsets:
out += b"%010d 00000 n \n" % off
out += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (
len(objects) + 1,
xref_pos,
)
return bytes(out)
def _page_objects(image_obj: bytes, extra_objs: list | None = None) -> list:
contents = b"q 480 0 0 360 66 216 cm /Im0 Do Q\n"
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
(
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %d %d] "
b"/Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>"
% (PAGE_W, PAGE_H)
),
b"<< /Length %d >>\nstream\n" % len(contents) + contents + b"endstream",
image_obj,
]
if extra_objs:
objects.extend(extra_objs)
return objects
def _circle_mask() -> bytes:
cx, cy, radius = IMG_W // 2, IMG_H // 2, 30
mask = bytearray(IMG_W * IMG_H)
for y in range(IMG_H):
for x in range(IMG_W):
if (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius:
mask[y * IMG_W + x] = 255
return bytes(mask)
def _build_smask_pdf(base_rgb=(0, 0, 0)) -> bytes:
"""Hand-built PDF: one RGB image shaped by an SMask circle.
The SMask is opaque (255) inside a filled circle and transparent (0)
elsewhere. A decoder that drops the mask shows the raw base plane only.
"""
r, g, b = base_rgb
base = bytes((r, g, b)) * (IMG_W * IMG_H)
mask = _circle_mask()
image = (
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R "
b"/Length %d >>\nstream\n" % (IMG_W, IMG_H, len(base))
+ base
+ b"\nendstream"
)
mask_obj = (
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceGray /BitsPerComponent 8 /Length %d >>\nstream\n"
% (IMG_W, IMG_H, len(mask))
+ mask
+ b"\nendstream"
)
return _pdf_from_objects(_page_objects(image, [mask_obj]))
def _build_opaque_gray_pdf(level: int = 128) -> bytes:
data = bytes((level,)) * (IMG_W * IMG_H)
image = (
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceGray /BitsPerComponent 8 /Length %d >>\nstream\n"
% (IMG_W, IMG_H, len(data))
+ data
+ b"\nendstream"
)
return _pdf_from_objects(_page_objects(image))
def _first_image_object(pdf):
for page in pdf:
for obj in page.get_objects():
if obj.type == pdfium_raw.FPDF_PAGEOBJ_IMAGE:
return obj
raise AssertionError("test PDF has no image object")
def _raw_decode(obj):
bitmap = obj.get_bitmap()
try:
pil = bitmap.to_pil()
if pil.mode in ("RGB", "L"):
return pil.copy()
return pil.convert("RGB")
finally:
bitmap.close()
class DecodeEmbeddedImageTest(unittest.TestCase):
def test_smask_image_composites_over_white(self):
pdf = pdfium.PdfDocument(_build_smask_pdf())
try:
pil = _decode_embedded_image_pil(_first_image_object(pdf))
finally:
pdf.close()
self.assertEqual(pil.mode, "RGB")
# Transparent corners become white page background, not black.
self.assertGreater(pil.getpixel((2, 2))[0], 200)
self.assertGreater(pil.getpixel((IMG_W - 3, IMG_H - 3))[0], 200)
# Opaque circle center keeps the base-plane colour (black).
self.assertLess(pil.getpixel((IMG_W // 2, IMG_H // 2))[0], 40)
def test_colored_smask_keeps_base_color(self):
pdf = pdfium.PdfDocument(_build_smask_pdf(base_rgb=(200, 30, 40)))
try:
pil = _decode_embedded_image_pil(_first_image_object(pdf))
finally:
pdf.close()
self.assertEqual(pil.mode, "RGB")
self.assertGreater(pil.getpixel((2, 2))[0], 200)
center = pil.getpixel((IMG_W // 2, IMG_H // 2))
self.assertGreater(center[0], 150)
self.assertLess(center[1], 80)
self.assertLess(center[2], 80)
def test_opaque_image_matches_raw_pixels(self):
buf = io.BytesIO()
Image.new("RGB", (100, 80), (10, 200, 30)).save(buf, format="PDF")
pdf = pdfium.PdfDocument(buf.getvalue())
try:
obj = _first_image_object(pdf)
raw = _raw_decode(obj)
pil = _decode_embedded_image_pil(obj)
finally:
pdf.close()
self.assertEqual(pil.size, raw.size)
self.assertEqual(pil.mode, raw.mode)
self.assertEqual(pil.tobytes(), raw.tobytes())
def test_opaque_gray_fallback_keeps_l_mode(self):
# render=True typically returns BGRA even for DeviceGray; the raw
# fallback must keep L so grayscale hashes/JPEGs stay single-channel.
pdf = pdfium.PdfDocument(_build_opaque_gray_pdf(128))
try:
obj = _first_image_object(pdf)
raw = _raw_decode(obj)
self.assertEqual(raw.mode, "L")
original = obj.get_bitmap
def _boom(render=False, **kwargs):
if render:
raise RuntimeError("render unavailable")
return original(render=render, **kwargs)
with patch.object(obj, "get_bitmap", side_effect=_boom):
with self.assertLogs("docreader.parser.pdf_parser", level="WARNING"):
pil = _decode_embedded_image_pil(obj)
finally:
pdf.close()
self.assertEqual(pil.mode, "L")
self.assertEqual(pil.getpixel((IMG_W // 2, IMG_H // 2)), 128)
self.assertEqual(pil.tobytes(), raw.tobytes())
def test_decoded_image_survives_bitmap_gc(self):
buf = io.BytesIO()
Image.new("RGB", (100, 80), (10, 200, 30)).save(buf, format="PDF")
pdf = pdfium.PdfDocument(buf.getvalue())
try:
pil = _decode_embedded_image_pil(_first_image_object(pdf))
finally:
pdf.close()
gc.collect()
self.assertEqual(pil.getpixel((50, 40)), (10, 200, 30))
def test_render_failure_falls_back_to_raw(self):
buf = io.BytesIO()
Image.new("RGB", (100, 80), (10, 200, 30)).save(buf, format="PDF")
pdf = pdfium.PdfDocument(buf.getvalue())
try:
obj = _first_image_object(pdf)
raw = _raw_decode(obj)
original = obj.get_bitmap
def _boom(render=False, **kwargs):
if render:
raise RuntimeError("render unavailable")
return original(render=render, **kwargs)
with patch.object(obj, "get_bitmap", side_effect=_boom):
with self.assertLogs(
"docreader.parser.pdf_parser", level="WARNING"
) as logs:
pil = _decode_embedded_image_pil(obj)
finally:
pdf.close()
self.assertTrue(any("falling back to raw decode" in m for m in logs.output))
self.assertEqual(pil.mode, raw.mode)
self.assertEqual(pil.tobytes(), raw.tobytes())
class ExtractEmbeddedImagesTest(unittest.TestCase):
def test_smask_figure_is_not_all_black(self):
pdf = pdfium.PdfDocument(_build_smask_pdf())
try:
result = _extract_embedded_images(
pdf, ["text"], pdfium_raw, "smask_doc", 85
)
finally:
pdf.close()
self.assertIn(0, result)
ref_path, b64_jpeg, _y_top = result[0][0]
self.assertTrue(ref_path.startswith("images/smask_doc_p1_img1"))
pil = Image.open(io.BytesIO(base64.b64decode(b64_jpeg))).convert("RGB")
total = bright = 0
for x in range(0, pil.width, 4):
for y in range(0, pil.height, 4):
total += 1
if max(pil.getpixel((x, y))) >= 200:
bright += 1
# Dropping the mask would make this ~0: the whole figure is black.
self.assertGreater(bright / total, 0.5)
if __name__ == "__main__":
unittest.main()
+521
View File
@@ -0,0 +1,521 @@
import io
import unittest
from PIL import Image
from docreader.parser.pdf_parser import (
PDFParser,
_classify_page,
_encode_rendered_page_images,
_filter_reading_columns,
_group_lines,
_is_artifact_column,
_join_line_glyphs,
_merge_orphan_punctuation_lines,
_point_in_boxes,
_segments_to_markdown,
_select_embedded_images,
_should_prefer_plain,
_split_columns,
_strip_repeating_lines,
)
def _char(ch, x0, x1, y0, y1):
return {"x0": x0, "x1": x1, "y0": y0, "y1": y1, "ch": ch}
def _line(text, h):
return {"text": text, "h": h}
def _make_image_only_pdf(num_pages: int = 2) -> bytes:
buf = io.BytesIO()
pages = [Image.new("RGB", (64, 64), color) for color in ("white", "black")]
pages = (pages * ((num_pages // 2) + 1))[:num_pages]
pages[0].save(buf, format="PDF", save_all=True, append_images=pages[1:])
return buf.getvalue()
class ClassifyPageTest(unittest.TestCase):
def test_full_page_image_is_scanned_even_with_text(self):
# Scanned newspaper: image covers the page, embedded OCR text exists.
self.assertEqual(_classify_page(2.0, 1620), "scanned")
# Scanned UN doc with garbled OCR text layer (ratio ~1.0).
self.assertEqual(_classify_page(1.0, 1500), "scanned")
def test_native_text_page_is_text(self):
self.assertEqual(_classify_page(0.01, 673), "text")
self.assertEqual(_classify_page(0.0, 1200), "text")
def test_sparse_text_with_image_is_scanned(self):
self.assertEqual(_classify_page(0.3, 2), "scanned")
def test_blank_page_is_text(self):
# No image, no text -> not rendered as an image.
self.assertEqual(_classify_page(0.0, 0), "text")
class RenderedPageEncodingTest(unittest.TestCase):
def test_encoding_releases_raw_pages_as_it_builds_response_images(self):
rendered = {1: b"page-two", 0: b"page-one"}
encoded = _encode_rendered_page_images(rendered, "scan")
self.assertEqual(rendered, {})
self.assertEqual(
encoded,
{
"images/scan_page_1.jpg": "cGFnZS1vbmU=",
"images/scan_page_2.jpg": "cGFnZS10d28=",
},
)
class StripRepeatingLinesTest(unittest.TestCase):
def test_removes_repeated_header_footer(self):
header = "ACME CONFIDENTIAL"
texts = [f"{header}\nbody page {i}\npage {i} footer" for i in range(6)]
# Make the footer identical across pages so it is detected.
texts = [f"{header}\nbody page {i}\nshared footer" for i in range(6)]
classes = ["text"] * 6
cleaned = _strip_repeating_lines(texts, classes)
for page in cleaned:
self.assertNotIn(header, page)
self.assertNotIn("shared footer", page)
self.assertIn("body page 0", cleaned[0])
def test_keeps_lines_when_too_few_pages(self):
texts = ["HEADER\nbody"] * 2
classes = ["text"] * 2
self.assertEqual(_strip_repeating_lines(texts, classes), texts)
class SelectEmbeddedImagesTest(unittest.TestCase):
def _fig(self, page, h="fig", w=200, ht=200, area=0.2):
return {"page": page, "width": w, "height": ht, "area_ratio": area, "hash": h}
def test_keeps_real_figure(self):
meta = [self._fig(0, "a")]
self.assertEqual(_select_embedded_images(meta, 1), [0])
def test_drops_tiny_and_small_images(self):
meta = [
self._fig(0, "tiny_area", area=0.001), # too small a share
self._fig(0, "tiny_px", w=20, ht=20), # too few pixels
]
self.assertEqual(_select_embedded_images(meta, 1), [])
def test_drops_repeated_logo_watermark(self):
# Same hash on 5 of 6 text pages -> running logo/watermark.
meta = [self._fig(p, "logo") for p in range(5)]
meta.append(self._fig(5, "unique"))
kept = _select_embedded_images(meta, 6)
kept_hashes = {meta[i]["hash"] for i in kept}
self.assertNotIn("logo", kept_hashes)
self.assertIn("unique", kept_hashes)
def test_dedups_identical_image_on_same_page(self):
meta = [self._fig(0, "dup"), self._fig(0, "dup")]
self.assertEqual(len(_select_embedded_images(meta, 1)), 1)
def test_respects_max_images_cap(self):
meta = [self._fig(i, f"h{i}") for i in range(10)]
self.assertEqual(len(_select_embedded_images(meta, 10, max_images=3)), 3)
class ReadingOrderTest(unittest.TestCase):
def test_single_column_stays_single(self):
# One column of glyphs at x~100, no full-height gutter.
chars = [_char("a", 100, 110, 700 - i * 12, 712 - i * 12) for i in range(5)]
cols = _split_columns(chars, scale=12.0, width=600.0)
self.assertEqual(len(cols), 1)
def test_two_columns_split_left_to_right(self):
# Left column x~50-150, right column x~400-500, wide empty gutter between.
left = [_char("L", 50, 150, 700 - i * 12, 712 - i * 12) for i in range(4)]
right = [_char("R", 400, 500, 700 - i * 12, 712 - i * 12) for i in range(4)]
cols = _split_columns(left + right, scale=12.0, width=600.0)
self.assertEqual(len(cols), 2)
# Reading order: left column before right column.
self.assertEqual(cols[0][0]["ch"], "L")
self.assertEqual(cols[1][0]["ch"], "R")
def test_group_lines_orders_by_y_then_x(self):
# Two visual lines; within a line glyphs given out of x-order.
chars = [
_char("B", 110, 120, 700, 712), # adjacent to A (no word-sized gap)
_char("A", 100, 110, 700, 712),
_char("C", 100, 110, 680, 692), # next line down
]
lines = _group_lines(chars)
self.assertEqual([ln["text"] for ln in lines], ["AB", "C"])
def test_join_line_glyphs_inserts_word_spaces(self):
# Wide gap between "copy" and "of" mimics positioned OCR / text layers.
chars = [
_char("c", 0, 4, 0, 10),
_char("f", 10, 14, 0, 10),
]
self.assertEqual(_join_line_glyphs(chars), "c f")
def test_join_line_glyphs_keeps_adjacent_letters(self):
chars = [_char("A", 100, 110, 700, 712), _char("B", 110, 120, 700, 712)]
self.assertEqual(_join_line_glyphs(chars), "AB")
class HeadingDetectionTest(unittest.TestCase):
def test_promotes_large_line_to_heading(self):
lines = [_line("Big Title", 24.0)] + [_line(f"body {i}", 10.0) for i in range(6)]
md = _segments_to_markdown(lines)
self.assertTrue(md.startswith("# Big Title"))
self.assertIn("\nbody 0", md)
def test_does_not_promote_when_sizes_uniform(self):
lines = [_line(f"line {i}", 10.0) for i in range(6)]
md = _segments_to_markdown(lines)
self.assertNotIn("#", md)
def test_skips_sentence_like_long_lines(self):
# Large but ends with a period and is long -> body text, not a heading.
lines = [_line("x" * 90 + ".", 30.0)] + [_line("y", 10.0) for _ in range(6)]
md = _segments_to_markdown(lines)
self.assertFalse(md.startswith("#"))
class HiddenTextFilterTest(unittest.TestCase):
def test_point_in_boxes(self):
boxes = [(0.0, 0.0, 10.0, 10.0)]
self.assertTrue(_point_in_boxes(5.0, 5.0, boxes))
self.assertFalse(_point_in_boxes(20.0, 5.0, boxes))
class MarginColumnFilterTest(unittest.TestCase):
def test_drops_narrow_vertical_margin_column(self):
# Mimics arXiv sidebar: narrow x span, one glyph per line.
margin = [
_char(c, 20, 28, 500 - i * 14, 512 - i * 14)
for i, c in enumerate("0202luJ22")
]
body = [
_char("L", 160, 170, 700, 712),
_char("a", 170, 180, 700, 712),
_char("n", 180, 190, 700, 712),
]
cols = _filter_reading_columns(margin + body, scale=10.0, width=612.0)
self.assertEqual(len(cols), 1)
self.assertEqual(cols[0][0]["ch"], "L")
def test_keeps_real_two_column_layout(self):
left = [_char("L", 50, 150, 700 - i * 12, 712 - i * 12) for i in range(4)]
right = [_char("R", 400, 500, 700 - i * 12, 712 - i * 12) for i in range(4)]
cols = _filter_reading_columns(left + right, scale=12.0, width=600.0)
self.assertEqual(len(cols), 2)
class PunctuationMergeTest(unittest.TestCase):
def test_merges_orphan_periods(self):
lines = [
_line("Figure 1 2", 10.0),
_line(". .", 10.0),
_line("Next", 10.0),
]
merged = _merge_orphan_punctuation_lines(lines)
self.assertEqual([ln["text"] for ln in merged], ["Figure 1 2..", "Next"])
class PdfTextSanitizeTest(unittest.TestCase):
def test_removes_fffe_placeholder(self):
from docreader.parser.pdf_parser import _postprocess_pdf_text
raw = "multi\ufffelayer and non\ufffetrivial"
out = _postprocess_pdf_text(raw)
self.assertEqual(out, "multilayer and nontrivial")
def test_strips_chart_axis_run(self):
from docreader.parser.pdf_parser import _postprocess_pdf_text
raw = (
"Deep convolutional neural networks have led to breakthroughs.\n"
"0 1 2 3 4 5 6 0\n"
"10\n"
"20\n"
"iter. (1e4)\n"
"training error (%)\n"
"56-layer\n"
"20-layer\n"
"Figure 1. Training error on CIFAR-10.\n"
)
out = _postprocess_pdf_text(raw)
self.assertIn("breakthroughs", out)
self.assertNotIn("56-layer", out)
self.assertIn("Figure 1.", out)
def test_strips_diagram_labels_above_caption(self):
from docreader.parser.pdf_parser import _postprocess_pdf_text
raw = (
"Paragraph before.\n"
"identity\n"
"weight layer\n"
"relu\n"
"Figure 2. Residual learning block.\n"
"Paragraph after.\n"
)
out = _postprocess_pdf_text(raw)
self.assertIn("Paragraph before.", out)
self.assertIn("Figure 2.", out)
self.assertIn("Paragraph after.", out)
self.assertNotIn("identity", out)
self.assertNotIn("weight layer", out)
def test_strips_arxiv_header_line(self):
from docreader.parser.pdf_parser import _postprocess_pdf_text
raw = "Body text.\n1\narXiv:1512.03385v1 [cs.CV] 10 Dec 2015\nMore body."
out = _postprocess_pdf_text(raw)
self.assertNotIn("arXiv:", out)
self.assertIn("Body text.", out)
class PlainWellFormedTest(unittest.TestCase):
def test_academic_plain_skips_layout(self):
from docreader.parser.pdf_parser import _plain_is_well_formed
plain = (
"Recent work [DL15, MBXS17] shows progress on NLP tasks "
"with pre-trained models."
)
self.assertTrue(_plain_is_well_formed(plain))
def test_glued_scan_plain_needs_layout(self):
from docreader.parser.pdf_parser import _plain_is_well_formed
self.assertFalse(_plain_is_well_formed("Thisisadigitalcopyofabook"))
class LayoutQualityFallbackTest(unittest.TestCase):
def test_prefers_plain_when_many_single_char_lines(self):
plain = "Language Models are Few-Shot Learners\nTom Brown"
layout = "0\n2\n0\n2\nl\nu\nJ\nLan ua e Models"
self.assertTrue(_should_prefer_plain(plain, layout))
def test_keeps_good_layout(self):
plain = "Hello world"
layout = "Hello world"
self.assertFalse(_should_prefer_plain(plain, layout))
class ResNetPaperFigureTest(unittest.TestCase):
"""Regression: ResNet PDF (arXiv:1512.03385) vector figures and captions."""
def test_resnet_figures_and_captions(self):
import os
from docreader.parser.pdf_parser import PDFParser
for path in (
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"testdata",
"rag_test",
"pdf_en",
"resnet.pdf",
),
"/tmp/resnet.pdf",
):
if os.path.isfile(path):
break
else:
self.skipTest("resnet.pdf not available")
with open(path, "rb") as f:
doc = PDFParser(file_name="resnet.pdf", file_type="pdf").parse_into_text(
f.read()
)
self.assertGreater(doc.metadata.get("vector_figure_count", 0), 0)
self.assertIn("![", doc.content)
self.assertIn("Figure 2. Residual learning", doc.content)
self.assertNotIn("arXiv:", doc.content)
fig2 = doc.content.find("Figure 2. Residual learning")
before = doc.content[max(0, fig2 - 120) : fig2]
self.assertIn("![", before)
self.assertNotIn("identity", before)
class Gpt3PaperLayoutTest(unittest.TestCase):
"""Regression: arXiv GPT-3 paper title page must not be one-glyph-per-line."""
def test_gpt3_page0_title_and_authors(self):
import os
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_r
from docreader.parser.pdf_parser import PDFParser, _extract_layout_text
pdf_path = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"testdata",
"rag_test",
"pdf_en",
"gpt3.pdf",
)
if not os.path.isfile(pdf_path):
self.skipTest("gpt3.pdf not in testdata")
with open(pdf_path, "rb") as f:
content = f.read()
with pdfium.PdfDocument(content) as pdf:
page = pdf[0]
try:
layout = _extract_layout_text(page, pdfium_r)
finally:
page.close()
# Margin sidebar must not appear as one-glyph-per-line prefix.
self.assertNotRegex(layout[:300], r"^0\n2\n0\n2")
self.assertIn("Few-Shot Learners", layout)
doc = PDFParser(file_name="gpt3.pdf", file_type="pdf").parse_into_text(content)
self.assertIn("Language Models are Few-Shot Learners", doc.content)
self.assertIn("Tom B. Brown", doc.content[:1200])
self.assertIn("[DL15, MBXS17, PNZtY18]", doc.content)
self.assertIn("task-specific architectures), and more recently", doc.content)
self.assertNotIn("k ifi hi d l", doc.content)
class ScanEnglishDictLayoutTest(unittest.TestCase):
"""Regression: Google Books-style PDFs lose spaces without gap inference."""
def test_scan_en_dict_page0_has_word_spaces(self):
import os
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_r
from docreader.parser.pdf_parser import _extract_layout_text
pdf_path = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"testdata",
"rag_test",
"pdf_scan",
"scan_en_dict.pdf",
)
if not os.path.isfile(pdf_path):
self.skipTest("scan_en_dict.pdf not in testdata")
with open(pdf_path, "rb") as f:
pdf = pdfium.PdfDocument(f.read())
try:
text = _extract_layout_text(pdf[0], pdfium_r)
finally:
pdf.close()
self.assertIn("This is a digital copy of a book", text)
self.assertNotIn("Thisisadigitalcopyofabook", text)
class PDFRouterIntegrationTest(unittest.TestCase):
def test_image_only_pdf_routes_to_scanned(self):
pdf_bytes = _make_image_only_pdf(2)
doc = PDFParser(file_name="imgonly.pdf", file_type="pdf").parse_into_text(
pdf_bytes
)
self.assertEqual(doc.metadata["image_source_type"], "scanned_pdf")
self.assertEqual(doc.metadata["page_count"], 2)
self.assertEqual(doc.metadata["scanned_page_count"], 2)
self.assertEqual(len(doc.images), 2)
self.assertIn("images/imgonly_page_1.jpg", doc.images)
self.assertIn("![imgonly_page_1.jpg](images/imgonly_page_1.jpg)", doc.content)
# JPEG magic bytes after decoding.
import base64
self.assertTrue(
base64.b64decode(doc.images["images/imgonly_page_1.jpg"]).startswith(
b"\xff\xd8"
)
)
def test_malformed_pdf_raises_after_fallback(self):
# Routing fails to open the PDF, falls back to full rendering which also
# fails on garbage input; the error surfaces to the caller.
with self.assertRaises(Exception):
PDFParser(file_name="broken.pdf", file_type="pdf").parse_into_text(
b"not a pdf"
)
class ForceScannedTest(unittest.TestCase):
"""Tests for the force-scanned PDF parsing mode."""
def test_default_text_pdf_is_not_force_scanned(self):
"""Without any override, a text PDF should NOT use scanned mode."""
parser = PDFParser(file_name="normal.pdf", file_type="pdf")
self.assertFalse(parser._force_scanned)
def test_force_scanned_via_kwarg_true(self):
"""Per-upload override pdf_force_scanned=true enables scanned mode."""
parser = PDFParser(
file_name="test.pdf", file_type="pdf", pdf_force_scanned="true"
)
self.assertTrue(parser._force_scanned)
def test_force_scanned_via_kwarg_false(self):
"""Per-upload override pdf_force_scanned=false disables scanned mode."""
parser = PDFParser(
file_name="test.pdf", file_type="pdf", pdf_force_scanned="false"
)
self.assertFalse(parser._force_scanned)
def test_force_scanned_via_kwarg_overrides_env(self, monkeypatch=None):
"""Per-upload override takes priority over global env var."""
import docreader.parser.pdf_parser as pdf_mod
old = pdf_mod.FORCE_SCANNED_PDF
try:
pdf_mod.FORCE_SCANNED_PDF = True
# Explicit false override should win over env=true
parser = PDFParser(
file_name="test.pdf", file_type="pdf", pdf_force_scanned="false"
)
self.assertFalse(parser._force_scanned)
finally:
pdf_mod.FORCE_SCANNED_PDF = old
def test_force_scanned_via_env(self):
"""Global env variable enables force scanned when no override."""
import docreader.parser.pdf_parser as pdf_mod
old = pdf_mod.FORCE_SCANNED_PDF
try:
pdf_mod.FORCE_SCANNED_PDF = True
parser = PDFParser(file_name="test.pdf", file_type="pdf")
self.assertTrue(parser._force_scanned)
finally:
pdf_mod.FORCE_SCANNED_PDF = old
def test_force_scanned_output_is_scanned_pdf(self):
"""Force-scanned mode produces scanned_pdf metadata and image refs."""
pdf_bytes = _make_image_only_pdf(2)
parser = PDFParser(
file_name="forced.pdf", file_type="pdf", pdf_force_scanned="true"
)
doc = parser.parse_into_text(pdf_bytes)
self.assertEqual(doc.metadata.get("image_source_type"), "scanned_pdf")
self.assertEqual(doc.metadata.get("page_count"), 2)
self.assertEqual(doc.metadata.get("scanned_page_count"), 2)
self.assertEqual(doc.metadata.get("text_page_count"), 0)
self.assertEqual(doc.metadata.get("embedded_image_count"), 0)
self.assertEqual(doc.metadata.get("vector_figure_count"), 0)
self.assertIn("![forced_page_1.jpg]", doc.content)
self.assertIn("![forced_page_2.jpg]", doc.content)
self.assertEqual(len(doc.images), 2)
if __name__ == "__main__":
unittest.main()
+94
View File
@@ -0,0 +1,94 @@
import shutil
import unittest
from pathlib import Path
from docreader.parser.ppt_convert import (
convert_ppt_to_pptx_bytes,
is_ole_compound,
is_zip_openxml,
needs_ppt_to_pptx_conversion,
normalize_ppt_bytes,
)
TESTDATA = Path(__file__).resolve().parents[2] / "testdata" / "rag_test"
LEGACY_PPT = TESTDATA / "ppt_old" / "en_38256.ppt"
WMF_IMAGE_PPT = LEGACY_PPT
IMAGE_HEAVY_PPT = TESTDATA / "ppt_old" / "en_41384.ppt"
PPTX_SAMPLE = TESTDATA / "pptx" / "en_marker.pptx"
class TestPptConvert(unittest.TestCase):
def test_legacy_ppt_magic(self):
if not LEGACY_PPT.is_file():
self.skipTest("legacy PPT fixture not available")
content = LEGACY_PPT.read_bytes()
self.assertTrue(is_ole_compound(content))
self.assertFalse(is_zip_openxml(content))
self.assertTrue(needs_ppt_to_pptx_conversion(content, "ppt"))
def test_pptx_does_not_need_conversion(self):
if not PPTX_SAMPLE.is_file():
self.skipTest("PPTX fixture not available")
content = PPTX_SAMPLE.read_bytes()
self.assertTrue(is_zip_openxml(content))
self.assertFalse(needs_ppt_to_pptx_conversion(content, "pptx"))
def test_normalize_pptx_passthrough(self):
if not PPTX_SAMPLE.is_file():
self.skipTest("PPTX fixture not available")
content = PPTX_SAMPLE.read_bytes()
out, ext = normalize_ppt_bytes(content, "pptx")
self.assertEqual(out, content)
self.assertEqual(ext, ".pptx")
def test_legacy_ppt_requires_soffice(self):
if not LEGACY_PPT.is_file():
self.skipTest("legacy PPT fixture not available")
if not shutil.which("soffice"):
with self.assertRaises(ValueError) as ctx:
normalize_ppt_bytes(LEGACY_PPT.read_bytes(), "ppt")
self.assertIn("LibreOffice", str(ctx.exception))
self.skipTest("LibreOffice not available")
converted = convert_ppt_to_pptx_bytes(LEGACY_PPT.read_bytes(), suffix=".ppt")
self.assertIsNotNone(converted)
self.assertTrue(is_zip_openxml(converted))
out, ext = normalize_ppt_bytes(LEGACY_PPT.read_bytes(), "ppt")
self.assertEqual(ext, ".pptx")
self.assertTrue(is_zip_openxml(out))
def test_wmf_legacy_ppt_extracts_rasterized_image(self):
if not shutil.which("soffice"):
self.skipTest("LibreOffice not available")
if not shutil.which("convert"):
self.skipTest("ImageMagick convert not available")
if not WMF_IMAGE_PPT.is_file():
self.skipTest("testdata missing")
from docreader.parser.markitdown_parser import MarkitdownParser
doc = MarkitdownParser(file_type="ppt").parse_into_text(
WMF_IMAGE_PPT.read_bytes()
)
self.assertEqual(len(doc.images), 1)
self.assertNotIn("bd10496_.jpg", doc.content)
self.assertIn("images/", doc.content)
def test_image_heavy_legacy_ppt_extracts_images(self):
if not shutil.which("soffice"):
self.skipTest("LibreOffice not available")
if not IMAGE_HEAVY_PPT.is_file():
self.skipTest("testdata missing")
from docreader.parser.markitdown_parser import MarkitdownParser
doc = MarkitdownParser(file_type="ppt").parse_into_text(
IMAGE_HEAVY_PPT.read_bytes()
)
self.assertGreaterEqual(len(doc.images), 2)
self.assertNotIn("![](.jpg)", doc.content)
for ref in doc.images:
self.assertTrue(ref.startswith("images/"))
if __name__ == "__main__":
unittest.main()
+371
View File
@@ -0,0 +1,371 @@
import base64
import io
import re
import shutil
import unittest
import zipfile
from unittest.mock import patch
from lxml import etree
from markitdown import MarkItDown
from PIL import Image
from pptx import Presentation
from pptx.opc.constants import RELATIONSHIP_TYPE
from pptx.oxml.ns import qn
from pptx.util import Inches
from docreader.parser import pptx_media
from docreader.parser.markitdown_parser import MarkitdownParser, StdMarkitdownParser
RED = (220, 30, 40)
BLUE = (30, 80, 220)
GREEN = (20, 170, 70)
IMAGE = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
def png(color):
output = io.BytesIO()
Image.new("RGB", (16, 16), color).save(output, format="PNG")
return output.getvalue()
def deck(colors, names=None, grouped=False, reverse_slides=False):
presentation = Presentation()
for index, color in enumerate(colors):
slide = presentation.slides.add_slide(presentation.slide_layouts[6])
shapes = slide.shapes.add_group_shape().shapes if grouped else slide.shapes
picture = shapes.add_picture(io.BytesIO(png(color)), Inches(1), Inches(1))
picture.name = names[index] if names else f"picture{index}"
picture._element._nvXxPr.cNvPr.set("descr", f"position{index}")
if reverse_slides:
ids = presentation.slides._sldIdLst
for child in list(ids):
ids.remove(child)
ids.insert(0, child)
output = io.BytesIO()
presentation.save(output)
return output.getvalue()
def rewrite_archive(data, *, reverse_media=False, unused=False, corrupt_first=False):
with zipfile.ZipFile(io.BytesIO(data)) as archive:
files = {name: archive.read(name) for name in archive.namelist()}
media = [name for name in files if name.startswith("ppt/media/")]
if corrupt_first:
files[media[0]] = b"not an image"
if reverse_media:
media.reverse()
if unused:
name = "ppt/media/unused.png"
files[name] = png(GREEN)
media.insert(0, name)
output = io.BytesIO()
with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
for name, blob in files.items():
if name not in media:
archive.writestr(name, blob)
for name in media:
archive.writestr(name, files[name])
return output.getvalue()
def fallback(data):
markdown = (
MarkItDown()
.convert(io.BytesIO(data), file_extension=".pptx", keep_data_uris=False)
.text_content
)
return pptx_media.attach_pptx_media_to_markdown(markdown, data)
def image_colors(markdown, images):
colors = []
for target in IMAGE.findall(markdown):
if target not in images:
colors.append(None)
continue
raw = base64.b64decode(images[target])
with Image.open(io.BytesIO(raw)) as image:
colors.append(image.convert("RGB").getpixel((8, 8)))
return colors
class TestPptxMediaAssociation(unittest.TestCase):
def test_document_order_control(self):
markdown, images = fallback(deck([RED, BLUE]))
self.assertEqual(image_colors(markdown, images), [RED, BLUE])
def test_zip_entry_order_does_not_change_which_picture_is_attached(self):
data = rewrite_archive(deck([RED, BLUE]), reverse_media=True)
markdown, images = fallback(data)
self.assertEqual(image_colors(markdown, images), [RED, BLUE])
def test_unused_media_does_not_replace_a_visible_picture(self):
data = rewrite_archive(deck([RED, BLUE]), unused=True)
markdown, images = fallback(data)
self.assertEqual(image_colors(markdown, images), [RED, BLUE])
def test_shared_image_is_attached_at_every_placement(self):
markdown, images = fallback(deck([RED, RED, BLUE]))
self.assertEqual(image_colors(markdown, images), [RED, RED, BLUE])
def test_failed_conversion_does_not_take_the_next_picture(self):
data = rewrite_archive(deck([RED, BLUE]), corrupt_first=True)
# A missing converter is a supported deployment condition. The bad
# PNG still exercises Pillow's actual decode failure.
with patch.object(pptx_media, "_find_convert", return_value=None):
markdown, images = fallback(data)
self.assertEqual(image_colors(markdown, images), [None, BLUE])
def test_duplicate_shape_names_keep_each_placement(self):
data = deck([RED, BLUE], names=["Picture 1", "Picture 1"])
markdown, images = fallback(data)
self.assertEqual(image_colors(markdown, images), [RED, BLUE])
def test_names_that_share_a_placeholder_keep_each_placement(self):
data = rewrite_archive(
deck([RED, BLUE], names=["Picture-1", "Picture 1"]), reverse_media=True
)
markdown, images = fallback(data)
self.assertEqual(image_colors(markdown, images), [RED, BLUE])
def test_presentation_order_takes_precedence_over_slide_filenames(self):
markdown, images = fallback(deck([RED, BLUE], reverse_slides=True))
self.assertEqual(image_colors(markdown, images), [BLUE, RED])
def test_same_slide_duplicate_names_follow_position_order(self):
# MarkItDown orders shapes by (top, left), not z-order.
for grouped in (False, True):
with self.subTest(grouped=grouped):
presentation = Presentation()
slide = presentation.slides.add_slide(presentation.slide_layouts[6])
shapes = (
slide.shapes.add_group_shape().shapes if grouped else slide.shapes
)
for color, top in ((RED, 4), (BLUE, 1)):
picture = shapes.add_picture(
io.BytesIO(png(color)), Inches(1), Inches(top)
)
picture.name = "Picture 1"
output = io.BytesIO()
presentation.save(output)
markdown, images = fallback(output.getvalue())
self.assertEqual(image_colors(markdown, images), [BLUE, RED])
def test_grouped_pictures_keep_their_source(self):
data = rewrite_archive(deck([RED, BLUE], grouped=True), reverse_media=True)
markdown, images = fallback(data)
self.assertEqual(image_colors(markdown, images), [RED, BLUE])
def test_external_picture_does_not_consume_the_next_embedded_image(self):
presentation = Presentation(io.BytesIO(deck([RED, BLUE])))
slide = presentation.slides[0]
picture = slide.shapes[0]
blip = picture._element.blipFill.blip
slide.part.drop_rel(blip.rEmbed)
del blip.attrib[qn("r:embed")]
relationship = slide.part.relate_to(
"https://example.invalid/external.png",
RELATIONSHIP_TYPE.IMAGE,
is_external=True,
)
blip.set(qn("r:link"), relationship)
output = io.BytesIO()
presentation.save(output)
markdown, images = fallback(output.getvalue())
self.assertEqual(image_colors(markdown, images), [None, BLUE])
def test_unrelated_links_and_unknown_placeholders_stay_unchanged(self):
data = deck([RED])
original = (
MarkItDown()
.convert(io.BytesIO(data), file_extension=".pptx", keep_data_uris=False)
.text_content
)
prefix = (
"![web](https://example.invalid/image.png)\n"
"![inline](data:image/png;base64,eA==)\n"
"![unknown](not-a-picture.jpg)\n"
)
markdown, images = pptx_media.attach_pptx_media_to_markdown(
prefix + original, data
)
self.assertTrue(markdown.startswith(prefix))
self.assertEqual(image_colors(markdown, images)[-1], RED)
def deck_with_broken_picture(mutate):
"""One slide: text, a good RED picture, then a BLUE picture `mutate` breaks."""
presentation = Presentation()
slide = presentation.slides.add_slide(presentation.slide_layouts[6])
textbox = slide.shapes.add_textbox(Inches(1), Inches(0.1), Inches(4), Inches(0.5))
textbox.text_frame.text = "SLIDE TEXT OK"
good = slide.shapes.add_picture(io.BytesIO(png(RED)), Inches(1), Inches(1))
good.name = "good"
bad = slide.shapes.add_picture(io.BytesIO(png(BLUE)), Inches(1), Inches(3))
bad.name = "bad"
media = mutate(slide, bad)
output = io.BytesIO()
presentation.save(output)
data = output.getvalue()
if media is None:
return data
# Drop the picture's media part from the package: python-pptx then drops
# the relationship at load time while the slide XML still points at it.
with zipfile.ZipFile(io.BytesIO(data)) as archive:
files = {name: archive.read(name) for name in archive.namelist()}
del files[media]
output = io.BytesIO()
with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
for name, blob in files.items():
archive.writestr(name, blob)
return output.getvalue()
def remove_blip(slide, picture):
blip = picture._element.blipFill.blip
blip.getparent().remove(blip)
def remove_blip_fill(slide, picture):
blip_fill = picture._element.blipFill
blip_fill.getparent().remove(blip_fill)
def dangling_embed(slide, picture):
picture._element.blipFill.blip.set(qn("r:embed"), "rId999")
def external_embed(slide, picture):
relationship = slide.part.relate_to(
"https://example.invalid/external.png",
RELATIONSHIP_TYPE.IMAGE,
is_external=True,
)
picture._element.blipFill.blip.set(qn("r:embed"), relationship)
def missing_media_part(slide, picture):
part = slide.part.related_part(picture._element.blipFill.blip.rEmbed)
return str(part.partname).lstrip("/")
class TestPptxMediaBrokenPictureRelationships(unittest.TestCase):
def test_broken_picture_keeps_the_document_and_other_pictures(self):
for mutate in (
remove_blip,
remove_blip_fill,
dangling_embed,
external_embed,
missing_media_part,
):
with self.subTest(mutate.__name__):
data = deck_with_broken_picture(mutate)
document = StdMarkitdownParser(
file_name="deck.pptx", file_type="pptx"
).parse_into_text(data)
self.assertIn("SLIDE TEXT OK", document.content)
self.assertEqual(
image_colors(document.content, document.images), [RED, None]
)
self.assertIn("(bad.jpg)", document.content)
parsed = MarkitdownParser(
file_name="deck.pptx", file_type="pptx"
).parse(data)
self.assertIn("SLIDE TEXT OK", parsed.content)
class TestPptxMediaRealFallback(unittest.TestCase):
@unittest.skipUnless(shutil.which("convert"), "ImageMagick is not installed")
def test_svg_fallback_preserves_picture_order(self):
# SVG is valid Office media, but Pillow cannot identify it. That makes
# pinned MarkItDown 0.1.3 naturally enter the actual fallback path.
data = deck([RED, BLUE])
with zipfile.ZipFile(io.BytesIO(data)) as archive:
files = {name: archive.read(name) for name in archive.namelist()}
original = "ppt/media/image2.png"
replacement = "ppt/media/image2.svg"
files[replacement] = (
b'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">'
b'<rect width="16" height="16" fill="#1e50dc"/></svg>'
)
del files[original]
for name, blob in list(files.items()):
if name.endswith(".rels"):
files[name] = blob.replace(b"image2.png", b"image2.svg")
types = etree.fromstring(files["[Content_Types].xml"])
etree.SubElement(
types,
"{http://schemas.openxmlformats.org/package/2006/content-types}Default",
Extension="svg",
ContentType="image/svg+xml",
)
files["[Content_Types].xml"] = etree.tostring(types)
output = io.BytesIO()
with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr(replacement, files.pop(replacement))
for name, blob in files.items():
archive.writestr(name, blob)
with self.assertLogs("docreader.parser.markitdown_parser", level="WARNING"):
document = MarkitdownParser(file_type="pptx").parse(output.getvalue())
self.assertEqual(image_colors(document.content, document.images), [RED, BLUE])
class TestPptxRasterTransparency(unittest.TestCase):
def assert_png_pixels_preserved(self, image, image_format="PNG"):
source = io.BytesIO()
image.save(source, format=image_format)
raw = source.getvalue()
with Image.open(io.BytesIO(raw)) as original:
expected = original.convert("RGBA").tobytes()
size = original.size
suffix = ".jpg" if image_format == "JPEG" else ".png"
with patch.object(
pptx_media, "_rasterize_with_imagemagick", side_effect=AssertionError
):
result = pptx_media.rasterize_media_bytes("picture" + suffix, raw)
self.assertIsNotNone(result)
with Image.open(io.BytesIO(result)) as converted:
self.assertEqual(converted.format, "PNG")
self.assertEqual(converted.size, size)
self.assertEqual(converted.convert("RGBA").tobytes(), expected)
def test_rgba_alpha_is_preserved(self):
image = Image.new("RGBA", (3, 1))
image.putdata([(255, 0, 0, 0), (0, 255, 0, 96), (0, 0, 255, 255)])
self.assert_png_pixels_preserved(image)
def test_grayscale_alpha_is_preserved(self):
image = Image.new("LA", (3, 1))
image.putdata([(10, 0), (90, 96), (230, 255)])
self.assert_png_pixels_preserved(image)
def palette_image(self):
image = Image.new("P", (3, 1))
image.putpalette([30, 50, 70, 90, 110, 130, 150, 170, 190] + [0] * 759)
image.putdata([0, 1, 2])
return image
def test_palette_alpha_table_is_preserved(self):
image = self.palette_image()
image.info["transparency"] = bytes([0, 96, 255])
self.assert_png_pixels_preserved(image)
def test_palette_transparent_index_is_preserved(self):
image = self.palette_image()
image.info["transparency"] = 1
self.assert_png_pixels_preserved(image)
def test_rgb_control_is_unchanged(self):
self.assert_png_pixels_preserved(Image.new("RGB", (3, 1), (20, 40, 60)))
def test_cmyk_jpeg_still_converts_to_rgb(self):
self.assert_png_pixels_preserved(
Image.new("CMYK", (3, 1), (0, 255, 255, 0)), image_format="JPEG"
)
if __name__ == "__main__":
unittest.main()
+292
View File
@@ -0,0 +1,292 @@
import io
import json
import os
from pathlib import Path
import tempfile
import sys
import threading
import time
import unittest
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import patch
import grpc
import numpy as np
from PIL import Image
from docreader.preprocess import MAX_IMAGE_BYTES, PreprocessLimits, PreprocessRunner
from docreader.preprocess_worker import process_image
from docreader.proto import docreader_pb2 as pb, docreader_pb2_grpc as rpc
class RequestContext:
def __init__(self, remaining=None):
self.cancelled = threading.Event()
self.remaining = remaining
def is_active(self):
return not self.cancelled.is_set()
def time_remaining(self):
return self.remaining
def wait_for(predicate, timeout=5):
end = time.monotonic() + timeout
while time.monotonic() < end:
value = predicate()
if value:
return value
time.sleep(0.01)
raise AssertionError("Timed out waiting for subprocess state")
def process_gone(pid):
try:
os.kill(pid, 0)
return False
except ProcessLookupError:
return True
class RunnerTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.pool = ThreadPoolExecutor(max_workers=2)
self.addCleanup(self.pool.shutdown, wait=True)
def runner(self, **limits):
runner = PreprocessRunner(PreprocessLimits(**limits),
worker_module="docreader.tests.preprocess_worker_fixture")
self.addCleanup(runner.close)
return runner
def blocking_command(self, **extra):
started = Path(self.temp.name) / "started"
release = Path(self.temp.name) / "release"
command = json.dumps(dict(started=str(started), release=str(release), **extra)).encode()
return command, started, release
def started_pid(self, path):
return int(wait_for(lambda: path.read_text() if path.exists() else ""))
def assert_reaped(self, pid):
wait_for(lambda: process_gone(pid))
def test_busy_declines_without_waiting_or_loading_a_second_engine(self):
runner = self.runner()
command, started, release = self.blocking_command()
first = self.pool.submit(runner.run, command, None)
pid = self.started_pid(started)
before = time.monotonic()
try:
response = runner.run(b"{}", None)
self.assertTrue(response.fallback_needed)
self.assertEqual(response.status, "busy")
self.assertLess(time.monotonic() - before, 0.5)
finally:
release.touch()
self.assertEqual(first.result(timeout=5).status, "ok")
self.assertEqual(int(runner.run(b"{}", None).image), pid, "successful calls reuse one worker")
def test_timeout_kills_running_native_work_and_releases_capacity(self):
runner = self.runner(timeout_seconds=1.5)
command, started, _ = self.blocking_command()
future = self.pool.submit(runner.run, command, None)
pid = self.started_pid(started)
response = future.result(timeout=5)
self.assertEqual(response.status, "timeout")
self.assertTrue(response.fallback_needed)
self.assert_reaped(pid)
next_response = runner.run(b"{}", None)
self.assertEqual(next_response.status, "ok")
self.assertNotEqual(int(next_response.image), pid)
def test_client_deadline_shortens_server_timeout(self):
runner = self.runner(timeout_seconds=30)
command, started, _ = self.blocking_command()
before = time.monotonic()
future = self.pool.submit(runner.run, command, RequestContext(remaining=1.5))
pid = self.started_pid(started)
self.assertEqual(future.result(timeout=5).status, "timeout")
self.assertLess(time.monotonic() - before, 5)
self.assert_reaped(pid)
def test_timeout_interrupts_a_partial_response(self):
runner = self.runner(timeout_seconds=1.5)
command, started, _ = self.blocking_command(partial_reply=True)
future = self.pool.submit(runner.run, command, None)
pid = self.started_pid(started)
self.assertEqual(future.result(timeout=5).status, "timeout")
self.assert_reaped(pid)
def test_cancellation_interrupts_blocked_image_transfer(self):
runner = self.runner()
started = Path(self.temp.name) / "started"
context = RequestContext()
with patch.dict(os.environ, {"PREPROCESS_FIXTURE_STALL_INPUT": str(started)}):
future = self.pool.submit(runner.run, b"x" * MAX_IMAGE_BYTES, context)
pid = self.started_pid(started)
context.cancelled.set()
self.assertEqual(future.result(timeout=5).status, "cancelled")
self.assert_reaped(pid)
self.assertEqual(runner.run(b"{}", None).status, "ok")
def test_cancelled_request_never_starts_a_worker(self):
runner = self.runner()
context = RequestContext()
context.cancelled.set()
with patch.object(runner, "_start_worker") as start:
self.assertEqual(runner.run(b"{}", context).status, "cancelled")
start.assert_not_called()
def test_memory_limit_kills_worker_and_allows_next_request(self):
runner = self.runner(memory_mb=96)
command, started, _ = self.blocking_command(memory=160 * 1024 * 1024)
future = self.pool.submit(runner.run, command, None)
pid = self.started_pid(started)
response = future.result(timeout=5)
self.assertEqual(response.status, "memory_limit")
self.assertTrue(response.fallback_needed)
self.assert_reaped(pid)
self.assertEqual(runner.run(b"{}", None).status, "ok")
def test_worker_crash_is_recovered_on_next_request(self):
runner = self.runner()
self.assertTrue(runner.run(b'{"crash":true}', None).fallback_needed)
self.assertEqual(runner.run(b"{}", None).status, "ok")
@unittest.skipUnless(sys.platform.startswith("linux"), "RLIMIT_AS is enforced in Linux containers")
def test_linux_worker_has_hard_address_space_limit(self):
runner = self.runner(memory_mb=128)
response = runner.run(b'{"check_address_limit":true}', None)
self.assertEqual(response.status, "ok")
self.assertEqual(json.loads(response.image), [128 * 1024 * 1024] * 2)
def test_close_kills_active_work_and_refuses_new_requests(self):
runner = self.runner()
command, started, _ = self.blocking_command()
future = self.pool.submit(runner.run, command, None)
pid = self.started_pid(started)
runner.close()
self.assert_reaped(pid)
self.assertTrue(future.result(timeout=5).fallback_needed)
self.assertEqual(runner.run(b"{}", None).status, "cancelled")
def test_oversized_message_is_declined_before_spawn(self):
runner = self.runner()
with patch.object(runner, "_start_worker") as start:
response = runner.run(b"x" * (MAX_IMAGE_BYTES + 1), None)
self.assertEqual(response.status, "image_too_large")
start.assert_not_called()
def test_grpc_cancellation_reaps_worker_without_blocking_normal_rpcs(self):
from docreader.main import DocReaderServicer
runner = self.runner()
servicer = DocReaderServicer(preprocess_runner=runner)
self.addCleanup(servicer.close)
with ThreadPoolExecutor(max_workers=1) as ordinary_pool:
server = grpc.server(ordinary_pool)
rpc.add_DocReaderServicer_to_server(servicer, server)
port = server.add_insecure_port("127.0.0.1:0")
server.start()
try:
with grpc.insecure_channel(f"127.0.0.1:{port}") as channel:
stub = rpc.DocReaderStub(channel)
command, started, _ = self.blocking_command()
call = stub.PreprocessImage.future(pb.PreprocessImageRequest(image=command), timeout=15)
pid = self.started_pid(started)
# With only one ordinary RPC thread, using the same executor
# for preprocessing would make this request time out.
response = stub.ListEngines(pb.ListEnginesRequest(), timeout=2)
self.assertTrue(response.engines)
document = stub.Read(pb.ReadRequest(
file_content=b"# Ordinary document\n\nStill readable.",
file_name="ordinary.md", file_type="md"), timeout=2)
self.assertIn("Still readable", document.markdown_content)
busy = stub.PreprocessImage(pb.PreprocessImageRequest(image=b"{}"), timeout=2)
self.assertEqual(busy.status, "busy")
self.assertTrue(call.cancel())
self.assert_reaped(pid)
wait_for(lambda: not runner._idle.empty())
self.assertEqual(stub.PreprocessImage(
pb.PreprocessImageRequest(image=b"{}"), timeout=5).status, "ok")
finally:
server.stop(0).wait()
class ImageBudgetTest(unittest.TestCase):
def image(self, size):
out = io.BytesIO()
Image.new("RGB", size, "white").save(out, format="PNG")
return out.getvalue()
def test_pixel_limit_is_checked_before_native_decode(self):
with patch("cv2.imdecode") as decode, patch("docreader.parser.image_preprocess.preprocess") as preprocess:
response = process_image(self.image((20, 20)), PreprocessLimits(max_pixels=100))
self.assertEqual(response.status, "image_too_large")
decode.assert_not_called()
preprocess.assert_not_called()
def test_crop_keeps_original_resolution_when_under_the_output_cap(self):
# A 4000x4000 page whose only content is a 500x500 block: detect on a
# 2000 probe, but crop the original, so the block stays 500x500.
shapes = []
quad_probe = np.array([[0, 0], [250, 0], [250, 250], [0, 250]], "float32")
def inspect(img):
shapes.append(img.shape[:2])
return {"status": "ok", "rect": np.zeros((10, 10, 3), "uint8"),
"quad_input": quad_probe, "n_boxes": 4, "n_kept": 4,
"residual": 0.0, "flip": False}
with patch("docreader.parser.image_preprocess.preprocess", side_effect=inspect):
response = process_image(self.image((4000, 4000)),
PreprocessLimits(probe_edge=2000, max_edge=2000))
self.assertEqual(shapes, [(2000, 2000)])
self.assertEqual(response.status, "ok")
with Image.open(io.BytesIO(response.image)) as encoded:
self.assertEqual(encoded.size, (500, 500))
def test_output_is_capped_after_cropping(self):
quad_probe = np.array([[0, 0], [200, 0], [200, 200], [0, 200]], "float32")
def inspect(img):
return {"status": "ok", "rect": np.zeros((10, 10, 3), "uint8"),
"quad_input": quad_probe, "n_boxes": 4, "n_kept": 4,
"residual": 0.0, "flip": False}
with patch("docreader.parser.image_preprocess.preprocess", side_effect=inspect):
response = process_image(self.image((400, 400)),
PreprocessLimits(probe_edge=200, max_edge=100))
self.assertEqual(response.status, "ok")
with Image.open(io.BytesIO(response.image)) as encoded:
self.assertEqual(encoded.size, (100, 100))
def test_small_input_uses_the_crop_directly(self):
rect = np.full((40, 30, 3), 200, "uint8")
def inspect(img):
return {"status": "ok", "rect": rect, "n_boxes": 4, "n_kept": 4,
"residual": 0.0, "flip": False}
with patch("docreader.parser.image_preprocess.preprocess", side_effect=inspect):
response = process_image(self.image((200, 200)), PreprocessLimits(probe_edge=200))
self.assertEqual(response.status, "ok")
with Image.open(io.BytesIO(response.image)) as encoded:
self.assertEqual(encoded.size, (30, 40))
def test_bad_image_and_declined_geometry_keep_original(self):
self.assertTrue(process_image(b"not an image", PreprocessLimits()).fallback_needed)
with patch("docreader.parser.image_preprocess.preprocess",
return_value={"status": "ok", "rect": object(), "residual": 3}):
response = process_image(self.image((20, 20)), PreprocessLimits())
self.assertTrue(response.fallback_needed)
self.assertEqual(response.status, "low_quality")
self.assertFalse(response.image)
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
import threading
import unittest
import weakref
from unittest.mock import patch
from docreader.utils.request_memory import (
RequestThreadPoolExecutor,
track_request_size,
)
class RequestMemoryTest(unittest.TestCase):
def test_large_request_is_reclaimed_after_worker_locals_are_released(self):
references = []
class Payload:
pass
def rpc_task():
payload = Payload()
references.append(weakref.ref(payload))
track_request_size(64 * 1024 * 1024)
return "completed"
def collect():
self.assertIsNone(references[0]())
with patch("docreader.utils.request_memory.gc.collect", side_effect=collect) as gc_collect:
with patch("docreader.utils.request_memory._malloc_trim") as trim:
with RequestThreadPoolExecutor(max_workers=1) as pool:
self.assertEqual(pool.submit(rpc_task).result(), "completed")
self.assertEqual(pool.submit(lambda: "small").result(), "small")
gc_collect.assert_called_once_with()
trim.assert_called_once_with(0)
def test_failed_large_request_is_reclaimed(self):
def rpc_task():
track_request_size(64 * 1024 * 1024)
raise ValueError("parse failed")
with patch("docreader.utils.request_memory.gc.collect") as gc_collect:
with patch("docreader.utils.request_memory._malloc_trim") as trim:
with RequestThreadPoolExecutor(max_workers=1) as pool:
with self.assertRaisesRegex(ValueError, "parse failed"):
pool.submit(rpc_task).result()
gc_collect.assert_called_once_with()
trim.assert_called_once_with(0)
def test_small_requests_do_not_trigger_collection(self):
def rpc_task():
track_request_size(1024)
return 42
with patch("docreader.utils.request_memory.gc.collect") as gc_collect:
with patch("docreader.utils.request_memory._malloc_trim") as trim:
with RequestThreadPoolExecutor(max_workers=1) as pool:
self.assertEqual(pool.submit(rpc_task).result(), 42)
gc_collect.assert_not_called()
trim.assert_not_called()
def test_collection_works_without_malloc_trim(self):
with patch("docreader.utils.request_memory.gc.collect") as gc_collect:
with patch("docreader.utils.request_memory._malloc_trim", None):
with RequestThreadPoolExecutor(max_workers=1) as pool:
pool.submit(track_request_size, 64 * 1024 * 1024).result()
gc_collect.assert_called_once_with()
def test_cleanup_flag_is_local_to_the_large_request_worker(self):
barrier = threading.Barrier(2)
collected_on = []
def rpc_task(size):
track_request_size(size)
barrier.wait(timeout=5)
return threading.get_ident()
with patch(
"docreader.utils.request_memory.gc.collect",
side_effect=lambda: collected_on.append(threading.get_ident()),
):
with patch("docreader.utils.request_memory._malloc_trim") as trim:
with RequestThreadPoolExecutor(max_workers=2) as pool:
large = pool.submit(rpc_task, 64 * 1024 * 1024)
small = pool.submit(rpc_task, 1024)
large_thread = large.result()
self.assertNotEqual(large_thread, small.result())
self.assertEqual(collected_on, [large_thread])
trim.assert_called_once_with(0)
if __name__ == "__main__":
unittest.main()
+292
View File
@@ -0,0 +1,292 @@
import os
import shlex
import signal
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path
from unittest.mock import ANY, Mock, call, patch
from docreader.parser.doc_parser import SandboxExecutor
def _mock_process(pid=4321):
process = Mock(pid=pid)
process.stdout = Mock()
process.stderr = Mock()
return process
@unittest.skipUnless(os.name == "posix", "process-group cleanup is POSIX-specific")
class TestSandboxExecutorProcessGroup(unittest.TestCase):
def test_timeout_kills_whole_process_group(self):
"""A timed-out command must terminate its parent and descendants."""
with tempfile.TemporaryDirectory() as temp_dir:
child_pid_file = Path(temp_dir) / "child.pid"
command = [
"sh",
"-c",
f"sleep 30 & echo $! > {shlex.quote(str(child_pid_file))}; wait",
]
executor = SandboxExecutor(default_timeout=1)
with self.assertRaises(RuntimeError):
executor.execute_in_sandbox(command)
child_pid = int(child_pid_file.read_text().strip())
deadline = time.monotonic() + 1
while True:
try:
os.kill(child_pid, 0)
except ProcessLookupError:
break
if time.monotonic() >= deadline:
self.fail("timed-out command left a child process running")
time.sleep(0.01)
def test_timeout_returns_when_descendant_leaves_process_group(self):
"""setsid descendants can survive killpg; cleanup must still return."""
with tempfile.TemporaryDirectory() as temp_dir:
child_pid_file = Path(temp_dir) / "child.pid"
command = [
sys.executable,
"-c",
(
"import os, time\n"
f"pid_file = {str(child_pid_file)!r}\n"
"if os.fork() == 0:\n"
" os.setsid()\n"
" with open(pid_file, 'w', encoding='utf-8') as handle:\n"
" handle.write(str(os.getpid()))\n"
" time.sleep(60)\n"
"time.sleep(30)\n"
),
]
executor = SandboxExecutor(default_timeout=1)
started = time.monotonic()
with self.assertRaises(RuntimeError):
executor.execute_in_sandbox(command)
self.assertLess(
time.monotonic() - started,
4,
"timeout cleanup hung waiting on an escaped descendant",
)
deadline = time.monotonic() + 2
while not child_pid_file.exists() or not child_pid_file.stat().st_size:
if time.monotonic() >= deadline:
self.fail("escaped child did not write its pid file")
time.sleep(0.01)
child_pid = int(child_pid_file.read_text().strip())
try:
os.kill(child_pid, 0)
except ProcessLookupError:
self.fail("expected setsid descendant to survive process-group kill")
try:
os.kill(child_pid, signal.SIGKILL)
except ProcessLookupError:
pass
class TestSandboxExecutorMock(unittest.TestCase):
@unittest.skipUnless(os.name == "posix", "POSIX signals are required")
def test_posix_timeout_terminates_group_and_reaps_process(self):
process = _mock_process()
process.communicate.side_effect = [subprocess.TimeoutExpired(["soffice"], 1)]
process.wait.side_effect = [
subprocess.TimeoutExpired(["soffice"], 0.5),
0,
]
with (
patch("docreader.parser.doc_parser.os.name", "posix"),
patch(
"docreader.parser.doc_parser.subprocess.Popen", return_value=process
) as popen,
patch("docreader.parser.doc_parser.os.killpg") as killpg,
patch(
"docreader.parser.doc_parser.time.monotonic", side_effect=[0, 0.5]
),
patch("docreader.parser.doc_parser.time.sleep") as sleep,
):
with self.assertRaisesRegex(RuntimeError, "timeout after 1"):
SandboxExecutor(default_timeout=1)._execute_with_proxy(["soffice"])
popen.assert_called_once_with(
["soffice"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=ANY,
start_new_session=True,
)
killpg.assert_has_calls(
[
call(4321, signal.SIGTERM),
call(4321, signal.SIGKILL),
]
)
sleep.assert_not_called()
self.assertEqual(process.communicate.call_args_list, [call(timeout=1)])
self.assertEqual(
process.wait.call_args_list,
[call(timeout=0.5), call(timeout=1.0)],
)
process.stdout.close.assert_called_once_with()
process.stderr.close.assert_called_once_with()
@unittest.skipUnless(os.name == "posix", "POSIX signals are required")
def test_posix_timeout_waits_full_grace_period_when_child_exits_early(self):
process = _mock_process()
process.communicate.side_effect = [subprocess.TimeoutExpired(["soffice"], 1)]
process.wait.side_effect = [0, 0]
with (
patch("docreader.parser.doc_parser.os.name", "posix"),
patch(
"docreader.parser.doc_parser.subprocess.Popen", return_value=process
),
patch("docreader.parser.doc_parser.os.killpg") as killpg,
patch(
"docreader.parser.doc_parser.time.monotonic", side_effect=[10, 10.2]
),
patch("docreader.parser.doc_parser.time.sleep") as sleep,
):
with self.assertRaisesRegex(RuntimeError, "timeout after 1"):
SandboxExecutor(default_timeout=1)._execute_with_proxy(["soffice"])
self.assertAlmostEqual(sleep.call_args.args[0], 0.3)
killpg.assert_has_calls(
[
call(4321, signal.SIGTERM),
call(4321, signal.SIGKILL),
]
)
self.assertEqual(process.communicate.call_args_list, [call(timeout=1)])
self.assertEqual(
process.wait.call_args_list,
[call(timeout=0.5), call(timeout=1.0)],
)
@unittest.skipUnless(os.name == "posix", "POSIX signals are required")
def test_posix_timeout_reaps_when_group_already_exited(self):
process = _mock_process()
process.communicate.side_effect = [subprocess.TimeoutExpired(["soffice"], 1)]
process.wait.side_effect = [
subprocess.TimeoutExpired(["soffice"], 0.5),
0,
]
with (
patch("docreader.parser.doc_parser.os.name", "posix"),
patch(
"docreader.parser.doc_parser.subprocess.Popen", return_value=process
),
patch(
"docreader.parser.doc_parser.os.killpg",
side_effect=ProcessLookupError,
) as killpg,
patch(
"docreader.parser.doc_parser.time.monotonic", side_effect=[0, 0.5]
),
patch("docreader.parser.doc_parser.time.sleep") as sleep,
):
with self.assertRaisesRegex(RuntimeError, "timeout after 1"):
SandboxExecutor(default_timeout=1)._execute_with_proxy(["soffice"])
self.assertEqual(killpg.call_count, 2)
sleep.assert_not_called()
self.assertEqual(process.wait.call_args_list[-1], call(timeout=1.0))
@unittest.skipUnless(os.name == "posix", "POSIX signals are required")
def test_posix_timeout_reaps_when_killpg_raises_permission_error(self):
process = _mock_process()
process.communicate.side_effect = [subprocess.TimeoutExpired(["soffice"], 1)]
process.wait.side_effect = [
subprocess.TimeoutExpired(["soffice"], 0.5),
0,
]
with (
patch("docreader.parser.doc_parser.os.name", "posix"),
patch(
"docreader.parser.doc_parser.subprocess.Popen", return_value=process
),
patch(
"docreader.parser.doc_parser.os.killpg",
side_effect=PermissionError,
) as killpg,
patch(
"docreader.parser.doc_parser.time.monotonic", side_effect=[0, 0.5]
),
patch("docreader.parser.doc_parser.time.sleep") as sleep,
):
with self.assertRaisesRegex(RuntimeError, "timeout after 1"):
SandboxExecutor(default_timeout=1)._execute_with_proxy(["soffice"])
self.assertEqual(killpg.call_count, 2)
sleep.assert_not_called()
self.assertEqual(process.wait.call_args_list[-1], call(timeout=1.0))
process.stdout.close.assert_called_once_with()
@unittest.skipUnless(os.name == "posix", "POSIX signals are required")
def test_posix_timeout_returns_when_final_wait_times_out(self):
process = _mock_process()
process.communicate.side_effect = [subprocess.TimeoutExpired(["soffice"], 1)]
process.wait.side_effect = [
subprocess.TimeoutExpired(["soffice"], 0.5),
subprocess.TimeoutExpired(["soffice"], 1.0),
subprocess.TimeoutExpired(["soffice"], 1.0),
]
with (
patch("docreader.parser.doc_parser.os.name", "posix"),
patch(
"docreader.parser.doc_parser.subprocess.Popen", return_value=process
),
patch("docreader.parser.doc_parser.os.killpg"),
patch(
"docreader.parser.doc_parser.time.monotonic", side_effect=[0, 0.5]
),
patch("docreader.parser.doc_parser.time.sleep"),
):
with self.assertRaisesRegex(RuntimeError, "timeout after 1"):
SandboxExecutor(default_timeout=1)._execute_with_proxy(["soffice"])
self.assertEqual(process.kill.call_count, 1)
process.stdout.close.assert_called_once_with()
process.stderr.close.assert_called_once_with()
def test_non_posix_timeout_kills_direct_child_and_reaps_process(self):
process = _mock_process()
process.communicate.side_effect = [subprocess.TimeoutExpired(["soffice"], 1)]
process.wait.return_value = 0
with (
patch("docreader.parser.doc_parser.os.name", "nt"),
patch(
"docreader.parser.doc_parser.subprocess.Popen", return_value=process
) as popen,
patch("docreader.parser.doc_parser.os.killpg", create=True) as killpg,
):
with self.assertRaisesRegex(RuntimeError, "timeout after 1"):
SandboxExecutor(default_timeout=1)._execute_with_proxy(["soffice"])
popen.assert_called_once_with(
["soffice"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=ANY,
start_new_session=False,
)
process.kill.assert_called_once_with()
killpg.assert_not_called()
self.assertEqual(process.communicate.call_args_list, [call(timeout=1)])
self.assertEqual(process.wait.call_args_list, [call(timeout=1.0)])
process.stdout.close.assert_called_once_with()
process.stderr.close.assert_called_once_with()
if __name__ == "__main__":
unittest.main()
+179
View File
@@ -0,0 +1,179 @@
import json
import unittest
from docreader.models.document import Document
from docreader.parser.source_locator import (
PageGeometry,
locate_lines,
page_blocks,
)
def _ln(text, x0, y0, x1, y1):
return {"text": text, "bbox": (x0, y0, x1, y1)}
class LocateLinesTest(unittest.TestCase):
def test_finds_lines_in_order_and_pulls_in_leading_markup(self):
text = "## 标题\n【版权声明】\n正文 第一行\n正文 第一行"
hits = locate_lines(text, ["标题", "版权声明】", "正文第一行", "正文 第一行", "无此行"])
self.assertEqual(hits[0], 0)
self.assertEqual(text[hits[1]:hits[1] + 2], "【版")
self.assertEqual(hits[2], text.index("正文"))
self.assertEqual(hits[3], text.rindex("正文"))
self.assertIsNone(hits[4])
class PageGeometryTest(unittest.TestCase):
def test_flips_to_top_left_origin(self):
g = PageGeometry((0, 0, 200, 100))
self.assertEqual(g.bbox((20, 80, 100, 90)), [0.1, 0.1, 0.5, 0.2])
def test_applies_cropbox_offset_and_rotation(self):
g = PageGeometry((100, 100, 300, 200), rotation=90)
# Unrotated [0.1, 0.1, 0.5, 0.2] turns clockwise.
self.assertEqual(g.bbox((120, 180, 200, 190)), [0.8, 0.1, 0.9, 0.5])
class PageBlocksTest(unittest.TestCase):
def test_groups_lines_into_boxed_paragraphs(self):
page = (
"8.14.11 索夹与吊索施工应符合下列规定:\n"
"1 在满足施工需要的前提下,应减小猫道面层开孔面积,并应在开孔位置四周绑\n"
"扎防滑木条,设立警示标志。\n"
"2 索夹在主缆上定位后,应紧固螺栓。"
)
lines = [
_ln("8.14.11 索夹与吊索施工应符合下列规定:", 50, 700, 300, 712),
_ln("1 在满足施工需要的前提下,应减小猫道面层开孔面积,并应在开孔位置四周绑", 60, 684, 540, 696),
_ln("扎防滑木条,设立警示标志。", 50, 668, 200, 680),
_ln("2 索夹在主缆上定位后,应紧固螺栓。", 60, 652, 400, 664),
]
blocks = page_blocks(page, 10, 57, lines, PageGeometry((0, 0, 600, 800)))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[0]["start"], 10)
item1 = blocks[1]
self.assertEqual(page[item1["start"] - 10:item1["end"] - 10].split("\n")[0][:1], "1")
self.assertIn("设立警示标志。", page[item1["start"] - 10:item1["end"] - 10])
self.assertEqual(item1["locator"]["page"], 57)
x0, y0, x1, y1 = item1["locator"]["bbox"]
self.assertAlmostEqual(y0, 1 - 696 / 800, places=3)
self.assertAlmostEqual(y1, 1 - 668 / 800, places=3)
self.assertEqual(blocks[-1]["end"], 10 + len(page))
def test_page_without_lines_gets_page_block(self):
blocks = page_blocks("文字", 5, 2, [], None)
self.assertEqual(blocks, [{"start": 5, "end": 7, "locator": {"type": "pdf", "page": 2, "mapping": "exact"}}])
class WireTest(unittest.TestCase):
def test_source_blocks_serialize_and_skip_malformed(self):
from docreader.source_wire import source_blocks_to_proto
doc = Document(
content="abc",
source_blocks=[
{"start": 0, "end": 3, "locator": {"type": "pdf", "page": 1}},
{"start": 2, "end": 2, "locator": {"type": "pdf", "page": 1}},
{"start": 0, "end": 1},
],
)
wire = source_blocks_to_proto(doc)
self.assertEqual(len(wire), 1)
self.assertEqual(json.loads(wire[0].locator_json), {"type": "pdf", "page": 1})
class LocateColumnsTest(unittest.TestCase):
def test_repeated_line_follows_its_own_column(self):
text = (
"alpha left first line\nsame tail phrase here\n"
"bravo left third line\nsame tail phrase here\n"
"omega right first line\nsigma right second line"
)
left, right = (0, 100), (120, 220)
lines = [
("alpha left first line", left, 700),
("omega right first line", right, 700),
("same tail phrase here", left, 680),
("sigma right second line", right, 680),
("bravo left third line", left, 660),
("same tail phrase here", left, 640),
]
hits = locate_lines(
text,
[t for t, _, _ in lines],
[(x[0], y, x[1], y + 10) for _, x, y in lines],
)
self.assertEqual(hits[2], text.index("same tail"))
self.assertEqual(hits[5], text.rindex("same tail"))
def test_short_repeated_label_is_not_placed(self):
text = "Figure shows the LLM pipeline\nThe LLM is prompted twice"
hits = locate_lines(text, ["LLM", "The LLM is prompted twice"])
self.assertIsNone(hits[0])
self.assertEqual(hits[1], text.index("The LLM"))
class SplitLineAtGapsTest(unittest.TestCase):
@staticmethod
def _line(chars):
glyphs = [
{"ch": ch, "x0": x, "x1": x + 5, "y0": 0.0, "y1": 10.0, "i": i}
for ch, x, i in chars
]
return {"text": "".join(c for c, _, _ in chars), "bbox": (0, 0, 0, 0), "chars": glyphs}
def test_cuts_fused_columns_at_a_stream_jump(self):
from docreader.parser.pdf_parser import _split_line_at_gaps
left = [(ch, 10 + 5 * k, 100 + k) for k, ch in enumerate("left side")]
right = [(ch, 80 + 5 * k, 900 + k) for k, ch in enumerate("right side")]
parts = _split_line_at_gaps(self._line(left + right))
self.assertEqual([p["bbox"][0] for p in parts], [10, 80])
def test_keeps_a_wide_word_space_within_one_column(self):
from docreader.parser.pdf_parser import _split_line_at_gaps
chars = [(ch, 10 + 5 * k, k) for k, ch in enumerate("wide")]
chars += [(ch, 60 + 5 * k, 5 + k) for k, ch in enumerate("space")]
self.assertEqual(len(_split_line_at_gaps(self._line(chars))), 1)
class PrecisionRegressionTest(unittest.TestCase):
def test_common_prefix_cannot_place_a_different_conclusion(self):
prefix = "Common opening repeated before the important conclusion "
self.assertEqual(locate_lines(prefix + "failed", [prefix + "passed"]), [None])
def test_numeric_meaning_is_preserved(self):
for source, quote in [("limit 15 mm", "limit 1.5 mm"), ("temperature 5 C", "temperature -5 C"), ("rate 5", "rate 5%")]:
self.assertEqual(locate_lines(source, [quote]), [None])
def test_unaccounted_duplicate_does_not_take_first_region(self):
quote = "A repeated paragraph with enough text"
self.assertEqual(locate_lines(quote + "\n" + quote, [quote]), [None])
def test_unmatched_text_never_inherits_previous_geometry(self):
page = "First matched line.\nUnmatched evidence in between.\nLast matched line."
lines = [_ln("First matched line.", 50, 700, 300, 712), _ln("Last matched line.", 50, 668, 300, 680)]
blocks = page_blocks(page, 0, 2, lines, PageGeometry((0, 0, 600, 800)))
at = page.index("Unmatched")
covering = [b for b in blocks if b["start"] <= at < b["end"]]
self.assertEqual(len(covering), 1)
self.assertNotIn("bbox", covering[0]["locator"])
self.assertEqual(covering[0]["locator"]["page"], 2)
def test_trailing_unmatched_text_has_only_page_provenance(self):
page = "Matched paragraph.\nUnrecognized trailing evidence."
blocks = page_blocks(page, 0, 7, [_ln("Matched paragraph.", 50, 700, 300, 712)], PageGeometry((0, 0, 600, 800)))
self.assertEqual(blocks[0]["end"], page.index("Unrecognized"))
self.assertNotIn("bbox", blocks[-1]["locator"])
def test_wire_preserves_verified_geometry_and_identity(self):
from docreader.source_wire import source_blocks_to_proto
locator = {"type": "pdf", "page": 501, "mapping": "exact", "source_id": "pdf:501:0:3", "bbox": [.1, .2, .8, .4]}
wire = source_blocks_to_proto(Document(content="abc", source_blocks=[{"start": 0, "end": 3, "locator": locator}]))
self.assertEqual(json.loads(wire[0].locator_json), locator)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,78 @@
"""Actual PDFium parsing through source blocks and the protobuf JSON boundary."""
import json
import unittest
from unittest.mock import patch
from docreader.parser.pdf_parser import PDFParser
from docreader.source_wire import source_blocks_to_proto
from docreader.tests.test_pdf_embedded_images import _pdf_from_objects
def pdf_fixture(pages):
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
("<< /Type /Pages /Count %d /Kids [%s] >>" % (
len(pages), " ".join(f"{4+i*2} 0 R" for i in range(len(pages)))
)).encode(),
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
]
for i, page in enumerate(pages):
stream = "\n".join(f"BT /F1 14 Tf {x} {y} Td ({text}) Tj ET" for text, x, y in page["lines"]).encode()
objects.extend([
(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Rotate {page.get('rotation', 0)} "
f"{page.get('crop', '')} /Resources << /Font << /F1 3 0 R >> >> /Contents {5+i*2} 0 R >>").encode(),
f"<< /Length {len(stream)} >>\nstream\n".encode() + stream + b"\nendstream",
])
return _pdf_from_objects(objects)
class NativePDFSourceTest(unittest.TestCase):
def parse(self, pages):
with patch("docreader.parser.pdf_parser.SOURCE_BOXES", True):
doc = PDFParser(file_name="source-regression.pdf", file_type="pdf", pdf_force_scanned=False).parse_into_text(pdf_fixture(pages))
self.assertFalse(doc.metadata.get("scanned_page_count"))
return doc
def test_page_and_region_survive_actual_parser_and_wire(self):
doc = self.parse([
{"lines": [("First page has independent original evidence.", 60, 700)]},
{"lines": [("Second page upper paragraph is unrelated.", 60, 700),
("Second page lower evidence: the limit is 1.5 mm.", 60, 400)]},
])
at = doc.content.index("Second page lower evidence")
source = [b for b in doc.source_blocks if b["start"] <= at < b["end"]]
self.assertEqual(len(source), 1)
loc = source[0]["locator"]
self.assertEqual(loc["page"], 2)
self.assertEqual(loc["mapping"], "exact")
self.assertGreater(loc["bbox"][1], .45)
self.assertLess(loc["bbox"][3], .55)
self.assertIn("1.5 mm", doc.content[source[0]["start"]:source[0]["end"]])
self.assertIn(loc, [json.loads(b.locator_json) for b in source_blocks_to_proto(doc)])
def test_cropbox_and_rotation_use_displayed_page_coordinates(self):
for rotation in (0, 90, 180, 270):
with self.subTest(rotation=rotation):
doc = self.parse([{"rotation": rotation, "crop": "/CropBox [100 100 500 700]",
"lines": [("Cropped and rotated source evidence.", 150, 600)]}])
loc = next(b["locator"] for b in doc.source_blocks if b["locator"].get("bbox"))
x0, y0, x1, y1 = loc["bbox"]
self.assertTrue(0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1)
if rotation == 0: self.assertLess(y1, .2)
elif rotation == 90: self.assertGreater(x0, .8)
elif rotation == 180: self.assertGreater(y0, .8)
else: self.assertLess(x1, .2)
def test_identical_paragraphs_keep_distinct_vertical_regions(self):
text = "Repeated paragraph with identical original evidence."
doc = self.parse([{"lines": [(text, 60, 700), (text, 60, 400)]}])
boxed = [b for b in doc.source_blocks if b["locator"].get("bbox")]
self.assertEqual(len(boxed), 2)
self.assertNotEqual(boxed[0]["locator"]["source_id"], boxed[1]["locator"]["source_id"])
self.assertLess(boxed[0]["locator"]["bbox"][1], .2)
self.assertGreater(boxed[1]["locator"]["bbox"][1], .45)
self.assertIn(text.rstrip('.'), doc.content[boxed[1]["start"]:boxed[1]["end"]])
if __name__ == "__main__":
unittest.main()
+107
View File
@@ -0,0 +1,107 @@
import ipaddress
import os
import unittest
from unittest.mock import patch
from docreader.utils.ssrf import is_ssrf_safe_url, reset_ssrf_whitelist_cache_for_test
class TestSSRFValidation(unittest.TestCase):
def setUp(self) -> None:
self._env_patch = patch.dict(
os.environ,
{"SSRF_WHITELIST": "", "SSRF_WHITELIST_EXTRA": ""},
clear=False,
)
self._env_patch.start()
reset_ssrf_whitelist_cache_for_test()
def tearDown(self) -> None:
self._env_patch.stop()
reset_ssrf_whitelist_cache_for_test()
def _whitelist_only(self, whitelist: str, only: str) -> None:
patcher = patch.dict(
os.environ,
{"SSRF_WHITELIST": whitelist, "SSRF_WHITELIST_EXTRA": "", "SSRF_DNS_WHITELIST_ONLY": only},
clear=False,
)
patcher.start()
self.addCleanup(patcher.stop)
reset_ssrf_whitelist_cache_for_test()
self.addCleanup(reset_ssrf_whitelist_cache_for_test)
def test_whitelist_only_refuses_before_dns(self):
self._whitelist_only("docs.internal", "true")
safe, reason = is_ssrf_safe_url("https://outside.invalid/page")
self.assertFalse(safe)
self.assertIn("not in the SSRF whitelist", reason)
self.assertNotIn("DNS resolution failed", reason)
def test_whitelist_only_admits_whitelisted_host(self):
self._whitelist_only("docs.internal", "true")
safe, reason = is_ssrf_safe_url("https://docs.internal/page")
self.assertTrue(safe, reason)
def test_whitelist_only_off_leaves_validation_alone(self):
self._whitelist_only("docs.internal", "false")
safe, reason = is_ssrf_safe_url("http://127.0.0.1:8080/page")
self.assertFalse(safe)
self.assertNotIn("not in the SSRF whitelist", reason)
def test_whitelist_only_unparsable_value_enables_it(self):
self._whitelist_only("docs.internal", "yes")
safe, reason = is_ssrf_safe_url("https://outside.invalid/page")
self.assertFalse(safe)
self.assertIn("not in the SSRF whitelist", reason)
def test_blocks_loopback_ip(self):
safe, reason = is_ssrf_safe_url("http://127.0.0.1:8080/page")
self.assertFalse(safe)
self.assertTrue(reason)
def test_blocks_restricted_hostname(self):
safe, reason = is_ssrf_safe_url("http://host.docker.internal/secret")
self.assertFalse(safe)
self.assertIn("restricted", reason)
def test_blocks_metadata_host(self):
safe, reason = is_ssrf_safe_url(
"http://169.254.169.254/latest/meta-data/iam/security-credentials/"
)
self.assertFalse(safe)
self.assertTrue(reason)
def test_blocks_invalid_port(self):
safe, reason = is_ssrf_safe_url("https://example.com:99999/path")
self.assertFalse(safe)
self.assertIn("invalid port", reason)
def test_blocks_ipv4_mapped_private_ipv6_resolution(self):
with patch(
"docreader.utils.ssrf._resolve_host_ips",
return_value=((ipaddress.ip_address("::ffff:127.0.0.1"),), None),
):
safe, reason = is_ssrf_safe_url("https://example.invalid/path")
self.assertFalse(safe)
self.assertIn("restricted", reason)
def test_blocks_local_use_nat64(self):
for address in ('64:ff9b:1::', '64:ff9b:1::a9fe:a9fe',
'64:ff9b:1::808:808', '64:ff9b:1:ffff:ffff:ffff:ffff:ffff'):
with self.subTest(address=address), patch(
'docreader.utils.ssrf._resolve_host_ips',
return_value=((ipaddress.ip_address(address),), None),
):
safe, reason = is_ssrf_safe_url('https://example.invalid/path')
self.assertFalse(safe)
self.assertIn('restricted', reason)
def test_allows_public_https(self):
safe, reason = is_ssrf_safe_url("https://example.com/article")
self.assertTrue(safe, reason)
self.assertEqual(reason, "")
if __name__ == "__main__":
unittest.main()
+115
View File
@@ -0,0 +1,115 @@
import asyncio
import ipaddress
import os
import unittest
from unittest.mock import patch
from docreader.utils.ssrf import reset_ssrf_whitelist_cache_for_test
from docreader.utils.ssrf_proxy import SSRFProxy, checked_address
class TestSSRFProxy(unittest.IsolatedAsyncioTestCase):
async def test_dns_rebinding_is_checked_before_connect(self):
for address in (
'127.0.0.1', '64:ff9b:1::a9fe:a9fe', '64:ff9b:1::808:808',
'64:ff9b:1:ffff:ffff:ffff:ffff:ffff',
):
with self.subTest(address=address), \
patch('docreader.utils.ssrf_proxy.is_ssrf_safe_url', return_value=(True, '')), \
patch('docreader.utils.ssrf_proxy._resolve_host_ips', return_value=((ipaddress.ip_address(address),), None)), \
patch('docreader.utils.ssrf_proxy._is_whitelisted', return_value=False):
with self.assertRaises(ValueError):
await checked_address('https://rebind.example/')
async def test_proxy_refuses_restricted_connect(self):
with patch.dict(os.environ, {'SSRF_WHITELIST': '', 'SSRF_WHITELIST_EXTRA': ''}):
reset_ssrf_whitelist_cache_for_test()
async with SSRFProxy() as proxy:
port = int(proxy.url.rsplit(':', 1)[1])
reader, writer = await asyncio.open_connection('127.0.0.1', port)
writer.write(b'CONNECT 127.0.0.1:443 HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n')
await writer.drain()
self.assertIn(b'403 Forbidden', await reader.read())
writer.close()
await writer.wait_closed()
reset_ssrf_whitelist_cache_for_test()
async def test_upstream_proxy_receives_numeric_connect(self):
seen = []
async def upstream(reader, writer):
try:
seen.append(await reader.readuntil(b'\r\n\r\n'))
writer.write(b'HTTP/1.1 200 Connection Established\r\n\r\n')
await writer.drain()
finally:
writer.close()
server = await asyncio.start_server(upstream, '127.0.0.1', 0)
port = server.sockets[0].getsockname()[1]
try:
proxy = SSRFProxy(f'http://127.0.0.1:{port}')
reader, writer = await proxy._connect('8.8.8.8', 443)
self.assertIn(b'CONNECT 8.8.8.8:443 HTTP/1.1', seen[0])
writer.close()
await writer.wait_closed()
finally:
server.close()
await server.wait_closed()
async def test_webkit_redirects_and_subresources_use_proxy(self):
try:
from playwright.async_api import async_playwright
except ImportError:
self.skipTest('Playwright is required for browser integration test')
secret_hits = []
connections = set()
async def serve(reader, writer):
connections.add(writer)
try:
head = await reader.readuntil(b'\r\n\r\n')
path = head.split(b' ')[1]
if path == b'/blocked':
location = f'http://localhost:{port}/secret'.encode()
reply = b'HTTP/1.1 302 Found\r\nLocation: ' + location + b'\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'
elif path == b'/redirect':
reply = b'HTTP/1.1 302 Found\r\nLocation: /ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'
else:
if path == b'/secret':
secret_hits.append(path)
content = f'<html>public content<img src="http://localhost:{port}/secret"></html>'.encode()
reply = b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\nContent-Length: ' + str(len(content)).encode() + b'\r\n\r\n' + content
writer.write(reply)
await writer.drain()
finally:
writer.close()
connections.discard(writer)
server = await asyncio.start_server(serve, '127.0.0.1', 0)
port = server.sockets[0].getsockname()[1]
try:
with patch.dict(os.environ, {'SSRF_WHITELIST': '127.0.0.1', 'SSRF_WHITELIST_EXTRA': ''}):
reset_ssrf_whitelist_cache_for_test()
async with SSRFProxy() as proxy, async_playwright() as p:
browser = await p.webkit.launch(proxy={'server': proxy.url, 'bypass': ''})
try:
page = await browser.new_page(service_workers='block')
# Intentionally no page.route: the proxy must cover hops
# that Playwright's route hook never observes.
await page.goto(f'http://127.0.0.1:{port}/redirect', wait_until='load')
self.assertTrue(page.url.endswith('/ok'))
self.assertIn('public content', await page.content())
try:
await page.goto(f'http://127.0.0.1:{port}/blocked', wait_until='load')
except Exception:
pass # WebKit may surface a proxy refusal as navigation failure.
self.assertEqual(secret_hits, [])
finally:
await browser.close()
finally:
server.close()
await server.wait_closed()
for writer in connections:
writer.close()
reset_ssrf_whitelist_cache_for_test()
+64
View File
@@ -0,0 +1,64 @@
"""A pipe inside a table cell stays in that cell; GFM escapes it as ``\\|``."""
import unittest
from docreader.parser.html_parser import HTMLParser
from docreader.parser.markdown_parser import MarkdownParser, MarkdownTableUtil
class TableCellPipeTest(unittest.TestCase):
def test_format_table_keeps_an_escaped_pipe_in_its_cell(self):
raw = "|Pattern|Matches|\n|---|---|\n|`a\\|b`|a or b|\n|x \\| y|literal|"
formatted = MarkdownTableUtil().format_table(raw)
self.assertEqual(
formatted,
"| Pattern | Matches |\n| --- | --- |\n"
"| `a\\|b` | a or b |\n| x \\| y | literal |",
)
def test_format_table_ends_a_cell_at_a_pipe_after_an_escaped_backslash(self):
# "\\\\" is an escaped backslash, so the pipe after it is a delimiter
formatted = MarkdownTableUtil().format_table("|a\\\\|b|\n|---|---|")
self.assertEqual(formatted, "| a\\\\ | b |\n| --- | --- |")
def test_markdown_upload_keeps_an_escaped_pipe(self):
content = "| Type | Notes |\n| --- | --- |\n| int \\| None | optional |\n"
document = MarkdownParser(
file_name="types.md", file_type="md"
).parse_into_text(content.encode())
self.assertIn("| int \\| None | optional |", document.content)
def test_html_upload_escapes_a_pipe_in_a_cell(self):
html = (
"<table><tr><th>Expr</th><th>Means</th></tr>"
"<tr><td>a|b</td><td>run <code>ls|wc</code></td></tr></table>"
)
document = HTMLParser(
file_name="pipes.html", file_type="html"
).parse_into_text(html.encode())
self.assertIn("| Expr | Means |", document.content)
self.assertIn("| a\\|b | run `ls\\|wc` |", document.content)
def test_html_comment_in_a_cell_stays_hidden(self):
html = (
"<table><tr><th>Name</th></tr>"
"<tr><td>pen<!-- sku|42 --></td></tr></table>"
)
document = HTMLParser(
file_name="comment.html", file_type="html"
).parse_into_text(html.encode())
self.assertIn("| pen |", document.content)
self.assertNotIn("sku", document.content)
if __name__ == "__main__":
unittest.main()
+89
View File
@@ -0,0 +1,89 @@
import os
import tempfile
import unittest
from unittest.mock import patch
from docreader.utils.tempfile import TempFileContext
class TempFileContextTest(unittest.TestCase):
def test_removes_file_when_write_fails_inside_enter(self):
created = []
real_ntf = tempfile.NamedTemporaryFile
def failing_ntf(*args, **kwargs):
f = real_ntf(*args, **kwargs)
created.append(f.name)
class Wrapper:
def __getattr__(self, name):
return getattr(f, name)
def write(self, data):
raise OSError(28, "No space left on device")
return Wrapper()
with patch("docreader.utils.tempfile.tempfile.NamedTemporaryFile", failing_ntf):
with self.assertRaises(OSError):
with TempFileContext(b"payload", ".doc"):
pass
self.assertEqual(len(created), 1)
self.assertFalse(os.path.exists(created[0]))
def test_removes_file_when_close_reraises_after_flush_fails(self):
# CPython NamedTemporaryFile.close() flushes again; after ENOSPC,
# close() typically re-raises and must not skip unlink or replace
# the original write/flush error.
created = []
real_ntf = tempfile.NamedTemporaryFile
def failing_ntf(*args, **kwargs):
f = real_ntf(*args, **kwargs)
created.append(f.name)
class Wrapper:
def __init__(self):
self.name = f.name
def write(self, data):
f.write(data)
def flush(self):
raise OSError(28, "No space left on device")
def close(self):
try:
raise OSError(5, "Input/output error")
finally:
f.close()
return Wrapper()
with patch("docreader.utils.tempfile.tempfile.NamedTemporaryFile", failing_ntf):
with self.assertRaises(OSError) as ctx:
with TempFileContext(b"payload", ".doc"):
pass
self.assertEqual(ctx.exception.errno, 28)
self.assertEqual(len(created), 1)
self.assertFalse(os.path.exists(created[0]))
def test_normal_roundtrip_and_cleanup(self):
payload = bytes(range(256)) * 4
with TempFileContext(payload, ".doc") as path:
self.assertTrue(path.endswith(".doc"))
with open(path, "rb") as f:
self.assertEqual(f.read(), payload)
self.assertFalse(os.path.exists(path))
def test_exception_inside_body_still_cleans_up(self):
with self.assertRaises(ValueError):
with TempFileContext(b"x", ".doc") as path:
raise ValueError("body")
self.assertFalse(os.path.exists(path))
if __name__ == "__main__":
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
import unittest
from docreader.utils.split import (
match_by_regex,
split_by_char,
split_by_regex,
split_by_sep,
split_text_keep_separator,
)
class SplitUtilsTest(unittest.TestCase):
def test_split_text_keep_separator_basic(self):
self.assertEqual(
split_text_keep_separator("Hello\nWorld\nTest", "\n"),
["Hello", "\nWorld", "\nTest"],
)
def test_split_text_keep_separator_no_separator(self):
self.assertEqual(split_text_keep_separator("no sep", ","), ["no sep"])
def test_split_text_keep_separator_filters_empty_parts(self):
self.assertEqual(split_text_keep_separator("a,,b", ","), ["a", ",", ",b"])
def test_split_by_sep_keep(self):
self.assertEqual(split_by_sep(",")("a,b,c"), ["a", ",b", ",c"])
def test_split_by_sep_discard(self):
self.assertEqual(split_by_sep(",", keep_sep=False)("a,,b"), ["a", "", "b"])
def test_split_by_char(self):
self.assertEqual(split_by_char()("abc"), ["a", "b", "c"])
def test_split_by_regex_keeps_separators(self):
self.assertEqual(split_by_regex("\n")("a\nb\nc"), ["a", "\n", "b", "\n", "c"])
def test_match_by_regex(self):
self.assertTrue(match_by_regex(r"^\d+")("123"))
self.assertFalse(match_by_regex(r"^\d+")("abc"))
if __name__ == "__main__":
unittest.main()
+153
View File
@@ -0,0 +1,153 @@
import os
import unittest
from unittest.mock import AsyncMock, patch
from docreader.parser.web_parser import (
StdWebParser,
WebParseError,
WebParser,
_ScrapeResult,
build_visible_text_fallback,
extract_markdown_from_html,
install_ssrf_route_guard,
)
from docreader.utils.ssrf import is_ssrf_safe_url, reset_ssrf_whitelist_cache_for_test
class TestWebParserHelpers(unittest.TestCase):
def setUp(self) -> None:
self._env_patch = patch.dict(
os.environ,
{"SSRF_WHITELIST": "", "SSRF_WHITELIST_EXTRA": ""},
clear=False,
)
self._env_patch.start()
reset_ssrf_whitelist_cache_for_test()
def tearDown(self) -> None:
self._env_patch.stop()
reset_ssrf_whitelist_cache_for_test()
def test_extract_markdown_empty_html(self):
self.assertIsNone(extract_markdown_from_html(""))
self.assertIsNone(extract_markdown_from_html(" "))
def test_extract_markdown_article_html(self):
html = """
<html><head><title>Demo</title></head><body>
<article><h1>Hello</h1><p>World paragraph with enough text for extraction.</p></article>
</body></html>
"""
md = extract_markdown_from_html(html)
self.assertIsNotNone(md)
self.assertIn("Hello", md)
def test_build_fallback_too_short(self):
self.assertIsNone(build_visible_text_fallback("short"))
self.assertIsNone(build_visible_text_fallback(""))
def test_build_fallback_with_title(self):
text = "A" * 60
md = build_visible_text_fallback(text, page_title="Academy")
self.assertIsNotNone(md)
self.assertTrue(md.startswith("# Academy"))
self.assertIn(text, md)
def test_build_fallback_without_title(self):
text = "B" * 60
md = build_visible_text_fallback(text, page_title="")
self.assertEqual(md, text)
def test_install_ssrf_route_guard_is_importable(self):
self.assertTrue(callable(install_ssrf_route_guard))
def test_redirect_target_blocked_before_navigation(self):
safe, reason = is_ssrf_safe_url("http://127.0.0.1:39127/audit.txt")
self.assertFalse(safe)
self.assertTrue(reason)
class TestStdWebParserFailures(unittest.TestCase):
"""Scrape/parse failures must raise, not become indexable document body."""
def _parser(self) -> StdWebParser:
return StdWebParser(title="page")
def test_empty_scrape_raises_instead_of_error_body(self):
empty = _ScrapeResult(
html="",
visible_text="",
page_title="",
error="navigation failed: Timeout",
)
parser = self._parser()
with patch.object(parser, "scrape", new=AsyncMock(return_value=empty)):
with self.assertRaises(WebParseError) as ctx:
parser.parse_into_text(b"https://example.com/blocked")
message = str(ctx.exception)
self.assertIn("https://example.com/blocked", message)
self.assertIn("navigation failed", message)
self.assertNotIn("Error parsing web page:", message)
def test_empty_scrape_without_error_field_still_raises(self):
empty = _ScrapeResult(html="", visible_text="", page_title="")
parser = self._parser()
with patch.object(parser, "scrape", new=AsyncMock(return_value=empty)):
with self.assertRaises(WebParseError) as ctx:
parser.parse_into_text(b"https://example.com/blank")
self.assertIn("no HTML or visible text", str(ctx.exception))
def test_unextractable_page_raises_instead_of_error_body(self):
scrape = _ScrapeResult(
html="<html><body><div></div></body></html>",
visible_text="short",
page_title="",
)
parser = self._parser()
with patch.object(parser, "scrape", new=AsyncMock(return_value=scrape)):
with patch(
"docreader.parser.web_parser.extract_markdown_from_html",
return_value=None,
):
with patch(
"docreader.parser.web_parser.build_visible_text_fallback",
return_value=None,
):
with self.assertRaises(WebParseError) as ctx:
parser.parse_into_text(b"https://example.com/empty")
self.assertIn("Failed to parse web page", str(ctx.exception))
self.assertIn("https://example.com/empty", str(ctx.exception))
def test_successful_scrape_returns_markdown_document(self):
html = """
<html><head><title>Demo</title></head><body>
<article><h1>Hello</h1><p>World paragraph with enough text for extraction.</p></article>
</body></html>
"""
scrape = _ScrapeResult(
html=html,
visible_text="Hello World paragraph with enough text for extraction.",
page_title="Demo",
)
parser = self._parser()
with patch.object(parser, "scrape", new=AsyncMock(return_value=scrape)):
doc = parser.parse_into_text(b"https://example.com/ok")
self.assertTrue(doc.is_valid())
self.assertNotIn("Error parsing web page:", doc.content)
self.assertIn("Hello", doc.content)
def test_pipeline_web_parser_does_not_index_scrape_error(self):
empty = _ScrapeResult(
html="",
visible_text="",
page_title="",
error="URL blocked by SSRF guard: loopback",
)
pipeline = WebParser(title="page")
with patch.object(StdWebParser, "scrape", new=AsyncMock(return_value=empty)):
with self.assertRaises(WebParseError):
pipeline.parse_into_text(b"https://example.com/ssrf")
if __name__ == "__main__":
unittest.main()
+377
View File
@@ -0,0 +1,377 @@
"""Tests for materializing XLSX percentage number formats (opt-in).
Excel keeps a percentage as the underlying fraction plus a display format:
the cell stores ``0.61123366`` and ``0.00%`` renders it as ``61.12%``.
openpyxl and pandas read the fraction and drop the format, so a cell the user
sees as ``61.12%`` reaches the pipeline as ``0.6112`` — a 100x error that a
model will happily copy into a report.
When ``DOCREADER_XLSX_PERCENT_AS_TEXT`` is on (or the per-upload
``parser_engine_overrides`` key ``xlsx_percent_as_text`` is set), percentage
cells are materialized as the literal text the user sees. The switch is off by
default because the value changes from a number into a string, so anything that
sorts or aggregates the cell would see different input; with it off every
workbook is read exactly as before.
"""
import datetime
import io
import os
import unittest
from unittest.mock import patch
import openpyxl
from docreader.parser.excel_parser import ExcelParser
from docreader.parser.parser import Parser
from docreader.parser.xlsx_merge import fill_merged_cells_xlsx, _format_percentage
PERCENT_ENV = "DOCREADER_XLSX_PERCENT_AS_TEXT"
ROW_HINT_ENV = "DOCREADER_XLSX_PCT_ROW_HINT_MIN"
OVERRIDE_KEY = "xlsx_percent_as_text"
def _workbook_with_percentages() -> bytes:
"""A real .xlsx mixing percentages, a merge, plain numbers and dates.
Layout (1-based; ``B3:B4`` is merged, so row 4's B cell is covered and has
no format of its own — exactly like the yearly columns of a financial
statement, where a label merge covers the row below):
A B C
1 科目 2024 2025
2 毛利率 0.61123366 (0.00%) 0.5512345 (0.00%)
3 收入占比 0.0833 (0.00%) 0.0912 (0.00%)
4 收入占比(续) <covered by B3:B4> 0.005509433890047721 (0.00%)
5 营业收入 1234567.89 (#,##0.00) 9876543.21 (#,##0.00)
6 报告日 2025-01-31 (yyyy-mm-dd) 2024-12-31 (yyyy-mm-dd)
7 汇总 0.5 (General) 6100 (General)
Row 4 is the regression case: it carries its own percentage cell in C, so a
merge fill that runs before the percentage pass leaves that row showing both
``0.55%`` and a raw ``0.0833``.
"""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "财务"
ws.append(["科目", "2024", "2025"])
ws.append(["毛利率", 0.61123366, 0.5512345])
ws.append(["收入占比", 0.0833, 0.0912])
ws.append(["收入占比(续)", None, 0.005509433890047721])
ws.append(["营业收入", 1234567.89, 9876543.21])
ws.append(["报告日", datetime.date(2025, 1, 31), datetime.date(2024, 12, 31)])
ws.append(["汇总", 0.5, 6100])
for row in (2, 3):
ws.cell(row=row, column=2).number_format = "0.00%"
ws.cell(row=row, column=3).number_format = "0.00%"
ws["C4"].number_format = "0.00%"
# Merged after the formats are set: openpyxl keeps only the master (B3)
# style, which is what makes the covered cell's format General.
ws.merge_cells("B3:B4")
for row in (5,):
ws.cell(row=row, column=2).number_format = "#,##0.00"
ws.cell(row=row, column=3).number_format = "#,##0.00"
ws["B6"].number_format = "yyyy-mm-dd"
ws["C6"].number_format = "yyyy-mm-dd"
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def _workbook_with_unformatted_cell_in_percentage_row() -> bytes:
"""A percentage row (3 formatted cells) with one cell left General (D2)."""
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["项目", "2024", "2025", "2026", "2027"])
ws.append(["折旧率", 0.0592, 0.0601, 0.5, 0.0612])
for col in (2, 3, 5):
ws.cell(row=2, column=col).number_format = "0.00%"
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def _workbook_without_merges() -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["项目", "值"])
ws.append(["占比", 0.25])
ws["B2"].number_format = "0%"
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def _read_cells(content: bytes, *coordinates: str):
"""Return the values of *coordinates* on the first worksheet."""
wb = openpyxl.load_workbook(io.BytesIO(content), data_only=True)
ws = wb.worksheets[0]
return [ws[c].value for c in coordinates]
def _upstream_fill_merged_cells_xlsx(content: bytes) -> bytes:
"""Frozen copy of the pre-change implementation, for byte-identity checks.
Kept verbatim (docreader/parser/xlsx_merge.py before the percentage switch)
so the default path of the new function can be compared byte for byte with
the behavior existing deployments have today.
"""
import zipfile
from io import BytesIO
if not zipfile.is_zipfile(BytesIO(content)):
return content
from openpyxl import load_workbook
wb = load_workbook(BytesIO(content), data_only=True)
changed = False
for ws in wb.worksheets:
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
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)
return out.getvalue()
class PercentMaterializationOffTests(unittest.TestCase):
"""Default behavior: unchanged, and byte-identical to the old function."""
def test_default_keeps_the_raw_fraction(self):
content = _workbook_with_percentages()
self.assertEqual(
fill_merged_cells_xlsx(content), _upstream_fill_merged_cells_xlsx(content)
)
values = _read_cells(fill_merged_cells_xlsx(content), "B2", "C2", "B3", "B4")
self.assertEqual(values, [0.61123366, 0.5512345, 0.0833, 0.0833])
def test_excel_parser_default_keeps_the_raw_fraction(self):
document = ExcelParser().parse_into_text(_workbook_with_percentages())
self.assertIn("A: 毛利率,B: 0.61123366", document.content)
self.assertNotIn("61.12%", document.content)
def test_switch_off_is_byte_identical_to_the_upstream_implementation(self):
for build in (
_workbook_with_percentages,
_workbook_without_merges,
_workbook_with_unformatted_cell_in_percentage_row,
):
content = build()
with self.subTest(fixture=build.__name__):
# Explicitly off, so a stray env var in the calling shell
# cannot turn this into an accidental behavior test.
with patch.dict(os.environ, {PERCENT_ENV: "0"}):
self.assertEqual(
fill_merged_cells_xlsx(content),
_upstream_fill_merged_cells_xlsx(content),
)
def test_env_var_off_forms_keep_the_raw_fraction(self):
content = _workbook_with_percentages()
for raw in ("0", "false", "FALSE", "no", "off", ""):
with self.subTest(value=raw):
with patch.dict(os.environ, {PERCENT_ENV: raw}):
self.assertEqual(
_read_cells(fill_merged_cells_xlsx(content), "B2"),
[0.61123366],
)
class PercentMaterializationOnTests(unittest.TestCase):
"""Enabled: percentages become the text the spreadsheet displays."""
def test_percent_cells_become_display_text(self):
content = _workbook_with_percentages()
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
values = _read_cells(fill_merged_cells_xlsx(content), "B2", "C2", "B3", "C4")
self.assertEqual(values, ["61.12%", "55.12%", "8.33%", "0.55%"])
def test_merged_rows_below_the_master_are_materialized_too(self):
"""The order pitfall: B4 is covered by B3:B4 and has no format itself."""
content = _workbook_with_percentages()
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
b3, b4 = _read_cells(fill_merged_cells_xlsx(content), "B3", "B4")
self.assertEqual(b3, "8.33%")
self.assertEqual(b4, "8.33%")
def test_no_row_shows_both_a_percentage_and_a_raw_fraction(self):
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
document = ExcelParser().parse_into_text(_workbook_with_percentages())
self.assertIn("A: 毛利率,B: 61.12%,C: 55.12%", document.content)
self.assertIn("A: 收入占比,B: 8.33%,C: 9.12%", document.content)
# Row 4 keeps its own percentage cell (C) and its merged B cell: both
# must be text, or the same row would read as two different scales.
self.assertIn("A: 收入占比(续),B: 8.33%,C: 0.55%", document.content)
for raw in ("0.61123366", "0.5512345", "0.0833", "0.0912", "0.005509433890047721"):
self.assertNotIn(raw, document.content)
def test_currency_plain_numbers_and_dates_are_not_touched(self):
content = _workbook_with_percentages()
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
income, income_2025, plain, whole, start, end = _read_cells(
fill_merged_cells_xlsx(content), "B5", "C5", "B7", "C7", "B6", "C6"
)
# Thousands separators / currency only affect readability.
self.assertEqual(income, 1234567.89)
self.assertEqual(income_2025, 9876543.21)
# 0.5 has no percentage format, so it must stay a number.
self.assertEqual(plain, 0.5)
self.assertEqual(whole, 6100)
# openpyxl already turns date formats into datetimes.
self.assertEqual(start, datetime.datetime(2025, 1, 31))
self.assertEqual(end, datetime.datetime(2024, 12, 31))
def test_decimals_follow_the_number_format(self):
"""The text mirrors what the format displays: 0%, 0.0%, 0.00%."""
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["项目", "0%", "0.0%", "0.00%", "red"])
ws.append(["毛利率", 0.61123366, 0.61123366, 0.61123366, 0.61123366])
for col, fmt in (
(2, "0%"),
(3, "0.0%"),
(4, "#,##0.00%"),
(5, "0.00%;[Red]-0.00%"),
):
ws.cell(row=2, column=col).number_format = fmt
bio = io.BytesIO()
wb.save(bio)
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
values = _read_cells(
fill_merged_cells_xlsx(bio.getvalue()), "B2", "C2", "D2", "E2"
)
self.assertEqual(values, ["61%", "61.1%", "61.12%", "61.12%"])
def test_unformatted_cell_in_a_percentage_row_needs_the_opt_in_fallback(self):
content = _workbook_with_unformatted_cell_in_percentage_row()
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
self.assertEqual(
_read_cells(fill_merged_cells_xlsx(content), "D2"), [0.5]
)
with patch.dict(
os.environ, {PERCENT_ENV: "true", ROW_HINT_ENV: "3"}
):
self.assertEqual(
_read_cells(fill_merged_cells_xlsx(content), "D2"), ["50.00%"]
)
class PercentageFormatSyntaxTests(unittest.TestCase):
def test_literal_and_conditional_percent_formats_are_not_scaled(self):
for fmt in (r"0.00\%", '0.00"%"', '[>1]0%;0.00%', '0.00%" growth"'):
with self.subTest(fmt=fmt):
self.assertIsNone(_format_percentage(0.5, fmt))
def test_selects_the_section_for_the_value(self):
for value, fmt, expected in (
(0.5, "0%;0.00%", "50%"),
(-0.5, "0%;[Red]-0.00%", "-50.00%"),
(-0.5, "0%;(0.00%)", "(50.00%)"),
(0, "0%;0.00%;0.0%", "0.0%"),
(-0.5, "0.00%", "-50.00%"),
(12.345, "#,##0.00%", "1,234.50%"),
):
with self.subTest(value=value, fmt=fmt):
self.assertEqual(_format_percentage(value, fmt), expected)
def test_row_hint_does_not_convert_literal_percent_or_count_it_as_a_hint(self):
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["label", "percent", "literal", "plain"])
ws.append(["mixed", 0.5, 0.5, 0.5])
ws.append(["literal only", 0.5, 0.5, 0.5])
ws["B2"].number_format = "0%"
ws["C2"].number_format = r"0.00\%"
ws["B3"].number_format = '0.00"%"'
data = io.BytesIO()
wb.save(data)
with patch.dict(os.environ, {PERCENT_ENV: "true", ROW_HINT_ENV: "1"}):
result = fill_merged_cells_xlsx(data.getvalue())
self.assertEqual(_read_cells(result, "B2", "C2", "D2"), ["50%", 0.5, "50.00%"])
self.assertEqual(_read_cells(result, "B3", "C3", "D3"), [0.5, 0.5, 0.5])
class PercentMaterializationSwitchTests(unittest.TestCase):
"""The switch itself: env default, per-upload override, precedence."""
def test_env_var_true_forms_enable_materialization(self):
content = _workbook_with_percentages()
for raw in ("1", "true", "TRUE", "yes", "y", "on"):
with self.subTest(value=raw):
with patch.dict(os.environ, {PERCENT_ENV: raw}):
self.assertEqual(
_read_cells(fill_merged_cells_xlsx(content), "B2"),
["61.12%"],
)
def test_excel_parser_accepts_the_override_key(self):
document = ExcelParser(xlsx_percent_as_text="true").parse_into_text(
_workbook_with_percentages()
)
self.assertIn("A: 毛利率,B: 61.12%", document.content)
def test_parser_engine_overrides_key_enables_materialization(self):
document = Parser().parse_file(
"report.xlsx",
"xlsx",
_workbook_with_percentages(),
engine_overrides={OVERRIDE_KEY: "true"},
)
self.assertIn("A: 毛利率,B: 61.12%", document.content)
def test_upload_override_wins_over_the_env_default(self):
content = _workbook_with_percentages()
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
off = ExcelParser(xlsx_percent_as_text="false").parse_into_text(content)
with patch.dict(os.environ, {PERCENT_ENV: "false"}):
on = ExcelParser(xlsx_percent_as_text="true").parse_into_text(content)
self.assertNotIn("61.12%", off.content)
self.assertIn("B: 0.61123366", off.content)
self.assertIn("61.12%", on.content)
def test_absent_override_keeps_the_env_default(self):
content = _workbook_with_percentages()
with patch.dict(os.environ, {PERCENT_ENV: "true"}):
document = ExcelParser().parse_into_text(content)
self.assertIn("A: 毛利率,B: 61.12%", document.content)
if __name__ == "__main__":
unittest.main()
+216
View File
@@ -0,0 +1,216 @@
"""Regression tests for non-conforming styles.xml fills (#3637).
Real-world exporters (cloud-doc systems, LabView, Acumatica ERP) write
``<fill>`` elements openpyxl cannot deserialize. The fixtures below replace
the first fill of an openpyxl-written workbook at the zip level, which
reproduces the production failure without an original file.
"""
import io
import os
import re
import subprocess
import sys
import tempfile
import unittest
import zipfile
from unittest.mock import patch
import openpyxl
import pandas as pd
from docreader.parser import xlsx_repair
from docreader.parser.excel_parser import _prepare_xlsx_bytes
from docreader.parser.markitdown_parser import StdMarkitdownParser
from docreader.parser.xlsx_merge import fill_merged_cells_xlsx
from docreader.parser.xlsx_repair import sanitize_xlsx_styles
CRASHING_FILLS = {
"empty-self-closing": b"<fill/>",
"capitalized": b"<Fill/>",
"text-content": b"<fill>oops</fill>",
}
# openpyxl happens to tolerate an unknown fill child, but it is still
# non-conforming; the sanitizer normalizes it like the crashing forms.
TOLERATED_FILL = b"<fill><Foo/></fill>"
def _workbook_bytes() -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "hello"
ws["B2"] = 42
ws["C3"] = "world"
ws.merge_cells("C3:D3")
bio = io.BytesIO()
wb.save(bio)
return bio.getvalue()
def _with_first_fill_replaced(workbook: bytes, fragment: bytes) -> bytes:
out = io.BytesIO()
with zipfile.ZipFile(io.BytesIO(workbook)) as zin, zipfile.ZipFile(
out, "w", zipfile.ZIP_DEFLATED
) as zout:
for item in zin.infolist():
data = zin.read(item.filename)
if item.filename == "xl/styles.xml":
data = re.sub(
b"<fill>.*?</fill>", fragment, data, count=1, flags=re.S
)
zout.writestr(item, data)
return out.getvalue()
def _with_rich_styles_part(workbook: bytes) -> bytes:
"""Add the xl/richData/richStyles.xml part Excel 365 writes for in-cell
images / data types; its name also ends in ``styles.xml``."""
out = io.BytesIO()
with zipfile.ZipFile(io.BytesIO(workbook)) as zin, zipfile.ZipFile(
out, "w", zipfile.ZIP_DEFLATED
) as zout:
for item in zin.infolist():
zout.writestr(item, zin.read(item.filename))
zout.writestr(
"xl/richData/richStyles.xml",
b'<richStyleSheet xmlns="http://schemas.microsoft.com/office/'
b'spreadsheetml/2017/richdata2"/>',
)
return out.getvalue()
class TestSanitizeXlsxStyles(unittest.TestCase):
def test_clean_workbook_is_returned_unchanged(self):
self.assertIsNone(sanitize_xlsx_styles(_workbook_bytes()))
def test_non_zip_input_is_ignored(self):
self.assertIsNone(sanitize_xlsx_styles(b"not a zip"))
def test_repair_is_logged_with_count(self):
fixture = _with_first_fill_replaced(
_workbook_bytes(), CRASHING_FILLS["empty-self-closing"]
)
with self.assertLogs("docreader.parser.xlsx_repair", level="INFO") as logs:
sanitize_xlsx_styles(fixture)
self.assertTrue(
any("Sanitized 1 non-conforming fill" in line for line in logs.output),
logs.output,
)
def test_internal_failure_returns_none_instead_of_raising(self):
fixture = _with_first_fill_replaced(
_workbook_bytes(), CRASHING_FILLS["empty-self-closing"]
)
with patch(
"docreader.parser.xlsx_repair._rewrite_zip", side_effect=OSError("boom")
):
with self.assertLogs("docreader.parser.xlsx_repair", level="WARNING"):
result = sanitize_xlsx_styles(fixture)
self.assertIsNone(result)
def test_each_malformed_form_is_repaired_in_place(self):
for name, fragment in {**CRASHING_FILLS, "tolerated-unknown-child": TOLERATED_FILL}.items():
with self.subTest(form=name):
fixture = _with_first_fill_replaced(_workbook_bytes(), fragment)
sanitized = sanitize_xlsx_styles(fixture)
self.assertIsNotNone(sanitized)
wb = openpyxl.load_workbook(io.BytesIO(sanitized), data_only=True)
ws = wb.active
self.assertEqual(ws["A1"].value, "hello")
self.assertEqual(ws["B2"].value, 42)
with zipfile.ZipFile(io.BytesIO(sanitized)) as z:
styles = z.read("xl/styles.xml")
count = re.search(rb'<fills count="(\d+)"', styles)
num_fills = len(re.findall(rb"<fill[ />]", styles))
self.assertIsNotNone(count)
self.assertEqual(int(count.group(1)), num_fills)
def test_workbook_stylesheet_is_picked_over_rich_styles_part(self):
fixture = _with_rich_styles_part(
_with_first_fill_replaced(
_workbook_bytes(), CRASHING_FILLS["empty-self-closing"]
)
)
sanitized = sanitize_xlsx_styles(fixture)
self.assertIsNotNone(sanitized)
openpyxl.load_workbook(io.BytesIO(sanitized), data_only=True)
def test_stylesheet_choice_does_not_depend_on_hash_seed(self):
# Zip member names are str, so any set-ordered lookup changes with
# PYTHONHASHSEED; run the sanitizer under several seeds.
fixture = _with_rich_styles_part(
_with_first_fill_replaced(
_workbook_bytes(), CRASHING_FILLS["empty-self-closing"]
)
)
repo_root = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(xlsx_repair.__file__)))
)
script = (
"import sys\n"
"from docreader.parser.xlsx_repair import sanitize_xlsx_styles\n"
"data = open(sys.argv[1], 'rb').read()\n"
"sys.exit(0 if sanitize_xlsx_styles(data) is not None else 1)\n"
)
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "rich.xlsx")
with open(path, "wb") as handle:
handle.write(fixture)
for seed in range(8):
with self.subTest(seed=seed):
env = {
**os.environ,
"PYTHONHASHSEED": str(seed),
"PYTHONPATH": os.pathsep.join(
filter(None, [repo_root, os.environ.get("PYTHONPATH")])
),
}
result = subprocess.run(
[sys.executable, "-c", script, path], env=env
)
self.assertEqual(result.returncode, 0)
def test_crashing_forms_raise_without_the_fix(self):
for name, fragment in CRASHING_FILLS.items():
with self.subTest(form=name):
fixture = _with_first_fill_replaced(_workbook_bytes(), fragment)
with self.assertRaises(TypeError):
openpyxl.load_workbook(io.BytesIO(fixture), data_only=True)
class TestBuiltinChain(unittest.TestCase):
def test_prepare_xlsx_bytes_recovers_and_keeps_merge_fill(self):
for name, fragment in CRASHING_FILLS.items():
with self.subTest(form=name):
fixture = _with_first_fill_replaced(_workbook_bytes(), fragment)
with self.assertRaises(TypeError):
fill_merged_cells_xlsx(fixture) # the unfixed failure
prepared = _prepare_xlsx_bytes(fixture)
excel = pd.ExcelFile(io.BytesIO(prepared), engine="openpyxl")
self.assertTrue(excel.sheet_names)
wb = openpyxl.load_workbook(io.BytesIO(prepared), data_only=True)
ws = wb.active
# the merge-cell prefill still applied on the sanitized bytes
self.assertEqual(ws["C3"].value, "world")
self.assertEqual(ws["D3"].value, "world")
class TestMarkitdownChain(unittest.TestCase):
def test_markitdown_engine_parses_sanitized_workbook(self):
for name, fragment in {**CRASHING_FILLS, "tolerated-unknown-child": TOLERATED_FILL}.items():
with self.subTest(form=name):
fixture = _with_first_fill_replaced(_workbook_bytes(), fragment)
parser = StdMarkitdownParser(file_type="xlsx")
doc = parser.parse_into_text(fixture)
self.assertIn("hello", doc.content)
self.assertIn("world", doc.content)
if __name__ == "__main__":
unittest.main()
+286
View File
@@ -0,0 +1,286 @@
import io
import json
import unittest
import zipfile
from unittest.mock import patch
from docreader.parser.xmind_parser import XMindParser
def _xmind_zip(entries: dict[str, bytes | str]) -> bytes:
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for name, value in entries.items():
payload = value.encode("utf-8") if isinstance(value, str) else value
archive.writestr(name, payload)
return buffer.getvalue()
def _modern_xmind_bytes(sheets: list[dict]) -> bytes:
return _xmind_zip({"content.json": json.dumps(sheets, ensure_ascii=False)})
def _classic_xmind_bytes(xml: str) -> bytes:
return _xmind_zip({"content.xml": xml})
def _mark_entry_encrypted(payload: bytes) -> bytes:
marked = bytearray(payload)
local_header = marked.index(b"PK\x03\x04")
central_header = marked.index(b"PK\x01\x02")
for offset in (local_header + 6, central_header + 8):
flags = int.from_bytes(marked[offset : offset + 2], "little") | 0x1
marked[offset : offset + 2] = flags.to_bytes(2, "little")
return bytes(marked)
class XMindParserModernTests(unittest.TestCase):
def test_finds_content_without_enumerating_unrelated_entries(self):
payload = _xmind_zip(
{
"attachments/preview.png": b"preview",
"content.json": json.dumps(
[{"title": "Outline", "rootTopic": {"title": "Root"}}]
),
}
)
with patch.object(
zipfile.ZipFile,
"namelist",
side_effect=AssertionError("archive entries must not be enumerated"),
):
document = XMindParser().parse_into_text(payload)
self.assertEqual("# Outline\n\n- Root", document.content)
def test_parses_topic_hierarchy_and_plain_notes(self):
payload = _modern_xmind_bytes(
[
{
"title": "Launch Plan",
"rootTopic": {
"title": "Release",
"notes": {"plain": {"content": "Coordinate teams"}},
"children": {
"attached": [
{
"title": "Backend",
"children": {
"attached": [{"title": "API freeze"}]
},
}
]
},
},
}
]
)
document = XMindParser(file_name="launch.xmind").parse_into_text(payload)
self.assertEqual(
"# Launch Plan\n\n"
"- Release\n"
" > Coordinate teams\n"
" - Backend\n"
" - API freeze",
document.content,
)
self.assertEqual(document.metadata["source_format"], "xmind")
self.assertEqual(document.metadata["xmind_content_format"], "json")
self.assertEqual(document.metadata["sheet_count"], 1)
self.assertEqual(document.metadata["topic_count"], 3)
self.assertEqual(document.metadata["note_count"], 1)
self.assertEqual(document.metadata["file_size"], len(payload))
def test_renders_multiple_sheets_with_fallback_title(self):
payload = _modern_xmind_bytes(
[
{"title": "One", "rootTopic": {"title": "Alpha"}},
{"title": " ", "rootTopic": {"title": "Beta"}},
]
)
document = XMindParser().parse_into_text(payload)
self.assertEqual(
"# One\n\n- Alpha\n\n---\n\n# Sheet 2\n\n- Beta",
document.content,
)
self.assertEqual(document.metadata["sheet_count"], 2)
self.assertEqual(document.metadata["topic_count"], 2)
def test_promotes_children_of_blank_topic(self):
payload = _modern_xmind_bytes(
[
{
"title": "Outline",
"rootTopic": {
"title": " ",
"children": {
"attached": [
{
"title": "Visible",
"children": {
"attached": [{"title": "Nested"}]
},
}
]
},
},
}
]
)
document = XMindParser().parse_into_text(payload)
self.assertEqual("# Outline\n\n- Visible\n - Nested", document.content)
self.assertEqual(document.metadata["topic_count"], 2)
def test_renders_multiline_note_as_blockquotes(self):
payload = _modern_xmind_bytes(
[
{
"title": "Notes",
"rootTopic": {
"title": "Root",
"notes": {
"plain": {"content": " First line \n\n Second line "}
},
},
}
]
)
document = XMindParser().parse_into_text(payload)
self.assertEqual(
"# Notes\n\n- Root\n > First line\n >\n > Second line",
document.content,
)
class XMindParserClassicTests(unittest.TestCase):
def test_parses_namespaced_xml_hierarchy_and_notes(self):
payload = _classic_xmind_bytes(
"""<?xml version="1.0" encoding="UTF-8"?>
<xmap-content xmlns="urn:xmind:xmap:xmlns:content:2.0">
<sheet>
<title>Architecture</title>
<topic>
<title>Platform</title>
<notes><plain>Owns ingress</plain></notes>
<children>
<topics type="attached">
<topic><title>Gateway</title></topic>
</topics>
</children>
</topic>
</sheet>
</xmap-content>
"""
)
document = XMindParser().parse_into_text(payload)
self.assertEqual(
"# Architecture\n\n- Platform\n > Owns ingress\n - Gateway",
document.content,
)
self.assertEqual(document.metadata["xmind_content_format"], "xml")
self.assertEqual(document.metadata["sheet_count"], 1)
self.assertEqual(document.metadata["topic_count"], 2)
self.assertEqual(document.metadata["note_count"], 1)
def test_prefers_content_json_when_both_entries_exist(self):
xml = """<xmap-content><sheet><title>XML</title>
<topic><title>XML topic</title></topic></sheet></xmap-content>"""
json_content = json.dumps(
[{"title": "JSON", "rootTopic": {"title": "JSON topic"}}]
)
payload = _xmind_zip(
{"content.xml": xml, "content.json": json_content}
)
document = XMindParser().parse_into_text(payload)
self.assertEqual("# JSON\n\n- JSON topic", document.content)
self.assertEqual(document.metadata["xmind_content_format"], "json")
class XMindParserValidationTests(unittest.TestCase):
def test_rejects_invalid_zip(self):
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(b"not a ZIP archive")
self.assertEqual(str(context.exception), "invalid XMind archive")
def test_rejects_archive_without_supported_content(self):
payload = _xmind_zip({"manifest.json": "{}"})
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(payload)
self.assertEqual(
str(context.exception),
"XMind archive is missing content.json or content.xml",
)
def test_rejects_malformed_json(self):
payload = _xmind_zip({"content.json": "{"})
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(payload)
self.assertEqual(str(context.exception), "invalid XMind content.json")
def test_rejects_malformed_xml(self):
payload = _classic_xmind_bytes("<xmap-content>")
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(payload)
self.assertEqual(str(context.exception), "invalid XMind content.xml")
def test_rejects_archive_without_renderable_topics(self):
payload = _modern_xmind_bytes(
[{"title": "Empty", "rootTopic": {"title": " "}}]
)
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(payload)
self.assertEqual(
str(context.exception),
"XMind archive contains no renderable topics",
)
def test_rejects_content_entry_over_limit(self):
payload = _xmind_zip({"content.json": "12345"})
with patch("docreader.parser.xmind_parser.MAX_CONTENT_BYTES", 4):
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(payload)
self.assertEqual(
str(context.exception),
"XMind content entry exceeds the 32 MiB limit",
)
def test_rejects_encrypted_content_entry(self):
payload = _mark_entry_encrypted(
_xmind_zip({"content.json": "[]"})
)
with self.assertRaises(ValueError) as context:
XMindParser().parse_into_text(payload)
self.assertEqual(
str(context.exception),
"encrypted XMind content is not supported",
)
if __name__ == "__main__":
unittest.main()