Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance model configuration by adding support for dynamic model sources and improving template handling
myhloli58460a5e22f2
diff --git a/mineru/cli_old/models_download.py b/mineru/cli_old/models_download.pyindex cc1ab48a..da7bd468 100644--- a/mineru/cli_old/models_download.py+++ b/mineru/cli_old/models_download.py@@ -1,69 +1,39 @@# Copyright (c) Opendatalab. All rights reserved.from contextlib import contextmanager-import jsonimport osimport sysimport click-import requestsfrom loguru import loggerfrom mineru.utils.enum_class import ModelPath-from mineru.utils.models_download_utils import auto_download_and_get_model_root_path+from mineru.utils.models_download_utils import (+ CONFIG_TEMPLATE_URL,+ auto_download_and_get_model_root_path,+ download_and_modify_json,+ get_tools_config_file_path,+ resolve_model_source,+)MODEL_SOURCE_ENV_VAR = 'MINERU_MODEL_SOURCE'-REMOTE_MODEL_SOURCES = ('huggingface', 'modelscope')---def download_json(url):- """下载JSON文件"""- response = requests.get(url)- response.raise_for_status()- return response.json()---def download_and_modify_json(url, local_filename, modifications):- """下载JSON并修改内容"""- if os.path.exists(local_filename):- data = json.load(open(local_filename))- config_version = data.get('config_version', '0.0.0')- if config_version < '1.3.1':- data = download_json(url)- else:- data = download_json(url)-- # 修改内容- for key, value in modifications.items():- if key in data:- if isinstance(data[key], dict):- # 如果是字典,合并新值- data[key].update(value)- else:- # 否则直接替换- data[key] = value-- # 保存修改后的内容- with open(local_filename, 'w', encoding='utf-8') as f:- json.dump(data, f, ensure_ascii=False, indent=4)+REMOTE_MODEL_SOURCES = ('auto', 'huggingface', 'modelscope')-def configure_model(model_dir, model_type):+def configure_model(model_dir, model_type, model_source):"""配置模型"""- json_url = 'https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/mineru.template.json'- config_file_name = os.getenv('MINERU_TOOLS_CONFIG_JSON', 'mineru.json')- home_dir = os.path.expanduser('~')- config_file = os.path.join(home_dir, config_file_name)+ config_file = get_tools_config_file_path()json_mods = {'models-dir': {f'{model_type}': model_dir- }+ },+ 'model-source': model_source,}- download_and_modify_json(json_url, config_file, json_mods)+ download_and_modify_json(CONFIG_TEMPLATE_URL, config_file, json_mods)logger.info(f'The configuration file has been successfully configured, the path is: {config_file}')-def download_pipeline_models():+def download_pipeline_models(model_source):"""下载Pipeline模型"""model_paths = [ModelPath.pp_doclayout_v2,@@ -79,14 +49,14 @@ def download_pipeline_models():logger.info(f"Downloading model: {model_path}")download_finish_path = auto_download_and_get_model_root_path(model_path, repo_mode='pipeline')logger.info(f"Pipeline models downloaded successfully to: {download_finish_path}")- configure_model(download_finish_path, "pipeline")+ configure_model(download_finish_path, "pipeline", model_source)-def download_vlm_models():+def download_vlm_models(model_source):"""下载VLM模型"""download_finish_path = auto_download_and_get_model_root_path("/", repo_mode='vlm')logger.info(f"VLM models downloaded successfully to: {download_finish_path}")- configure_model(download_finish_path, "vlm")+ configure_model(download_finish_path, "vlm", model_source)def get_effective_download_model_source(requested_model_source):@@ -98,12 +68,12 @@ def get_effective_download_model_source(requested_model_source):f"`mineru-models-download` will temporarily use '{requested_model_source}' "f"to perform a real download.")- return requested_model_source+ return resolve_model_source(requested_model_source, allow_auto=True)if current_model_source is None:- return requested_model_source+ return resolve_model_source(requested_model_source, allow_auto=True)- return current_model_source+ return resolve_model_source(current_model_source)@contextmanager@@ -151,7 +121,7 @@ def download_models(model_source, model_type):model_source = click.prompt("Please select the model download source: ",type=click.Choice(REMOTE_MODEL_SOURCES),- default='huggingface'+ default='auto')effective_model_source = get_effective_download_model_source(model_source)@@ -169,12 +139,12 @@ def download_models(model_source, model_type):try:with temporary_model_source(effective_model_source):if model_type == 'pipeline':- download_pipeline_models()+ download_pipeline_models(effective_model_source)elif model_type == 'vlm':- download_vlm_models()+ download_vlm_models(effective_model_source)elif model_type == 'all':- download_pipeline_models()- download_vlm_models()+ download_pipeline_models(effective_model_source)+ download_vlm_models(effective_model_source)else:click.echo(f"Unsupported model type: {model_type}", err=True)sys.exit(1)diff --git a/mineru/kit/commands/models.py b/mineru/kit/commands/models.pyindex b6a83136..55dc6da0 100644--- a/mineru/kit/commands/models.py+++ b/mineru/kit/commands/models.py@@ -7,7 +7,13 @@ import typerfrom loguru import loggerfrom ...utils.enum_class import ModelPath-from ...utils.models_download_utils import auto_download_and_get_model_root_path+from ...utils.models_download_utils import (+ MINERU_CONFIG_VERSION,+ auto_download_and_get_model_root_path,+ is_config_version_outdated,+ merge_config_dict,+ resolve_model_source,+)from ..common import PIPELINE_MODEL_PATHS, VLM_MODEL_MARKERS, read_json_file, resolve_models_config_path, write_json_filefrom ..errors import exit_with_messagefrom ..output import print_info, print_success@@ -15,17 +21,19 @@ from ..output import print_info, print_successapp = typer.Typer(help="Download, inspect, and verify local MinerU models.", no_args_is_help=True)MODEL_SOURCE_ENV_VAR = "MINERU_MODEL_SOURCE"-REMOTE_MODEL_SOURCES = ("huggingface", "modelscope")+REMOTE_MODEL_SOURCES = ("auto", "huggingface", "modelscope")def _load_or_template_config() -> dict:config_path = resolve_models_config_path()payload = read_json_file(config_path)+ template_path = Path(__file__).resolve().parents[3] / "mineru.template.json"+ template_payload = read_json_file(template_path) or {"models-dir": {}, "config_version": MINERU_CONFIG_VERSION}if payload is not None:- if payload.get("config_version", "0.0.0") >= "1.3.1":+ if not is_config_version_outdated(payload.get("config_version", "0.0.0")):return payload- template_path = Path(__file__).resolve().parents[3] / "mineru.template.json"- return read_json_file(template_path) or {"models-dir": {}, "config_version": "1.3.1"}+ return merge_config_dict(template_payload, payload, skip_keys={"config_version"})+ return template_payloaddef _update_models_dir(bundle: str, model_dir: str) -> Path:@@ -36,6 +44,9 @@ def _update_models_dir(bundle: str, model_dir: str) -> Path:models_dir = {}payload["models-dir"] = models_dirmodels_dir[bundle] = model_dir+ model_source = os.getenv(MODEL_SOURCE_ENV_VAR)+ if model_source in {"huggingface", "modelscope"}:+ payload["model-source"] = model_sourcewrite_json_file(config_path, payload)return config_path@@ -47,10 +58,10 @@ def _get_effective_download_model_source(requested_model_source: str) -> str:f"{MODEL_SOURCE_ENV_VAR}=local means using pre-downloaded local models. "f"`mineru-kit models download` will temporarily use '{requested_model_source}' to perform a real download.")- return requested_model_source+ return resolve_model_source(requested_model_source, allow_auto=True)if current_model_source is None:- return requested_model_source- return current_model_source+ return resolve_model_source(requested_model_source, allow_auto=True)+ return resolve_model_source(current_model_source)def _download_pipeline_models() -> str:@@ -83,7 +94,7 @@ def _with_temporary_model_source(model_source: str):@app.command("download")def download_cmd(bundle: str = typer.Argument(..., help="Model bundle: pipeline, vlm, all"),- source: str = typer.Option("huggingface", "--source", "-s", help="Model source: huggingface or modelscope"),+ source: str = typer.Option("auto", "--source", "-s", help="Model source: auto, huggingface, or modelscope"),verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),) -> None:"""Download a model bundle and update mineru.json."""@@ -123,6 +134,7 @@ def show_cmd() -> None:lines = [f"Config: {config_path}",f"MINERU_MODEL_SOURCE={os.getenv(MODEL_SOURCE_ENV_VAR, '') or '(unset)'}",+ f"model-source: {payload.get('model-source', '') or '(unset)'}",f"pipeline: {pipeline or '(unset)'}",f"pipeline.exists: {Path(pipeline).exists() if pipeline else False}",f"vlm: {vlm or '(unset)'}",