Skip to content

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

feat: remove data writer, refactor vlm server.

jinzhenj0635bc7fc6dc
diff --git a/docs/en/quick_start/extension_modules.md b/docs/en/quick_start/extension_modules.md
index daec8c4d..aa407ec5 100644
--- a/docs/en/quick_start/extension_modules.md
+++ b/docs/en/quick_start/extension_modules.md
@@ -4,21 +4,13 @@ MinerU supports installing extension modules on demand based on different needs
## Common Scenarios
### Core Functionality Installation
-The `core` module is the core dependency of MinerU, containing common parsing features but not optional modules such as `vllm`/`lmdeploy`/`s3`. Installing this module ensures the basic functionality of MinerU works properly.
+The `core` module is the core dependency of MinerU, containing common parsing features but not optional modules such as `vllm`/`lmdeploy`. Installing this module ensures the basic functionality of MinerU works properly.
```bash
uv pip install "mineru[core]"
```
---
-### Using S3 Input and Output
-If you need to read from or write to S3, install the `s3` extension module.
-```bash
-uv pip install "mineru[s3]"
-```
-
----
-
### Using `vllm` to Accelerate VLM Model Inference
> [!NOTE]
> `vllm` and `lmdeploy` have nearly identical VLM inference acceleration effects and usage methods. You can choose one of them to install and use based on your actual needs, but it is not recommended to install both modules simultaneously to avoid potential dependency conflicts.
diff --git a/docs/zh/quick_start/extension_modules.md b/docs/zh/quick_start/extension_modules.md
index bc150eb6..ea00e102 100644
--- a/docs/zh/quick_start/extension_modules.md
+++ b/docs/zh/quick_start/extension_modules.md
@@ -4,21 +4,13 @@ MinerU 支持根据不同需求,按需安装扩展模块,以增强功能或
## 常见场景
### 核心功能安装
-`core` 模块是 MinerU 的核心依赖,包含了常用解析功能,不包含`vllm`/`lmdeploy`/`s3`等可选模块。安装此模块可以确保 MinerU 的基本功能正常运行。
+`core` 模块是 MinerU 的核心依赖,包含了常用解析功能,不包含`vllm`/`lmdeploy`等可选模块。安装此模块可以确保 MinerU 的基本功能正常运行。
```bash
uv pip install "mineru[core]"
```
---
-### 使用 S3 输入输出
-如需通过 S3 读取或写入文件,请安装`s3`扩展模块。
-```bash
-uv pip install "mineru[s3]"
-```
-
----
-
### 使用`vllm`加速 VLM 模型推理
> [!NOTE]
> `vllm`和`lmdeploy`对vlm的推理加速效果和使用方式几乎相同,您可以根据实际情况选择其中之一进行安装和使用,但不建议同时安装这两个模块,以避免潜在的依赖冲突。
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 9d0e38e7..ff363873 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -19,9 +19,9 @@ from mineru.backend.office.xlsx_analyze import office_xlsx_analyze
from mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyze
from mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
from mineru.cli_old.visualization import select_pages_for_pdf_visualization
-from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
from mineru.render import render_content_list, render_markdown, render_structured_content
+from mineru.render.writer import FileBasedDataWriter
from mineru.utils.backend_options import DEFAULT_HYBRID_EFFORT, normalize_backend, validate_effort
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
@@ -237,10 +237,7 @@ def _prepare_pdf_inputs(
end_page_id: int | None,
) -> list[PreparedPdfBytes]:
"""批量准备 PDF 输入,并为 backend 保留逐文档页号映射。"""
- return [
- prepare_pdf_bytes_with_page_map(pdf_bytes, start_page_id, end_page_id)
- for pdf_bytes in pdf_bytes_list
- ]
+ return [prepare_pdf_bytes_with_page_map(pdf_bytes, start_page_id, end_page_id) for pdf_bytes in pdf_bytes_list]
def _process_output(
diff --git a/mineru/cli_old/vlm_server.py b/mineru/cli_old/vlm_server.py
deleted file mode 100644
index 0155199f..00000000
--- a/mineru/cli_old/vlm_server.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import click
-import sys
-
-from loguru import logger
-
-
-def vllm_server():
- from mineru.model.vlm.vllm_server import main
- main()
-
-
-def lmdeploy_server():
- from mineru.model.vlm.lmdeploy_server import main
- main()
-
-
[email protected](context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
- '-e',
- '--engine',
- 'inference_engine',
- type=click.Choice(['auto', 'vllm', 'lmdeploy']),
- default='auto',
- help='Select the inference engine used to accelerate VLM inference, default is "auto".',
-)
-def openai_server(ctx, inference_engine):
- sys.argv = [sys.argv[0]] + ctx.args
- if inference_engine == 'auto':
- try:
- import vllm
- inference_engine = 'vllm'
- logger.info("Using vLLM as the inference engine for VLM server.")
- except ImportError:
- logger.info("vLLM not found, attempting to use LMDeploy as the inference engine for VLM server.")
- try:
- import lmdeploy
- inference_engine = 'lmdeploy'
- # Success message moved after successful import
- logger.info("Using LMDeploy as the inference engine for VLM server.")
- except ImportError:
- logger.error("Neither vLLM nor LMDeploy is installed. Please install at least one of them.")
- sys.exit(1)
-
- if inference_engine == 'vllm':
- try:
- import vllm
- except ImportError:
- logger.error("vLLM is not installed. Please install vLLM or choose LMDeploy as the inference engine.")
- sys.exit(1)
- vllm_server()
- elif inference_engine == 'lmdeploy':
- try:
- import lmdeploy
- except ImportError:
- logger.error("LMDeploy is not installed. Please install LMDeploy or choose vLLM as the inference engine.")
- sys.exit(1)
- lmdeploy_server()
-
-if __name__ == "__main__":
- openai_server()
\ No newline at end of file
diff --git a/mineru/data/__init__.py b/mineru/data/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/data/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/data/data_reader_writer/__init__.py b/mineru/data/data_reader_writer/__init__.py
deleted file mode 100644
index d55489f3..00000000
--- a/mineru/data/data_reader_writer/__init__.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from .base import DataReader, DataWriter
-from .dummy import DummyDataWriter
-from .filebase import FileBasedDataReader, FileBasedDataWriter
-
-__all__ = [
- "DataReader",
- "DataWriter",
- "FileBasedDataReader",
- "FileBasedDataWriter",
- "S3DataReader",
- "S3DataWriter",
- "MultiBucketS3DataReader",
- "MultiBucketS3DataWriter",
- "DummyDataWriter",
-]
-
-
-def __getattr__(name):
- """按需加载 S3 DataReader/DataWriter,避免默认安装场景强制依赖 boto3。"""
- if name in {"MultiBucketS3DataReader", "MultiBucketS3DataWriter"}:
- from .multi_bucket_s3 import MultiBucketS3DataReader, MultiBucketS3DataWriter
-
- s3_exports = {
- "MultiBucketS3DataReader": MultiBucketS3DataReader,
- "MultiBucketS3DataWriter": MultiBucketS3DataWriter,
- }
- globals().update(s3_exports)
- return s3_exports[name]
-
- if name in {"S3DataReader", "S3DataWriter"}:
- from .s3 import S3DataReader, S3DataWriter
-
- s3_exports = {"S3DataReader": S3DataReader, "S3DataWriter": S3DataWriter}
- globals().update(s3_exports)
- return s3_exports[name]
-
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/mineru/data/data_reader_writer/base.py b/mineru/data/data_reader_writer/base.py
deleted file mode 100644
index 38b6be9e..00000000
--- a/mineru/data/data_reader_writer/base.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-from abc import ABC, abstractmethod
-
-
-class DataReader(ABC):
-
- def read(self, path: str) -> bytes:
- """Read the file.
-
- Args:
- path (str): file path to read
-
- Returns:
- bytes: the content of the file
- """
- return self.read_at(path)
-
- @abstractmethod
- def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
- """Read the file at offset and limit.
-
- Args:
- path (str): the file path
- offset (int, optional): the number of bytes skipped. Defaults to 0.
- limit (int, optional): the length of bytes want to read. Defaults to -1.
-
- Returns:
- bytes: the content of the file
- """
- pass
-
-
-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):
- 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
diff --git a/mineru/data/data_reader_writer/dummy.py b/mineru/data/data_reader_writer/dummy.py
deleted file mode 100644
index c7941734..00000000
--- a/mineru/data/data_reader_writer/dummy.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from .base import DataWriter
-
-
-class DummyDataWriter(DataWriter):
- def write(self, path: str, data: bytes) -> None:
- """Dummy write method that does nothing."""
- pass
-
- def write_string(self, path: str, data: str) -> None:
- """Dummy write_string method that does nothing."""
- pass
diff --git a/mineru/data/data_reader_writer/filebase.py b/mineru/data/data_reader_writer/filebase.py
deleted file mode 100644
index 0ad4f79c..00000000
--- a/mineru/data/data_reader_writer/filebase.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import os
-
-from .base import DataReader, DataWriter
-
-
-class FileBasedDataReader(DataReader):
- def __init__(self, parent_dir: str = ''):
- """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 read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
- """Read at offset and limit.
-
- Args:
- path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
- offset (int, optional): the number of bytes skipped. Defaults to 0.
- limit (int, optional): the length of bytes want to read. Defaults to -1.
-
- Returns:
- bytes: the content of file
- """
- 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)
-
- with open(fn_path, 'rb') as f:
- f.seek(offset)
- if limit == -1:
- return f.read()
- else:
- return f.read(limit)
-
-
-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)
diff --git a/mineru/data/data_reader_writer/multi_bucket_s3.py b/mineru/data/data_reader_writer/multi_bucket_s3.py
deleted file mode 100644
index 96bac1f1..00000000
--- a/mineru/data/data_reader_writer/multi_bucket_s3.py
+++ /dev/null
@@ -1,158 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-from ..utils.exceptions import InvalidConfig, InvalidParams
-from .base import DataReader, DataWriter
-from ..utils.schemas import S3Config
-from ..utils.path_utils import parse_s3_range_params, parse_s3path, remove_non_official_s3_args
-
-
-def _load_s3_io_classes():
- """延迟加载 S3 IO 类,仅在实际读写 S3 时要求安装 boto3。"""
- try:
- from ..io.s3 import S3Reader, S3Writer
- except ModuleNotFoundError as exc:
- raise ModuleNotFoundError(
- "S3 reader/writer requires optional dependencies. Install them with `pip install 'mineru[s3]'`."
- ) from exc
-
- return S3Reader, S3Writer
-
-
-class MultiS3Mixin:
- def __init__(self, default_prefix: str, s3_configs: list[S3Config]):
- """Initialized with multiple s3 configs.
-
- Args:
- default_prefix (str): the default prefix of the relative path. for example, {some_bucket}/{some_prefix} or {some_bucket}
- s3_configs (list[S3Config]): list of s3 configs, the bucket_name must be unique in the list.
-
- Raises:
- InvalidConfig: default bucket config not in s3_configs.
- InvalidConfig: bucket name not unique in s3_configs.
- InvalidConfig: default bucket must be provided.
- """
- if len(default_prefix) == 0:
- raise InvalidConfig('default_prefix must be provided')
-
- arr = default_prefix.strip('/').split('/')
- self.default_bucket = arr[0]
- self.default_prefix = '/'.join(arr[1:])
-
- found_default_bucket_config = False
- for conf in s3_configs:
- if conf.bucket_name == self.default_bucket:
- found_default_bucket_config = True
- break
-
- if not found_default_bucket_config:
- raise InvalidConfig(
- f'default_bucket: {self.default_bucket} config must be provided in s3_configs: {s3_configs}'
- )
-
- uniq_bucket = set([conf.bucket_name for conf in s3_configs])
- if len(uniq_bucket) != len(s3_configs):
- raise InvalidConfig(
- f'the bucket_name in s3_configs: {s3_configs} must be unique'
- )
-
- self.s3_configs = s3_configs
- self._s3_clients_h: dict = {}
-
-
-class MultiBucketS3DataReader(DataReader, MultiS3Mixin):
- def read(self, path: str) -> bytes:
- """Read the path from s3, select diffect bucket client for each request
- based on the bucket, also support range read.
-
- Args:
- path (str): the s3 path of file, the path must be in the format of s3://bucket_name/path?offset,limit.
- for example: s3://bucket_name/path?0,100.
-
- Returns:
- bytes: the content of s3 file.
- """
- may_range_params = parse_s3_range_params(path)
- if may_range_params is None or 2 != len(may_range_params):
- byte_start, byte_len = 0, -1
- else:
- byte_start, byte_len = int(may_range_params[0]), int(may_range_params[1])
- path = remove_non_official_s3_args(path)
- return self.read_at(path, byte_start, byte_len)
-
- def __get_s3_client(self, bucket_name: str):
- if bucket_name not in set([conf.bucket_name for conf in self.s3_configs]):
- raise InvalidParams(
- f'bucket name: {bucket_name} not found in s3_configs: {self.s3_configs}'
- )
- if bucket_name not in self._s3_clients_h:
- conf = next(
- filter(lambda conf: conf.bucket_name == bucket_name, self.s3_configs)
- )
- S3Reader, _ = _load_s3_io_classes()
- self._s3_clients_h[bucket_name] = S3Reader(
- bucket_name,
- conf.access_key,
- conf.secret_key,
- conf.endpoint_url,
- conf.addressing_style,
- )
- return self._s3_clients_h[bucket_name]
-
- def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
- """Read the file with offset and limit, select diffect bucket client
- for each request based on the bucket.
-
- Args:
- path (str): the file path.
- offset (int, optional): the number of bytes skipped. Defaults to 0.
- limit (int, optional): the number of bytes want to read. Defaults to -1 which means infinite.
-
- Returns:
- bytes: the file content.
- """
- if path.startswith('s3://'):
- bucket_name, path = parse_s3path(path)
- s3_reader = self.__get_s3_client(bucket_name)
- else:
- s3_reader = self.__get_s3_client(self.default_bucket)
- if self.default_prefix:
- path = self.default_prefix + '/' + path
- return s3_reader.read_at(path, offset, limit)
-
-
-class MultiBucketS3DataWriter(DataWriter, MultiS3Mixin):
- def __get_s3_client(self, bucket_name: str):
- if bucket_name not in set([conf.bucket_name for conf in self.s3_configs]):
- raise InvalidParams(
- f'bucket name: {bucket_name} not found in s3_configs: {self.s3_configs}'
- )
- if bucket_name not in self._s3_clients_h:
- conf = next(
- filter(lambda conf: conf.bucket_name == bucket_name, self.s3_configs)
- )
- _, S3Writer = _load_s3_io_classes()
- self._s3_clients_h[bucket_name] = S3Writer(
- bucket_name,
- conf.access_key,
- conf.secret_key,
- conf.endpoint_url,
- conf.addressing_style,
- )
- return self._s3_clients_h[bucket_name]
-
- def write(self, path: str, data: bytes) -> None:
- """Write file with data, also select diffect bucket client for each
- request based on the bucket.
-
- 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.
- """
- if path.startswith('s3://'):
- bucket_name, path = parse_s3path(path)
- s3_writer = self.__get_s3_client(bucket_name)
- else:
- s3_writer = self.__get_s3_client(self.default_bucket)
- if self.default_prefix:
- path = self.default_prefix + '/' + path
- return s3_writer.write(path, data)
diff --git a/mineru/data/data_reader_writer/s3.py b/mineru/data/data_reader_writer/s3.py
deleted file mode 100644
index 57312cbb..00000000
--- a/mineru/data/data_reader_writer/s3.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from .multi_bucket_s3 import MultiBucketS3DataReader, MultiBucketS3DataWriter
-from ..utils.schemas import S3Config
-
-
-class S3DataReader(MultiBucketS3DataReader):
- def __init__(
- self,
- default_prefix_without_bucket: str,
- bucket: str,
- ak: str,
- sk: str,
- endpoint_url: str,
- addressing_style: str = 'auto',
- ):
- """s3 reader client.
-
- Args:
- default_prefix_without_bucket: prefix that not contains bucket
- bucket (str): bucket name
- ak (str): access key
- sk (str): secret key
- endpoint_url (str): endpoint url of s3
- addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
- refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
- """
- super().__init__(
- f'{bucket}/{default_prefix_without_bucket}',
- [
- S3Config(
- bucket_name=bucket,
- access_key=ak,
- secret_key=sk,
- endpoint_url=endpoint_url,
- addressing_style=addressing_style,
- )
- ],
- )
-
-
-class S3DataWriter(MultiBucketS3DataWriter):
- def __init__(
- self,
- default_prefix_without_bucket: str,
- bucket: str,
- ak: str,
- sk: str,
- endpoint_url: str,
- addressing_style: str = 'auto',
- ):
- """s3 writer client.
-
- Args:
- default_prefix_without_bucket: prefix that not contains bucket
- bucket (str): bucket name
- ak (str): access key
- sk (str): secret key
- endpoint_url (str): endpoint url of s3
- addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
- refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
- """
- super().__init__(
- f'{bucket}/{default_prefix_without_bucket}',
- [
- S3Config(
- bucket_name=bucket,
- access_key=ak,
- secret_key=sk,
- endpoint_url=endpoint_url,
- addressing_style=addressing_style,
- )
- ],
- )
diff --git a/mineru/data/io/__init__.py b/mineru/data/io/__init__.py
deleted file mode 100644
index c8071a57..00000000
--- a/mineru/data/io/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-from .base import IOReader, IOWriter
-from .http import HttpReader, HttpWriter
-
-__all__ = ['IOReader', 'IOWriter', 'HttpReader', 'HttpWriter', 'S3Reader', 'S3Writer']
-
-
-def __getattr__(name):
- """按需加载 S3 IO 类,避免默认安装场景强制依赖 boto3。"""
- if name in {'S3Reader', 'S3Writer'}:
- from .s3 import S3Reader, S3Writer
-
- s3_exports = {'S3Reader': S3Reader, 'S3Writer': S3Writer}
- globals().update(s3_exports)
- return s3_exports[name]
-
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/mineru/data/io/base.py b/mineru/data/io/base.py
deleted file mode 100644
index ede371f0..00000000
--- a/mineru/data/io/base.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from abc import ABC, abstractmethod
-
-
-class IOReader(ABC):
- @abstractmethod
- def read(self, path: str) -> bytes:
- """Read the file.
-
- Args:
- path (str): file path to read
-
- Returns:
- bytes: the content of the file
- """
- pass
-
- @abstractmethod
- def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
- """Read at offset and limit.
-
- Args:
- path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
- offset (int, optional): the number of bytes skipped. Defaults to 0.
- limit (int, optional): the length of bytes want to read. Defaults to -1.
-
- Returns:
- bytes: the content of file
- """
- pass
-
-
-class IOWriter(ABC):
-
- @abstractmethod
- 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
- """
- pass
diff --git a/mineru/data/io/http.py b/mineru/data/io/http.py
deleted file mode 100644
index 328cb2ac..00000000
--- a/mineru/data/io/http.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-import io
-
-import httpx
-
-from .base import IOReader, IOWriter
-
-
-class HttpReader(IOReader):
- def read(self, url: str) -> bytes:
- """Read the file.
-
- Args:
- path (str): file path to read
-
- Returns:
- bytes: the content of the file
- """
- return httpx.get(url).content
-
- def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
- """Not Implemented."""
- raise NotImplementedError
-
-
-class HttpWriter(IOWriter):
- def write(self, url: 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
- """
- files = {"file": io.BytesIO(data)}
- response = httpx.post(url, files=files)
- assert 300 > response.status_code and response.status_code > 199
diff --git a/mineru/data/io/s3.py b/mineru/data/io/s3.py
deleted file mode 100644
index 58d82759..00000000
--- a/mineru/data/io/s3.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from ..io.base import IOReader, IOWriter
-
-
-def _load_s3_client_dependencies():
- """按需加载 S3 客户端依赖,避免导入 S3 类时强制安装 boto3。"""
- try:
- import boto3
- from botocore.config import Config
- except ImportError as exc:
- raise ModuleNotFoundError(
- "S3 IO requires optional dependencies. Install them with `pip install 'mineru[s3]'`."
- ) from exc
-
- return boto3, Config
-
-
-class S3Reader(IOReader):
- def __init__(
- self,
- bucket: str,
- ak: str,
- sk: str,
- endpoint_url: str,
- addressing_style: str = "auto",
- ):
- """s3 reader client.
-
- Args:
- bucket (str): bucket name
- ak (str): access key
- sk (str): secret key
- endpoint_url (str): endpoint url of s3
- addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
- refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
- """
-
- boto3, Config = _load_s3_client_dependencies()
-
- self._bucket = bucket
- self._ak = ak
- self._sk = sk
- self._s3_client = boto3.client(
- service_name="s3",
- aws_access_key_id=ak,
- aws_secret_access_key=sk,
- endpoint_url=endpoint_url,
- config=Config(
- s3={"addressing_style": addressing_style},
- retries={"max_attempts": 5, "mode": "standard"},
- ),
- )
-
- def read(self, key: str) -> bytes:
- """Read the file.
-
- Args:
- path (str): file path to read
-
- Returns:
- bytes: the content of the file
- """
- return self.read_at(key)
-
- def read_at(self, key: str, offset: int = 0, limit: int = -1) -> bytes:
- """Read at offset and limit.
-
- Args:
- path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
- offset (int, optional): the number of bytes skipped. Defaults to 0.
- limit (int, optional): the length of bytes want to read. Defaults to -1.
-
- Returns:
- bytes: the content of file
- """
- if limit > -1:
- range_header = f"bytes={offset}-{offset + limit - 1}"
- res = self._s3_client.get_object(Bucket=self._bucket, Key=key, Range=range_header)
- else:
- res = self._s3_client.get_object(Bucket=self._bucket, Key=key, Range=f"bytes={offset}-")
- return res["Body"].read()
-
-
-class S3Writer(IOWriter):
- def __init__(
- self,
- bucket: str,
- ak: str,
- sk: str,
- endpoint_url: str,
- addressing_style: str = "auto",
- ):
- """s3 reader client.
-
- Args:
- bucket (str): bucket name
- ak (str): access key
- sk (str): secret key
- endpoint_url (str): endpoint url of s3
- addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
- refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
- """
-
- boto3, Config = _load_s3_client_dependencies()
-
- self._bucket = bucket
- self._ak = ak
- self._sk = sk
- self._s3_client = boto3.client(
- service_name="s3",
- aws_access_key_id=ak,
- aws_secret_access_key=sk,
- endpoint_url=endpoint_url,
- config=Config(
- s3={"addressing_style": addressing_style},
- retries={"max_attempts": 5, "mode": "standard"},
- ),
- )
-
- def write(self, key: str, data: bytes):
- """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
- """
- self._s3_client.put_object(Bucket=self._bucket, Key=key, Body=data)
diff --git a/mineru/data/utils/__init__.py b/mineru/data/utils/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/data/utils/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/data/utils/exceptions.py b/mineru/data/utils/exceptions.py
deleted file mode 100644
index 0b0c52c6..00000000
--- a/mineru/data/utils/exceptions.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-class FileNotExisted(Exception):
-
- def __init__(self, path):
- self.path = path
-
- def __str__(self):
- return f'File {self.path} does not exist.'
-
-
-class InvalidConfig(Exception):
- def __init__(self, msg):
- self.msg = msg
-
- def __str__(self):
- return f'Invalid config: {self.msg}'
-
-
-class InvalidParams(Exception):
- def __init__(self, msg):
- self.msg = msg
-
- def __str__(self):
- return f'Invalid params: {self.msg}'
-
-
-class EmptyData(Exception):
- def __init__(self, msg):
- self.msg = msg
-
- def __str__(self):
- return f'Empty data: {self.msg}'
-
-class CUDA_NOT_AVAILABLE(Exception):
- def __init__(self, msg):
- self.msg = msg
-
- def __str__(self):
- return f'CUDA not available: {self.msg}'
\ No newline at end of file
diff --git a/mineru/data/utils/path_utils.py b/mineru/data/utils/path_utils.py
deleted file mode 100644
index fc321f6f..00000000
--- a/mineru/data/utils/path_utils.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-
-def remove_non_official_s3_args(s3path):
- """
- example: s3://abc/xxxx.json?bytes=0,81350 ==> s3://abc/xxxx.json
- """
- arr = s3path.split("?")
- return arr[0]
-
-def parse_s3path(s3path: str):
- # from s3pathlib import S3Path
- # p = S3Path(remove_non_official_s3_args(s3path))
- # return p.bucket, p.key
- s3path = remove_non_official_s3_args(s3path).strip()
- if s3path.startswith(('s3://', 's3a://')):
- prefix, path = s3path.split('://', 1)
- bucket_name, key = path.split('/', 1)
- return bucket_name, key
- elif s3path.startswith('/'):
- raise ValueError("The provided path starts with '/'. This does not conform to a valid S3 path format.")
- else:
- raise ValueError("Invalid S3 path format. Expected 's3://bucket-name/key' or 's3a://bucket-name/key'.")
-
-
-def parse_s3_range_params(s3path: str):
- """
- example: s3://abc/xxxx.json?bytes=0,81350 ==> [0, 81350]
- """
- arr = s3path.split("?bytes=")
- if len(arr) == 1:
- return None
- return arr[1].split(",")
diff --git a/mineru/data/utils/schemas.py b/mineru/data/utils/schemas.py
deleted file mode 100644
index 0802892c..00000000
--- a/mineru/data/utils/schemas.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-from pydantic import BaseModel, Field
-
-
-class S3Config(BaseModel):
- """S3 config
- """
- bucket_name: str = Field(description='s3 bucket name', min_length=1)
- access_key: str = Field(description='s3 access key', min_length=1)
- secret_key: str = Field(description='s3 secret key', min_length=1)
- endpoint_url: str = Field(description='s3 endpoint url', min_length=1)
- addressing_style: str = Field(description='s3 addressing style', default='auto', min_length=1)
diff --git a/mineru/kit/commands/vlm_server.py b/mineru/kit/commands/vlm_server.py
index 157424e2..cfcf0351 100644
--- a/mineru/kit/commands/vlm_server.py
+++ b/mineru/kit/commands/vlm_server.py
@@ -1,26 +1,96 @@
from __future__ import annotations
+import importlib
+import importlib.util
+import sys
+from collections.abc import Callable
+from typing import Literal
+
import typer
+from loguru import logger
-from ...cli_old import vlm_server as old_vlm_server
+from ...utils.check_sys_env import is_mac_os_version_supported
from ..errors import exit_with_message
+def _module_available(module_name: str) -> bool:
+ try:
+ importlib.import_module(module_name)
+ except ImportError:
+ return False
+ return True
+
+
+def _mlx_server_available() -> bool:
+ if not is_mac_os_version_supported():
+ return False
+ try:
+ return importlib.util.find_spec("mlx_vlm.server") is not None
+ except ModuleNotFoundError:
+ return False
+
+
+def _run_with_forwarded_argv(main_fn: Callable[[], None], args: list[str]) -> None:
+ original_argv = sys.argv
+ sys.argv = [sys.argv[0], *args]
+ try:
+ main_fn()
+ except SystemExit as exc:
+ code = exc.code if isinstance(exc.code, int) else 1
+ raise typer.Exit(code) from None
+ finally:
+ sys.argv = original_argv
+
+
+def _resolve_auto_engine() -> Literal["vllm", "lmdeploy", "mlx"]:
+ if _module_available("vllm"):
+ logger.info("Using vLLM as the inference engine for VLM server.")
+ return "vllm"
+ if _module_available("lmdeploy"):
+ logger.info("Using LMDeploy as the inference engine for VLM server.")
+ return "lmdeploy"
+ if _mlx_server_available():
+ logger.info("Using MLX-VLM as the inference engine for VLM server.")
+ return "mlx"
+ logger.info("vLLM/LMDeploy/MLX-VLM is not installed. Please install at least one of them.")
+ raise typer.Exit(1) from None
+
+
def vlm_server_cmd(
engine: str = "auto",
ctx: typer.Context | None = None,
) -> None:
- if engine not in {"auto", "vllm", "lmdeploy", "sglang", "mlx"}:
+ if engine not in {"auto", "vllm", "lmdeploy", "mlx"}:
exit_with_message("invalid_request", f"Unsupported engine '{engine}'.", "engine")
- if engine in {"sglang", "mlx"}:
- exit_with_message("invalid_request", f"Engine '{engine}' is not implemented yet in mineru-kit vlm-server.", "engine")
extra_args = list(ctx.args) if ctx is not None else []
- try:
- old_vlm_server.openai_server.main(
- args=["--engine", engine, *extra_args],
+
+ if engine == "auto":
+ engine = _resolve_auto_engine()
+
+ if engine == "vllm":
+ if not _module_available("vllm"):
+ logger.error("vLLM is not installed. Please install vLLM or choose lmdeploy/mlx as the engine.")
+ raise typer.Exit(1) from None
+ from ..vlm_server import vllm_server
+
+ _run_with_forwarded_argv(vllm_server.main, extra_args)
+
+ elif engine == "lmdeploy":
+ if not _module_available("lmdeploy"):
+ logger.error("LMDeploy is not installed. Please install LMDeploy or choose vllm/mlx as the engine.")
+ raise typer.Exit(1) from None
+ from ..vlm_server import lmdeploy_server
+
+ _run_with_forwarded_argv(lmdeploy_server.main, extra_args)
+
+ elif engine == "mlx":
+ if not _mlx_server_available():
+ logger.error("MLX-VLM is not installed. Please install MLX-VLM or choose vllm/lmdeploy as the engine.")
+ raise typer.Exit(1) from None
+ from ..vlm_server import mlx_vlm_server
+
+ mlx_vlm_server.main(
+ args=extra_args,
prog_name="mineru-kit vlm-server",
standalone_mode=False,
)
- except SystemExit as exc:
- assert isinstance(exc.code, int)
- raise typer.Exit(exc.code) from None
diff --git a/mineru/kit/common.py b/mineru/kit/common.py
index a142e233..6f6d7966 100644
--- a/mineru/kit/common.py
+++ b/mineru/kit/common.py
@@ -8,8 +8,8 @@ import zipfile
from pathlib import Path
from typing import Literal
-from ..data.data_reader_writer.filebase import FileBasedDataWriter
from ..parser.base import ParseResult
+from ..render.writer import FileBasedDataWriter
from ..types import Tier
from ..utils.image_payload import validate_image_sidecar_path
@@ -189,8 +189,7 @@ def _write_image_sidecars(output_dir: Path, images: dict[str, bytes]) -> None:
"""将 public middle_json 引用的图片 sidecar 写到输出目录,避免 image_path 悬空。"""
writer = FileBasedDataWriter(str(output_dir))
safe_images = [
- (_resolve_safe_sidecar_path(output_dir, image_path), image_bytes)
- for image_path, image_bytes in images.items()
+ (_resolve_safe_sidecar_path(output_dir, image_path), image_bytes) for image_path, image_bytes in images.items()
]
for image_path, image_bytes in safe_images:
writer.write(image_path, image_bytes)
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index b14cb85c..2e96e6bf 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -118,7 +118,7 @@ def api_server_command(
)
def vlm_server_command(
ctx: typer.Context,
- engine: str = typer.Option("auto", "--engine", help="VLM serving engine: auto, vllm, lmdeploy, sglang, mlx"),
+ engine: str = typer.Option("auto", "--engine", help="VLM serving engine: auto, vllm, lmdeploy, mlx"),
) -> None:
"""Start the local VLM server with OpenAI-compatible chat completions."""
vlm_server.vlm_server_cmd(engine=engine, ctx=ctx)
diff --git a/mineru/kit/vlm_server/__init__.py b/mineru/kit/vlm_server/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/mineru/model/vlm/lmdeploy_server.py b/mineru/kit/vlm_server/lmdeploy_server.py
similarity index 100%
rename from mineru/model/vlm/lmdeploy_server.py
rename to mineru/kit/vlm_server/lmdeploy_server.py
diff --git a/mineru/kit/vlm_server/mlx_vlm_server.py b/mineru/kit/vlm_server/mlx_vlm_server.py
new file mode 100644
index 00000000..4d1e96fe
--- /dev/null
+++ b/mineru/kit/vlm_server/mlx_vlm_server.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+import inspect
+import time
+from typing import Any
+
+import click
+import uvicorn
+from fastapi import FastAPI, HTTPException, Request
+from mineru_vl_utils.mlx_compat import load_mlx_model
+
+from ...utils.models_download_utils import auto_download_and_get_model_root_path
+
+
+async def _resolve_result(value: Any) -> Any:
+ if inspect.isawaitable(value):
+ return await value
+ return value
+
+
+def _default_model_id(configured_model: str | None) -> str:
+ if configured_model:
+ return configured_model
+ return auto_download_and_get_model_root_path("/", "vlm")
+
+
+def _load_mlx_model_for_server(path_or_hf_repo: str, adapter_path: str | None = None, **kwargs: Any) -> Any:
+ if adapter_path is not None:
+ kwargs["adapter_path"] = adapter_path
+ return load_mlx_model(path_or_hf_repo, **kwargs)
+
+
+def _text_from_content_part(part: Any) -> str:
+ if not isinstance(part, dict):
+ return ""
+ part_type = part.get("type")
+ if part_type in {"text", "input_text", "output_text"}:
+ text = part.get("text")
+ return text if isinstance(text, str) else ""
+ return ""
+
+
+def _sanitize_chat_template_prompt(prompt: Any) -> Any:
+ if not isinstance(prompt, list):
+ return prompt
+
+ sanitized = []
+ for message in prompt:
+ if isinstance(message, dict):
+ role = message.get("role", "user")
+ content = message.get("content")
+ else:
+ role = getattr(message, "role", "user")
+ content = getattr(message, "content", "")
+ if isinstance(content, list):
+ content = "".join(_text_from_content_part(part) for part in content)
+ sanitized.append({"role": role, "content": content})
+ return sanitized
+
+
+def _wrap_apply_chat_template(apply_chat_template: Any) -> Any:
+ def _apply_chat_template(processor: Any, config: Any, prompt: Any, *args: Any, **kwargs: Any) -> Any:
+ return apply_chat_template(processor, config, _sanitize_chat_template_prompt(prompt), *args, **kwargs)
+
+ return _apply_chat_template
+
+
+def create_app(default_model: str | None = None) -> FastAPI:
+ try:
+ from mlx_vlm import server as mlx_server
+ except ImportError as exc:
+ raise click.ClickException(
+ "mlx-vlm is not installed. Install optional MLX dependencies in this environment, "
+ "for example: pip install 'mineru[mlx]'."
+ ) from exc
+
+ mlx_server.load = _load_mlx_model_for_server
+ mlx_server.apply_chat_template = _wrap_apply_chat_template(mlx_server.apply_chat_template)
+ default_model_id = _default_model_id(default_model)
+
+ app = FastAPI(
+ title="MinerU MLX VLM Server",
+ description="OpenAI-compatible adapter for mlx-vlm.",
+ version=getattr(mlx_server, "__version__", "unknown"),
+ )
+
+ @app.post("/v1/chat/completions")
+ async def v1_chat_completions(request: Request) -> Any:
+ payload = await request.json()
+ if not isinstance(payload, dict):
+ raise HTTPException(status_code=400, detail="Request body must be a JSON object.")
+ if not payload.get("model"):
+ payload["model"] = default_model_id
+ chat_request = mlx_server.ChatRequest.model_validate(payload)
+ return await _resolve_result(mlx_server.chat_completions_endpoint(chat_request))
+
+ @app.post("/chat/completions")
+ async def chat_completions(request: Request) -> Any:
+ return await v1_chat_completions(request)
+
+ @app.get("/v1/models")
+ async def v1_models() -> dict[str, Any]:
+ return {
+ "object": "list",
+ "data": [
+ {
+ "id": default_model_id,
+ "object": "model",
+ "created": int(time.time()),
+ }
+ ],
+ }
+
+ @app.get("/models")
+ async def models() -> dict[str, Any]:
+ return await v1_models()
+
+ @app.get("/health")
+ async def health() -> Any:
+ health_check = getattr(mlx_server, "health_check", None)
+ if health_check is None:
+ return {"status": "healthy", "loaded_model": None, "loaded_adapter": None}
+ return await _resolve_result(health_check())
+
+ @app.post("/unload")
+ async def unload() -> Any:
+ unload_model_endpoint = getattr(mlx_server, "unload_model_endpoint", None)
+ if unload_model_endpoint is None:
+ return {"status": "no_model_loaded", "message": "No model unload endpoint is available."}
+ return await _resolve_result(unload_model_endpoint())
+
+ return app
+
+
[email protected](context_settings={"ignore_unknown_options": True, "allow_extra_args": True})
[email protected]("--host", default="127.0.0.1", show_default=True, help="Host for the HTTP server.")
[email protected]("--port", default=8080, show_default=True, type=int, help="Port for the HTTP server.")
[email protected]("--model", default=None, help="Default MLX VLM model id or local model path.")
+def _command(host: str, port: int, model: str | None) -> None:
+ app = create_app(default_model=model)
+ uvicorn.run(app, host=host, port=port, workers=1)
+
+
+def main(*, args: list[str], prog_name: str, standalone_mode: bool) -> None:
+ _command.main(args=args, prog_name=prog_name, standalone_mode=standalone_mode)
+
+
+__all__ = ["create_app", "main"]
diff --git a/mineru/model/vlm/vllm_server.py b/mineru/kit/vlm_server/vllm_server.py
similarity index 100%
rename from mineru/model/vlm/vllm_server.py
rename to mineru/kit/vlm_server/vllm_server.py
diff --git a/mineru/model/vlm/__init__.py b/mineru/model/vlm/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/model/vlm/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/render/writer.py b/mineru/render/writer.py
new file mode 100644
index 00000000..01c24385
--- /dev/null
+++ b/mineru/render/writer.py
@@ -0,0 +1,63 @@
+# 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):
+ 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)
diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.py
index 9ff63eec..e1ff3932 100644
--- a/mineru/utils/config_reader.py
+++ b/mineru/utils/config_reader.py
@@ -51,54 +51,10 @@ def get_configured_model_source(default: str | None = None) -> str | None:
if normalized_model_source in supported_sources:
return normalized_model_source
- logger.warning(
- f"Unsupported 'model-source' in {get_tools_config_file_path()}: {model_source}, use {default} as default"
- )
+ logger.warning(f"Unsupported 'model-source' in {get_tools_config_file_path()}: {model_source}, use {default} as default")
return default
-def get_s3_config(bucket_name: str) -> tuple[str, str, str]:
- """~/magic-pdf.json 读出来."""
- config = read_config()
-
- bucket_info = config.get("bucket_info")
- if bucket_name not in bucket_info:
- access_key, secret_key, storage_endpoint = bucket_info["[default]"]
- else:
- access_key, secret_key, storage_endpoint = bucket_info[bucket_name]
-
- if access_key is None or secret_key is None or storage_endpoint is None:
- raise Exception(f"ak, sk or endpoint not found in {CONFIG_FILE_NAME}")
-
- # logger.info(f"get_s3_config: ak={access_key}, sk={secret_key}, endpoint={storage_endpoint}")
-
- return access_key, secret_key, storage_endpoint
-
-
-def get_s3_config_dict(path: str) -> dict[str, str]:
- access_key, secret_key, storage_endpoint = get_s3_config(get_bucket_name(path))
- return {"ak": access_key, "sk": secret_key, "endpoint": storage_endpoint}
-
-
-def get_bucket_name(path: str) -> str:
- bucket, key = parse_bucket_key(path)
- return bucket
-
-
-def parse_bucket_key(s3_full_path: str) -> tuple[str, str]:
- """
- 输入 s3://bucket/path/to/my/file.txt
- 输出 bucket, path/to/my/file.txt
- """
- s3_full_path = s3_full_path.strip()
- if s3_full_path.startswith("s3://"):
- s3_full_path = s3_full_path[5:]
- if s3_full_path.startswith("/"):
- s3_full_path = s3_full_path[1:]
- bucket, key = s3_full_path.split("/", 1)
- return bucket, key
-
-
def get_device() -> str:
device_mode = os.getenv("MINERU_DEVICE_MODE", None)
if device_mode is not None:
diff --git a/pyproject.toml b/pyproject.toml
index effd8682..1ccc1913 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -116,9 +116,6 @@ mlx = [
"mlx-vlm>=0.3.3,<0.4",
"mlx<=0.31.1",
]
-s3 = [
- "boto3>=1.28.43",
-]
pipeline = [
"ftfy>=6.3.1,<7",
"shapely>=2.0.7,<3",
@@ -139,7 +136,6 @@ core = [
]
all = [
"mineru[core]",
- "mineru[s3]",
"mineru[mlx] ; sys_platform == 'darwin'",
"mineru[vllm] ; sys_platform == 'linux'",
"mineru[lmdeploy] ; sys_platform == 'win32'",
diff --git a/tests/unittest/test_e2e.py b/tests/unittest/test_e2e.py
index b109236f..da5fc9fa 100644
--- a/tests/unittest/test_e2e.py
+++ b/tests/unittest/test_e2e.py
@@ -9,9 +9,9 @@ from loguru import logger
from mineru.backend.pipeline.pipeline_analyze import doc_analyze_streaming as pipeline_doc_analyze_streaming
from mineru.cli_old.common import convert_pdf_bytes_to_bytes, prepare_env, read_fn
-from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
from mineru.render import render_content_list, render_markdown
+from mineru.render.writer import FileBasedDataWriter
def test_pipeline_with_two_config():
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index 1016c6b6..9dcee26a 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -5,14 +5,17 @@ import asyncio
from pathlib import Path
import subprocess
import sys
+from types import ModuleType
from types import SimpleNamespace
from typing import Any
import pytest
+from fastapi.testclient import TestClient
from typer.testing import CliRunner
from mineru.kit.commands import api_server, models, parse, router, vlm_server
from mineru.kit.main import app
+from mineru.kit.vlm_server import mlx_vlm_server
runner = CliRunner()
@@ -22,6 +25,10 @@ def _assert_unsafe_sidecar_error(output: str) -> None:
assert "Unsafe image sidecar path" in " ".join(output.split())
+def _fake_apply_chat_template(_processor: Any, _config: Any, _prompt: Any, *_args: Any, **_kwargs: Any) -> str:
+ return "formatted"
+
+
def test_kit_root_and_models_help() -> None:
result = runner.invoke(app, ["--help"])
models_result = runner.invoke(app, ["models", "--help"])
@@ -80,6 +87,37 @@ print("ok")
assert result.stdout.strip() == "ok"
+def test_kit_vlm_server_import_does_not_import_legacy_vlm_server() -> None:
+ repo_root = Path(__file__).resolve().parents[2]
+ code = """
+import importlib.abc
+import sys
+
+
+class BlockLegacyVlmServerFinder(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname == "mineru.cli_old.vlm_server":
+ raise ModuleNotFoundError("blocked legacy vlm server import")
+ return None
+
+
+sys.meta_path.insert(0, BlockLegacyVlmServerFinder())
+import mineru.kit.commands.vlm_server
+print("ok")
+"""
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ cwd=repo_root,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == "ok"
+
+
def test_cli_old_router_import_supports_upstream_only_without_local_dependencies() -> None:
repo_root = Path(__file__).resolve().parents[2]
code = """
@@ -313,14 +351,14 @@ def test_api_server_rejects_removed_ch_lite_language() -> None:
assert "Language ch_lite not supported" in result.output
-def test_vlm_server_rejects_unimplemented_engine() -> None:
+def test_vlm_server_rejects_removed_sglang_engine() -> None:
result = runner.invoke(app, ["vlm-server", "--engine", "sglang"])
assert result.exit_code == 1
- assert "not implemented yet" in result.output
+ assert "Unsupported engine 'sglang'" in result.output
-def test_vlm_server_forwards_extra_args(monkeypatch: Any) -> None:
+def test_vlm_server_forwards_mlx_to_mlx_server(monkeypatch: Any) -> None:
seen: dict[str, Any] = {}
def _fake_main(*, args: list[str], prog_name: str, standalone_mode: bool) -> None:
@@ -328,18 +366,210 @@ def test_vlm_server_forwards_extra_args(monkeypatch: Any) -> None:
seen["prog_name"] = prog_name
seen["standalone_mode"] = standalone_mode
- monkeypatch.setattr(vlm_server.old_vlm_server.openai_server, "main", _fake_main)
+ monkeypatch.setattr(vlm_server, "_mlx_server_available", lambda: True)
+ monkeypatch.setattr(mlx_vlm_server, "main", _fake_main)
- result = runner.invoke(app, ["vlm-server", "--host", "0.0.0.0", "--port", "30000"])
+ result = runner.invoke(
+ app,
+ ["vlm-server", "--engine", "mlx", "--model", "test-model", "--host", "127.0.0.1", "--port", "18080"],
+ )
assert result.exit_code == 0
assert seen == {
- "args": ["--engine", "auto", "--host", "0.0.0.0", "--port", "30000"],
+ "args": ["--model", "test-model", "--host", "127.0.0.1", "--port", "18080"],
"prog_name": "mineru-kit vlm-server",
"standalone_mode": False,
}
+def test_vlm_server_auto_falls_back_to_mlx_when_non_mlx_engines_are_unavailable(monkeypatch: Any) -> None:
+ seen: dict[str, Any] = {}
+
+ def _fake_main(*, args: list[str], prog_name: str, standalone_mode: bool) -> None:
+ seen["args"] = args
+ seen["prog_name"] = prog_name
+ seen["standalone_mode"] = standalone_mode
+
+ monkeypatch.setattr(vlm_server, "_mlx_server_available", lambda: True)
+ monkeypatch.setattr(vlm_server, "_module_available", lambda _module_name: False)
+ monkeypatch.setattr(mlx_vlm_server, "main", _fake_main)
+
+ result = runner.invoke(app, ["vlm-server", "--host", "127.0.0.1", "--port", "18080"])
+
+ assert result.exit_code == 0
+ assert seen == {
+ "args": ["--host", "127.0.0.1", "--port", "18080"],
+ "prog_name": "mineru-kit vlm-server",
+ "standalone_mode": False,
+ }
+
+
+def test_vlm_server_auto_treats_missing_mlx_as_unavailable(monkeypatch: Any) -> None:
+ def _missing_spec(_module_name: str) -> None:
+ raise ModuleNotFoundError("No module named 'mlx_vlm'")
+
+ monkeypatch.setattr(vlm_server, "is_mac_os_version_supported", lambda: True)
+ monkeypatch.setattr(vlm_server.importlib.util, "find_spec", _missing_spec)
+
+ assert vlm_server._mlx_server_available() is False
+
+
+def test_vlm_server_forwards_extra_args(monkeypatch: Any) -> None:
+ seen: dict[str, Any] = {}
+
+ def _fake_vllm_main() -> None:
+ seen["args"] = sys.argv[1:]
+
+ fake_vllm_server = ModuleType("mineru.kit.vlm_server.vllm_server")
+ fake_vllm_server.main = _fake_vllm_main
+ monkeypatch.setattr(vlm_server, "_mlx_server_available", lambda: False)
+ monkeypatch.setattr(vlm_server, "_module_available", lambda module_name: module_name == "vllm")
+ monkeypatch.setitem(sys.modules, "mineru.kit.vlm_server.vllm_server", fake_vllm_server)
+
+ result = runner.invoke(app, ["vlm-server", "--host", "0.0.0.0", "--port", "30000"])
+
+ assert result.exit_code == 0
+ assert seen == {"args": ["--host", "0.0.0.0", "--port", "30000"]}
+
+
+def test_mlx_vlm_server_adapter_exposes_v1_chat_completions(monkeypatch: Any) -> None:
+ seen: dict[str, Any] = {}
+
+ class FakeChatRequest:
+ def __init__(self, **payload: Any) -> None:
+ self.payload = payload
+ self.model = payload.get("model")
+
+ @classmethod
+ def model_validate(cls, payload: dict[str, Any]) -> "FakeChatRequest":
+ return cls(**payload)
+
+ async def _fake_chat_completions_endpoint(request: FakeChatRequest) -> dict[str, Any]:
+ seen["model"] = request.model
+ return {"model": request.model}
+
+ fake_mlx_server = SimpleNamespace(
+ ChatRequest=FakeChatRequest,
+ apply_chat_template=_fake_apply_chat_template,
+ chat_completions_endpoint=_fake_chat_completions_endpoint,
+ )
+ monkeypatch.setitem(sys.modules, "mlx_vlm", SimpleNamespace(server=fake_mlx_server))
+ monkeypatch.setitem(sys.modules, "mlx_vlm.server", fake_mlx_server)
+
+ client = TestClient(mlx_vlm_server.create_app(default_model="test-model"))
+ response = client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "hello"}]})
+
+ assert response.status_code == 200
+ assert response.json() == {"model": "test-model"}
+ assert seen == {"model": "test-model"}
+
+
+def test_mlx_vlm_server_adapter_exposes_single_v1_model(monkeypatch: Any) -> None:
+ fake_mlx_server = SimpleNamespace(apply_chat_template=_fake_apply_chat_template)
+ monkeypatch.setitem(sys.modules, "mlx_vlm", SimpleNamespace(server=fake_mlx_server))
+ monkeypatch.setitem(sys.modules, "mlx_vlm.server", fake_mlx_server)
+
+ client = TestClient(mlx_vlm_server.create_app(default_model="test-model"))
+ response = client.get("/v1/models")
+ body = response.json()
+
+ assert response.status_code == 200
+ assert body["object"] == "list"
+ assert body["data"][0]["id"] == "test-model"
+ assert body["data"][0]["object"] == "model"
+ assert isinstance(body["data"][0]["created"], int)
+
+
+def test_mlx_vlm_server_adapter_defaults_to_mineru_vlm_model(monkeypatch: Any) -> None:
+ fake_mlx_server = SimpleNamespace(
+ DEFAULT_MODEL_PATH="mlx-community/nanoLLaVA-1.5-8bit",
+ apply_chat_template=_fake_apply_chat_template,
+ )
+ monkeypatch.setitem(sys.modules, "mlx_vlm", SimpleNamespace(server=fake_mlx_server))
+ monkeypatch.setitem(sys.modules, "mlx_vlm.server", fake_mlx_server)
+ monkeypatch.setattr(mlx_vlm_server, "auto_download_and_get_model_root_path", lambda path, repo_mode: "/models/mineru-vlm")
+
+ client = TestClient(mlx_vlm_server.create_app())
+ response = client.get("/v1/models")
+
+ assert response.status_code == 200
+ assert response.json()["data"][0]["id"] == "/models/mineru-vlm"
+
+
+def test_mlx_vlm_server_adapter_uses_mineru_mlx_compat_loader(monkeypatch: Any) -> None:
+ seen: dict[str, Any] = {}
+
+ def _raw_load() -> None:
+ raise AssertionError("raw mlx-vlm load should be replaced")
+
+ def _compat_load(path_or_hf_repo: str, **kwargs: Any) -> tuple[str, dict[str, Any]]:
+ seen["path_or_hf_repo"] = path_or_hf_repo
+ seen["kwargs"] = kwargs
+ return path_or_hf_repo, kwargs
+
+ fake_mlx_server = SimpleNamespace(load=_raw_load, apply_chat_template=_fake_apply_chat_template)
+ monkeypatch.setitem(sys.modules, "mlx_vlm", SimpleNamespace(server=fake_mlx_server))
+ monkeypatch.setitem(sys.modules, "mlx_vlm.server", fake_mlx_server)
+ monkeypatch.setattr(mlx_vlm_server, "load_mlx_model", _compat_load)
+
+ mlx_vlm_server.create_app(default_model="test-model")
+ result = fake_mlx_server.load("model-path", "adapter-path", trust_remote_code=True)
+
+ assert result == ("model-path", {"adapter_path": "adapter-path", "trust_remote_code": True})
+ assert seen == {
+ "path_or_hf_repo": "model-path",
+ "kwargs": {"adapter_path": "adapter-path", "trust_remote_code": True},
+ }
+
+
+def test_mlx_vlm_server_adapter_strips_data_urls_before_chat_template() -> None:
+ prompt = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
+ {"type": "text", "text": "Read this page."},
+ ],
+ }
+ ]
+
+ sanitized = mlx_vlm_server._sanitize_chat_template_prompt(prompt)
+
+ assert sanitized == [{"role": "user", "content": "Read this page."}]
+
+
+def test_mlx_vlm_server_adapter_patches_chat_template_sanitizer(monkeypatch: Any) -> None:
+ seen: dict[str, Any] = {}
+
+ def _apply_chat_template(_processor: Any, _config: Any, prompt: Any, *_args: Any, **_kwargs: Any) -> Any:
+ seen["prompt"] = prompt
+ return "formatted"
+
+ fake_mlx_server = SimpleNamespace(
+ apply_chat_template=_apply_chat_template,
+ )
+ monkeypatch.setitem(sys.modules, "mlx_vlm", SimpleNamespace(server=fake_mlx_server))
+ monkeypatch.setitem(sys.modules, "mlx_vlm.server", fake_mlx_server)
+
+ mlx_vlm_server.create_app(default_model="test-model")
+ result = fake_mlx_server.apply_chat_template(
+ object(),
+ {"model_type": "qwen2_5_vl"},
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
+ {"type": "text", "text": "Read this page."},
+ ],
+ }
+ ],
+ )
+
+ assert result == "formatted"
+ assert seen["prompt"] == [{"role": "user", "content": "Read this page."}]
+
+
def test_router_forwards_known_and_extra_args(monkeypatch: Any) -> None:
seen: dict[str, Any] = {}