Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

refactor: reorganize model runtime and shared utilities

myhloli85021ae50fc2
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.py
index 17a6dba7..6e6d3db2 100644
--- a/mineru/doclib/background/parse_server_health.py
+++ b/mineru/doclib/background/parse_server_health.py
@@ -19,7 +19,7 @@ import httpx
from ...config import LogConfig, ManagedParseServerConfig, config
from ...parser.api_client import should_trust_env_for_url
from ...types import DEPLOYMENT_TIERS, TIERS, DeploymentTier, Tier
-from ...utils.managed_process_control import ManagedProcessControl
+from ...parser.process_control import ManagedProcessControl
from ...utils.stdio import utf8_subprocess_env
from ..config_defaults import CONFIG_DEFAULTS
from ..remote_api import resolve_remote_api_key
diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.py
index fcfdc280..a3e2d598 100644
--- a/mineru/kit/commands/api_server.py
+++ b/mineru/kit/commands/api_server.py
@@ -7,7 +7,7 @@ import typer
from ...parser import api_server as parser_api_server
from ...types import SERVER_TIERS, ServerTier
-from ...utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
+from ...model.ocr.language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
from ..errors import exit_with_message
API_SERVER_LANGUAGES = PUBLIC_OCR_LANGUAGES
diff --git a/mineru/kit/commands/models.py b/mineru/kit/commands/models.py
index 85d3946d..580a99bd 100644
--- a/mineru/kit/commands/models.py
+++ b/mineru/kit/commands/models.py
@@ -6,7 +6,7 @@ import typer
from ...config import config, get_config_file_exists, get_config_file_path, get_config_source
from ...types import DEPLOYMENT_TIERS
-from ...utils.model_registry import (
+from ...model.registry import (
MODEL_REPOS,
ModelRepo,
get_model_repo,
@@ -15,7 +15,7 @@ from ...utils.model_registry import (
resolve_model_stack,
validate_model_tier,
)
-from ...utils.models_download_utils import (
+from ...model.download import (
DOWNLOAD_MODEL_SOURCES,
MODEL_SOURCE_ENV_VAR,
download_model_repo,
diff --git a/mineru/kit/commands/parse.py b/mineru/kit/commands/parse.py
index cd1218ce..c139949d 100644
--- a/mineru/kit/commands/parse.py
+++ b/mineru/kit/commands/parse.py
@@ -10,7 +10,7 @@ from ...filetypes import ensure_tier_supported_for_parse_extension, is_flash_onl
from ...parser import MinerUApiParser
from ...parser import parse as local_parse
from ...types import Tier
-from ...utils.backend_options import normalize_backend
+from ...parser.tier import normalize_backend
from ..common import (
build_remote_api_url,
effective_local_tier_and_backend,
diff --git a/mineru/kit/commands/vlm_server.py b/mineru/kit/commands/vlm_server.py
index 30f250d8..5fc95165 100644
--- a/mineru/kit/commands/vlm_server.py
+++ b/mineru/kit/commands/vlm_server.py
@@ -9,7 +9,7 @@ from typing import Literal
import typer
from loguru import logger
-from ...utils.check_sys_env import is_mac_os_version_supported
+from ...utils.platform import is_mac_os_version_supported
from ..errors import exit_with_message
diff --git a/mineru/kit/vlm_server/lmdeploy_server.py b/mineru/kit/vlm_server/lmdeploy_server.py
index ac4ed987..e2cbc5c9 100644
--- a/mineru/kit/vlm_server/lmdeploy_server.py
+++ b/mineru/kit/vlm_server/lmdeploy_server.py
@@ -5,7 +5,7 @@ import sys
from loguru import logger
from ...model.vlm.engine_utils import set_lmdeploy_backend
-from ...utils.model_registry import MINERU_2_5_PRO_2605_1_2B
+from ...model.registry import MINERU_2_5_PRO_2605_1_2B
def main() -> None:
diff --git a/mineru/kit/vlm_server/mlx_vlm_server.py b/mineru/kit/vlm_server/mlx_vlm_server.py
index 3410b311..8e3a1c14 100644
--- a/mineru/kit/vlm_server/mlx_vlm_server.py
+++ b/mineru/kit/vlm_server/mlx_vlm_server.py
@@ -9,7 +9,7 @@ import uvicorn
from fastapi import FastAPI, HTTPException, Request
from mineru_vl_utils.mlx_compat import load_mlx_model
-from ...utils.model_registry import MINERU_2_5_PRO_2605_1_2B
+from ...model.registry import MINERU_2_5_PRO_2605_1_2B
async def _resolve_result(value: Any) -> Any:
diff --git a/mineru/kit/vlm_server/vllm_server.py b/mineru/kit/vlm_server/vllm_server.py
index 07cb541e..a99f38fd 100644
--- a/mineru/kit/vlm_server/vllm_server.py
+++ b/mineru/kit/vlm_server/vllm_server.py
@@ -7,7 +7,7 @@ from ...model.vlm.engine_utils import (
mod_kwargs_by_device_type,
set_default_gpu_memory_utilization,
)
-from ...utils.model_registry import MINERU_2_5_PRO_2605_1_2B
+from ...model.registry import MINERU_2_5_PRO_2605_1_2B
from vllm.entrypoints.cli.main import main as vllm_main
diff --git a/mineru/model/__init__.py b/mineru/model/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/__init__.py
+++ b/mineru/model/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/_internal/__init__.py b/mineru/model/_internal/__init__.py
new file mode 100644
index 00000000..b31156ff
--- /dev/null
+++ b/mineru/model/_internal/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""模型实现共享的私有第三方适配代码。"""
+
+__all__: list[str] = []
diff --git a/mineru/model/utils/pytorchocr/__init__.py b/mineru/model/_internal/pytorchocr/__init__.py
similarity index 66%
rename from mineru/model/utils/pytorchocr/__init__.py
rename to mineru/model/_internal/pytorchocr/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/utils/pytorchocr/__init__.py
+++ b/mineru/model/_internal/pytorchocr/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/utils/pytorchocr/base_ocr_v20.py b/mineru/model/_internal/pytorchocr/base_ocr_v20.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/base_ocr_v20.py
rename to mineru/model/_internal/pytorchocr/base_ocr_v20.py
diff --git a/mineru/model/utils/pytorchocr/data/__init__.py b/mineru/model/_internal/pytorchocr/data/__init__.py
similarity index 84%
rename from mineru/model/utils/pytorchocr/data/__init__.py
rename to mineru/model/_internal/pytorchocr/data/__init__.py
index c547df16..09daf2ee 100644
--- a/mineru/model/utils/pytorchocr/data/__init__.py
+++ b/mineru/model/_internal/pytorchocr/data/__init__.py
@@ -6,4 +6,4 @@ from __future__ import unicode_literals
from .imaug import transform, create_operators
-
+__all__ = ["create_operators", "transform"]
diff --git a/mineru/model/utils/pytorchocr/data/imaug/__init__.py b/mineru/model/_internal/pytorchocr/data/imaug/__init__.py
similarity index 96%
rename from mineru/model/utils/pytorchocr/data/imaug/__init__.py
rename to mineru/model/_internal/pytorchocr/data/imaug/__init__.py
index 6ba2f911..ba29a95b 100644
--- a/mineru/model/utils/pytorchocr/data/imaug/__init__.py
+++ b/mineru/model/_internal/pytorchocr/data/imaug/__init__.py
@@ -46,4 +46,6 @@ def create_operators(op_param_list, global_config=None):
param.update(global_config)
op = eval(op_name)(**param)
ops.append(op)
- return ops
\ No newline at end of file
+ return ops
+
+__all__ = ["create_operators", "transform"]
diff --git a/mineru/model/utils/pytorchocr/data/imaug/operators.py b/mineru/model/_internal/pytorchocr/data/imaug/operators.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/data/imaug/operators.py
rename to mineru/model/_internal/pytorchocr/data/imaug/operators.py
diff --git a/mineru/model/utils/pytorchocr/modeling/__init__.py b/mineru/model/_internal/pytorchocr/infer/__init__.py
similarity index 66%
rename from mineru/model/utils/pytorchocr/modeling/__init__.py
rename to mineru/model/_internal/pytorchocr/infer/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/utils/pytorchocr/modeling/__init__.py
+++ b/mineru/model/_internal/pytorchocr/infer/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/utils/tools/infer/predict_cls.py b/mineru/model/_internal/pytorchocr/infer/predict_cls.py
similarity index 97%
rename from mineru/model/utils/tools/infer/predict_cls.py
rename to mineru/model/_internal/pytorchocr/infer/predict_cls.py
index f4ca6444..6dc8a6a1 100644
--- a/mineru/model/utils/tools/infer/predict_cls.py
+++ b/mineru/model/_internal/pytorchocr/infer/predict_cls.py
@@ -5,9 +5,9 @@ import numpy as np
import math
import time
import torch
-from ...pytorchocr.base_ocr_v20 import BaseOCRV20
+from ..base_ocr_v20 import BaseOCRV20
from . import pytorchocr_utility as utility
-from ...pytorchocr.postprocess import build_post_process
+from ..postprocess import build_post_process
class TextClassifier(BaseOCRV20):
diff --git a/mineru/model/utils/tools/infer/predict_det.py b/mineru/model/_internal/pytorchocr/infer/predict_det.py
similarity index 98%
rename from mineru/model/utils/tools/infer/predict_det.py
rename to mineru/model/_internal/pytorchocr/infer/predict_det.py
index 8c6ab03c..d160ceae 100644
--- a/mineru/model/utils/tools/infer/predict_det.py
+++ b/mineru/model/_internal/pytorchocr/infer/predict_det.py
@@ -6,10 +6,10 @@ import numpy as np
import time
import torch
from tqdm import tqdm
-from ...pytorchocr.base_ocr_v20 import BaseOCRV20
+from ..base_ocr_v20 import BaseOCRV20
from . import pytorchocr_utility as utility
-from ...pytorchocr.data import create_operators, transform
-from ...pytorchocr.postprocess import build_post_process
+from ..data import create_operators, transform
+from ..postprocess import build_post_process
class TextDetector(BaseOCRV20):
diff --git a/mineru/model/utils/tools/infer/predict_rec.py b/mineru/model/_internal/pytorchocr/infer/predict_rec.py
similarity index 99%
rename from mineru/model/utils/tools/infer/predict_rec.py
rename to mineru/model/_internal/pytorchocr/infer/predict_rec.py
index 15f3cb6e..1f8d2768 100644
--- a/mineru/model/utils/tools/infer/predict_rec.py
+++ b/mineru/model/_internal/pytorchocr/infer/predict_rec.py
@@ -7,10 +7,10 @@ import time
import torch
from tqdm import tqdm
-from ...pytorchocr.base_ocr_v20 import BaseOCRV20
+from ..base_ocr_v20 import BaseOCRV20
from . import pytorchocr_utility as utility
-from ...pytorchocr.postprocess import build_post_process
-from ...pytorchocr.modeling.backbones.rec_hgnet import ConvBNAct
+from ..modeling.backbones.rec_hgnet import ConvBNAct
+from ..postprocess import build_post_process
class TextRecognizer(BaseOCRV20):
diff --git a/mineru/model/utils/tools/infer/predict_system.py b/mineru/model/_internal/pytorchocr/infer/predict_system.py
similarity index 100%
rename from mineru/model/utils/tools/infer/predict_system.py
rename to mineru/model/_internal/pytorchocr/infer/predict_system.py
diff --git a/mineru/model/utils/tools/infer/pytorchocr_utility.py b/mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.py
similarity index 95%
rename from mineru/model/utils/tools/infer/pytorchocr_utility.py
rename to mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.py
index 7441b9ec..bd74c141 100644
--- a/mineru/model/utils/tools/infer/pytorchocr_utility.py
+++ b/mineru/model/_internal/pytorchocr/infer/pytorchocr_utility.py
@@ -7,9 +7,9 @@ import cv2
import argparse
-root_dir = Path(__file__).resolve().parent.parent.parent
-DEFAULT_CFG_PATH = root_dir / "pytorchocr" / "utils" / "resources" / "arch_config.yaml"
-DEFAULT_REC_CHAR_DICT_PATH = root_dir / "pytorchocr" / "utils" / "resources" / "dict" / "ppocrv6_dict.txt"
+resource_dir = Path(__file__).resolve().parent.parent / "utils" / "resources"
+DEFAULT_CFG_PATH = resource_dir / "arch_config.yaml"
+DEFAULT_REC_CHAR_DICT_PATH = resource_dir / "dict" / "ppocrv6_dict.txt"
def init_args():
@@ -112,8 +112,7 @@ def init_args():
parser.add_argument("--e2e_pgnet_score_thresh", type=float, default=0.5)
parser.add_argument(
"--e2e_char_dict_path", type=str,
- default=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
- 'pytorchocr/utils/ic15_dict.txt'))
+ default=str(resource_dir / "ic15_dict.txt"))
parser.add_argument("--e2e_pgnet_valid_set", type=str, default='totaltext')
parser.add_argument("--e2e_pgnet_polygon", type=bool, default=True)
parser.add_argument("--e2e_pgnet_mode", type=str, default='fast')
diff --git a/mineru/model/utils/__init__.py b/mineru/model/_internal/pytorchocr/modeling/__init__.py
similarity index 66%
rename from mineru/model/utils/__init__.py
rename to mineru/model/_internal/pytorchocr/modeling/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/utils/__init__.py
+++ b/mineru/model/_internal/pytorchocr/modeling/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/utils/pytorchocr/modeling/architectures/__init__.py b/mineru/model/_internal/pytorchocr/modeling/architectures/__init__.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/architectures/__init__.py
rename to mineru/model/_internal/pytorchocr/modeling/architectures/__init__.py
diff --git a/mineru/model/utils/pytorchocr/modeling/architectures/base_model.py b/mineru/model/_internal/pytorchocr/modeling/architectures/base_model.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/architectures/base_model.py
rename to mineru/model/_internal/pytorchocr/modeling/architectures/base_model.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/__init__.py b/mineru/model/_internal/pytorchocr/modeling/backbones/__init__.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/__init__.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/__init__.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/det_mobilenet_v3.py b/mineru/model/_internal/pytorchocr/modeling/backbones/det_mobilenet_v3.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/det_mobilenet_v3.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/det_mobilenet_v3.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_donut_swin.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_donut_swin.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_donut_swin.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_donut_swin.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_hgnet.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_hgnet.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_hgnet.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_hgnet.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_lcnetv3.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_lcnetv3.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_lcnetv3.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_lcnetv3.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_lcnetv4.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_lcnetv4.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_lcnetv4.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_lcnetv4.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_mobilenet_v3.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_mobilenet_v3.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_mobilenet_v3.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_mobilenet_v3.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_mv1_enhance.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_mv1_enhance.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_mv1_enhance.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_mv1_enhance.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_pphgnetv2.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_pphgnetv2.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_pphgnetv2.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_pphgnetv2.py
diff --git a/mineru/model/utils/pytorchocr/modeling/backbones/rec_svtrnet.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_svtrnet.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/backbones/rec_svtrnet.py
rename to mineru/model/_internal/pytorchocr/modeling/backbones/rec_svtrnet.py
diff --git a/mineru/model/utils/pytorchocr/modeling/common.py b/mineru/model/_internal/pytorchocr/modeling/common.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/common.py
rename to mineru/model/_internal/pytorchocr/modeling/common.py
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/__init__.py b/mineru/model/_internal/pytorchocr/modeling/heads/__init__.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/heads/__init__.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/__init__.py
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/cls_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/cls_head.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/heads/cls_head.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/cls_head.py
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/det_db_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/det_db_head.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/heads/det_db_head.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/det_db_head.py
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/rec_ctc_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/rec_ctc_head.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/heads/rec_ctc_head.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/rec_ctc_head.py
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/rec_multi_head.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/rec_multi_head.py
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py
similarity index 99%
rename from mineru/model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py
index 07ea47b5..6ba09d25 100644
--- a/mineru/model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py
+++ b/mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py
@@ -24,7 +24,7 @@ from dataclasses import dataclass, fields, is_dataclass
from sympy import totient
-from mineru.utils.config_reader import get_device
+from .....runtime.device import get_device
from .rec_unimernet_head import (
MBartForCausalLM,
MBartDecoder,
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py
similarity index 99%
rename from mineru/model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py
rename to mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py
index 9ab6a998..f36be7f8 100644
--- a/mineru/model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py
+++ b/mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py
@@ -15,7 +15,7 @@ from torch import Tensor
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
-from mineru.utils.config_reader import get_device
+from .....runtime.device import get_device
class ModelOutput(OrderedDict):
diff --git a/mineru/model/utils/pytorchocr/modeling/necks/__init__.py b/mineru/model/_internal/pytorchocr/modeling/necks/__init__.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/necks/__init__.py
rename to mineru/model/_internal/pytorchocr/modeling/necks/__init__.py
diff --git a/mineru/model/utils/pytorchocr/modeling/necks/db_fpn.py b/mineru/model/_internal/pytorchocr/modeling/necks/db_fpn.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/necks/db_fpn.py
rename to mineru/model/_internal/pytorchocr/modeling/necks/db_fpn.py
diff --git a/mineru/model/utils/pytorchocr/modeling/necks/intracl.py b/mineru/model/_internal/pytorchocr/modeling/necks/intracl.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/necks/intracl.py
rename to mineru/model/_internal/pytorchocr/modeling/necks/intracl.py
diff --git a/mineru/model/utils/pytorchocr/modeling/necks/rnn.py b/mineru/model/_internal/pytorchocr/modeling/necks/rnn.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/modeling/necks/rnn.py
rename to mineru/model/_internal/pytorchocr/modeling/necks/rnn.py
diff --git a/mineru/model/utils/pytorchocr/postprocess/__init__.py b/mineru/model/_internal/pytorchocr/postprocess/__init__.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/postprocess/__init__.py
rename to mineru/model/_internal/pytorchocr/postprocess/__init__.py
diff --git a/mineru/model/utils/pytorchocr/postprocess/cls_postprocess.py b/mineru/model/_internal/pytorchocr/postprocess/cls_postprocess.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/postprocess/cls_postprocess.py
rename to mineru/model/_internal/pytorchocr/postprocess/cls_postprocess.py
diff --git a/mineru/model/utils/pytorchocr/postprocess/db_postprocess.py b/mineru/model/_internal/pytorchocr/postprocess/db_postprocess.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/postprocess/db_postprocess.py
rename to mineru/model/_internal/pytorchocr/postprocess/db_postprocess.py
diff --git a/mineru/model/utils/pytorchocr/postprocess/rec_postprocess.py b/mineru/model/_internal/pytorchocr/postprocess/rec_postprocess.py
similarity index 100%
rename from mineru/model/utils/pytorchocr/postprocess/rec_postprocess.py
rename to mineru/model/_internal/pytorchocr/postprocess/rec_postprocess.py
diff --git a/mineru/model/utils/pytorchocr/utils/__init__.py b/mineru/model/_internal/pytorchocr/utils/__init__.py
similarity index 66%
rename from mineru/model/utils/pytorchocr/utils/__init__.py
rename to mineru/model/_internal/pytorchocr/utils/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/utils/pytorchocr/utils/__init__.py
+++ b/mineru/model/_internal/pytorchocr/utils/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/utils/pytorchocr/utils/resources/arch_config.yaml b/mineru/model/_internal/pytorchocr/utils/resources/arch_config.yaml
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/arch_config.yaml
rename to mineru/model/_internal/pytorchocr/utils/resources/arch_config.yaml
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ka_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ka_dict.txt
similarity index 99%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ka_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ka_dict.txt
index d506b691..9a6ed223 100644
--- a/mineru/model/utils/pytorchocr/utils/resources/dict/ka_dict.txt
+++ b/mineru/model/_internal/pytorchocr/utils/resources/dict/ka_dict.txt
@@ -150,4 +150,3 @@ $
(
?
+
-
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv6_dict.txt b/mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv6_dict.txt
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv6_dict.txt
rename to mineru/model/_internal/pytorchocr/utils/resources/dict/ppocrv6_dict.txt
diff --git a/mineru/model/utils/pytorchocr/utils/resources/models_config.yml b/mineru/model/_internal/pytorchocr/utils/resources/models_config.yml
similarity index 100%
rename from mineru/model/utils/pytorchocr/utils/resources/models_config.yml
rename to mineru/model/_internal/pytorchocr/utils/resources/models_config.yml
diff --git a/mineru/model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml b/mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
similarity index 87%
rename from mineru/model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
rename to mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
index c95f8853..f04e01d4 100644
--- a/mineru/model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
+++ b/mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
@@ -16,9 +16,9 @@ Architecture:
decoder_layers: 6
temperature: 0.2
do_sample: False
- top_p: 0.95
+ top_p: 0.95
encoder_hidden_size: 2048
is_export: False
- length_aware: False
+ length_aware: False
use_parallel: False
parallel_step: 0
\ No newline at end of file
diff --git a/mineru/utils/models_download_utils.py b/mineru/model/download.py
similarity index 73%
rename from mineru/utils/models_download_utils.py
rename to mineru/model/download.py
index 50c3f0a2..b8f69817 100644
--- a/mineru/utils/models_download_utils.py
+++ b/mineru/model/download.py
@@ -2,10 +2,11 @@
from __future__ import annotations
import os
+import re
from collections.abc import Sequence
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
import requests
from filelock import FileLock
@@ -16,7 +17,100 @@ from loguru import logger
from modelscope import snapshot_download as ms_snapshot_download
from ..config import config, get_config_source, update_config_file
-from .model_registry import MODEL_COMPLETE_MARKER, ModelPath, ModelRepo, model_path_exists
+
+if TYPE_CHECKING:
+ from ..config import ModelSource
+
+DownloadMode = Literal["full", "required_paths"]
+MODEL_COMPLETE_MARKER = ".mineru_complete"
+
+
+def _join_model_path(*parts: str) -> str:
+ """连接并校验模型仓库内的相对路径片段。"""
+ cleaned: list[str] = []
+ for raw in parts:
+ value = str(raw).replace("\\", "/").strip("/")
+ if not value:
+ continue
+ cleaned.extend(part for part in value.split("/") if part and part != ".")
+ if any(part == ".." for part in cleaned):
+ raise ValueError("Model paths must not contain '..' segments.")
+ return "/".join(cleaned)
+
+
+@dataclass(frozen=True)
+class ModelPath:
+ """表示模型仓库中的一个具名相对路径。"""
+
+ repo: "ModelRepo"
+ name: str
+ relative_path: str
+
+ def path(self, relative_path: str, /, *children: str) -> "ModelPath":
+ """基于当前路径派生一个更深的模型路径。"""
+ joined = _join_model_path(self.relative_path, relative_path, *children)
+ name = _join_model_path(self.name, relative_path, *children)
+ return ModelPath(repo=self.repo, name=name, relative_path=joined)
+
+ def local_path(self) -> Path:
+ """返回该模型路径在本地模型根目录中的位置。"""
+ return self.repo.local_dir() / self.relative_path
+
+ def ensure(self, *, source: "ModelSource | None" = None) -> Path:
+ """确保当前模型路径已下载并返回本地位置。"""
+ download_model_files(self.repo, [self], source=source, reuse_ready=True)
+ return self.local_path()
+
+
+@dataclass(frozen=True)
+class ModelRepo:
+ """定义一个可从多来源获取的模型仓库。"""
+
+ name: str
+ repos: dict[str, str]
+ local_name: str = ""
+ paths: dict[str, str] = field(default_factory=dict)
+ download_mode: DownloadMode = "full"
+ stack: str = "full"
+
+ def __post_init__(self) -> None:
+ """缺少本地名称时使用稳定仓库名。"""
+ if not self.local_name:
+ object.__setattr__(self, "local_name", self.name)
+
+ def __getattr__(self, name: str) -> ModelPath:
+ """允许通过具名字段读取仓库预定义路径。"""
+ try:
+ return self.named_path(name)
+ except KeyError as exc:
+ raise AttributeError(name) from exc
+
+ def named_path(self, name: str) -> ModelPath:
+ """返回仓库中已声明的具名模型路径。"""
+ return ModelPath(repo=self, name=name, relative_path=self.paths[name])
+
+ def path(self, relative_path: str, /, *children: str) -> ModelPath:
+ """按任意安全相对路径构造模型路径。"""
+ joined = _join_model_path(relative_path, *children)
+ return ModelPath(repo=self, name=joined, relative_path=joined)
+
+ def required_paths(self) -> tuple[ModelPath, ...]:
+ """返回仓库声明的全部必需路径。"""
+ return tuple(self.named_path(name) for name in self.paths)
+
+ def local_dir(self) -> Path:
+ """返回仓库在 MinerU 模型目录中的本地根路径。"""
+ return Path(config.model.base_dir).expanduser() / self.local_name
+
+ def lock_path(self) -> Path:
+ """返回仓库下载互斥锁的稳定路径。"""
+ safe_name = re.sub(r"[^A-Za-z0-9_.-]+", "_", self.local_name).strip("._") or "model"
+ return Path(config.model.base_dir).expanduser() / ".locks" / f"{safe_name}.lock"
+
+ def ensure(self, *, source: "ModelSource | None" = None) -> Path:
+ """确保完整仓库可用并返回本地根路径。"""
+ return download_model_repo(self, source=source, reuse_ready=True)
+
MODEL_SOURCE_ENV_VAR = "MINERU_MODEL_SOURCE"
_HUGGINGFACE_MODELS_PAGE_URL = "https://huggingface.co/models"
@@ -311,12 +405,37 @@ def verify_model_repo(repo: ModelRepo) -> ModelReadyResult:
return _verify_paths(repo, list(repo.required_paths()))
+def model_path_exists(path: ModelPath) -> bool:
+ """判断模型路径存在且所属目录已写入完整标记。"""
+ local_path = path.local_path()
+ if local_path.is_file():
+ return True
+ if not local_path.is_dir():
+ return False
+ repo_root = path.repo.local_dir()
+ try:
+ local_path.relative_to(repo_root)
+ except ValueError:
+ return False
+ for directory in (local_path, *local_path.parents):
+ if (directory / MODEL_COMPLETE_MARKER).is_file():
+ return True
+ if directory == repo_root:
+ break
+ return False
+
+
__all__ = [
"DOWNLOAD_MODEL_SOURCES",
+ "DownloadMode",
+ "MODEL_COMPLETE_MARKER",
"MODEL_SOURCE_ENV_VAR",
+ "ModelPath",
"ModelReadyResult",
+ "ModelRepo",
"download_model_files",
"download_model_repo",
+ "model_path_exists",
"resolve_model_source",
"verify_model_repo",
]
diff --git a/mineru/model/layout/__init__.py b/mineru/model/layout/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/layout/__init__.py
+++ b/mineru/model/layout/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/layout/pp_doclayout_v2_base.py b/mineru/model/layout/pp_doclayout_v2_base.py
index a42d4135..fbc66fc9 100644
--- a/mineru/model/layout/pp_doclayout_v2_base.py
+++ b/mineru/model/layout/pp_doclayout_v2_base.py
@@ -18,7 +18,7 @@ from typing import Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
from PIL import Image, ImageDraw, ImageFont
-from ...utils.bbox_utils import normalize_to_int_bbox
+from ...utils.geometry import normalize_to_int_bbox
DEFAULT_IMAGE_SIZE = (800, 800)
DEFAULT_RESCALE_FACTOR = 1.0 / 255.0
diff --git a/mineru/model/layout/pp_doclayout_v2_onnx.py b/mineru/model/layout/pp_doclayout_v2_onnx.py
index ac409c4f..2b32e94c 100644
--- a/mineru/model/layout/pp_doclayout_v2_onnx.py
+++ b/mineru/model/layout/pp_doclayout_v2_onnx.py
@@ -19,7 +19,7 @@ from loguru import logger
from PIL import Image
from tqdm import tqdm
-from ..utils.onnxruntime_provider import ort_session
+from ..runtime.onnx import ort_session
from .pp_doclayout_v2_base import PP_DOCLAYOUT_V2_LABELS, PPDocLayoutV2PostProcessor
__all__ = ["PPDocLayoutV2LayoutModelONNX"]
@@ -207,12 +207,12 @@ if __name__ == "__main__":
args = parser.parse_args()
if args.model is None:
- from ...utils.model_registry import PP_DOCLAYOUT_V2_ONNX
+ from ..registry import PP_DOCLAYOUT_V2_ONNX
args.model = str(PP_DOCLAYOUT_V2_ONNX.onnx.ensure())
if args.device is None:
- from ...utils.config_reader import get_device
+ from ..runtime.device import get_device
args.device = get_device()
diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.py
index 9914bf47..c9a7e2ae 100644
--- a/mineru/model/layout/pp_doclayoutv2.py
+++ b/mineru/model/layout/pp_doclayoutv2.py
@@ -1558,12 +1558,12 @@ if __name__ == "__main__":
args = parser.parse_args()
if args.device is None:
- from mineru.utils.config_reader import get_device
+ from ..runtime.device import get_device
args.device = get_device()
if args.model is None:
- from ...utils.model_registry import PDF_EXTRACT_KIT
+ from ..registry import PDF_EXTRACT_KIT
args.model = str(PDF_EXTRACT_KIT.pp_doclayout_v2.ensure())
diff --git a/mineru/model/mfr/__init__.py b/mineru/model/mfr/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/mfr/__init__.py
+++ b/mineru/model/mfr/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/__init__.py b/mineru/model/mfr/pp_formulanet_plus_m/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m/__init__.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
index 33ac30a6..91c7f568 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
@@ -7,8 +7,8 @@ import torch
import yaml
from tqdm import tqdm
-from mineru.model.utils.pytorchocr.base_ocr_v20 import BaseOCRV20
-from mineru.model.utils.tools.infer import pytorchocr_utility
+from ..._internal.pytorchocr.base_ocr_v20 import BaseOCRV20
+from ..._internal.pytorchocr.infer import pytorchocr_utility
from ..utils import build_mfr_batch_groups
from .processors import (
@@ -30,13 +30,13 @@ class FormulaRecognizer(BaseOCRV20):
weight_dir,
"PP-FormulaNet_plus-M.pth",
)
- self.yaml_path = os.path.join(
- Path(__file__).parent.parent.parent,
- "utils",
- "pytorchocr",
- "utils",
- "resources",
- "pp_formulanet_arch_config.yaml",
+ self.yaml_path = str(
+ Path(__file__).resolve().parents[2]
+ / "_internal"
+ / "pytorchocr"
+ / "utils"
+ / "resources"
+ / "pp_formulanet_arch_config.yaml"
)
self.infer_yaml_path = os.path.join(
weight_dir,
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/processors.py b/mineru/model/mfr/pp_formulanet_plus_m/processors.py
index bd42c071..a53524cc 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m/processors.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m/processors.py
@@ -10,7 +10,7 @@ from PIL import Image, ImageOps
from tokenizers import AddedToken
from tokenizers import Tokenizer as TokenizerFast
-from mineru.model.mfr.post_process import post_process_formula
+from ..post_process import post_process_formula
class UniMERNetImgDecode(object):
diff --git a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
index 00afc7da..62acc49d 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
@@ -24,7 +24,7 @@ from loguru import logger
from PIL import Image, ImageOps
from tqdm import tqdm
-from ..utils.onnxruntime_provider import ort_session
+from ..runtime.onnx import ort_session
from .post_process import post_process_formula
__all__ = ["PPFormulaNetPlusMONNX"]
diff --git a/mineru/model/mfr/unimernet/__init__.py b/mineru/model/mfr/unimernet/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/mfr/unimernet/__init__.py
+++ b/mineru/model/mfr/unimernet/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/ocr/__init__.py b/mineru/model/ocr/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/ocr/__init__.py
+++ b/mineru/model/ocr/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/ocr/geometry.py b/mineru/model/ocr/geometry.py
new file mode 100644
index 00000000..ba348692
--- /dev/null
+++ b/mineru/model/ocr/geometry.py
@@ -0,0 +1,200 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""OCR 文本框排序、重叠判断与检测框几何变换。"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import numpy as np
+
+from ...types import BBox
+
+LINE_WIDTH_TO_HEIGHT_RATIO_THRESHOLD = 4
+
+
+def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:
+ """按纵向重叠把 OCR span 聚合为文本行。"""
+ if not spans:
+ return []
+ spans.sort(key=lambda span: span["bbox"][1])
+ lines: list[list[dict[str, Any]]] = []
+ current_line = [spans[0]]
+ for span in spans[1:]:
+ if _is_overlaps_y_exceeds_threshold(span["bbox"], current_line[-1]["bbox"], threshold):
+ current_line.append(span)
+ else:
+ lines.append(current_line)
+ current_line = [span]
+ lines.append(current_line)
+ return lines
+
+
+def _is_overlaps_y_exceeds_threshold(
+ bbox1: BBox,
+ bbox2: BBox,
+ overlap_ratio_threshold: float = 0.8,
+) -> bool:
+ """判断两个框在纵轴上的重叠是否超过较小高度的阈值。"""
+ _, y0_1, _, y1_1 = bbox1
+ _, y0_2, _, y1_2 = bbox2
+ overlap = max(0, min(y1_1, y1_2) - max(y0_1, y0_2))
+ min_height = min(y1_1 - y0_1, y1_2 - y0_2)
+ return (overlap / min_height) > overlap_ratio_threshold if min_height > 0 else False
+
+
+def _is_overlaps_x_exceeds_threshold(
+ bbox1: BBox,
+ bbox2: BBox,
+ overlap_ratio_threshold: float = 0.8,
+) -> bool:
+ """判断两个框在横轴上的重叠是否超过较小宽度的阈值。"""
+ x0_1, _, x1_1, _ = bbox1
+ x0_2, _, x1_2, _ = bbox2
+ overlap = max(0, min(x1_1, x1_2) - max(x0_1, x0_2))
+ min_width = min(x1_1 - x0_1, x1_2 - x0_2)
+ return (overlap / min_width) > overlap_ratio_threshold if min_width > 0 else False
+
+
+def sorted_boxes(dt_boxes: list[Any]) -> list[Any]:
+ """按从上到下、同行从左到右稳定排序检测框。"""
+ boxes = sorted(dt_boxes, key=lambda box: (box[0][1], box[0][0]))
+ for index in range(len(boxes) - 1):
+ for previous_index in range(index, -1, -1):
+ if abs(boxes[previous_index + 1][0][1] - boxes[previous_index][0][1]) < 10 and (
+ boxes[previous_index + 1][0][0] < boxes[previous_index][0][0]
+ ):
+ boxes[previous_index], boxes[previous_index + 1] = boxes[previous_index + 1], boxes[previous_index]
+ else:
+ break
+ return boxes
+
+
+def bbox_to_points(bbox: BBox) -> np.ndarray:
+ """将四元组 bbox 转换为顺时针四点数组。"""
+ x0, y0, x1, y1 = bbox
+ return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).astype("float32")
+
+
+def points_to_bbox(points: np.ndarray) -> BBox:
+ """将顺时针四点数组转换为四元组 bbox。"""
+ x0, y0 = points[0]
+ x1, _ = points[1]
+ _, y1 = points[2]
+ return x0, y0, x1, y1
+
+
+def merge_intervals(intervals: list[list[float]]) -> list[list[float]]:
+ """合并相互重叠的闭区间。"""
+ intervals.sort(key=lambda interval: interval[0])
+ merged: list[list[float]] = []
+ for interval in intervals:
+ if not merged or merged[-1][1] < interval[0]:
+ merged.append(interval)
+ else:
+ merged[-1][1] = max(merged[-1][1], interval[1])
+ return merged
+
+
+def remove_intervals(original: list[float], masks: list[list[float]]) -> list[list[float]]:
+ """从一个闭区间中移除全部遮罩区间。"""
+ result: list[list[float]] = []
+ original_start, original_end = original
+ for mask_start, mask_end in merge_intervals(masks):
+ if mask_start > original_end or mask_end < original_start:
+ continue
+ if original_start < mask_start:
+ result.append([original_start, mask_start - 1])
+ original_start = max(mask_end + 1, original_start)
+ if original_start <= original_end:
+ result.append([original_start, original_end])
+ return result
+
+
+def update_det_boxes(dt_boxes: list[Any], mfd_res: list[dict[str, Any]]) -> list[Any]:
+ """从横向 OCR 检测框中裁除公式检测区间。"""
+ new_dt_boxes: list[Any] = []
+ angle_boxes: list[Any] = []
+ for text_box in dt_boxes:
+ if calculate_is_angle(text_box):
+ angle_boxes.append(text_box)
+ continue
+ text_bbox = points_to_bbox(text_box)
+ masks = [
+ [mf_box["bbox"][0], mf_box["bbox"][2]]
+ for mf_box in mfd_res
+ if _is_overlaps_y_exceeds_threshold(text_bbox, mf_box["bbox"])
+ ]
+ for remaining in remove_intervals([text_bbox[0], text_bbox[2]], masks):
+ new_dt_boxes.append(bbox_to_points((remaining[0], text_bbox[1], remaining[1], text_bbox[3])))
+ new_dt_boxes.extend(angle_boxes)
+ return new_dt_boxes
+
+
+def merge_overlapping_spans(spans: list[BBox]) -> list[BBox]:
+ """合并同一行中横向重叠的 bbox。"""
+ if not spans:
+ return []
+ spans.sort(key=lambda span: span[0])
+ merged: list[BBox] = []
+ for span in spans:
+ x1, y1, x2, y2 = span
+ if not merged or merged[-1][2] < x1:
+ merged.append(span)
+ continue
+ previous = merged.pop()
+ merged.append((min(previous[0], x1), min(previous[1], y1), max(previous[2], x2), max(previous[3], y2)))
+ return merged
+
+
+def merge_det_boxes(dt_boxes: list[Any]) -> list[Any]:
+ """把同一横向文本行中的 OCR 检测框合并为较大区域。"""
+ horizontal_boxes: list[dict[str, Any]] = []
+ angle_boxes: list[Any] = []
+ for text_box in dt_boxes:
+ text_bbox = points_to_bbox(text_box)
+ if calculate_is_angle(text_box):
+ angle_boxes.append(text_box)
+ else:
+ horizontal_boxes.append({"bbox": text_bbox})
+
+ new_dt_boxes: list[Any] = []
+ for line in merge_spans_to_line(horizontal_boxes):
+ line_bboxes = [span["bbox"] for span in line]
+ min_x = min(bbox[0] for bbox in line_bboxes)
+ max_x = max(bbox[2] for bbox in line_bboxes)
+ min_y = min(bbox[1] for bbox in line_bboxes)
+ max_y = max(bbox[3] for bbox in line_bboxes)
+ if max_x - min_x > (max_y - min_y) * LINE_WIDTH_TO_HEIGHT_RATIO_THRESHOLD:
+ line_bboxes = merge_overlapping_spans(line_bboxes)
+ new_dt_boxes.extend(bbox_to_points(bbox) for bbox in line_bboxes)
+ new_dt_boxes.extend(angle_boxes)
+ return new_dt_boxes
+
+
+def calculate_is_angle(poly: list[Any]) -> bool:
+ """判断四点检测框是否明显偏离水平矩形。"""
+ p1, p2, p3, p4 = poly
+ height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
+ return not 0.8 * height <= (p3[1] - p1[1]) <= 1.2 * height
+
+
+def is_bbox_aligned_rect(points: np.ndarray) -> bool:
+ """判断四点数组是否为轴对齐矩形。"""
+ return len(np.unique(points[:, 0])) == 2 and len(np.unique(points[:, 1])) == 2
+
+
+__all__ = [
+ "_is_overlaps_x_exceeds_threshold",
+ "_is_overlaps_y_exceeds_threshold",
+ "bbox_to_points",
+ "calculate_is_angle",
+ "is_bbox_aligned_rect",
+ "merge_det_boxes",
+ "merge_intervals",
+ "merge_overlapping_spans",
+ "merge_spans_to_line",
+ "points_to_bbox",
+ "remove_intervals",
+ "sorted_boxes",
+ "update_det_boxes",
+]
diff --git a/mineru/model/ocr/image.py b/mineru/model/ocr/image.py
new file mode 100644
index 00000000..60af8304
--- /dev/null
+++ b/mineru/model/ocr/image.py
@@ -0,0 +1,130 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""OCR 输入图像解码、遮罩与旋转裁剪。"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import cv2
+import numpy as np
+
+from ...utils.geometry import normalize_to_int_bbox
+from .geometry import is_bbox_aligned_rect
+
+TEXT_REC_ROTATE_RATIO = 1.5
+
+
+def img_decode(content: bytes) -> Any:
+ """把编码图片字节解码为 OpenCV 数组。"""
+ np_arr = np.frombuffer(content, dtype=np.uint8)
+ return cv2.imdecode(np_arr, cv2.IMREAD_UNCHANGED)
+
+
+def check_img(img: bytes | np.ndarray) -> Any:
+ """统一字节与灰度图输入为 OCR 可处理的图像数组。"""
+ if isinstance(img, bytes):
+ img = img_decode(img)
+ if isinstance(img, np.ndarray) and len(img.shape) == 2:
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
+ return img
+
+
+def alpha_to_color(img: np.ndarray, alpha_color: tuple[int, int, int] = (255, 255, 255)) -> np.ndarray:
+ """把带透明通道的图像合成到指定纯色背景。"""
+ if len(img.shape) == 3 and img.shape[2] == 4:
+ blue, green, red, alpha_channel = cv2.split(img)
+ alpha = alpha_channel / 255
+ red = (alpha_color[0] * (1 - alpha) + red * alpha).astype(np.uint8)
+ green = (alpha_color[1] * (1 - alpha) + green * alpha).astype(np.uint8)
+ blue = (alpha_color[2] * (1 - alpha) + blue * alpha).astype(np.uint8)
+ img = cv2.merge((blue, green, red))
+ return img
+
+
+def preprocess_image(image: np.ndarray) -> np.ndarray:
+ """将 OCR 输入图像统一合成到白色背景。"""
+ return alpha_to_color(image, (255, 255, 255))
+
+
+def mask_formula_regions_for_ocr_det(
+ bgr_image: np.ndarray,
+ mask_boxes: list[dict[str, Any]] | None,
+) -> np.ndarray:
+ """将公式区域涂白后再做 OCR 检测,避免公式框干扰文本检测。"""
+ if not mask_boxes:
+ return bgr_image
+
+ masked_image = bgr_image.copy()
+ image_h, image_w = masked_image.shape[:2]
+ for mask_box in mask_boxes:
+ bbox = mask_box.get("bbox")
+ if bbox is None:
+ continue
+ int_bbox = normalize_to_int_bbox(bbox, image_size=(image_h, image_w))
+ if int_bbox is None:
+ continue
+ x0, y0, x1, y1 = int_bbox
+ masked_image[y0:y1, x0:x1] = 255
+ return masked_image
+
+
+def get_rotate_crop_image(img: np.ndarray, points: np.ndarray) -> np.ndarray:
+ """按四边形透视裁剪文本区域,并自动转正高纵横比结果。"""
+ assert len(points) == 4, "shape of points must be 4*2"
+ if is_bbox_aligned_rect(points):
+ xmin = int(np.min(points[:, 0]))
+ xmax = int(np.max(points[:, 0]))
+ ymin = int(np.min(points[:, 1]))
+ ymax = int(np.max(points[:, 1]))
+ new_img = img[ymin:ymax, xmin:xmax].copy()
+ if new_img.shape[0] > 0 and new_img.shape[1] > 0:
+ return new_img
+
+ img_crop_width = int(max(np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3])))
+ img_crop_height = int(max(np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2])))
+ pts_std = np.float32([[0, 0], [img_crop_width, 0], [img_crop_width, img_crop_height], [0, img_crop_height]])
+ matrix = cv2.getPerspectiveTransform(points, pts_std)
+ dst_img = cv2.warpPerspective(
+ img,
+ matrix,
+ (img_crop_width, img_crop_height),
+ borderMode=cv2.BORDER_REPLICATE,
+ flags=cv2.INTER_CUBIC,
+ )
+ dst_img_height, dst_img_width = dst_img.shape[:2]
+ if dst_img_height / dst_img_width >= TEXT_REC_ROTATE_RATIO:
+ dst_img = np.rot90(dst_img)
+ return dst_img
+
+
+def rotate_vertical_crop_if_needed(
+ crop_img: np.ndarray | None,
+ rotate_ratio: float = TEXT_REC_ROTATE_RATIO,
+) -> np.ndarray | None:
+ """在裁图明显竖长时旋转九十度供文字识别。"""
+ if crop_img is None or crop_img.size == 0:
+ return crop_img
+ crop_height, crop_width = crop_img.shape[:2]
+ if crop_width == 0:
+ return crop_img
+ if crop_height / crop_width >= rotate_ratio:
+ return np.rot90(crop_img)
+ return crop_img
+
+
+def get_rotate_crop_image_for_text_rec(img: np.ndarray, points: np.ndarray) -> np.ndarray | None:
+ """裁剪四边形文本区域并应用文字识别方向规则。"""
+ return rotate_vertical_crop_if_needed(get_rotate_crop_image(img, points))
+
+
+__all__ = [
+ "TEXT_REC_ROTATE_RATIO",
+ "alpha_to_color",
+ "check_img",
+ "get_rotate_crop_image",
+ "get_rotate_crop_image_for_text_rec",
+ "img_decode",
+ "mask_formula_regions_for_ocr_det",
+ "preprocess_image",
+ "rotate_vertical_crop_if_needed",
+]
diff --git a/mineru/utils/ocr_language.py b/mineru/model/ocr/language.py
similarity index 86%
rename from mineru/utils/ocr_language.py
rename to mineru/model/ocr/language.py
index 72f3793e..94be5647 100644
--- a/mineru/utils/ocr_language.py
+++ b/mineru/model/ocr/language.py
@@ -1,5 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
+from collections.abc import Collection
+
PUBLIC_OCR_LANGUAGES = (
"ch",
"ch_server",
@@ -24,9 +26,7 @@ _PUBLIC_OCR_LANGUAGE_DESCRIPTIONS = {
"ka": "Kannada",
"th": "Thai, English",
"el": "Greek, English",
- "arabic": (
- "Arabic, Persian, Uyghur, Urdu, Pashto, Kurdish, Sindhi, Balochi, English"
- ),
+ "arabic": ("Arabic, Persian, Uyghur, Urdu, Pashto, Kurdish, Sindhi, Balochi, English"),
"east_slavic": "Russian, Belarusian, Ukrainian, English",
"cyrillic": (
"Russian, Belarusian, Ukrainian, Serbian (Cyrillic), Bulgarian, Mongolian, "
@@ -41,10 +41,7 @@ _PUBLIC_OCR_LANGUAGE_DESCRIPTIONS = {
),
}
-PUBLIC_OCR_LANGUAGE_CHOICES = tuple(
- f"{lang} ({_PUBLIC_OCR_LANGUAGE_DESCRIPTIONS[lang]})"
- for lang in PUBLIC_OCR_LANGUAGES
-)
+PUBLIC_OCR_LANGUAGE_CHOICES = tuple(f"{lang} ({_PUBLIC_OCR_LANGUAGE_DESCRIPTIONS[lang]})" for lang in PUBLIC_OCR_LANGUAGES)
PUBLIC_OCR_LANGUAGE_SCHEMA_EXTRA = {"items": {"enum": list(PUBLIC_OCR_LANGUAGES)}}
@@ -102,15 +99,11 @@ _DEVANAGARI_LANG_ALIASES = {
def format_public_ocr_lang_description() -> str:
"""生成公开 API 使用的 OCR 语言说明,避免入口文案各自维护。"""
- option_lines = [
- f"- {lang}: {_PUBLIC_OCR_LANGUAGE_DESCRIPTIONS[lang]}."
- for lang in PUBLIC_OCR_LANGUAGES
- ]
+ option_lines = [f"- {lang}: {_PUBLIC_OCR_LANGUAGE_DESCRIPTIONS[lang]}." for lang in PUBLIC_OCR_LANGUAGES]
return (
"(Mainly for Hybrid medium local OCR and table OCR; accepted by other "
"Hybrid efforts for compatibility.) Input the languages in the pdf "
- "to improve OCR accuracy when language-aware OCR is used. Options:\n"
- + "\n".join(option_lines)
+ "to improve OCR accuracy when language-aware OCR is used. Options:\n" + "\n".join(option_lines)
)
@@ -118,10 +111,7 @@ def validate_public_ocr_lang(lang: str) -> str:
"""校验公开入口允许的 OCR 语言,并将隐藏兼容别名归一到 ch。"""
normalized_lang = "ch" if lang in _CH_LANG_ALIASES else lang
if normalized_lang not in PUBLIC_OCR_LANGUAGES:
- raise ValueError(
- f"Language {lang} not supported. Allowed values: "
- + ", ".join(PUBLIC_OCR_LANGUAGES)
- )
+ raise ValueError(f"Language {lang} not supported. Allowed values: " + ", ".join(PUBLIC_OCR_LANGUAGES))
return normalized_lang
@@ -135,7 +125,7 @@ def normalize_ocr_model_lang(
lang: str | None,
*,
device: str | None = None,
- supported_langs=None,
+ supported_langs: Collection[str] | None = None,
) -> str:
"""将 OCR 语言参数归一为模型配置 key,保留内部 seal 与语系短码能力。"""
normalized_lang = lang or "ch"
diff --git a/mineru/model/ocr/pp_ocr_v6_onnx.py b/mineru/model/ocr/pp_ocr_v6_onnx.py
index f210f554..f8d3bd34 100644
--- a/mineru/model/ocr/pp_ocr_v6_onnx.py
+++ b/mineru/model/ocr/pp_ocr_v6_onnx.py
@@ -28,15 +28,9 @@ from loguru import logger
from shapely.geometry import Polygon
from tqdm import tqdm
-from ...utils.ocr_utils import (
- check_img,
- get_rotate_crop_image_for_text_rec,
- merge_det_boxes,
- preprocess_image,
- sorted_boxes,
- update_det_boxes,
-)
-from ..utils.onnxruntime_provider import ort_session
+from ..runtime.onnx import ort_session
+from .geometry import merge_det_boxes, sorted_boxes, update_det_boxes
+from .image import check_img, get_rotate_crop_image_for_text_rec, preprocess_image
__all__ = ["PPOCRv6ONNX"]
@@ -589,7 +583,7 @@ if __name__ == "__main__":
# 默认从 model_registry 获取路径
if args.det is None or args.rec is None:
- from ...utils.model_registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX
+ from ..registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX
if args.det is None:
args.det = str(PP_OCR_V6_SMALL_DET_ONNX.onnx.ensure())
@@ -598,7 +592,7 @@ if __name__ == "__main__":
if args.dict is None:
# rec 的 dict 内嵌在 inference.yml 里,但我们直接用 ModelScope 下载的 dict
# 从 rec 的 model_registry config path 读取
- from ...utils.model_registry import PP_OCR_V6_SMALL_REC_ONNX
+ from ..registry import PP_OCR_V6_SMALL_REC_ONNX
rec_dir = PP_OCR_V6_SMALL_REC_ONNX.onnx.local_path().parent
# 尝试从 inference.yml 提取 dict,或使用内置的
diff --git a/mineru/model/ocr/pytorch_paddle.py b/mineru/model/ocr/pytorch_paddle.py
index 377ad4cf..57cd7911 100644
--- a/mineru/model/ocr/pytorch_paddle.py
+++ b/mineru/model/ocr/pytorch_paddle.py
@@ -10,20 +10,14 @@ import numpy as np
import yaml
from loguru import logger
-from mineru.model.ocr.seal_crop import CropByPolys, SortPolyBoxes
-from mineru.utils.config_reader import get_device
-from ...utils.model_registry import PDF_EXTRACT_KIT
-from mineru.utils.ocr_language import normalize_ocr_model_lang
-from mineru.utils.ocr_utils import (
- check_img,
- preprocess_image,
- sorted_boxes,
- merge_det_boxes,
- update_det_boxes,
- get_rotate_crop_image_for_text_rec,
-)
-from mineru.model.utils.tools.infer.predict_system import TextSystem
-from mineru.model.utils.tools.infer import pytorchocr_utility as utility
+from ..registry import PDF_EXTRACT_KIT
+from ..runtime.device import get_device
+from .._internal.pytorchocr.infer import pytorchocr_utility as utility
+from .._internal.pytorchocr.infer.predict_system import TextSystem
+from .geometry import merge_det_boxes, sorted_boxes, update_det_boxes
+from .image import check_img, get_rotate_crop_image_for_text_rec, preprocess_image
+from .language import normalize_ocr_model_lang
+from .seal_crop import CropByPolys, SortPolyBoxes
import argparse
@@ -38,7 +32,7 @@ def get_model_params(lang, config):
raise Exception (f'Language {lang} not supported')
-root_dir = os.path.join(Path(__file__).resolve().parent.parent, 'utils')
+PYTORCHOCR_RESOURCE_DIR = Path(__file__).resolve().parents[1] / "_internal" / "pytorchocr" / "utils" / "resources"
DEFAULT_SEAL_DEBUG_DIR = os.path.join(
Path(__file__).resolve().parents[3],
'output_images',
@@ -57,7 +51,7 @@ class PytorchPaddleOCR(TextSystem):
self.enable_merge_det_boxes = kwargs.get("enable_merge_det_boxes", True)
device = get_device()
- models_config_path = os.path.join(root_dir, 'pytorchocr', 'utils', 'resources', 'models_config.yml')
+ models_config_path = PYTORCHOCR_RESOURCE_DIR / "models_config.yml"
with open(models_config_path, encoding='utf-8') as file:
config = yaml.safe_load(file)
self.lang = normalize_ocr_model_lang(
@@ -70,7 +64,7 @@ class PytorchPaddleOCR(TextSystem):
rec_model_path = str(PDF_EXTRACT_KIT.pytorch_paddle.path(rec).ensure())
kwargs['det_model_path'] = det_model_path
kwargs['rec_model_path'] = rec_model_path
- kwargs['rec_char_dict_path'] = os.path.join(root_dir, 'pytorchocr', 'utils', 'resources', 'dict', dict_file)
+ kwargs['rec_char_dict_path'] = str(PYTORCHOCR_RESOURCE_DIR / "dict" / dict_file)
kwargs['rec_batch_num'] = 6
if self.is_seal:
# Seal detector 的 BatchNorm 统计量会在 fp16 下溢出,初始化时固定使用 fp32。
diff --git a/mineru/model/ocr/results.py b/mineru/model/ocr/results.py
new file mode 100644
index 00000000..f0a4d634
--- /dev/null
+++ b/mineru/model/ocr/results.py
@@ -0,0 +1,100 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""OCR 原始输出到 Analyze 检测结果的坐标回投。"""
+
+from __future__ import annotations
+
+import copy
+from typing import Any
+
+import numpy as np
+
+from ...utils.geometry import normalize_to_int_bbox
+from .geometry import calculate_is_angle
+from .image import get_rotate_crop_image_for_text_rec
+
+
+class OcrConfidence:
+ """集中保存 OCR 结果过滤阈值。"""
+
+ min_confidence = 0.5
+ min_width = 3
+
+
+def get_adjusted_mfdetrec_res(
+ single_page_mfdetrec_res: list[dict[str, Any]],
+ useful_list: list[int],
+) -> list[dict[str, Any]]:
+ """把整页公式框换算为当前 OCR 裁图坐标。"""
+ paste_x, paste_y, xmin, ymin, _xmax, _ymax, new_width, new_height = useful_list
+ adjusted_mfdetrec_res = []
+ for mf_res in single_page_mfdetrec_res:
+ mf_xmin, mf_ymin, mf_xmax, mf_ymax = mf_res["bbox"]
+ x0 = mf_xmin - xmin + paste_x
+ y0 = mf_ymin - ymin + paste_y
+ x1 = mf_xmax - xmin + paste_x
+ y1 = mf_ymax - ymin + paste_y
+ if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):
+ continue
+ adjusted_mfdetrec_res.append({"bbox": [x0, y0, x1, y1]})
+ return adjusted_mfdetrec_res
+
+
+def get_ocr_result_list(
+ ocr_res: list[Any],
+ useful_list: list[int],
+ ocr_enable: bool,
+ bgr_image: np.ndarray,
+) -> list[dict[str, Any]]:
+ """过滤 OCR 输出并将坐标回投到原始页面。"""
+ paste_x, paste_y, xmin, ymin, _xmax, _ymax, _new_width, _new_height = useful_list
+ ocr_result_list = []
+ ori_im = bgr_image.copy()
+ for box_ocr_res in ocr_res:
+ img_crop = None
+ need_ocr_rec = False
+ if len(box_ocr_res) == 2:
+ p1, p2, p3, p4 = box_ocr_res[0]
+ text, score = box_ocr_res[1]
+ if score < OcrConfidence.min_confidence:
+ continue
+ else:
+ p1, p2, p3, p4 = box_ocr_res
+ text, score = "", 1
+ if ocr_enable:
+ tmp_box = copy.deepcopy(np.array([p1, p2, p3, p4]).astype("float32"))
+ img_crop = get_rotate_crop_image_for_text_rec(ori_im, tmp_box)
+ need_ocr_rec = True
+
+ poly = [p1, p2, p3, p4]
+ if (p3[0] - p1[0]) < OcrConfidence.min_width:
+ continue
+ if calculate_is_angle(poly):
+ x_center = sum(point[0] for point in poly) / 4
+ y_center = sum(point[1] for point in poly) / 4
+ new_height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
+ new_width = p3[0] - p1[0]
+ p1 = [x_center - new_width / 2, y_center - new_height / 2]
+ p2 = [x_center + new_width / 2, y_center - new_height / 2]
+ p3 = [x_center + new_width / 2, y_center + new_height / 2]
+ p4 = [x_center - new_width / 2, y_center + new_height / 2]
+
+ p1 = [p1[0] - paste_x + xmin, p1[1] - paste_y + ymin]
+ p2 = [p2[0] - paste_x + xmin, p2[1] - paste_y + ymin]
+ p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]
+ p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]
+ bbox = normalize_to_int_bbox([p1, p2, p3, p4])
+ if bbox is None:
+ continue
+ ocr_item = {
+ "label": "ocr_text",
+ "bbox": bbox,
+ "score": 1.0 if ocr_enable else float(round(score, 2)),
+ "text": text,
+ }
+ if need_ocr_rec:
+ ocr_item["np_img"] = img_crop
+ ocr_result_list.append(ocr_item)
+ return ocr_result_list
+
+
+__all__ = ["OcrConfidence", "get_adjusted_mfdetrec_res", "get_ocr_result_list"]
diff --git a/mineru/utils/model_registry.py b/mineru/model/registry.py
similarity index 66%
rename from mineru/utils/model_registry.py
rename to mineru/model/registry.py
index e5df14cf..bd35b9db 100644
--- a/mineru/utils/model_registry.py
+++ b/mineru/model/registry.py
@@ -1,93 +1,12 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""模型仓库目录、具名资源路径与部署档位映射。"""
+
from __future__ import annotations
-import re
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import TYPE_CHECKING, Literal
+from typing import Literal
-from ..config import config
from ..types import DEPLOYMENT_TIERS, DeploymentTier
-
-if TYPE_CHECKING:
- from ..config import ModelSource
-
-DownloadMode = Literal["full", "required_paths"]
-MODEL_COMPLETE_MARKER = ".mineru_complete"
-
-
-def _join_model_path(*parts: str) -> str:
- cleaned: list[str] = []
- for raw in parts:
- value = str(raw).replace("\\", "/").strip("/")
- if not value:
- continue
- cleaned.extend(part for part in value.split("/") if part and part != ".")
- if any(part == ".." for part in cleaned):
- raise ValueError("Model paths must not contain '..' segments.")
- return "/".join(cleaned)
-
-
-@dataclass(frozen=True)
-class ModelPath:
- repo: "ModelRepo"
- name: str
- relative_path: str
-
- def path(self, relative_path: str, /, *children: str) -> "ModelPath":
- joined = _join_model_path(self.relative_path, relative_path, *children)
- name = _join_model_path(self.name, relative_path, *children)
- return ModelPath(repo=self.repo, name=name, relative_path=joined)
-
- def local_path(self) -> Path:
- return self.repo.local_dir() / self.relative_path
-
- def ensure(self, *, source: "ModelSource | None" = None) -> Path:
- from .models_download_utils import download_model_files
-
- download_model_files(self.repo, [self], source=source, reuse_ready=True)
- return self.local_path()
-
-
-@dataclass(frozen=True)
-class ModelRepo:
- name: str
- repos: dict[str, str]
- local_name: str = ""
- paths: dict[str, str] = field(default_factory=dict)
- download_mode: DownloadMode = "full"
- stack: str = "full" # "light" | "full"
-
- def __post_init__(self) -> None:
- if not self.local_name:
- object.__setattr__(self, "local_name", self.name)
-
- def __getattr__(self, name: str) -> ModelPath:
- try:
- return self.named_path(name)
- except KeyError as exc:
- raise AttributeError(name) from exc
-
- def named_path(self, name: str) -> ModelPath:
- return ModelPath(repo=self, name=name, relative_path=self.paths[name])
-
- def path(self, relative_path: str, /, *children: str) -> ModelPath:
- joined = _join_model_path(relative_path, *children)
- return ModelPath(repo=self, name=joined, relative_path=joined)
-
- def required_paths(self) -> tuple[ModelPath, ...]:
- return tuple(self.named_path(name) for name in self.paths)
-
- def local_dir(self) -> Path:
- return Path(config.model.base_dir).expanduser() / self.local_name
-
- def lock_path(self) -> Path:
- safe_name = re.sub(r"[^A-Za-z0-9_.-]+", "_", self.local_name).strip("._") or "model"
- return Path(config.model.base_dir).expanduser() / ".locks" / f"{safe_name}.lock"
-
- def ensure(self, *, source: "ModelSource | None" = None) -> Path:
- from .models_download_utils import download_model_repo
-
- return download_model_repo(self, source=source, reuse_ready=True)
+from .download import MODEL_COMPLETE_MARKER, DownloadMode, ModelPath, ModelRepo, model_path_exists
PDF_EXTRACT_KIT = ModelRepo(
@@ -233,7 +152,7 @@ def resolve_model_stack(stack: str | None) -> Literal["light", "full"]:
``None`` 或 ``"auto"`` 走 ``get_model_stack()``(依据 ``config.model.stack`` 与设备自动选择)。
"""
- from ..utils.config_reader import get_model_stack
+ from .runtime.device import get_model_stack
if stack in ("light", "full"):
return stack # type: ignore[return-value]
@@ -296,25 +215,6 @@ def model_repo_names() -> tuple[str, ...]:
return tuple(MODEL_REPOS_BY_NAME)
-def model_path_exists(path: ModelPath) -> bool:
- local_path = path.local_path()
- if local_path.is_file():
- return True
- if not local_path.is_dir():
- return False
- repo_root = path.repo.local_dir()
- try:
- local_path.relative_to(repo_root)
- except ValueError:
- return False
- for directory in (local_path, *local_path.parents):
- if (directory / MODEL_COMPLETE_MARKER).is_file():
- return True
- if directory == repo_root:
- break
- return False
-
-
__all__ = [
"MINERU_2_5_PRO_2605_1_2B",
"MINERU_2_5_PRO_2605_1_2B_GGUF",
diff --git a/mineru/model/runtime/__init__.py b/mineru/model/runtime/__init__.py
new file mode 100644
index 00000000..ab461706
--- /dev/null
+++ b/mineru/model/runtime/__init__.py
@@ -0,0 +1,17 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""模型设备、资源与本地推理上下文的私有运行时。"""
+
+from .contracts import AtomicModelName
+from .device import get_device, get_model_stack
+from .hybrid import HybridLocalModelContext, HybridLocalModelContextSingleton
+from .memory import clean_memory, get_vram
+
+__all__ = [
+ "AtomicModelName",
+ "HybridLocalModelContext",
+ "HybridLocalModelContextSingleton",
+ "clean_memory",
+ "get_device",
+ "get_model_stack",
+ "get_vram",
+]
diff --git a/mineru/model/model_types.py b/mineru/model/runtime/contracts.py
similarity index 80%
rename from mineru/model/model_types.py
rename to mineru/model/runtime/contracts.py
index d2ed8f1b..d46f81f4 100644
--- a/mineru/model/model_types.py
+++ b/mineru/model/runtime/contracts.py
@@ -1,3 +1,4 @@
+# Copyright (c) Opendatalab. All rights reserved.
"""模型层共享的稳定标识类型。"""
@@ -11,3 +12,6 @@ class AtomicModelName:
WiredTable = "wired_table"
TableCls = "table_cls"
TableOrientationCls = "table_ori_cls"
+
+
+__all__ = ["AtomicModelName"]
diff --git a/mineru/model/runtime/device.py b/mineru/model/runtime/device.py
new file mode 100644
index 00000000..42114695
--- /dev/null
+++ b/mineru/model/runtime/device.py
@@ -0,0 +1,58 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""模型运行设备与轻量/完整模型栈选择。"""
+
+from __future__ import annotations
+
+import os
+from typing import Literal, cast
+
+
+def get_device() -> str:
+ """返回显式配置或当前环境中可用的首选模型设备。"""
+ configured_device = os.getenv("MINERU_DEVICE_MODE")
+ if configured_device is not None:
+ return configured_device
+
+ try:
+ import torch
+ except ImportError:
+ return "cpu"
+
+ try:
+ if torch.cuda.is_available():
+ return "cuda"
+ except Exception:
+ pass
+ try:
+ if torch.backends.mps.is_available():
+ return "mps"
+ except Exception:
+ pass
+ try:
+ import torch_npu
+
+ if torch_npu.npu.is_available():
+ return "npu"
+ except Exception:
+ pass
+ for device_name in ("gcu", "musa", "mlu", "sdaa"):
+ try:
+ device_api = getattr(torch, device_name)
+ if device_api.is_available():
+ return device_name
+ except Exception:
+ pass
+ return "cpu"
+
+
+def get_model_stack() -> Literal["light", "full"]:
+ """按配置和实际设备解析轻量或完整模型推理栈。"""
+ from ...config import config
+
+ configured_stack = config.model.stack
+ if configured_stack in ("light", "full"):
+ return cast(Literal["light", "full"], configured_stack)
+ return "light" if get_device() == "cpu" else "full"
+
+
+__all__ = ["get_device", "get_model_stack"]
diff --git a/mineru/backend/local_model_runtime.py b/mineru/model/runtime/hybrid.py
similarity index 91%
rename from mineru/backend/local_model_runtime.py
rename to mineru/model/runtime/hybrid.py
index fb6f8ed7..98964e0c 100644
--- a/mineru/backend/local_model_runtime.py
+++ b/mineru/model/runtime/hybrid.py
@@ -11,21 +11,21 @@ from typing import TYPE_CHECKING, Any
from loguru import logger
-from ..model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer
-from ..model.model_types import AtomicModelName
-from ..model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel
-from ..model.table.cls.paddle_table_cls import PaddleTableClsModel
-from ..model.table.rec.slanet_plus.main import PaddleTableModel
-from ..model.table.rec.unet_table.main import UnetTableModel
+from ..mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer
+from ..ocr.language import normalize_ocr_model_lang
+from ..table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel
+from ..table.cls.paddle_table_cls import PaddleTableClsModel
+from ..table.rec.slanet_plus.main import PaddleTableModel
+from ..table.rec.unet_table.main import UnetTableModel
+from .contracts import AtomicModelName
if TYPE_CHECKING:
- from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
- from ..model.mfr.unimernet.Unimernet import UnimernetModel
- from ..model.ocr.pytorch_paddle import PytorchPaddleOCR
+ from ..layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
+ from ..mfr.unimernet.Unimernet import UnimernetModel
+ from ..ocr.pytorch_paddle import PytorchPaddleOCR
-from ..utils.config_reader import get_device, get_model_stack
-from ..utils.model_registry import PDF_EXTRACT_KIT, ModelPath
-from ..utils.ocr_language import normalize_ocr_model_lang
+from ..registry import PDF_EXTRACT_KIT, ModelPath
+from .device import get_device, get_model_stack
LOCAL_MODEL_INIT_LOCK = threading.RLock()
# 这些锁保护 Hybrid medium/high/xhigh 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
@@ -131,7 +131,7 @@ def wireless_table_model_init(lang: str | None = None) -> PaddleTableModel:
def mfr_model_init(weight_dir: str, device: str = "cpu") -> "UnimernetModel":
- from ..model.mfr.unimernet.Unimernet import UnimernetModel
+ from ..mfr.unimernet.Unimernet import UnimernetModel
return UnimernetModel(weight_dir, device)
@@ -139,7 +139,7 @@ def mfr_model_init(weight_dir: str, device: str = "cpu") -> "UnimernetModel":
def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> "PPDocLayoutV2LayoutModel":
"""在指定设备上初始化 PP-DocLayoutV2 版面分析模型。"""
- from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
+ from ..layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
if str(device).startswith("npu"):
import torch
@@ -157,7 +157,7 @@ def ocr_model_init(
) -> "PytorchPaddleOCR":
"""按语言和检测阈值初始化本地 Paddle OCR 模型。"""
- from ..model.ocr.pytorch_paddle import PytorchPaddleOCR
+ from ..ocr.pytorch_paddle import PytorchPaddleOCR
ocr_kwargs = {
"lang": normalize_ocr_model_lang(lang),
@@ -217,8 +217,8 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
atom_model = None
if model_name == AtomicModelName.Layout:
if stack == "light":
- from ..model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX
- from ..utils.model_registry import PP_DOCLAYOUT_V2_ONNX
+ from ..layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX
+ from ..registry import PP_DOCLAYOUT_V2_ONNX
atom_model = PPDocLayoutV2LayoutModelONNX(
weight=str(PP_DOCLAYOUT_V2_ONNX.onnx.ensure()),
@@ -228,8 +228,8 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))
elif model_name == AtomicModelName.MFR:
if stack == "light":
- from ..model.mfr.pp_formulanet_plus_m_onnx import PPFormulaNetPlusMONNX
- from ..utils.model_registry import PP_FORMULANET_PLUS_M_ONNX
+ from ..mfr.pp_formulanet_plus_m_onnx import PPFormulaNetPlusMONNX
+ from ..registry import PP_FORMULANET_PLUS_M_ONNX
atom_model = PPFormulaNetPlusMONNX(
model_path=str(PP_FORMULANET_PLUS_M_ONNX.onnx.ensure()),
@@ -240,8 +240,8 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))
elif model_name == AtomicModelName.OCR:
if stack == "light":
- from ..model.ocr.pp_ocr_v6_onnx import PPOCRv6ONNX
- from ..utils.model_registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX
+ from ..ocr.pp_ocr_v6_onnx import PPOCRv6ONNX
+ from ..registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX
atom_model = PPOCRv6ONNX(
det_model_path=str(PP_OCR_V6_SMALL_DET_ONNX.onnx.ensure()),
diff --git a/mineru/model/runtime/memory.py b/mineru/model/runtime/memory.py
new file mode 100644
index 00000000..4509dcf0
--- /dev/null
+++ b/mineru/model/runtime/memory.py
@@ -0,0 +1,85 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""模型推理显存探测与缓存释放。"""
+
+from __future__ import annotations
+
+import gc
+import os
+from typing import Any
+
+from loguru import logger
+
+
+def _optional_torch() -> tuple[Any | None, Any | None]:
+ """惰性加载 torch 与可选 NPU 扩展,避免公共门面触发重依赖。"""
+ try:
+ import torch
+ except ImportError:
+ return None, None
+ try:
+ import torch_npu
+ except ImportError:
+ torch_npu = None
+ return torch, torch_npu
+
+
+def clean_memory(device: str = "cuda") -> None:
+ """释放指定模型设备的框架缓存并执行 Python 垃圾回收。"""
+ torch, torch_npu = _optional_torch()
+ if torch is None:
+ gc.collect()
+ return
+
+ device_name = str(device)
+ if device_name.startswith("cuda") and torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ elif device_name.startswith("npu") and torch_npu is not None and torch_npu.npu.is_available():
+ torch_npu.npu.empty_cache()
+ elif device_name.startswith("mps"):
+ torch.mps.empty_cache()
+ else:
+ for accelerator_name in ("gcu", "musa", "mlu", "sdaa"):
+ if not device_name.startswith(accelerator_name):
+ continue
+ accelerator = getattr(torch, accelerator_name, None)
+ if accelerator is not None and accelerator.is_available():
+ accelerator.empty_cache()
+ break
+ gc.collect()
+
+
+def get_vram(device: str) -> int:
+ """返回指定设备的整数 GB 显存,无法探测时保守返回一。"""
+ configured_vram = os.getenv("MINERU_VIRTUAL_VRAM_SIZE")
+ if configured_vram is not None:
+ try:
+ total_memory = int(configured_vram)
+ if total_memory > 0:
+ return total_memory
+ logger.warning(
+ f"MINERU_VIRTUAL_VRAM_SIZE value '{configured_vram}' is not positive, falling back to auto-detection"
+ )
+ except ValueError:
+ logger.warning(
+ f"MINERU_VIRTUAL_VRAM_SIZE value '{configured_vram}' is not a valid integer, falling back to auto-detection"
+ )
+
+ torch, torch_npu = _optional_torch()
+ if torch is None:
+ return 1
+
+ device_name = str(device)
+ if device_name.startswith("cuda") and torch.cuda.is_available():
+ return round(torch.cuda.get_device_properties(device).total_memory / (1024**3))
+ if device_name.startswith("npu") and torch_npu is not None and torch_npu.npu.is_available():
+ return round(torch_npu.npu.get_device_properties(device).total_memory / (1024**3))
+ for accelerator_name in ("gcu", "musa", "mlu", "sdaa"):
+ if not device_name.startswith(accelerator_name):
+ continue
+ accelerator = getattr(torch, accelerator_name, None)
+ if accelerator is not None and accelerator.is_available():
+ return round(accelerator.get_device_properties(device).total_memory / (1024**3))
+ return 1
+
+
+__all__ = ["clean_memory", "get_vram"]
diff --git a/mineru/model/utils/onnxruntime_provider.py b/mineru/model/runtime/onnx.py
similarity index 72%
rename from mineru/model/utils/onnxruntime_provider.py
rename to mineru/model/runtime/onnx.py
index ac9c5379..a2ddc7a5 100644
--- a/mineru/model/utils/onnxruntime_provider.py
+++ b/mineru/model/runtime/onnx.py
@@ -1,8 +1,25 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""ONNX Runtime provider、会话与线程配置。"""
+
+import os
+
import onnxruntime as ort
AVAILABLE_PROVIDERS: list[str] = ort.get_available_providers()
+def get_op_num_threads(env_name: str) -> int:
+ """读取 ONNX 算子线程数,缺失或非法时返回负一。"""
+ raw_value = os.getenv(env_name)
+ if raw_value is None:
+ return -1
+ try:
+ value = int(raw_value)
+ except ValueError:
+ return -1
+ return value if value > 0 else -1
+
+
def ort_providers(device: str | None = None) -> list[tuple[str, dict[str, object]]]:
"""根据 device 选择 onnxruntime providers。"""
norm = (device or "").lower().split(":", 1)[0]
@@ -26,3 +43,6 @@ def ort_session(model_path: str, device: str | None = None, intra_op_num_threads
if intra_op_num_threads > 0:
opts.intra_op_num_threads = intra_op_num_threads
return ort.InferenceSession(model_path, sess_options=opts, providers=ort_providers(device))
+
+
+__all__ = ["get_op_num_threads", "ort_providers", "ort_session"]
diff --git a/mineru/model/table/__init__.py b/mineru/model/table/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/table/__init__.py
+++ b/mineru/model/table/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/table/cls/__init__.py b/mineru/model/table/cls/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/table/cls/__init__.py
+++ b/mineru/model/table/cls/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/table/cls/paddle_table_cls.py b/mineru/model/table/cls/paddle_table_cls.py
index 2259e41b..e2d45c16 100644
--- a/mineru/model/table/cls/paddle_table_cls.py
+++ b/mineru/model/table/cls/paddle_table_cls.py
@@ -4,13 +4,13 @@ import numpy as np
from PIL import Image
from tqdm import tqdm
-from ....utils.model_registry import PDF_EXTRACT_KIT
-from ...utils.onnxruntime_provider import ort_session
+from ...registry import PDF_EXTRACT_KIT
+from ...runtime.onnx import ort_session
class PaddleTableClsModel:
def __init__(self):
- from mineru.model.model_types import AtomicModelName
+ from ...runtime.contracts import AtomicModelName
self.sess = ort_session(str(PDF_EXTRACT_KIT.paddle_table_cls.ensure()))
self.less_length = 256
diff --git a/mineru/model/table/rec/__init__.py b/mineru/model/table/rec/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/table/rec/__init__.py
+++ b/mineru/model/table/rec/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/table/rec/slanet_plus/__init__.py b/mineru/model/table/rec/slanet_plus/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/table/rec/slanet_plus/__init__.py
+++ b/mineru/model/table/rec/slanet_plus/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/table/rec/slanet_plus/main.py b/mineru/model/table/rec/slanet_plus/main.py
index cab2ad3b..86492359 100644
--- a/mineru/model/table/rec/slanet_plus/main.py
+++ b/mineru/model/table/rec/slanet_plus/main.py
@@ -11,7 +11,7 @@ import numpy as np
from loguru import logger
from tqdm import tqdm
-from .....utils.model_registry import PDF_EXTRACT_KIT
+from ....registry import PDF_EXTRACT_KIT
from .matcher import TableMatch
from .table_structure import TableStructurer
diff --git a/mineru/model/table/rec/slanet_plus/table_structure.py b/mineru/model/table/rec/slanet_plus/table_structure.py
index d9b2f0ce..cfd8a20a 100644
--- a/mineru/model/table/rec/slanet_plus/table_structure.py
+++ b/mineru/model/table/rec/slanet_plus/table_structure.py
@@ -16,7 +16,7 @@ from typing import Any, Dict, List, Tuple
import numpy as np
-from mineru.utils.os_env_config import get_op_num_threads
+from ....runtime.onnx import get_op_num_threads
from .table_structure_utils import (
OrtInferSession,
TableLabelDecode,
diff --git a/mineru/model/table/rec/slanet_plus/table_structure_utils.py b/mineru/model/table/rec/slanet_plus/table_structure_utils.py
index 98eb90bd..c4cda6d2 100644
--- a/mineru/model/table/rec/slanet_plus/table_structure_utils.py
+++ b/mineru/model/table/rec/slanet_plus/table_structure_utils.py
@@ -21,7 +21,7 @@ import numpy as np
from loguru import logger
from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions
-from ....utils.onnxruntime_provider import ort_providers
+from ....runtime.onnx import ort_providers
class OrtInferSession:
diff --git a/mineru/model/table/rec/unet_table/__init__.py b/mineru/model/table/rec/unet_table/__init__.py
index 1e17167c..818730ae 100644
--- a/mineru/model/table/rec/unet_table/__init__.py
+++ b/mineru/model/table/rec/unet_table/__init__.py
@@ -1 +1,3 @@
# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/model/table/rec/unet_table/main.py b/mineru/model/table/rec/unet_table/main.py
index 1d72a505..15950060 100644
--- a/mineru/model/table/rec/unet_table/main.py
+++ b/mineru/model/table/rec/unet_table/main.py
@@ -12,8 +12,8 @@ from bs4 import BeautifulSoup
from loguru import logger
from PIL import Image
-from mineru.utils.image_utils import calculate_contrast
-from .....utils.model_registry import PDF_EXTRACT_KIT
+from .....utils.image import calculate_contrast
+from ....registry import PDF_EXTRACT_KIT
from .table_recover import TableRecover
from .table_structure_unet import TSRUnet
diff --git a/mineru/model/table/rec/unet_table/table_structure_unet.py b/mineru/model/table/rec/unet_table/table_structure_unet.py
index c7b2bd9f..baf3b585 100644
--- a/mineru/model/table/rec/unet_table/table_structure_unet.py
+++ b/mineru/model/table/rec/unet_table/table_structure_unet.py
@@ -6,7 +6,7 @@ from typing import Optional, Dict, Any, Tuple
import cv2
import numpy as np
-from mineru.utils.os_env_config import get_op_num_threads
+from ....runtime.onnx import get_op_num_threads
from .utils import OrtInferSession, resize_img
from .utils_table_line_rec import (
get_table_line,
diff --git a/mineru/model/utils/tools/__init__.py b/mineru/model/utils/tools/__init__.py
deleted file mode 100644
index f64ba567..00000000
--- a/mineru/model/utils/tools/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
\ No newline at end of file
diff --git a/mineru/model/utils/tools/infer/__init__.py b/mineru/model/utils/tools/infer/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/model/utils/tools/infer/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/model/vlm/engine_utils.py b/mineru/model/vlm/engine_utils.py
index 79e1ee78..8922c9ab 100644
--- a/mineru/model/vlm/engine_utils.py
+++ b/mineru/model/vlm/engine_utils.py
@@ -6,9 +6,9 @@ from typing import Any, Literal
from loguru import logger
from packaging import version
-from ...utils.check_sys_env import is_linux_environment, is_windows_environment
-from ...utils.config_reader import get_device
-from ...utils.model_utils import get_vram
+from ...utils.platform import is_linux_environment, is_windows_environment
+from ..runtime.device import get_device
+from ..runtime.memory import get_vram
def enable_custom_logits_processors() -> bool:
diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.py
index fbdade2f..10c818c2 100644
--- a/mineru/model/vlm/runtime.py
+++ b/mineru/model/vlm/runtime.py
@@ -12,13 +12,12 @@ from contextlib import asynccontextmanager, contextmanager
from typing import Any, AsyncIterator, Generator, Iterator, Literal
from loguru import logger
-from mineru.utils.model_utils import get_vram
from mineru_vl_utils import MinerUClient
from packaging import version
-from ...utils.check_sys_env import is_mac_os_version_supported
-from ...utils.config_reader import get_device
-from ...utils.model_registry import MINERU_2_5_PRO_2605_1_2B, MINERU_2_5_PRO_2605_1_2B_GGUF
+from ...utils.platform import is_mac_os_version_supported
+from ..runtime.device import get_device
+from ..registry import MINERU_2_5_PRO_2605_1_2B, MINERU_2_5_PRO_2605_1_2B_GGUF
from .engine_utils import (
enable_custom_logits_processors,
mod_kwargs_by_device_type,
diff --git a/mineru/utils/engine_utils.py b/mineru/model/vlm/selector.py
similarity index 81%
rename from mineru/utils/engine_utils.py
rename to mineru/model/vlm/selector.py
index 67965736..c6eca3f2 100644
--- a/mineru/utils/engine_utils.py
+++ b/mineru/model/vlm/selector.py
@@ -3,7 +3,7 @@ from typing import Literal, TypeAlias
from loguru import logger
-from .check_sys_env import is_linux_environment, is_mac_environment, is_mac_os_version_supported, is_windows_environment
+from ...utils.platform import is_linux_environment, is_mac_environment, is_mac_os_version_supported, is_windows_environment
VlmEngine: TypeAlias = Literal[
"llama-cpp-engine",
@@ -45,7 +45,9 @@ def get_vlm_engine(inference_engine: Literal["auto"], is_async: bool = False) ->
def _select_windows_engine() -> VlmEngine:
"""Windows 平台引擎选择"""
try:
- import lmdeploy # type: ignore
+ import lmdeploy as _lmdeploy # type: ignore
+
+ del _lmdeploy
return "lmdeploy-engine"
except ImportError:
@@ -55,7 +57,9 @@ def _select_windows_engine() -> VlmEngine:
def _select_linux_engine(is_async: bool) -> VlmEngine:
"""Linux 平台引擎选择"""
try:
- import vllm # type: ignore
+ import vllm as _vllm # type: ignore
+
+ del _vllm
if is_async:
return "vllm-async-engine"
@@ -63,7 +67,9 @@ def _select_linux_engine(is_async: bool) -> VlmEngine:
return "vllm-engine"
except ImportError:
try:
- import lmdeploy # type: ignore
+ import lmdeploy as _lmdeploy # type: ignore
+
+ del _lmdeploy
return "lmdeploy-engine"
except ImportError:
@@ -74,7 +80,9 @@ def _select_mac_engine() -> VlmEngine:
"""macOS 平台引擎选择"""
try:
if is_mac_os_version_supported():
- import mlx_vlm # type: ignore
+ import mlx_vlm as _mlx_vlm # type: ignore
+
+ del _mlx_vlm
return "mlx-engine"
except ImportError:
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 113ff27f..006ef1ab 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -45,12 +45,12 @@ from ..filetypes import (
file_type_for_extension,
is_flash_only_parse_extension,
)
-from ..render.writer import DataWriter
+from .writer import DataWriter
from ..types import SERVER_TIERS, TIERS_BY_SERVER_TIER, DeploymentTier, PageInfo, ServerTier, Tier, select_default_quality_tier
-from ..utils.backend_options import effort_for_tier
+from .tier import effort_for_tier
from ..utils.image_payload import validate_image_sidecar_path
-from ..utils.managed_process_control import ManagedProcessControlWatcher
-from ..utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
+from .process_control import ManagedProcessControlWatcher
+from ..model.ocr.language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
from ..utils.stdio import configure_standard_streams
from ..version import __version__
from . import parse_async
@@ -2046,8 +2046,8 @@ def _classify_model_preload_error(exc: Exception) -> tuple[str, str]:
def _preload_local_models(language: str) -> None:
# TODO: fix import
- from ..backend.local_model_runtime import HybridLocalModelContextSingleton
- from ..model.model_types import AtomicModelName
+ from ..model.runtime.contracts import AtomicModelName
+ from ..model.runtime.hybrid import HybridLocalModelContextSingleton
context = HybridLocalModelContextSingleton().get_model()
manager = context.atom_model_manager
@@ -2063,7 +2063,7 @@ def _preload_server_models(tier: DeploymentTier, *, language: str) -> _ModelPrel
_preload_local_models(language)
return _ModelPreloadResult(tier=tier, engine="hybrid-local")
- from ..utils.engine_utils import get_vlm_engine
+ from ..model.vlm.selector import get_vlm_engine
engine = get_vlm_engine("auto", is_async=True)
from ..model.vlm.runtime import ModelSingleton
diff --git a/mineru/utils/guess_suffix_or_lang.py b/mineru/parser/file_type.py
similarity index 81%
rename from mineru/utils/guess_suffix_or_lang.py
rename to mineru/parser/file_type.py
index a4feb6a6..30c39b19 100644
--- a/mineru/utils/guess_suffix_or_lang.py
+++ b/mineru/parser/file_type.py
@@ -1,5 +1,8 @@
# Copyright (c) Opendatalab. All rights reserved.
+"""根据文件内容和容器结构识别 MinerU 支持的输入后缀。"""
+
from io import BytesIO
+from functools import lru_cache
from pathlib import Path
from xml.etree import ElementTree
from zipfile import BadZipFile, ZipFile
@@ -7,7 +10,6 @@ from zipfile import BadZipFile, ZipFile
from loguru import logger
from magika import Magika
-DEFAULT_LANG = "txt"
PDF_SIG_BYTES = b"%PDF"
OLE2_SIG_BYTES = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
OOXML_ROOT_RELS = "_rels/.rels"
@@ -28,53 +30,12 @@ OLE2_STREAM_SUFFIX_MAP: dict[str, str] = {
"Book": "xls",
"PowerPoint Document": "ppt",
}
-magika = Magika()
-
-
-def _normalize_text_for_language_guess(code: str) -> str:
- if not code:
- return ""
-
- normalized = []
- index = 0
- while index < len(code):
- current_char = code[index]
- current_ord = ord(current_char)
-
- if 0xD800 <= current_ord <= 0xDBFF:
- if index + 1 < len(code):
- next_char = code[index + 1]
- next_ord = ord(next_char)
- if 0xDC00 <= next_ord <= 0xDFFF:
- pair = current_char + next_char
- normalized.append(pair.encode("utf-16", "surrogatepass").decode("utf-16"))
- index += 2
- continue
- index += 1
- continue
-
- if 0xDC00 <= current_ord <= 0xDFFF:
- index += 1
- continue
- normalized.append(current_char)
- index += 1
- return "".join(normalized)
-
-
-def guess_language_by_text(code: str) -> str:
- normalized_code = _normalize_text_for_language_guess(code)
- if not normalized_code:
- return DEFAULT_LANG
-
- try:
- codebytes = normalized_code.encode("utf-8", errors="replace")
- lang = magika.identify_bytes(codebytes).prediction.output.label
- except Exception:
- return DEFAULT_LANG
-
- return lang if lang != "unknown" else DEFAULT_LANG
+@lru_cache(maxsize=1)
+def _magika() -> Magika:
+ """惰性创建文件类型识别器,避免导入 parser 时加载模型。"""
+ return Magika()
def _strip_package_part_name(part_name: str | None) -> str:
@@ -167,7 +128,7 @@ def _guess_ooxml_suffix_by_path(file_path: Path) -> str | None:
def _guess_ole2_suffix_by_bytes(file_bytes: bytes) -> str | None:
"""用 OLE2 magic + olefile 内部 stream 区分 doc/xls/ppt。
- olefile 是纯 Python 库且已是核心依赖(mineru.model.flash.legacy_office 使用)。
+ olefile 是纯 Python 库且已是核心依赖(mineru.model.flash.office.legacy 使用)。
在 OOXML 识别失败后、Magika 兜底前插入此层,避免 Magika 对 OLE2 返回 unknown。
"""
if len(file_bytes) < 8 or file_bytes[:8] != OLE2_SIG_BYTES:
@@ -204,7 +165,7 @@ def guess_suffix_by_bytes(file_bytes: bytes, file_path: str | None = None) -> st
if ole2_suffix:
return ole2_suffix
- suffix = magika.identify_bytes(file_bytes).prediction.output.label
+ suffix = _magika().identify_bytes(file_bytes).prediction.output.label
if (
file_path
and suffix in ["ai", "html"]
@@ -227,7 +188,7 @@ def guess_suffix_by_path(file_path: str | Path) -> str:
if ole2_suffix:
return ole2_suffix
- suffix = magika.identify_path(file_path).prediction.output.label
+ suffix = _magika().identify_path(file_path).prediction.output.label
if suffix in ["ai", "html"] and file_path.suffix.lower() in [".pdf"]:
try:
with open(file_path, "rb") as f:
@@ -236,3 +197,6 @@ def guess_suffix_by_path(file_path: str | Path) -> str:
except Exception as e:
logger.warning(f"Failed to read file {file_path} for PDF signature check: {e}")
return suffix
+
+
+__all__ = ["guess_suffix_by_bytes", "guess_suffix_by_path"]
diff --git a/mineru/utils/pdf_page_id.py b/mineru/parser/page_range.py
similarity index 97%
rename from mineru/utils/pdf_page_id.py
rename to mineru/parser/page_range.py
index a1dfec00..a144efe5 100644
--- a/mineru/utils/pdf_page_id.py
+++ b/mineru/parser/page_range.py
@@ -54,3 +54,6 @@ def parse_page_range(raw: str, page_count: int) -> list[int]:
result.extend(range(lo, hi + 1))
return sorted(set(result))
+
+
+__all__ = ["get_end_page_id", "parse_page_range"]
diff --git a/mineru/utils/managed_process_control.py b/mineru/parser/process_control.py
similarity index 98%
rename from mineru/utils/managed_process_control.py
rename to mineru/parser/process_control.py
index a4e5a121..d9a95283 100644
--- a/mineru/utils/managed_process_control.py
+++ b/mineru/parser/process_control.py
@@ -1,4 +1,5 @@
-"""Private parent-child control channel for managed subprocesses."""
+# Copyright (c) Opendatalab. All rights reserved.
+"""托管解析子进程使用的私有父子控制通道。"""
from __future__ import annotations
diff --git a/mineru/parser/tier.py b/mineru/parser/tier.py
index 49674fbb..5f7f9271 100644
--- a/mineru/parser/tier.py
+++ b/mineru/parser/tier.py
@@ -6,31 +6,129 @@ import platform
import sys
from dataclasses import dataclass
from importlib import metadata as importlib_metadata
+from typing import Final
from ..types import DEPLOYMENT_TIERS, DeploymentTier, Tier, validate_tier
-from ..utils.backend_options import (
- CANONICAL_HYBRID_ENGINE,
- LEGACY_PIPELINE_BACKEND_ALIASES,
- LEGACY_VLM_BACKEND_ALIASES,
- SUPPORTED_BACKENDS,
- effort_for_tier,
- is_hybrid_backend,
- normalize_backend,
-)
+
+CANONICAL_HYBRID_ENGINE: Final = "hybrid-engine"
+LOCAL_HYBRID_EFFORT: Final = "medium"
+LAYOUT_HYBRID_EFFORT: Final = "high"
+MAX_HYBRID_EFFORT: Final = "xhigh"
+DEFAULT_BACKEND: Final = CANONICAL_HYBRID_ENGINE
+DEFAULT_HYBRID_EFFORT: Final = LAYOUT_HYBRID_EFFORT
+DEFAULT_EFFORT: Final = DEFAULT_HYBRID_EFFORT
+HYBRID_EFFORT_HELP: Final = "Higher effort improves parsing quality but may be slower; medium is the fastest local Hybrid mode."
+LOCAL_BACKEND_CHOICES: Final[tuple[str, ...]] = (CANONICAL_HYBRID_ENGINE,)
+HTTP_CLIENT_BACKEND_CHOICES: Final[tuple[str, ...]] = ("hybrid-http-client",)
+PUBLIC_BACKEND_CHOICES: Final[tuple[str, ...]] = LOCAL_BACKEND_CHOICES + HTTP_CLIENT_BACKEND_CHOICES
+HYBRID_EFFORT_CHOICES: Final[tuple[str, ...]] = (LOCAL_HYBRID_EFFORT, LAYOUT_HYBRID_EFFORT, MAX_HYBRID_EFFORT)
+HYBRID_EFFORT_BY_TIER: Final[dict[str, str]] = {
+ "flash": "flash",
+ "basic": LOCAL_HYBRID_EFFORT,
+ "standard": LAYOUT_HYBRID_EFFORT,
+ "advanced": MAX_HYBRID_EFFORT,
+}
+BACKEND_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(PUBLIC_BACKEND_CHOICES)}
+HYBRID_EFFORT_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(HYBRID_EFFORT_CHOICES)}
+BACKEND_ALIASES: Final[dict[str, str]] = {
+ "hybrid-auto-engine": CANONICAL_HYBRID_ENGINE,
+ "pipeline": CANONICAL_HYBRID_ENGINE,
+ "vlm-engine": CANONICAL_HYBRID_ENGINE,
+ "vlm-auto-engine": CANONICAL_HYBRID_ENGINE,
+ "vlm-http-client": "hybrid-http-client",
+}
+LEGACY_PIPELINE_BACKEND_ALIASES: Final[frozenset[str]] = frozenset({"pipeline"})
+LEGACY_VLM_BACKEND_ALIASES: Final[frozenset[str]] = frozenset({"vlm-engine", "vlm-auto-engine", "vlm-http-client"})
+SUPPORTED_BACKENDS: Final[tuple[str, ...]] = PUBLIC_BACKEND_CHOICES + ("flash",)
+SUPPORTED_EFFORTS: Final[tuple[str, ...]] = HYBRID_EFFORT_CHOICES
+
+
+def normalize_backend(backend: str | None) -> str:
+ """规范化 backend 名称,并将旧 VLM backend 映射到 Hybrid backend。"""
+ normalized = (backend or "").strip()
+ if normalized in BACKEND_ALIASES:
+ return BACKEND_ALIASES[normalized]
+ if normalized in SUPPORTED_BACKENDS:
+ return normalized
+ raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(SUPPORTED_BACKENDS)}")
+
+
+def normalize_public_backend(backend: str | None) -> str:
+ """规范化公开 backend,同时拒绝 flash 和隐藏兼容选项。"""
+ normalized = (backend or "").strip()
+ if normalized in BACKEND_ALIASES:
+ return BACKEND_ALIASES[normalized]
+ if normalized in PUBLIC_BACKEND_CHOICES:
+ return normalized
+ raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(PUBLIC_BACKEND_CHOICES)}")
+
+
+def validate_effort(effort: str | None) -> str:
+ """校验 Hybrid effort 只使用 medium、high 或 xhigh。"""
+ normalized = (effort or DEFAULT_EFFORT).strip().lower()
+ if normalized in HYBRID_EFFORT_CHOICES:
+ return normalized
+ raise ValueError(f"Unsupported effort '{effort}'. Supported efforts: {', '.join(HYBRID_EFFORT_CHOICES)}")
+
+
+def effort_for_tier(tier: str | None) -> str:
+ """将公开 tier 映射为对应的 Hybrid effort。"""
+ normalized = (tier or "").strip().lower()
+ if normalized in HYBRID_EFFORT_BY_TIER:
+ return HYBRID_EFFORT_BY_TIER[normalized]
+ supported_tiers = ", ".join(HYBRID_EFFORT_BY_TIER)
+ raise ValueError(f"Unsupported tier '{tier}'. Supported hybrid tiers: {supported_tiers}")
+
+
+def resolve_backend_and_effort(backend: str | None, effort: str | None = None) -> tuple[str, str]:
+ """同时解析 backend 与 effort,并保留旧 backend 的质量档位语义。"""
+ raw_backend = (backend or "").strip()
+ resolved_backend = normalize_backend(raw_backend)
+ resolved_effort = validate_effort(effort)
+ if raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES:
+ resolved_effort = LOCAL_HYBRID_EFFORT
+ elif raw_backend in LEGACY_VLM_BACKEND_ALIASES:
+ resolved_effort = MAX_HYBRID_EFFORT
+ return resolved_backend, resolved_effort
+
+
+def is_hybrid_backend(backend: str) -> bool:
+ """判断规范化后的 backend 是否属于 Hybrid 后端族。"""
+ return normalize_backend(backend).startswith("hybrid-")
+
__all__ = [
+ "BACKEND_SCHEMA_EXTRA",
+ "CANONICAL_HYBRID_ENGINE",
+ "DEFAULT_BACKEND",
+ "DEFAULT_EFFORT",
+ "DEFAULT_HYBRID_EFFORT",
+ "HYBRID_EFFORT_CHOICES",
+ "HYBRID_EFFORT_HELP",
+ "HYBRID_EFFORT_SCHEMA_EXTRA",
+ "LEGACY_PIPELINE_BACKEND_ALIASES",
+ "LEGACY_VLM_BACKEND_ALIASES",
"PARSER_BACKENDS",
+ "PUBLIC_BACKEND_CHOICES",
"ParserRuntimeOptions",
+ "SUPPORTED_BACKENDS",
+ "SUPPORTED_EFFORTS",
"TierDependencyError",
"backend_for_tier",
"ensure_tier_runtime_dependencies",
"installed_distribution_name",
"missing_modules_for_tier",
+ "effort_for_tier",
+ "is_hybrid_backend",
+ "normalize_backend",
+ "normalize_public_backend",
"required_modules_for_tier",
"resolve_runtime_options",
"resolve_tier_and_backend",
"runtime_options_for_tier",
"tier_for_backend",
+ "resolve_backend_and_effort",
+ "validate_effort",
]
PARSER_BACKENDS = SUPPORTED_BACKENDS
@@ -171,7 +269,7 @@ def runtime_options_for_tier(
def required_modules_for_tier(tier: DeploymentTier) -> list[str]:
if tier not in DEPLOYMENT_TIERS:
raise ValueError(f"Unsupported deployment tier '{tier}'. Supported tiers: {', '.join(DEPLOYMENT_TIERS)}")
- from ..utils.config_reader import get_model_stack
+ from ..model.runtime.device import get_model_stack
stack = get_model_stack()
if stack == "light":
diff --git a/mineru/parser/writer.py b/mineru/parser/writer.py
new file mode 100644
index 00000000..5f5464fe
--- /dev/null
+++ b/mineru/parser/writer.py
@@ -0,0 +1,66 @@
+# Copyright (c) Opendatalab. All rights reserved.
+import os
+from abc import ABC, abstractmethod
+
+
+class DataWriter(ABC):
+ @abstractmethod
+ def write(self, path: str, data: bytes) -> None:
+ """Write the data to the file.
+
+ Args:
+ path (str): the target file where to write
+ data (bytes): the data want to write
+ """
+ pass
+
+ def write_string(self, path: str, data: str) -> None:
+ """Write the data to file, the data will be encoded to bytes.
+
+ Args:
+ path (str): the target file where to write
+ data (str): the data want to write
+ """
+
+ def safe_encode(data: str, method: str) -> tuple[bytes | None, bool]:
+ try:
+ bit_data = data.encode(encoding=method, errors="replace")
+ return bit_data, True
+ except: # noqa
+ return None, False
+
+ for method in ["utf-8", "ascii"]:
+ bit_data, flag = safe_encode(data, method)
+ if flag:
+ self.write(path, bit_data)
+ break
+
+
+class FileBasedDataWriter(DataWriter):
+ def __init__(self, parent_dir: str = "") -> None:
+ """Initialized with parent_dir.
+
+ Args:
+ parent_dir (str, optional): the parent directory that may be used within methods. Defaults to ''.
+ """
+ self._parent_dir = parent_dir
+
+ def write(self, path: str, data: bytes) -> None:
+ """Write file with data.
+
+ Args:
+ path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
+ data (bytes): the data want to write
+ """
+ fn_path = path
+ if not os.path.isabs(fn_path) and len(self._parent_dir) > 0:
+ fn_path = os.path.join(self._parent_dir, path)
+
+ if not os.path.exists(os.path.dirname(fn_path)) and os.path.dirname(fn_path) != "":
+ os.makedirs(os.path.dirname(fn_path), exist_ok=True)
+
+ with open(fn_path, "wb") as f:
+ f.write(data)
+
+
+__all__ = ["DataWriter", "FileBasedDataWriter"]
diff --git a/mineru/utils/backend_options.py b/mineru/utils/backend_options.py
deleted file mode 100644
index fff74cdc..00000000
--- a/mineru/utils/backend_options.py
+++ /dev/null
@@ -1,110 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from typing import Final
-
-CANONICAL_HYBRID_ENGINE: Final = "hybrid-engine"
-LOCAL_HYBRID_EFFORT: Final = "medium"
-LAYOUT_HYBRID_EFFORT: Final = "high"
-MAX_HYBRID_EFFORT: Final = "xhigh"
-DEFAULT_BACKEND: Final = CANONICAL_HYBRID_ENGINE
-DEFAULT_HYBRID_EFFORT: Final = LAYOUT_HYBRID_EFFORT
-DEFAULT_EFFORT: Final = DEFAULT_HYBRID_EFFORT
-HYBRID_EFFORT_HELP: Final = (
- "Higher effort improves parsing quality but may be slower; medium is the fastest local Hybrid mode."
-)
-
-LOCAL_BACKEND_CHOICES: Final[tuple[str, ...]] = (
- CANONICAL_HYBRID_ENGINE,
-)
-HTTP_CLIENT_BACKEND_CHOICES: Final[tuple[str, ...]] = (
- "hybrid-http-client",
-)
-PUBLIC_BACKEND_CHOICES: Final[tuple[str, ...]] = LOCAL_BACKEND_CHOICES + HTTP_CLIENT_BACKEND_CHOICES
-HYBRID_EFFORT_CHOICES: Final[tuple[str, ...]] = (
- LOCAL_HYBRID_EFFORT,
- LAYOUT_HYBRID_EFFORT,
- MAX_HYBRID_EFFORT,
-)
-HYBRID_EFFORT_BY_TIER: Final[dict[str, str]] = {
- "flash": "flash",
- "basic": LOCAL_HYBRID_EFFORT,
- "standard": LAYOUT_HYBRID_EFFORT,
- "advanced": MAX_HYBRID_EFFORT,
-}
-BACKEND_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(PUBLIC_BACKEND_CHOICES)}
-HYBRID_EFFORT_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(HYBRID_EFFORT_CHOICES)}
-
-BACKEND_ALIASES: Final[dict[str, str]] = {
- "hybrid-auto-engine": CANONICAL_HYBRID_ENGINE,
- "pipeline": CANONICAL_HYBRID_ENGINE,
- "vlm-engine": CANONICAL_HYBRID_ENGINE,
- "vlm-auto-engine": CANONICAL_HYBRID_ENGINE,
- "vlm-http-client": "hybrid-http-client",
-}
-LEGACY_PIPELINE_BACKEND_ALIASES: Final[frozenset[str]] = frozenset({"pipeline"})
-LEGACY_VLM_BACKEND_ALIASES: Final[frozenset[str]] = frozenset(
- {
- "vlm-engine",
- "vlm-auto-engine",
- "vlm-http-client",
- }
-)
-
-SUPPORTED_BACKENDS: Final[tuple[str, ...]] = PUBLIC_BACKEND_CHOICES + ("flash",)
-
-SUPPORTED_EFFORTS: Final[tuple[str, ...]] = HYBRID_EFFORT_CHOICES
-
-
-def normalize_backend(backend: str | None) -> str:
- """规范化 backend 名称,并将旧 VLM backend 兼容映射到 Hybrid backend。"""
- normalized = (backend or "").strip()
- if normalized in BACKEND_ALIASES:
- return BACKEND_ALIASES[normalized]
- if normalized in SUPPORTED_BACKENDS:
- return normalized
- raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(SUPPORTED_BACKENDS)}")
-
-
-def normalize_public_backend(backend: str | None) -> str:
- """规范化公开 CLI/API backend 名称,但不暴露 flash 和旧 VLM 选项。"""
- normalized = (backend or "").strip()
- if normalized in BACKEND_ALIASES:
- return BACKEND_ALIASES[normalized]
- if normalized in PUBLIC_BACKEND_CHOICES:
- return normalized
- raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(PUBLIC_BACKEND_CHOICES)}")
-
-
-def validate_effort(effort: str | None) -> str:
- """校验 Hybrid effort 级别,只允许 medium/high/xhigh 三档。"""
- normalized = (effort or DEFAULT_EFFORT).strip().lower()
- if normalized in HYBRID_EFFORT_CHOICES:
- return normalized
- raise ValueError(f"Unsupported effort '{effort}'. Supported efforts: {', '.join(HYBRID_EFFORT_CHOICES)}")
-
-
-def effort_for_tier(tier: str | None) -> str:
- """将公开 tier 映射为 Hybrid effort,保证 API、Gradio 与 parser 使用同一规则。"""
- normalized = (tier or "").strip().lower()
- if normalized in HYBRID_EFFORT_BY_TIER:
- return HYBRID_EFFORT_BY_TIER[normalized]
- supported_tiers = ", ".join(HYBRID_EFFORT_BY_TIER)
- raise ValueError(f"Unsupported tier '{tier}'. Supported hybrid tiers: {supported_tiers}")
-
-
-def resolve_backend_and_effort(backend: str | None, effort: str | None = None) -> tuple[str, str]:
- """同时解析 backend 与 effort,旧 pipeline/VLM backend 分别统一转为 Hybrid medium/xhigh。"""
- raw_backend = (backend or "").strip()
- resolved_backend = normalize_backend(raw_backend)
- resolved_effort = validate_effort(effort)
- if raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES:
- resolved_effort = LOCAL_HYBRID_EFFORT
- elif raw_backend in LEGACY_VLM_BACKEND_ALIASES:
- resolved_effort = MAX_HYBRID_EFFORT
- return resolved_backend, resolved_effort
-
-
-def is_hybrid_backend(backend: str) -> bool:
- """判断规范化后的 backend 是否属于 Hybrid 后端族。"""
- return normalize_backend(backend).startswith("hybrid-")
diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.py
deleted file mode 100644
index 46f6de9f..00000000
--- a/mineru/utils/config_reader.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import os
-
-from loguru import logger
-
-
-def get_device() -> str:
- device_mode = os.getenv("MINERU_DEVICE_MODE", None)
- if device_mode is not None:
- return device_mode
- try:
- import torch
- except ImportError:
- return "cpu"
- try:
- if torch.cuda.is_available(): # type: ignore
- return "cuda"
- except Exception:
- pass
- try:
- if torch.backends.mps.is_available(): # type: ignore
- return "mps"
- except Exception:
- pass
- try:
- import torch_npu
-
- if torch_npu.npu.is_available(): # type: ignore
- return "npu"
- except Exception:
- pass
- try:
- if torch.gcu.is_available(): # type: ignore
- return "gcu"
- except Exception:
- pass
- try:
- if torch.musa.is_available(): # type: ignore
- return "musa"
- except Exception:
- pass
- try:
- if torch.mlu.is_available(): # type: ignore
- return "mlu"
- except Exception:
- pass
- try:
- if torch.sdaa.is_available(): # type: ignore
- return "sdaa"
- except Exception:
- pass
- return "cpu"
-
-
-def get_model_stack() -> str:
- """返回模型推理技术栈:``"light"`` 或 ``"full"``。
-
- 优先读取 ``config.model.stack``(支持环境变量 ``MINERU_MODEL_STACK``)。
- 当值为 ``"auto"`` 时,根据 ``get_device()`` 的结果自动选择:
- device 为 ``"cpu"`` 时用 ``"light"``(onnxruntime / llama.cpp),否则用 ``"full"``(PyTorch / transformers)。
- """
- from ..config import config
-
- stack = config.model.stack
- if stack in ("light", "full"):
- return stack
- # auto: cpu → light, 其他 → full
- device = get_device()
- return "light" if device == "cpu" else "full"
-
-
-def get_processing_window_size(default: int = 64) -> int:
- value = os.getenv("MINERU_PROCESSING_WINDOW_SIZE")
- if value is None:
- return default
- try:
- window_size = int(value)
- except ValueError:
- logger.warning(f"Invalid MINERU_PROCESSING_WINDOW_SIZE value: {value}, use default {default}")
- return default
- return max(1, window_size)
-
-
-def get_max_concurrent_requests(default: int = 3) -> int:
- if default <= 0:
- raise ValueError(f"default max_concurrent_requests must be a positive integer, got {default}")
- value = os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS")
- if value is None:
- return default
- try:
- max_concurrent_requests = int(value)
- except ValueError as exc:
- raise ValueError(f"Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: {value}. Expected a positive integer.") from exc
- if max_concurrent_requests <= 0:
- raise ValueError(f"Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: {value}. Expected a positive integer.")
- return max_concurrent_requests
diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.py
deleted file mode 100644
index 9e5fef06..00000000
--- a/mineru/utils/enum_class.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-
-class ImageType:
- PIL = "pil_img"
- BASE64 = "base64_img"
diff --git a/mineru/utils/bbox_utils.py b/mineru/utils/geometry.py
similarity index 100%
rename from mineru/utils/bbox_utils.py
rename to mineru/utils/geometry.py
diff --git a/mineru/utils/hash_utils.py b/mineru/utils/hash_utils.py
deleted file mode 100644
index 2393e842..00000000
--- a/mineru/utils/hash_utils.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import hashlib
-
-
-def str_sha256(input_string: str) -> str:
- hasher = hashlib.sha256()
- # 在Python3中,需要将字符串转化为字节对象才能被哈希函数处理
- input_bytes = input_string.encode("utf-8")
- hasher.update(input_bytes)
- return hasher.hexdigest()
diff --git a/mineru/utils/image_utils.py b/mineru/utils/image.py
similarity index 61%
rename from mineru/utils/image_utils.py
rename to mineru/utils/image.py
index 1d34ffd9..2b8a9f30 100644
--- a/mineru/utils/image_utils.py
+++ b/mineru/utils/image.py
@@ -1,5 +1,12 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""跨模型共享的轻量图像统计与裁剪原语。"""
+
import cv2
import numpy as np
+from PIL import Image
+
+from ..types import BBox
+from .geometry import normalize_to_int_bbox
def calculate_contrast(img: np.ndarray, img_mode: str) -> float:
@@ -25,3 +32,14 @@ def calculate_contrast(img: np.ndarray, img_mode: str) -> float:
contrast = std_dev / (mean_value + 1e-6)
# logger.debug(f"contrast: {contrast}")
return round(float(contrast), 2)
+
+
+def crop_pil_image(bbox: BBox, image: Image.Image, scale: float = 2.0) -> Image.Image:
+ """按缩放后的 bbox 裁剪 Pillow 图像。"""
+ scaled_bbox = normalize_to_int_bbox([float(value) * scale for value in bbox])
+ if scaled_bbox is None:
+ return image.crop((0, 0, 0, 0))
+ return image.crop(tuple(scaled_bbox))
+
+
+__all__ = ["calculate_contrast", "crop_pil_image"]
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index 7dc738ae..e4f4b849 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -3,12 +3,11 @@ from __future__ import annotations
import base64
import binascii
+import hashlib
from pathlib import Path, PureWindowsPath
import re
import xml.etree.ElementTree as ElementTree
-from .hash_utils import str_sha256
-
INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)", re.DOTALL)
@@ -90,7 +89,7 @@ class ImagePayloadCache:
else:
ext = normalize_image_extension(image_format)
payload_key = base64.b64encode(img_bytes).decode("ascii")
- img_path = f"{str_sha256(payload_key)}.{ext}"
+ img_path = f"{hashlib.sha256(payload_key.encode('utf-8')).hexdigest()}.{ext}"
self._images[img_path] = img_bytes
return img_path
diff --git a/mineru/utils/language.py b/mineru/utils/language.py
index 073daa0c..b86c3f76 100644
--- a/mineru/utils/language.py
+++ b/mineru/utils/language.py
@@ -1,16 +1,19 @@
# Copyright (c) Opendatalab. All rights reserved.
import os
+from pathlib import Path
import unicodedata
-if not os.getenv("FTLANG_CACHE"):
- current_file_path = os.path.abspath(__file__)
- current_dir = os.path.dirname(current_file_path)
- root_dir = os.path.dirname(current_dir)
- ftlang_cache_dir = os.path.join(root_dir, "resources", "fasttext-langdetect")
- os.environ["FTLANG_CACHE"] = str(ftlang_cache_dir)
- # print(os.getenv("FTLANG_CACHE"))
+DEFAULT_CODE_LANGUAGE = "txt"
-from fast_langdetect import detect_language
+
+def _detect_language(text: str) -> object:
+ """首次检测时配置本地模型缓存并惰性加载语言识别器。"""
+ if not os.getenv("FTLANG_CACHE"):
+ cache_dir = Path(__file__).resolve().parents[1] / "resources" / "fasttext-langdetect"
+ os.environ["FTLANG_CACHE"] = str(cache_dir)
+ from fast_langdetect import detect_language
+
+ return detect_language(text)
def remove_invalid_surrogates(text: str) -> str:
@@ -19,7 +22,6 @@ def remove_invalid_surrogates(text: str) -> str:
def detect_lang(text: str) -> str:
-
if len(text) == 0:
return ""
@@ -27,10 +29,10 @@ def detect_lang(text: str) -> str:
text = remove_invalid_surrogates(text)
try:
- lang_upper = detect_language(text)
+ lang_upper = _detect_language(text)
except Exception:
html_no_ctrl_chars = "".join([c for c in text if unicodedata.category(c)[0] not in ["C"]])
- lang_upper = detect_language(html_no_ctrl_chars)
+ lang_upper = _detect_language(html_no_ctrl_chars)
try:
lang = lang_upper.lower()
@@ -39,6 +41,48 @@ def detect_lang(text: str) -> str:
return lang
+def _normalize_text_for_language_guess(code: str) -> str:
+ """移除孤立代理字符并还原合法代理对,供代码语言识别使用。"""
+ if not code:
+ return ""
+ normalized: list[str] = []
+ index = 0
+ while index < len(code):
+ current_char = code[index]
+ current_ord = ord(current_char)
+ if 0xD800 <= current_ord <= 0xDBFF:
+ if index + 1 < len(code):
+ next_char = code[index + 1]
+ next_ord = ord(next_char)
+ if 0xDC00 <= next_ord <= 0xDFFF:
+ pair = current_char + next_char
+ normalized.append(pair.encode("utf-16", "surrogatepass").decode("utf-16"))
+ index += 2
+ continue
+ index += 1
+ continue
+ if 0xDC00 <= current_ord <= 0xDFFF:
+ index += 1
+ continue
+ normalized.append(current_char)
+ index += 1
+ return "".join(normalized)
+
+
+def guess_code_language(code: str) -> str:
+ """使用 Magika 推断代码块语言,失败时返回纯文本类型。"""
+ normalized_code = _normalize_text_for_language_guess(code)
+ if not normalized_code:
+ return DEFAULT_CODE_LANGUAGE
+ try:
+ from magika import Magika
+
+ lang = Magika().identify_bytes(normalized_code.encode("utf-8", errors="replace")).prediction.output.label
+ except Exception:
+ return DEFAULT_CODE_LANGUAGE
+ return lang if lang != "unknown" else DEFAULT_CODE_LANGUAGE
+
+
if __name__ == "__main__":
print(os.getenv("FTLANG_CACHE"))
print(detect_lang("This is a test."))
@@ -46,3 +90,6 @@ if __name__ == "__main__":
print(detect_lang("这个是中文测试。"))
print(detect_lang("<html>这个是中文测试。</html>"))
print(detect_lang("〖\ud835\udc46\ud835〗这是个包含utf-16的中文测试"))
+
+
+__all__ = ["DEFAULT_CODE_LANGUAGE", "detect_lang", "guess_code_language", "remove_invalid_surrogates"]
diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.py
deleted file mode 100644
index 4373c290..00000000
--- a/mineru/utils/model_utils.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import gc
-import math
-import os
-from typing import Any
-
-import numpy as np
-from loguru import logger
-from PIL import Image
-
-from ..types import BBox, IntBBox
-
-try:
- import torch
- import torch_npu
- _TORCH_AVAILABLE = True
-except ImportError:
- _TORCH_AVAILABLE = False
-
-
-def _get_bbox(item: dict[str, Any]) -> BBox:
- bbox = item["bbox"]
- assert bbox is not None
- xmin, ymin, xmax, ymax = bbox
- return float(xmin), float(ymin), float(xmax), float(ymax)
-
-
-def _get_int_bbox(item: dict[str, Any]) -> IntBBox:
- xmin, ymin, xmax, ymax = _get_bbox(item)
- return math.floor(xmin), math.floor(ymin), math.ceil(xmax), math.ceil(ymax)
-
-
-def crop_img(
- input_res: dict[str, Any],
- input_img: Image.Image | np.ndarray,
- crop_paste_x: int = 0,
- crop_paste_y: int = 0,
-) -> tuple[Image.Image | np.ndarray, list[int]]:
- crop_xmin, crop_ymin, crop_xmax, crop_ymax = _get_int_bbox(input_res)
-
- # Calculate new dimensions
- crop_new_width = crop_xmax - crop_xmin + crop_paste_x * 2
- crop_new_height = crop_ymax - crop_ymin + crop_paste_y * 2
-
- if isinstance(input_img, np.ndarray):
- # Create a white background array
- return_image = np.ones((crop_new_height, crop_new_width, 3), dtype=np.uint8) * 255
-
- # Crop the original image using numpy slicing
- cropped_img = input_img[crop_ymin:crop_ymax, crop_xmin:crop_xmax]
-
- # Paste the cropped image onto the white background
- return_image[
- crop_paste_y : crop_paste_y + (crop_ymax - crop_ymin), crop_paste_x : crop_paste_x + (crop_xmax - crop_xmin)
- ] = cropped_img
- else:
- # Create a white background array
- return_image = Image.new("RGB", (crop_new_width, crop_new_height), "white")
- # Crop image
- crop_box = (crop_xmin, crop_ymin, crop_xmax, crop_ymax)
- cropped_img = input_img.crop(crop_box)
- return_image.paste(cropped_img, (crop_paste_x, crop_paste_y))
-
- return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width, crop_new_height]
- return return_image, return_list
-
-
-def clean_memory(device: str = "cuda") -> None:
- if not _TORCH_AVAILABLE:
- gc.collect()
- return
- if str(device).startswith("cuda"):
- if torch.cuda.is_available(): # type: ignore
- torch.cuda.empty_cache() # type: ignore
- # torch.cuda.ipc_collect()
- elif str(device).startswith("npu"):
- if torch_npu.npu.is_available(): # type: ignore
- torch_npu.npu.empty_cache() # type: ignore
- elif str(device).startswith("mps"):
- torch.mps.empty_cache() # type: ignore
- elif str(device).startswith("gcu"):
- if torch.gcu.is_available(): # type: ignore
- torch.gcu.empty_cache() # type: ignore
- elif str(device).startswith("musa"):
- if torch.musa.is_available(): # type: ignore
- torch.musa.empty_cache() # type: ignore
- elif str(device).startswith("mlu"):
- if torch.mlu.is_available(): # type: ignore
- torch.mlu.empty_cache() # type: ignore
- elif str(device).startswith("sdaa"):
- if torch.sdaa.is_available(): # type: ignore
- torch.sdaa.empty_cache() # type: ignore
- gc.collect()
-
-
-def get_vram(device: str) -> int:
- env_vram = os.getenv("MINERU_VIRTUAL_VRAM_SIZE")
-
- # 如果环境变量已配置,尝试解析并返回
- if env_vram is not None:
- try:
- total_memory = int(env_vram)
- if total_memory > 0:
- return total_memory
- else:
- logger.warning(f"MINERU_VIRTUAL_VRAM_SIZE value '{env_vram}' is not positive, falling back to auto-detection")
- except ValueError:
- logger.warning(
- f"MINERU_VIRTUAL_VRAM_SIZE value '{env_vram}' is not a valid integer, falling back to auto-detection"
- )
-
- # 环境变量未配置或配置错误,根据device自动获取
- total_memory = 1
- if not _TORCH_AVAILABLE:
- return total_memory
- if torch.cuda.is_available() and str(device).startswith("cuda"): # type: ignore
- total_memory = round(torch.cuda.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 将字节转换为 GB
- elif str(device).startswith("npu"):
- if torch_npu.npu.is_available(): # type: ignore
- total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
- elif str(device).startswith("gcu"):
- if torch.gcu.is_available(): # type: ignore
- total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
- elif str(device).startswith("musa"):
- if torch.musa.is_available(): # type: ignore
- total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
- elif str(device).startswith("mlu"):
- if torch.mlu.is_available(): # type: ignore
- total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
- elif str(device).startswith("sdaa"):
- if torch.sdaa.is_available(): # type: ignore
- total_memory = round(torch.sdaa.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
-
- return total_memory
diff --git a/mineru/utils/ocr_utils.py b/mineru/utils/ocr_utils.py
deleted file mode 100644
index 94d8c6a3..00000000
--- a/mineru/utils/ocr_utils.py
+++ /dev/null
@@ -1,507 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import copy
-from typing import Any
-
-import cv2
-import numpy as np
-
-from ..types import BBox
-from .bbox_utils import normalize_to_int_bbox
-
-
-class OcrConfidence:
- min_confidence = 0.5
- min_width = 3
-
-
-LINE_WIDTH_TO_HEIGHT_RATIO_THRESHOLD = 4 # 一般情况下,行宽度超过高度4倍时才是一个正常的横向文本块
-TEXT_REC_ROTATE_RATIO = 1.5
-
-
-def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:
- if len(spans) == 0:
- return []
- else:
- # 按照y0坐标排序
- spans.sort(key=lambda span: span["bbox"][1])
-
- lines = []
- current_line = [spans[0]]
- for span in spans[1:]:
- # 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行
- if _is_overlaps_y_exceeds_threshold(span["bbox"], current_line[-1]["bbox"], threshold):
- current_line.append(span)
- else:
- # 否则,开始新行
- lines.append(current_line)
- current_line = [span]
-
- # 添加最后一行
- if current_line:
- lines.append(current_line)
-
- return lines
-
-
-def _is_overlaps_y_exceeds_threshold(bbox1: BBox, bbox2: BBox, overlap_ratio_threshold: float = 0.8) -> bool:
- """检查两个bbox在y轴上是否有重叠,并且该重叠区域的高度占两个bbox高度更低的那个超过80%"""
- _, y0_1, _, y1_1 = bbox1
- _, y0_2, _, y1_2 = bbox2
-
- overlap = max(0, min(y1_1, y1_2) - max(y0_1, y0_2))
- height1, height2 = y1_1 - y0_1, y1_2 - y0_2
- # max_height = max(height1, height2)
- min_height = min(height1, height2)
-
- return (overlap / min_height) > overlap_ratio_threshold if min_height > 0 else False
-
-
-def _is_overlaps_x_exceeds_threshold(bbox1: BBox, bbox2: BBox, overlap_ratio_threshold: float = 0.8) -> bool:
- """检查两个bbox在x轴上是否有重叠,并且该重叠区域的宽度占两个bbox宽度更低的那个超过指定阈值"""
- x0_1, _, x1_1, _ = bbox1
- x0_2, _, x1_2, _ = bbox2
-
- overlap = max(0, min(x1_1, x1_2) - max(x0_1, x0_2))
- width1, width2 = x1_1 - x0_1, x1_2 - x0_2
- min_width = min(width1, width2)
-
- return (overlap / min_width) > overlap_ratio_threshold if min_width > 0 else False
-
-
-def img_decode(content: bytes) -> Any:
- np_arr = np.frombuffer(content, dtype=np.uint8)
- return cv2.imdecode(np_arr, cv2.IMREAD_UNCHANGED)
-
-
-def check_img(img: bytes | np.ndarray) -> Any:
- if isinstance(img, bytes):
- img = img_decode(img)
- if isinstance(img, np.ndarray) and len(img.shape) == 2:
- img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
- return img
-
-
-def alpha_to_color(img: np.ndarray, alpha_color: tuple[int, int, int] = (255, 255, 255)) -> np.ndarray:
- if len(img.shape) == 3 and img.shape[2] == 4:
- B, G, R, A = cv2.split(img)
- alpha = A / 255
-
- R = (alpha_color[0] * (1 - alpha) + R * alpha).astype(np.uint8)
- G = (alpha_color[1] * (1 - alpha) + G * alpha).astype(np.uint8)
- B = (alpha_color[2] * (1 - alpha) + B * alpha).astype(np.uint8)
-
- img = cv2.merge((B, G, R))
- return img
-
-
-def preprocess_image(_image: np.ndarray) -> np.ndarray:
- alpha_color = (255, 255, 255)
- _image = alpha_to_color(_image, alpha_color)
- return _image
-
-
-def mask_formula_regions_for_ocr_det(
- bgr_image: np.ndarray,
- mask_boxes: list[dict[str, Any]] | None,
-) -> np.ndarray:
- """将公式区域涂白后再做 OCR det,避免公式框干扰文本检测。"""
- if not mask_boxes:
- return bgr_image
-
- masked_image = bgr_image.copy()
- image_h, image_w = masked_image.shape[:2]
- for mask_box in mask_boxes:
- bbox = mask_box.get("bbox")
- if bbox is None:
- continue
-
- int_bbox = normalize_to_int_bbox(bbox, image_size=(image_h, image_w))
- if int_bbox is None:
- continue
-
- x0, y0, x1, y1 = int_bbox
- masked_image[y0:y1, x0:x1] = 255
-
- return masked_image
-
-
-def sorted_boxes(dt_boxes: list[Any]) -> list[Any]:
- """
- Sort text boxes in order from top to bottom, left to right
- args:
- dt_boxes(array):detected text boxes with shape [4, 2]
- return:
- sorted boxes(array) with shape [4, 2]
- """
- num_boxes = len(dt_boxes)
- sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
- _boxes = list(sorted_boxes)
-
- for i in range(num_boxes - 1):
- for j in range(i, -1, -1):
- if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and (_boxes[j + 1][0][0] < _boxes[j][0][0]):
- tmp = _boxes[j]
- _boxes[j] = _boxes[j + 1]
- _boxes[j + 1] = tmp
- else:
- break
- return _boxes
-
-
-def bbox_to_points(bbox: BBox) -> np.ndarray:
- """将bbox格式转换为四个顶点的数组"""
- x0, y0, x1, y1 = bbox
- return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).astype("float32")
-
-
-def points_to_bbox(points: np.ndarray) -> BBox:
- """将四个顶点的数组转换为bbox格式"""
- x0, y0 = points[0]
- x1, _ = points[1]
- _, y1 = points[2]
- return (x0, y0, x1, y1)
-
-
-def merge_intervals(intervals: list[list[float]]) -> list[list[float]]:
- # Sort the intervals based on the start value
- intervals.sort(key=lambda x: x[0])
-
- merged = []
- for interval in intervals:
- # If the list of merged intervals is empty or if the current
- # interval does not overlap with the previous, simply append it.
- if not merged or merged[-1][1] < interval[0]:
- merged.append(interval)
- else:
- # Otherwise, there is overlap, so we merge the current and previous intervals.
- merged[-1][1] = max(merged[-1][1], interval[1])
-
- return merged
-
-
-def remove_intervals(original: list[float], masks: list[list[float]]) -> list[list[float]]:
- # Merge all mask intervals
- merged_masks = merge_intervals(masks)
-
- result = []
- original_start, original_end = original
-
- for mask in merged_masks:
- mask_start, mask_end = mask
-
- # If the mask starts after the original range, ignore it
- if mask_start > original_end:
- continue
-
- # If the mask ends before the original range starts, ignore it
- if mask_end < original_start:
- continue
-
- # Remove the masked part from the original range
- if original_start < mask_start:
- result.append([original_start, mask_start - 1])
-
- original_start = max(mask_end + 1, original_start)
-
- # Add the remaining part of the original range, if any
- if original_start <= original_end:
- result.append([original_start, original_end])
-
- return result
-
-
-def update_det_boxes(dt_boxes: list[Any], mfd_res: list[dict[str, Any]]) -> list[Any]:
- new_dt_boxes = []
- angle_boxes_list = []
- for text_box in dt_boxes:
- if calculate_is_angle(text_box):
- angle_boxes_list.append(text_box)
- continue
-
- text_bbox = points_to_bbox(text_box)
- masks_list = []
- for mf_box in mfd_res:
- mf_bbox = mf_box["bbox"]
- if _is_overlaps_y_exceeds_threshold(text_bbox, mf_bbox):
- masks_list.append([mf_bbox[0], mf_bbox[2]])
- text_x_range = [text_bbox[0], text_bbox[2]]
- text_remove_mask_range = remove_intervals(text_x_range, masks_list)
- temp_dt_box = []
- for text_remove_mask in text_remove_mask_range:
- _bbox = (text_remove_mask[0], text_bbox[1], text_remove_mask[1], text_bbox[3])
- temp_dt_box.append(bbox_to_points(_bbox))
- if len(temp_dt_box) > 0:
- new_dt_boxes.extend(temp_dt_box)
-
- new_dt_boxes.extend(angle_boxes_list)
-
- return new_dt_boxes
-
-
-def merge_overlapping_spans(spans: list[BBox]) -> list[BBox]:
- """
- Merges overlapping spans on the same line.
-
- :param spans: A list of span coordinates [(x1, y1, x2, y2), ...]
- :return: A list of merged spans
- """
- # Return an empty list if the input spans list is empty
- if not spans:
- return []
-
- # Sort spans by their starting x-coordinate
- spans.sort(key=lambda x: x[0])
-
- # Initialize the list of merged spans
- merged = []
- for span in spans:
- # Unpack span coordinates
- x1, y1, x2, y2 = span
- # If the merged list is empty or there's no horizontal overlap, add the span directly
- if not merged or merged[-1][2] < x1:
- merged.append(span)
- else:
- # If there is horizontal overlap, merge the current span with the previous one
- last_span = merged.pop()
- # Update the merged span's top-left corner to the smaller (x1, y1) and bottom-right to the larger (x2, y2)
- x1 = min(last_span[0], x1)
- y1 = min(last_span[1], y1)
- x2 = max(last_span[2], x2)
- y2 = max(last_span[3], y2)
- # Add the merged span back to the list
- merged.append((x1, y1, x2, y2))
-
- # Return the list of merged spans
- return merged
-
-
-def merge_det_boxes(dt_boxes: list[Any]) -> list[Any]:
- """
- Merge detection boxes.
-
- This function takes a list of detected bounding boxes, each represented by four corner points.
- The goal is to merge these bounding boxes into larger text regions.
-
- Parameters:
- dt_boxes (list): A list containing multiple text detection boxes, where each box is defined by four corner points.
-
- Returns:
- list: A list containing the merged text regions, where each region is represented by four corner points.
- """
- # Convert the detection boxes into a dictionary format with bounding boxes and type
- dt_boxes_dict_list = []
- angle_boxes_list = []
- for text_box in dt_boxes:
- text_bbox = points_to_bbox(text_box)
-
- if calculate_is_angle(text_box):
- angle_boxes_list.append(text_box)
- continue
-
- text_box_dict = {"bbox": text_bbox}
- dt_boxes_dict_list.append(text_box_dict)
-
- # Merge adjacent text regions into lines
- lines = merge_spans_to_line(dt_boxes_dict_list)
-
- # Initialize a new list for storing the merged text regions
- new_dt_boxes = []
- for line in lines:
- line_bbox_list = []
- for span in line:
- line_bbox_list.append(span["bbox"])
-
- # 计算整行的宽度和高度
- min_x = min(bbox[0] for bbox in line_bbox_list)
- max_x = max(bbox[2] for bbox in line_bbox_list)
- min_y = min(bbox[1] for bbox in line_bbox_list)
- max_y = max(bbox[3] for bbox in line_bbox_list)
- line_width = max_x - min_x
- line_height = max_y - min_y
-
- # 只有当行宽度超过高度4倍时才进行合并
- if line_width > line_height * LINE_WIDTH_TO_HEIGHT_RATIO_THRESHOLD:
- # Merge overlapping text regions within the same line
- merged_spans = merge_overlapping_spans(line_bbox_list)
-
- # Convert the merged text regions back to point format and add them to the new detection box list
- for span in merged_spans:
- new_dt_boxes.append(bbox_to_points(span))
- else:
- # 不进行合并,直接添加原始区域
- for bbox in line_bbox_list:
- new_dt_boxes.append(bbox_to_points(bbox))
-
- new_dt_boxes.extend(angle_boxes_list)
-
- return new_dt_boxes
-
-
-def get_adjusted_mfdetrec_res(single_page_mfdetrec_res: list[dict[str, Any]], useful_list: list[int]) -> list[dict[str, Any]]:
- paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
- # Adjust the coordinates of the formula area
- adjusted_mfdetrec_res = []
- for mf_res in single_page_mfdetrec_res:
- mf_xmin, mf_ymin, mf_xmax, mf_ymax = mf_res["bbox"]
- # Adjust the coordinates of the formula area to the coordinates relative to the cropping area
- x0 = mf_xmin - xmin + paste_x
- y0 = mf_ymin - ymin + paste_y
- x1 = mf_xmax - xmin + paste_x
- y1 = mf_ymax - ymin + paste_y
- # Filter formula blocks outside the graph
- if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):
- continue
- else:
- adjusted_mfdetrec_res.append(
- {
- "bbox": [x0, y0, x1, y1],
- }
- )
- return adjusted_mfdetrec_res
-
-
-def get_ocr_result_list(
- ocr_res: list[Any],
- useful_list: list[int],
- ocr_enable: bool,
- bgr_image: np.ndarray,
-) -> list[dict[str, Any]]:
- paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
- ocr_result_list = []
- ori_im = bgr_image.copy()
- for box_ocr_res in ocr_res:
- img_crop = None
- need_ocr_rec = False
-
- if len(box_ocr_res) == 2:
- p1, p2, p3, p4 = box_ocr_res[0]
- text, score = box_ocr_res[1]
- # logger.info(f"text: {text}, score: {score}")
- if score < OcrConfidence.min_confidence: # 过滤低置信度的结果
- continue
- else:
- p1, p2, p3, p4 = box_ocr_res
- text, score = "", 1
-
- if ocr_enable:
- tmp_box = copy.deepcopy(np.array([p1, p2, p3, p4]).astype("float32"))
- img_crop = get_rotate_crop_image_for_text_rec(ori_im, tmp_box)
- need_ocr_rec = True
-
- # average_angle_degrees = calculate_angle_degrees(box_ocr_res[0])
- # if average_angle_degrees > 0.5:
- poly = [p1, p2, p3, p4]
-
- if (p3[0] - p1[0]) < OcrConfidence.min_width:
- # logger.info(f"width too small: {p3[0] - p1[0]}, text: {text}")
- continue
-
- if calculate_is_angle(poly):
- # logger.info(f"average_angle_degrees: {average_angle_degrees}, text: {text}")
- # 与x轴的夹角超过0.5度,对边界做一下矫正
- # 计算几何中心
- x_center = sum(point[0] for point in poly) / 4
- y_center = sum(point[1] for point in poly) / 4
- new_height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
- new_width = p3[0] - p1[0]
- p1 = [x_center - new_width / 2, y_center - new_height / 2]
- p2 = [x_center + new_width / 2, y_center - new_height / 2]
- p3 = [x_center + new_width / 2, y_center + new_height / 2]
- p4 = [x_center - new_width / 2, y_center + new_height / 2]
-
- # Convert the coordinates back to the original coordinate system
- p1 = [p1[0] - paste_x + xmin, p1[1] - paste_y + ymin]
- p2 = [p2[0] - paste_x + xmin, p2[1] - paste_y + ymin]
- p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]
- p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]
-
- bbox = normalize_to_int_bbox([p1, p2, p3, p4])
- if bbox is None:
- continue
-
- ocr_item = {
- "label": "ocr_text",
- "bbox": bbox,
- "score": 1.0 if ocr_enable else float(round(score, 2)),
- "text": text,
- }
- if need_ocr_rec:
- ocr_item["np_img"] = img_crop
- ocr_result_list.append(ocr_item)
-
- return ocr_result_list
-
-
-def calculate_is_angle(poly: list[Any]) -> bool:
- p1, p2, p3, p4 = poly
- height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
- if 0.8 * height <= (p3[1] - p1[1]) <= 1.2 * height:
- return False
- else:
- # logger.info((p3[1] - p1[1])/height)
- return True
-
-
-def is_bbox_aligned_rect(points: np.ndarray) -> bool:
- x_coords = points[:, 0]
- y_coords = points[:, 1]
- unique_x = np.unique(x_coords)
- unique_y = np.unique(y_coords)
- return len(unique_x) == 2 and len(unique_y) == 2
-
-
-def get_rotate_crop_image(img: np.ndarray, points: np.ndarray) -> np.ndarray:
- """
- img_height, img_width = img.shape[0:2]
- left = int(np.min(points[:, 0]))
- right = int(np.max(points[:, 0]))
- top = int(np.min(points[:, 1]))
- bottom = int(np.max(points[:, 1]))
- img_crop = img[top:bottom, left:right, :].copy()
- points[:, 0] = points[:, 0] - left
- points[:, 1] = points[:, 1] - top
- """
- assert len(points) == 4, "shape of points must be 4*2"
-
- if is_bbox_aligned_rect(points):
- xmin = int(np.min(points[:, 0]))
- xmax = int(np.max(points[:, 0]))
- ymin = int(np.min(points[:, 1]))
- ymax = int(np.max(points[:, 1]))
- new_img = img[ymin:ymax, xmin:xmax].copy()
- if new_img.shape[0] > 0 and new_img.shape[1] > 0:
- return new_img
-
- img_crop_width = int(max(np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3])))
- img_crop_height = int(max(np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2])))
- pts_std = np.float32([[0, 0], [img_crop_width, 0], [img_crop_width, img_crop_height], [0, img_crop_height]])
- M = cv2.getPerspectiveTransform(points, pts_std)
- dst_img = cv2.warpPerspective(
- img, M, (img_crop_width, img_crop_height), borderMode=cv2.BORDER_REPLICATE, flags=cv2.INTER_CUBIC
- )
- dst_img_height, dst_img_width = dst_img.shape[0:2]
- if dst_img_height * 1.0 / dst_img_width >= TEXT_REC_ROTATE_RATIO:
- dst_img = np.rot90(dst_img)
- return dst_img
-
-
-def rotate_vertical_crop_if_needed(
- crop_img: np.ndarray | None, rotate_ratio: float = TEXT_REC_ROTATE_RATIO
-) -> np.ndarray | None:
- if crop_img is None or crop_img.size == 0:
- return crop_img
-
- crop_height, crop_width = crop_img.shape[:2]
- if crop_width == 0:
- return crop_img
-
- if crop_height * 1.0 / crop_width >= rotate_ratio:
- return np.rot90(crop_img)
- return crop_img
-
-
-def get_rotate_crop_image_for_text_rec(img: np.ndarray, points: np.ndarray) -> np.ndarray | None:
- crop_img = get_rotate_crop_image(img, points)
- return rotate_vertical_crop_if_needed(crop_img)
diff --git a/mineru/utils/os_env_config.py b/mineru/utils/os_env_config.py
deleted file mode 100644
index 90f3dc23..00000000
--- a/mineru/utils/os_env_config.py
+++ /dev/null
@@ -1,36 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import os
-
-
-def get_op_num_threads(env_name: str) -> int:
- env_value = os.getenv(env_name, None)
- return get_value_from_string(env_value, -1)
-
-
-def get_load_images_timeout() -> int:
- env_value = os.getenv("MINERU_PDF_RENDER_TIMEOUT", None)
- return get_value_from_string(env_value, 300)
-
-
-def get_load_images_threads() -> int:
- env_value = os.getenv("MINERU_PDF_RENDER_THREADS", None)
- return get_value_from_string(env_value, 3)
-
-
-def get_value_from_string(env_value: str, default_value: int) -> int:
- if env_value is not None:
- try:
- num_threads = int(env_value)
- if num_threads > 0:
- return num_threads
- except ValueError:
- return default_value
- return default_value
-
-
-if __name__ == "__main__":
- print(get_value_from_string("1", -1))
- print(get_value_from_string("0", -1))
- print(get_value_from_string("-1", -1))
- print(get_value_from_string("abc", -1))
- print(get_load_images_timeout())
diff --git a/mineru/utils/check_sys_env.py b/mineru/utils/platform.py
similarity index 100%
rename from mineru/utils/check_sys_env.py
rename to mineru/utils/platform.py
diff --git a/mineru/utils/stdio.py b/mineru/utils/stdio.py
index 8b9deec3..005dd44b 100644
--- a/mineru/utils/stdio.py
+++ b/mineru/utils/stdio.py
@@ -1,4 +1,5 @@
-"""Standard stream configuration helpers."""
+# Copyright (c) Opendatalab. All rights reserved.
+"""标准流与子进程 UTF-8 环境配置。"""
from __future__ import annotations
diff --git a/mineru/utils/text_utils.py b/mineru/utils/text.py
similarity index 98%
rename from mineru/utils/text_utils.py
rename to mineru/utils/text.py
index 37cb9771..5a695389 100644
--- a/mineru/utils/text_utils.py
+++ b/mineru/utils/text.py
@@ -80,11 +80,7 @@ def merge_text_line_contents(
) -> str:
"""按累计文本上下文折叠物理行,支持跨越三行以上的 URL 连续拼接。"""
- normalized_lines = [
- str(content)
- for content in line_contents
- if str(content)
- ]
+ normalized_lines = [str(content) for content in line_contents if str(content)]
if not normalized_lines:
return ""
merged_content = normalized_lines[0]
diff --git a/pyproject.toml b/pyproject.toml
index f4332b4d..17680346 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -139,7 +139,7 @@ namespaces = false
[tool.setuptools.package-data]
"mineru" = ["resources/**"]
"mineru.doclib.migrations" = ["*.sql"]
-"mineru.model.utils.pytorchocr.utils" = ["resources/**"]
+"mineru.model._internal.pytorchocr.utils" = ["resources/**"]
[tool.setuptools]
include-package-data = true