mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 20:11:38 +08:00
fix: Windows MinerU parsing — subprocess UTF-8 decoding & render-thread crash (#844)
* fix: Windows robustness — MinerU UTF-8 decode, render-thread crash & atomic-write PermissionError - mineru/local.py: pass encoding="utf-8", errors="replace" to subprocess.Popen so MinerU's combined stdout/stderr is decoded as UTF-8 instead of the platform default (GBK on zh-CN Windows), which previously crashed with a UnicodeDecodeError (0x8b). - mineru/models.py: set MINERU_PDF_RENDER_THREADS=1 in model_env_overrides to avoid MinerU's multi-threaded PDF rendering heap-corruption crash (0xc0000409) on Windows. - services/file_io.py: retry atomic replace on transient PermissionError (e.g. target locked by antivirus/indexer) with exponential backoff, instead of failing the whole write on Windows. * fix(mineru): gate the render-thread guard to Windows `MINERU_PDF_RENDER_THREADS=1` was set unconditionally, but the variable is honored on Linux and macOS too (upstream default 3-4 render workers), so a Windows-only heap-corruption workaround was serializing page rendering for every platform. It also sat in `model_env_overrides`, whose contract is the model-weight download source — and adding a key there broke that function's exact-equality test. Move it to its own `render_env_overrides()` next to the other MinerU env knowledge, guarded on `sys.platform`, and merge it into the subprocess env at the local-CLI branch in `backend.py`. Only that branch renders pages in this process tree; cloud mode never does. --------- Co-authored-by: Frank <bingxizhao@novix.science>
This commit is contained in:
@@ -6,9 +6,34 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _atomic_replace(src: Path, dst: Path, *, max_retries: int = 5) -> None:
|
||||
"""Replace *dst* with *src*, retrying on transient ``PermissionError``.
|
||||
|
||||
On Windows the destination file is occasionally locked by another process
|
||||
(antivirus, indexer, or a concurrent reader), which makes ``Path.replace``
|
||||
raise ``PermissionError``. A short exponential backoff recovers in most
|
||||
cases without losing the already-written content.
|
||||
"""
|
||||
delay = 0.2
|
||||
last_err: PermissionError | None = None
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
src.replace(dst)
|
||||
return
|
||||
except PermissionError as exc: # pragma: no cover - platform specific
|
||||
last_err = exc
|
||||
if attempt == max_retries - 1:
|
||||
break
|
||||
time.sleep(delay)
|
||||
delay = min(delay * 2, 1.6)
|
||||
assert last_err is not None
|
||||
raise last_err
|
||||
|
||||
|
||||
def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
|
||||
"""Write *payload* as UTF-8 JSON without exposing a partial target file."""
|
||||
path = Path(path)
|
||||
@@ -29,7 +54,7 @@ def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
|
||||
os.fsync(handle.fileno())
|
||||
except OSError:
|
||||
pass
|
||||
temporary_path.replace(path)
|
||||
_atomic_replace(temporary_path, path)
|
||||
finally:
|
||||
if temporary_path is not None:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
@@ -54,7 +79,7 @@ def atomic_write_text(path: Path, text: str) -> None:
|
||||
os.fsync(handle.fileno())
|
||||
except OSError:
|
||||
pass
|
||||
temporary_path.replace(path)
|
||||
_atomic_replace(temporary_path, path)
|
||||
finally:
|
||||
if temporary_path is not None:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
|
||||
@@ -124,7 +124,7 @@ def _parse_local(
|
||||
"""Local-CLI branch: delegate to the existing subprocess parser and return
|
||||
the deterministic output directory it writes to (``<base>/<stem>``)."""
|
||||
from .local import parse_pdf_with_mineru
|
||||
from .models import model_env_overrides
|
||||
from .models import model_env_overrides, render_env_overrides
|
||||
|
||||
cli_command = None
|
||||
if (config.local_cli_path or "").strip():
|
||||
@@ -139,6 +139,9 @@ def _parse_local(
|
||||
# A lazy first-parse model download must honor the configured source and
|
||||
# custom address, not just the explicit Download button.
|
||||
download_env = model_env_overrides(config.model_download_source, config.model_download_endpoint)
|
||||
# Only the local CLI renders pages in this process tree; cloud mode never
|
||||
# does, so the Windows render-thread guard belongs on this branch alone.
|
||||
subprocess_env = {**download_env, **render_env_overrides()}
|
||||
|
||||
logger.info("Parsing %s via local MinerU CLI (%s)", pdf_path.name, cli_command or "PATH")
|
||||
ok = parse_pdf_with_mineru(
|
||||
@@ -146,7 +149,7 @@ def _parse_local(
|
||||
str(output_base),
|
||||
on_output=on_output,
|
||||
cli_command=cli_command,
|
||||
extra_env=download_env,
|
||||
extra_env=subprocess_env,
|
||||
)
|
||||
if not ok:
|
||||
raise MinerUError(
|
||||
|
||||
@@ -139,6 +139,8 @@ def parse_pdf_with_mineru(
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
shell=False,
|
||||
env={**os.environ, **extra_env} if extra_env else None,
|
||||
)
|
||||
|
||||
@@ -20,6 +20,7 @@ import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
@@ -71,6 +72,20 @@ def model_env_overrides(source: str, endpoint: str = "") -> dict[str, str]:
|
||||
return overrides
|
||||
|
||||
|
||||
def render_env_overrides() -> dict[str, str]:
|
||||
"""Env vars that steer how MinerU renders PDF pages to images.
|
||||
|
||||
MinerU renders pages with several worker threads (``MINERU_PDF_RENDER_THREADS``,
|
||||
upstream default 3-4). On Windows that concurrency can abort the parse
|
||||
process with a heap-corruption fault (0xc0000409), so serialize it there.
|
||||
The variable is honored on every platform, hence the explicit guard: Linux
|
||||
and macOS keep the parallel renderer and its throughput.
|
||||
"""
|
||||
if sys.platform != "win32":
|
||||
return {}
|
||||
return {"MINERU_PDF_RENDER_THREADS": "1"}
|
||||
|
||||
|
||||
class ModelDownloadManager:
|
||||
"""At most one model-download subprocess, with a cursor-based line log.
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from deeptutor.services.parsing.engines.mineru import models as mineru_models
|
||||
from deeptutor.services.parsing.engines.mineru.models import (
|
||||
ModelDownloadManager,
|
||||
model_env_overrides,
|
||||
render_env_overrides,
|
||||
resolve_models_downloader,
|
||||
)
|
||||
|
||||
@@ -173,3 +174,22 @@ def test_manager_rejects_concurrent_start_and_cancels(
|
||||
|
||||
def test_manager_cancel_without_job() -> None:
|
||||
assert ModelDownloadManager().cancel()["ok"] is False
|
||||
|
||||
|
||||
def test_render_env_overrides_is_windows_only(monkeypatch) -> None:
|
||||
"""The render-thread guard must not slow Linux/macOS.
|
||||
|
||||
``MINERU_PDF_RENDER_THREADS`` is honored on every platform (upstream
|
||||
default 3-4 workers), so serializing it unconditionally would cost every
|
||||
non-Windows user parse throughput for a Windows-only heap-corruption crash.
|
||||
"""
|
||||
import deeptutor.services.parsing.engines.mineru.models as models
|
||||
|
||||
monkeypatch.setattr(models.sys, "platform", "win32")
|
||||
assert render_env_overrides() == {"MINERU_PDF_RENDER_THREADS": "1"}
|
||||
|
||||
monkeypatch.setattr(models.sys, "platform", "linux")
|
||||
assert render_env_overrides() == {}
|
||||
|
||||
monkeypatch.setattr(models.sys, "platform", "darwin")
|
||||
assert render_env_overrides() == {}
|
||||
|
||||
Reference in New Issue
Block a user