Skip to content

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

Add i18n support for CLI messages and error handling; update README for language configuration

myhloli37a96bf110c9
diff --git a/docs/next/cli/README.md b/docs/next/cli/README.md
index 67efc89d..89ff24e1 100644
--- a/docs/next/cli/README.md
+++ b/docs/next/cli/README.md
@@ -56,6 +56,16 @@ MinerU 仓库提供两款命令行工具:
- CLI 错误应使用结构化错误码和可执行修复建议。
- 错误码、`retryable` 和 `user_action` 语义见 [错误码体系](../errors.md)。
+## 5. 界面语言
+
+`mineru` 与 `mineru-kit` 的用户可见文案(帮助、运行时消息、表格、错误提示)提供中英双语,启动时自动选择:
+
+- 检测顺序为 `MINERU_LANG` > `LC_ALL` > `LC_MESSAGES` > `LANG`(POSIX 语义,`C`/`POSIX` 视为该层决定英文);语言部分以 `zh` 开头(覆盖 `zh_CN`/`zh_TW`/`zh_HK`/`zh-Hans`)即使用简体中文,否则英文;全部未设置时 Windows 回退系统 UI 语言,其余平台英文。
+- 设置 `MINERU_LANG=en|zh` 可强制指定语言。
+- click/typer 框架脚手架词(`Usage:`、`Options:`、`Show this message and exit.` 等)保持英文。
+- 不翻译项:JSON 输出的键与枚举值、`<!-- Next: ... -->` 续读标记等协议串、错误码注册表、Gradio WebUI(自带 i18n)。
+- 词条维护在 `mineru/utils/translations.py`(英文原文作 key);`tests/unittest/test_cli_i18n.py` 提供词典完整性与占位符一致性守卫。
+
## 未决问题
CLI 选项命名和 Agent message contract,集中维护在 [开放问题清单](../open-questions.md)。
diff --git a/mineru/cli/commands/cleanup.py b/mineru/cli/commands/cleanup.py
index 8b58b4c9..219bdfcb 100644
--- a/mineru/cli/commands/cleanup.py
+++ b/mineru/cli/commands/cleanup.py
@@ -13,20 +13,21 @@ from ...doclib.types import (
CleanupTempRequest,
CleanupTempResponse,
)
+from ...utils.i18n import t
from ..contracts import CliContext
from ..runtime import run_cli
app = typer.Typer(
name="cleanup",
- help="Clean up local doclib records and temp files.",
+ help=t("Clean up local doclib records and temp files."),
no_args_is_help=True,
)
[email protected]("deleted-files")
[email protected]("deleted-files", help=t("Remove all file rows already marked as deleted."))
def cleanup_deleted_files(
- dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help="Preview only"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help=t("Preview only")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Remove all file rows already marked as deleted."""
run_cli(
@@ -36,10 +37,10 @@ def cleanup_deleted_files(
)
[email protected]("orphan-docs")
[email protected]("orphan-docs", help=t("Remove docs that are no longer referenced by any file row."))
def cleanup_orphan_docs(
- dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help="Preview only"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help=t("Preview only")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Remove docs that are no longer referenced by any file row."""
run_cli(
@@ -49,10 +50,10 @@ def cleanup_orphan_docs(
)
[email protected]("temp", help=t("Remove old process temp files."))
def cleanup_temp_files(
- older_than: int = typer.Option(7, "--older-than", help="Days threshold for temp cleanup"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ older_than: int = typer.Option(7, "--older-than", help=t("Days threshold for temp cleanup")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Remove old process temp files."""
run_cli(
@@ -68,15 +69,15 @@ def _client() -> DoclibClient:
def _render_cleanup_deleted(data: CleanupDeletedResponse) -> str:
if data.dry_run:
- return f"Would remove {data.deleted_files} deleted file record(s). Use --no-dry-run to proceed."
- return f"Removed {data.deleted_files} deleted file record(s)."
+ return t("Would remove {count} deleted file record(s). Use --no-dry-run to proceed.", count=data.deleted_files)
+ return t("Removed {count} deleted file record(s).", count=data.deleted_files)
def _render_cleanup_orphans(data: CleanupOrphansResponse) -> str:
if data.dry_run:
- return f"Would remove {data.orphan_docs} orphan doc(s). Use --no-dry-run to proceed."
- return f"Removed {data.orphan_docs} orphan doc(s)."
+ return t("Would remove {count} orphan doc(s). Use --no-dry-run to proceed.", count=data.orphan_docs)
+ return t("Removed {count} orphan doc(s).", count=data.orphan_docs)
def _render_cleanup_temp(data: CleanupTempResponse) -> str:
- return f"Removed {data.temp_files_removed} temp file(s)."
+ return t("Removed {count} temp file(s).", count=data.temp_files_removed)
diff --git a/mineru/cli/commands/config.py b/mineru/cli/commands/config.py
index 9d6fb411..59361535 100644
--- a/mineru/cli/commands/config.py
+++ b/mineru/cli/commands/config.py
@@ -23,57 +23,58 @@ from ...doclib.types import (
)
from ...parser.page_range import normalize_page_range_input
from ...types import Tier
+from ...utils.i18n import t
from ..contracts import CliContext
from ..runtime import run_cli
-app = typer.Typer(help="Configuration management", no_args_is_help=True)
+app = typer.Typer(help=t("Configuration management"), no_args_is_help=True)
-exclude_rules_app = typer.Typer(help="Exclude rule management", no_args_is_help=True)
-parsing_rules_app = typer.Typer(help="Parsing rule management", no_args_is_help=True)
+exclude_rules_app = typer.Typer(help=t("Exclude rule management"), no_args_is_help=True)
+parsing_rules_app = typer.Typer(help=t("Parsing rule management"), no_args_is_help=True)
app.add_typer(exclude_rules_app, name="exclude-rules")
app.add_typer(parsing_rules_app, name="parsing-rules")
-def config_show(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("show", help=t("Show effective configuration values."))
+def config_show(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Show effective configuration values."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().get_config(), render=_render_config)
[email protected]("get", help=t("Show one effective configuration value."))
def config_get(
- key: str = typer.Argument(..., help="Configuration key"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ key: str = typer.Argument(..., help=t("Configuration key")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Show one effective configuration value."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().get_config_key(key), render=_render_config_value)
[email protected]("set", help=t("Set a configuration override."))
def config_set(
- key: str = typer.Argument(..., help="Configuration key"),
- value: str = typer.Argument(..., help="Configuration value"),
+ key: str = typer.Argument(..., help=t("Configuration key")),
+ value: str = typer.Argument(..., help=t("Configuration value")),
) -> None:
"""Set a configuration override."""
ctx = CliContext(json_mode=False)
run_cli(ctx, lambda: _client().set_config(key, ConfigSetRequest(value=value)), render=_render_config_set)
-def config_unset(key: str = typer.Argument(..., help="Configuration key")) -> None:
[email protected]("unset", help=t("Remove a configuration override and fall back to the default."))
+def config_unset(key: str = typer.Argument(..., help=t("Configuration key"))) -> None:
"""Remove a configuration override and fall back to the default."""
ctx = CliContext(json_mode=False)
run_cli(ctx, lambda: _client().unset_config(key), render=_render_config_unset)
-@exclude_rules_app.command("add")
+@exclude_rules_app.command("add", help=t("Add an exclusion rule."))
def exclude_rules_add(
- pattern: str = typer.Argument(..., help="Glob pattern to exclude"),
- priority: int = typer.Option(0, "--priority", help="Rule priority"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ pattern: str = typer.Argument(..., help=t("Glob pattern to exclude")),
+ priority: int = typer.Option(0, "--priority", help=t("Rule priority")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Add an exclusion rule."""
ctx = CliContext(json_mode=json_mode)
@@ -84,28 +85,28 @@ def exclude_rules_add(
)
-@exclude_rules_app.command("list")
-def exclude_rules_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
+@exclude_rules_app.command("list", help=t("List exclusion rules."))
+def exclude_rules_list(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""List exclusion rules."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().list_exclude_rules(), render=_render_exclude_rules)
-@exclude_rules_app.command("remove")
-def exclude_rules_remove(rule_id: int = typer.Argument(..., help="Rule id to remove")) -> None:
+@exclude_rules_app.command("remove", help=t("Remove an exclusion rule."))
+def exclude_rules_remove(rule_id: int = typer.Argument(..., help=t("Rule id to remove"))) -> None:
"""Remove an exclusion rule."""
ctx = CliContext(json_mode=False)
run_cli(ctx, lambda: _client().remove_exclude_rule(rule_id), render=_render_exclude_rule_removed)
-@parsing_rules_app.command("add")
+@parsing_rules_app.command("add", help=t("Add a parsing rule."))
def parsing_rules_add(
- pattern: str = typer.Argument(..., help="Glob pattern to match"),
- tier: Tier | None = typer.Option(None, "--tier", help="Parse tier: flash, basic, standard, advanced"),
- pages: str | None = typer.Option(None, "--pages", help="PDF pages, e.g. all, 1-10 or r3-r1"),
- remote: bool = typer.Option(False, "--remote", help="Allow remote parsing"),
- name: str | None = typer.Option(None, "--name", help="Rule name"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ pattern: str = typer.Argument(..., help=t("Glob pattern to match")),
+ tier: Tier | None = typer.Option(None, "--tier", help=t("Parse tier: flash, basic, standard, advanced")),
+ pages: str | None = typer.Option(None, "--pages", help=t("PDF pages, e.g. all, 1-10 or r3-r1")),
+ remote: bool = typer.Option(False, "--remote", help=t("Allow remote parsing")),
+ name: str | None = typer.Option(None, "--name", help=t("Rule name")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Add a parsing rule."""
ctx = CliContext(json_mode=json_mode)
@@ -126,15 +127,15 @@ def _add_parsing_rule(
)
-@parsing_rules_app.command("list")
-def parsing_rules_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
+@parsing_rules_app.command("list", help=t("List parsing rules."))
+def parsing_rules_list(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""List parsing rules."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().list_parsing_rules(), render=_render_parsing_rules)
-@parsing_rules_app.command("remove")
-def parsing_rules_remove(rule_id: int = typer.Argument(..., help="Rule id to remove")) -> None:
+@parsing_rules_app.command("remove", help=t("Remove a parsing rule."))
+def parsing_rules_remove(rule_id: int = typer.Argument(..., help=t("Rule id to remove"))) -> None:
"""Remove a parsing rule."""
ctx = CliContext(json_mode=False)
run_cli(ctx, lambda: _client().remove_parsing_rule(rule_id), render=_render_parsing_rule_removed)
@@ -145,77 +146,79 @@ def _client() -> DoclibClient:
def _render_config(data: ConfigResponse) -> Table:
- table = Table(title="Config")
- table.add_column("Key", style="cyan")
- table.add_column("Value", style="green")
- table.add_column("Source")
+ table = Table(title=t("Config"))
+ table.add_column(t("Key"), style="cyan")
+ table.add_column(t("Value"), style="green")
+ table.add_column(t("Source"))
for key in sorted(data.config):
value = data.config[key]
- source = data.sources.get(key, "default")
+ source = data.sources.get(key, t("default"))
table.add_row(key, value, source)
return table
def _render_config_value(data: ConfigValueResponse) -> str:
- return f"{data.key} = {data.value} [{data.source}]"
+ return t("{key} = {value} [{source}]", key=data.key, value=data.value, source=data.source)
def _render_config_set(data: ConfigSetResponse) -> str:
- return f"{data.key} = {data.value} [{data.source}]"
+ return t("{key} = {value} [{source}]", key=data.key, value=data.value, source=data.source)
def _render_config_unset(data: ConfigUnsetResponse) -> str:
- action = "removed" if data.removed else "unchanged"
- return f"{data.key} = {data.value} [{data.source}] ({action})"
+ action = t("removed") if data.removed else t("unchanged")
+ return t("{key} = {value} [{source}] ({action})", key=data.key, value=data.value, source=data.source, action=action)
def _render_exclude_rule_added(data: ExcludeRuleInfo) -> str:
- return f"Exclude rule added: id={data.id}"
+ return t("Exclude rule added: id={id}", id=data.id)
def _render_exclude_rules(data: ExcludeRuleListResponse) -> Table | str:
if not data.rules:
- return "No exclude rules configured."
- table = Table(title="Exclude Rules")
- table.add_column("ID", justify="right")
- table.add_column("Pattern", style="cyan")
- table.add_column("Priority", justify="right")
+ return t("No exclude rules configured.")
+ table = Table(title=t("Exclude Rules"))
+ table.add_column(t("ID"), justify="right")
+ table.add_column(t("Pattern"), style="cyan")
+ table.add_column(t("Priority"), justify="right")
for rule in data.rules:
table.add_row(str(rule.id), rule.pattern, str(rule.priority))
return table
def _render_exclude_rule_removed(data: RemoveExcludeRuleResponse) -> str:
- action = "removed" if data.removed else "unchanged"
- return f"Exclude rule {data.rule_id} {action}."
+ if data.removed:
+ return t("Exclude rule {rule_id} removed.", rule_id=data.rule_id)
+ return t("Exclude rule {rule_id} unchanged.", rule_id=data.rule_id)
def _render_parsing_rule_added(data: ParsingRuleInfo) -> str:
- return f"Parsing rule added: id={data.id}"
+ return t("Parsing rule added: id={id}", id=data.id)
def _render_parsing_rules(data: ParsingRuleListResponse) -> Table | str:
if not data.rules:
- return "No parsing rules configured."
- table = Table(title="Parsing Rules")
- table.add_column("ID", justify="right")
- table.add_column("Pattern", style="cyan")
- table.add_column("Tier")
- table.add_column("Pages")
- table.add_column("Remote")
- table.add_column("Name")
+ return t("No parsing rules configured.")
+ table = Table(title=t("Parsing Rules"))
+ table.add_column(t("ID"), justify="right")
+ table.add_column(t("Pattern"), style="cyan")
+ table.add_column(t("Tier"))
+ table.add_column(t("Pages"))
+ table.add_column(t("Remote"))
+ table.add_column(t("Name"))
for rule in data.rules:
table.add_row(
str(rule.id),
rule.pattern,
rule.tier or "-",
rule.page_range or "-",
- "yes" if rule.remote else "no",
+ t("yes") if rule.remote else t("no"),
rule.name or "-",
)
return table
def _render_parsing_rule_removed(data: RemoveParsingRuleResponse) -> str:
- action = "removed" if data.removed else "unchanged"
- return f"Parsing rule {data.rule_id} {action}."
+ if data.removed:
+ return t("Parsing rule {rule_id} removed.", rule_id=data.rule_id)
+ return t("Parsing rule {rule_id} unchanged.", rule_id=data.rule_id)
diff --git a/mineru/cli/commands/forget.py b/mineru/cli/commands/forget.py
index 39c7b47d..c30598ee 100644
--- a/mineru/cli/commands/forget.py
+++ b/mineru/cli/commands/forget.py
@@ -6,15 +6,16 @@ import typer
from ...doclib.client import DoclibClient
from ...doclib.types import ForgetPathRequest, ForgetPathResponse
+from ...utils.i18n import t
from ..contracts import CliContext
from ..path_utils import normalize_cli_path
from ..runtime import run_cli
def forget_cmd(
- path: str = typer.Argument(..., help="File or directory path to forget from doclib"),
- dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help="Preview only"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ path: str = typer.Argument(..., help=t("File or directory path to forget from doclib")),
+ dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help=t("Preview only")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
run_cli(
CliContext(json_mode=json_mode),
@@ -28,7 +29,13 @@ def forget_cmd(
def _render_forget_result(data: ForgetPathResponse) -> str:
if data.dry_run:
- return (
- f"Would forget {data.forgotten_files} file record(s) (matched_as={data.matched_as}). Use --no-dry-run to proceed."
+ return t(
+ "Would forget {count} file record(s) (matched_as={matched_as}). Use --no-dry-run to proceed.",
+ count=data.forgotten_files,
+ matched_as=data.matched_as,
)
- return f"Forgot {data.forgotten_files} file record(s) (matched_as={data.matched_as})."
+ return t(
+ "Forgot {count} file record(s) (matched_as={matched_as}).",
+ count=data.forgotten_files,
+ matched_as=data.matched_as,
+ )
diff --git a/mineru/cli/commands/invalidate.py b/mineru/cli/commands/invalidate.py
index d573d869..884eead2 100644
--- a/mineru/cli/commands/invalidate.py
+++ b/mineru/cli/commands/invalidate.py
@@ -10,14 +10,15 @@ from ...doclib.client import DoclibClient
from ...doclib.types import InvalidateRequest, InvalidateResponse
from ...errors import MineruError
from ...types import Tier
+from ...utils.i18n import t
from ..path_utils import normalize_cli_path
from ..contracts import CliContext
from ..runtime import run_cli
def invalidate_cmd(
- path: str = typer.Argument(..., help="Path to the document file"),
- tier: Tier | None = typer.Option(None, "--tier", help="Parse tier to invalidate (omit = all tiers)"),
+ path: str = typer.Argument(..., help=t("Path to the document file")),
+ tier: Tier | None = typer.Option(None, "--tier", help=t("Parse tier to invalidate (omit = all tiers)")),
) -> None:
"""Mark done parse results as superseded."""
ctx = CliContext(json_mode=False)
@@ -28,7 +29,7 @@ def _invalidate(path: str, *, tier: Tier | None) -> InvalidateResponse:
file_path = normalize_cli_path(path)
if not Path(file_path).exists():
- raise MineruError("file_not_found", f"File not found: {file_path}", "path")
+ raise MineruError("file_not_found", t("File not found: {path}", path=file_path), "path")
return DoclibClient(timeout=10).invalidate(InvalidateRequest(path=file_path, tier=tier))
@@ -37,5 +38,10 @@ def _render_invalidate(data: InvalidateResponse) -> str:
doc_id = data.short_id
tier_label = f" (tier={data.tier})" if data.tier else ""
if count:
- return f"Invalidated {count} batch(es) for {doc_id}{tier_label}. Use 'mineru parse' to re-parse."
- return f"No done batches found for {doc_id}{tier_label}."
+ return t(
+ "Invalidated {count} batch(es) for {doc_id}{tier_label}. Use 'mineru parse' to re-parse.",
+ count=count,
+ doc_id=doc_id,
+ tier_label=tier_label,
+ )
+ return t("No done batches found for {doc_id}{tier_label}.", doc_id=doc_id, tier_label=tier_label)
diff --git a/mineru/cli/commands/list_resources.py b/mineru/cli/commands/list_resources.py
index 241d131e..efbaaf25 100644
--- a/mineru/cli/commands/list_resources.py
+++ b/mineru/cli/commands/list_resources.py
@@ -17,19 +17,20 @@ from ...doclib.types import (
ScanStatus,
)
from ...types import Tier
+from ...utils.i18n import t
from ..contracts import CliContext
from ..runtime import run_cli
-app = typer.Typer(help="List doclib resources", no_args_is_help=True)
+app = typer.Typer(help=t("List doclib resources"), no_args_is_help=True)
[email protected]("parses", help=t("List parse tasks."))
def list_parses(
- status: ParseStatus | None = typer.Option(None, "--status", help="Parse status filter"),
- tier: Tier | None = typer.Option(None, "--tier", help="Parse tier filter"),
- limit: int = typer.Option(50, "--limit", "-n", help="Max rows"),
- offset: int = typer.Option(0, "--offset", help="Result offset"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ status: ParseStatus | None = typer.Option(None, "--status", help=t("Parse status filter")),
+ tier: Tier | None = typer.Option(None, "--tier", help=t("Parse tier filter")),
+ limit: int = typer.Option(50, "--limit", "-n", help=t("Max rows")),
+ offset: int = typer.Option(0, "--offset", help=t("Result offset")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""List parse tasks."""
run_cli(
@@ -39,14 +40,14 @@ def list_parses(
)
[email protected]("scans", help=t("List scan tasks."))
def list_scans(
- status: ScanStatus | None = typer.Option(None, "--status", help="Scan status filter"),
- kind: ScanKind | None = typer.Option(None, "--kind", help="Scan kind filter"),
- watch_id: int | None = typer.Option(None, "--watch-id", help="Watch id filter"),
- limit: int = typer.Option(50, "--limit", "-n", help="Max rows"),
- offset: int = typer.Option(0, "--offset", help="Result offset"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ status: ScanStatus | None = typer.Option(None, "--status", help=t("Scan status filter")),
+ kind: ScanKind | None = typer.Option(None, "--kind", help=t("Scan kind filter")),
+ watch_id: int | None = typer.Option(None, "--watch-id", help=t("Watch id filter")),
+ limit: int = typer.Option(50, "--limit", "-n", help=t("Max rows")),
+ offset: int = typer.Option(0, "--offset", help=t("Result offset")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""List scan tasks."""
run_cli(
@@ -56,14 +57,14 @@ def list_scans(
)
[email protected]("files", help=t("List file path records."))
def list_files(
- status: FileStatus | None = typer.Option(None, "--status", help="File status filter"),
- ext: str | None = typer.Option(None, "--ext", help="File extension filter, e.g. pdf"),
- watch_id: int | None = typer.Option(None, "--watch-id", help="Watch id filter"),
- limit: int = typer.Option(200, "--limit", "-n", help="Max rows"),
- offset: int = typer.Option(0, "--offset", help="Result offset"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ status: FileStatus | None = typer.Option(None, "--status", help=t("File status filter")),
+ ext: str | None = typer.Option(None, "--ext", help=t("File extension filter, e.g. pdf")),
+ watch_id: int | None = typer.Option(None, "--watch-id", help=t("Watch id filter")),
+ limit: int = typer.Option(200, "--limit", "-n", help=t("Max rows")),
+ offset: int = typer.Option(0, "--offset", help=t("Result offset")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""List file path records."""
run_cli(
@@ -73,12 +74,12 @@ def list_files(
)
[email protected]("docs", help=t("List active docs."))
def list_docs(
- file_type: str | None = typer.Option(None, "--file-type", help="Document file type filter, e.g. pdf"),
- limit: int = typer.Option(200, "--limit", "-n", help="Max rows"),
- offset: int = typer.Option(0, "--offset", help="Result offset"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ file_type: str | None = typer.Option(None, "--file-type", help=t("Document file type filter, e.g. pdf")),
+ limit: int = typer.Option(200, "--limit", "-n", help=t("Max rows")),
+ offset: int = typer.Option(0, "--offset", help=t("Result offset")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""List active docs."""
run_cli(
@@ -94,13 +95,13 @@ def _client() -> DoclibClient:
def _render_list_parses(data: ListParsesResponse) -> Table | str:
if not data.parses:
- return "No parses found."
- table = Table(title=f"Parses ({data.total} total)")
- table.add_column("ID", justify="right")
- table.add_column("Status", style="green")
- table.add_column("Tier", style="cyan")
- table.add_column("Pages")
- table.add_column("Doc ID")
+ return t("No parses found.")
+ table = Table(title=t("Parses ({total} total)", total=data.total))
+ table.add_column(t("ID"), justify="right")
+ table.add_column(t("Status"), style="green")
+ table.add_column(t("Tier"), style="cyan")
+ table.add_column(t("Pages"))
+ table.add_column(t("Doc ID"))
for item in data.parses:
table.add_row(str(item.id), item.status, item.tier, item.page_range, item.short_id)
return table
@@ -108,15 +109,15 @@ def _render_list_parses(data: ListParsesResponse) -> Table | str:
def _render_list_scans(data: ScanListResponse) -> Table | str:
if not data.scans:
- return "No scans found."
- table = Table(title=f"Scans ({data.total} total)")
- table.add_column("ID", justify="right")
- table.add_column("Status", style="green")
- table.add_column("Kind", style="cyan")
- table.add_column("Path")
- table.add_column("Seen", justify="right")
- table.add_column("Refreshed", justify="right")
- table.add_column("Errors", justify="right")
+ return t("No scans found.")
+ table = Table(title=t("Scans ({total} total)", total=data.total))
+ table.add_column(t("ID"), justify="right")
+ table.add_column(t("Status"), style="green")
+ table.add_column(t("Kind"), style="cyan")
+ table.add_column(t("Path"))
+ table.add_column(t("Seen"), justify="right")
+ table.add_column(t("Refreshed"), justify="right")
+ table.add_column(t("Errors"), justify="right")
for item in data.scans:
table.add_row(
str(item.id),
@@ -132,12 +133,12 @@ def _render_list_scans(data: ScanListResponse) -> Table | str:
def _render_list_files(data: ListFilesResponse) -> Table | str:
if not data.files:
- return "No files found."
- table = Table(title=f"Files ({data.total} total)")
- table.add_column("Status", style="green")
- table.add_column("Path")
- table.add_column("Ext", style="cyan")
- table.add_column("Doc ID")
+ return t("No files found.")
+ table = Table(title=t("Files ({total} total)", total=data.total))
+ table.add_column(t("Status"), style="green")
+ table.add_column(t("Path"))
+ table.add_column(t("Ext"), style="cyan")
+ table.add_column(t("Doc ID"))
for item in data.files:
table.add_row(item.status, item.path, item.ext, item.short_id or "-")
return table
@@ -145,12 +146,12 @@ def _render_list_files(data: ListFilesResponse) -> Table | str:
def _render_list_docs(data: ListDocsResponse) -> Table | str:
if not data.docs:
- return "No docs found."
- table = Table(title=f"Docs ({data.total} total)")
- table.add_column("Doc ID")
- table.add_column("Type", style="cyan")
- table.add_column("Pages", justify="right")
- table.add_column("Title")
+ return t("No docs found.")
+ table = Table(title=t("Docs ({total} total)", total=data.total))
+ table.add_column(t("Doc ID"))
+ table.add_column(t("Type"), style="cyan")
+ table.add_column(t("Pages"), justify="right")
+ table.add_column(t("Title"))
for item in data.docs:
title = item.title or "-"
table.add_row(item.short_id, item.file_type or "-", str(item.page_count or "-"), title)
diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.py
index 32e33f57..370056db 100644
--- a/mineru/cli/commands/parse.py
+++ b/mineru/cli/commands/parse.py
@@ -23,6 +23,7 @@ from ...doclib.types import (
from ...errors import MineruError, error_response
from ...parser.page_range import normalize_page_range_input
from ...types import Tier
+from ...utils.i18n import t
from ..contracts import CliContext, CliResult
from ..guidance import api_key_guidance_for_error
from ..path_utils import normalize_cli_path
@@ -75,24 +76,24 @@ def _validate_page_range_input(page_range: str | None) -> None:
def parse_cmd(
- path: str = typer.Argument(..., help="Path to the document file"),
+ path: str = typer.Argument(..., help=t("Path to the document file")),
tier: Tier | None = typer.Option(
None,
"--tier",
- help="Parse tier: flash, basic, standard, advanced (default: server decides)",
+ help=t("Parse tier: flash, basic, standard, advanced (default: server decides)"),
),
- pages: str = typer.Option(None, "-p", "--pages", help="PDF pages: '1-5,8,r3-r1' or 'all'; default: first 10 pages"),
- after: str = typer.Option(None, "--after", help="Continue reading after a content cursor"),
- limit: int | None = typer.Option(None, "--limit", help="Soft character limit for STDOUT content"),
- format: Literal["markdown"] = typer.Option("markdown", "-f", "--format", help="Output format: markdown"),
- force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),
- remote: bool = typer.Option(False, "--remote", help="Use remote parse-server"),
- wait: int = typer.Option(60, "--wait", help="Max seconds to wait for parse to complete"),
- no_wait: bool = typer.Option(False, "--no-wait", help="Don't wait — return immediately"),
- output: str = typer.Option(None, "-o", "--output", help="Output path; creates parent directories"),
- no_marker: bool = typer.Option(False, "--no-marker", help="Omit document structure markers from output"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
- verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),
+ pages: str = typer.Option(None, "-p", "--pages", help=t("PDF pages: '1-5,8,r3-r1' or 'all'; default: first 10 pages")),
+ after: str = typer.Option(None, "--after", help=t("Continue reading after a content cursor")),
+ limit: int | None = typer.Option(None, "--limit", help=t("Soft character limit for STDOUT content")),
+ format: Literal["markdown"] = typer.Option("markdown", "-f", "--format", help=t("Output format: markdown")),
+ force: bool = typer.Option(False, "--force", help=t("Force re-parse, ignore cache")),
+ remote: bool = typer.Option(False, "--remote", help=t("Use remote parse-server")),
+ wait: int = typer.Option(60, "--wait", help=t("Max seconds to wait for parse to complete")),
+ no_wait: bool = typer.Option(False, "--no-wait", help=t("Don't wait — return immediately")),
+ output: str = typer.Option(None, "-o", "--output", help=t("Output path; creates parent directories")),
+ no_marker: bool = typer.Option(False, "--no-marker", help=t("Omit document structure markers from output")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
+ verbose: bool = typer.Option(False, "-v", "--verbose", help=t("Verbose output")),
) -> None:
"""Parse a document file."""
ctx = CliContext(json_mode=json_mode, verbose=verbose)
@@ -145,7 +146,7 @@ def _parse(
file_path = normalize_cli_path(path)
if not Path(file_path).exists():
- raise MineruError("file_not_found", f"File not found: {file_path}", "path")
+ raise MineruError("file_not_found", t("File not found: {path}", path=file_path), "path")
_validate_page_range_input(pages)
pages = normalize_page_range_input(pages) or None
@@ -173,7 +174,7 @@ def _parse(
# cached
if status == "done":
if verbose:
- _emit_notice("Cache hit — returning cached result.", json_mode=json_mode)
+ _emit_notice(t("Cache hit — returning cached result."), json_mode=json_mode)
return _prepare_parse_result(
client,
result,
@@ -197,7 +198,7 @@ def _parse(
# poll until done or timeout
if verbose:
- _emit_notice(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...", json_mode=json_mode)
+ _emit_notice(t("Parse queued (tier={tier}). Waiting up to {wait}s...", tier=req_tier, wait=wait), json_mode=json_mode)
wait_started_at = time.time()
deadline = time.time() + wait
@@ -225,7 +226,7 @@ def _parse(
if st in ("pending", "parsing"):
latest_wait_status = st
if verbose and not json_mode:
- _emit_notice(f" Parse status: {st}", json_mode=json_mode)
+ _emit_notice(t(" Parse status: {status}", status=st), json_mode=json_mode)
if st == "done":
_record_parse_wait(client, wait_parse_ids, "succeeded", wait_started_at)
@@ -248,19 +249,19 @@ def _parse(
failed = next((row for row in parse_rows if row.status == "failed"), None)
_record_parse_wait(client, wait_parse_ids, "failed", wait_started_at)
error_code = (failed.error_code if failed else None) or "parse_failed"
- error_msg = (failed.error_msg if failed else None) or "Parse failed."
+ error_msg = (failed.error_msg if failed else None) or t("Parse failed.")
error_param = "parse_server.remote.api_key" if error_code == "invalid_api_key" else None
raise MineruError(error_code, error_msg, error_param)
_record_parse_wait(client, wait_parse_ids, "timeout", wait_started_at)
- timeout_error = MineruError("parse_wait_timeout", f"Parse did not finish within {wait} seconds.", "wait")
+ timeout_error = MineruError("parse_wait_timeout", t("Parse did not finish within {seconds} seconds.", seconds=wait), "wait")
if json_mode:
return cli_ok(
_parse_json_payload(
result,
None,
error=timeout_error,
- parse_overrides={"status": latest_wait_status, "tip": "Re-run the same command to continue waiting."},
+ parse_overrides={"status": latest_wait_status, "tip": t("Re-run the same command to continue waiting.")},
),
exit_code=1,
)
@@ -322,7 +323,7 @@ def _prepare_parse_result(
)
if json_mode:
return cli_ok(_parse_json_payload(parse_result, None, output=exported.output))
- return cli_ok(ParseTextOutput(f"Written to {exported.output}"), render=_render_parse_text)
+ return cli_ok(ParseTextOutput(t("Written to {path}", path=exported.output)), render=_render_parse_text)
content = _fetch_doc_content(
client,
@@ -335,7 +336,7 @@ def _prepare_parse_result(
no_marker=no_marker,
)
if not content.content and content.format == "markdown" and not content.content_ranges:
- raise MineruError("parse_empty", "No content returned from parse.")
+ raise MineruError("parse_empty", t("No content returned from parse."))
if json_mode:
return cli_ok(_parse_json_payload(parse_result, content))
return _prepare_parse_content_output(
@@ -406,16 +407,19 @@ def _prepare_parse_summary_output(
render=_render_parse_summary,
exit_code=exit_code,
)
- return cli_ok(ParseSummaryOutput(f"Parse complete (tier={parse_result.tier}) {tip}"), render=_render_parse_summary)
+ return cli_ok(
+ ParseSummaryOutput(t("Parse complete (tier={tier}) {tip}", tier=parse_result.tier, tip=tip)),
+ render=_render_parse_summary,
+ )
def _format_parse_in_progress(parse_result: ParseResponse, *, waited_seconds: int | None, tip: str = "") -> str:
- elapsed = f" after {waited_seconds}s" if waited_seconds is not None else ""
- lines = [f"Parse still in progress{elapsed} (tier={parse_result.tier})."]
+ elapsed = f" {t('after {seconds}s', seconds=waited_seconds)}" if waited_seconds is not None else ""
+ lines = [t("Parse still in progress{elapsed} (tier={tier}).", elapsed=elapsed, tier=parse_result.tier)]
parse_ids = parse_result.wait_parse_ids
if parse_ids:
- label = "Parse ID" if len(parse_ids) == 1 else "Parse IDs"
- lines.append(f"{label}: {', '.join(str(parse_id) for parse_id in parse_ids)}")
+ label = t("Parse ID") if len(parse_ids) == 1 else t("Parse IDs")
+ lines.append(t("{label}: {ids}", label=label, ids=", ".join(str(parse_id) for parse_id in parse_ids)))
if len(parse_ids) == 1:
lines.append(f"Check status: mineru show parse {parse_ids[0]}")
else:
@@ -440,7 +444,7 @@ def _prepare_parse_content_output(
next_marker_remote: bool = False,
) -> CliResult[ParseTextOutput] | CliResult[None]:
if not content.content and content.content_ranges:
- message = "No renderable content in requested pages."
+ message = t("No renderable content in requested pages.")
if content.next_request and not no_marker:
marker = _parse_next_marker(
source_path,
diff --git a/mineru/cli/commands/read.py b/mineru/cli/commands/read.py
index e7674296..9bfc2d76 100644
--- a/mineru/cli/commands/read.py
+++ b/mineru/cli/commands/read.py
@@ -12,6 +12,7 @@ import typer
from ...doclib.client import DoclibClient
from ...doclib.types import ContentNextRequest, DocContentResponse, ImageFormat
from ...errors import MineruError
+from ...utils.i18n import t
from ..contracts import CliContext, CliResult
from ..runtime import cli_ok, run_cli
from .parse import _append_next_marker, _ensure_output_parent, _output_info
@@ -23,13 +24,13 @@ class ReadTextOutput:
def read_cmd(
- locator: str = typer.Argument(..., help="Doclib locator, e.g. doc:ab12cd3/tier:basic/page:4"),
- context: int = typer.Option(0, "--context", help="Read N pages/blocks before and after the locator"),
- limit: int = typer.Option(30000, "--limit", help="Soft character limit for STDOUT content"),
- format: Literal["markdown", "image"] = typer.Option("markdown", "-f", "--format", help="Output format: markdown, image"),
- output: str = typer.Option(None, "-o", "--output", help="Output path; creates parent directories"),
- no_marker: bool = typer.Option(False, "--no-marker", help="Omit continuation marker from output"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ locator: str = typer.Argument(..., help=t("Doclib locator, e.g. doc:ab12cd3/tier:basic/page:4")),
+ context: int = typer.Option(0, "--context", help=t("Read N pages/blocks before and after the locator")),
+ limit: int = typer.Option(30000, "--limit", help=t("Soft character limit for STDOUT content")),
+ format: Literal["markdown", "image"] = typer.Option("markdown", "-f", "--format", help=t("Output format: markdown, image")),
+ output: str = typer.Option(None, "-o", "--output", help=t("Output path; creates parent directories")),
+ no_marker: bool = typer.Option(False, "--no-marker", help=t("Omit continuation marker from output")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Read parsed doclib content by locator."""
ctx = CliContext(json_mode=json_mode)
@@ -91,7 +92,7 @@ def _prepare_read_output(
payload: dict[str, object] = content.model_dump(mode="json")
if content.format == "image":
if content.asset is None:
- raise MineruError("asset_not_available", "No image asset returned.", "format")
+ raise MineruError("asset_not_available", t("No image asset returned."), "format")
shutil.copyfile(content.asset.path, output_path)
else:
Path(output_path).write_text(content.content, encoding="utf-8")
@@ -104,19 +105,19 @@ def _prepare_read_output(
if content.format == "image":
if content.asset is None:
- raise MineruError("asset_not_available", "No image asset returned.", "format")
+ raise MineruError("asset_not_available", t("No image asset returned."), "format")
asset_path = content.asset.path
if output_path and output_path != "-":
shutil.copyfile(asset_path, output_path)
- return cli_ok(ReadTextOutput(f"Written to {output_path}"), render=_render_read_text)
+ return cli_ok(ReadTextOutput(t("Written to {path}", path=output_path)), render=_render_read_text)
return cli_ok(ReadTextOutput(asset_path), render=_render_read_text)
if output_path and output_path != "-":
Path(output_path).write_text(content.content, encoding="utf-8")
- return cli_ok(ReadTextOutput(f"Written to {output_path}"), render=_render_read_text)
+ return cli_ok(ReadTextOutput(t("Written to {path}", path=output_path)), render=_render_read_text)
if not content.content and content.content_ranges:
- message = "No renderable content in requested pages."
+ message = t("No renderable content in requested pages.")
if content.next_request and not no_marker:
marker = _read_next_marker(content.next_request)
if marker:
@@ -141,7 +142,7 @@ def _image_format_for_output(*, format: Literal["markdown", "image"], output: st
if output == "-":
raise MineruError(
"image_output_extension_unsupported",
- "Image output requires a file path ending with .png, .jpg, .jpeg, or .webp; stdout is not supported.",
+ t("Image output requires a file path ending with .png, .jpg, .jpeg, or .webp; stdout is not supported."),
"output",
)
suffix = Path(output).suffix.lower()
@@ -153,7 +154,7 @@ def _image_format_for_output(*, format: Literal["markdown", "image"], output: st
return "webp"
raise MineruError(
"image_output_extension_unsupported",
- "Image output path must end with .png, .jpg, .jpeg, or .webp.",
+ t("Image output path must end with .png, .jpg, .jpeg, or .webp."),
"output",
)
diff --git a/mineru/cli/commands/scan.py b/mineru/cli/commands/scan.py
index 09b32426..caea542e 100644
--- a/mineru/cli/commands/scan.py
+++ b/mineru/cli/commands/scan.py
@@ -10,16 +10,17 @@ import typer
from ...doclib.client import DoclibClient
from ...doclib.types import ScanInfo, ScanRequest
from ...errors import MineruError
+from ...utils.i18n import t
from ..contracts import CliContext, CliTaskResult
from ..path_utils import normalize_cli_path
from ..runtime import cli_task, run_cli
def scan_cmd(
- path: str = typer.Argument(..., help="File or directory path to scan"),
- wait: int = typer.Option(30, "--wait", help="Max seconds to wait for scan completion"),
- no_wait: bool = typer.Option(False, "--no-wait", help="Return immediately after creating the scan"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ path: str = typer.Argument(..., help=t("File or directory path to scan")),
+ wait: int = typer.Option(30, "--wait", help=t("Max seconds to wait for scan completion")),
+ no_wait: bool = typer.Option(False, "--no-wait", help=t("Return immediately after creating the scan")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _scan(path, wait=wait, no_wait=no_wait), render=_render_scan)
@@ -28,7 +29,7 @@ def scan_cmd(
def _scan(path: str, *, wait: int, no_wait: bool) -> CliTaskResult[ScanInfo]:
scan_path = normalize_cli_path(path)
if not Path(scan_path).exists():
- raise MineruError("file_not_found", f"File or directory not found: {scan_path}", "path")
+ raise MineruError("file_not_found", t("File or directory not found: {path}", path=scan_path), "path")
client = _client()
scan_info = client.create_scan(ScanRequest(path=scan_path, kind="manual", source="cli"))
if not no_wait and wait > 0:
@@ -52,11 +53,18 @@ def _wait_for_scan(client: DoclibClient, scan_id: int, wait_seconds: int) -> Sca
def _render_scan(scan_info: ScanInfo) -> str:
status = scan_info.status
if status == "failed":
- return f"Scan failed: {scan_info.error_code or ''} {scan_info.error_msg or ''}"
- return (
- f"Scan {scan_info.id} {status}: "
- f"seen={scan_info.files_seen}, refreshed={scan_info.files_refreshed}, "
- f"new={scan_info.files_new}, changed={scan_info.files_changed}, "
- f"deleted={scan_info.files_deleted}, unreachable={scan_info.files_unreachable}, "
- f"excluded={scan_info.files_excluded}, unsupported={scan_info.files_unsupported}"
+ return t("Scan failed: {code} {msg}", code=scan_info.error_code or "", msg=scan_info.error_msg or "")
+ return t(
+ "Scan {id} {status}: seen={seen}, refreshed={refreshed}, new={new}, changed={changed}, deleted={deleted}, "
+ "unreachable={unreachable}, excluded={excluded}, unsupported={unsupported}",
+ id=scan_info.id,
+ status=status,
+ seen=scan_info.files_seen,
+ refreshed=scan_info.files_refreshed,
+ new=scan_info.files_new,
+ changed=scan_info.files_changed,
+ deleted=scan_info.files_deleted,
+ unreachable=scan_info.files_unreachable,
+ excluded=scan_info.files_excluded,
+ unsupported=scan_info.files_unsupported,
)
diff --git a/mineru/cli/commands/search.py b/mineru/cli/commands/search.py
index 420afe06..c1523507 100644
--- a/mineru/cli/commands/search.py
+++ b/mineru/cli/commands/search.py
@@ -8,6 +8,7 @@ from ...doclib.client import DoclibClient
from ...doclib.types import FindResponse, SearchResponse
from ...filetypes import FILE_TYPE_BY_EXTENSION
from ...types import Tier
+from ...utils.i18n import t
from ..contracts import CliContext
from ..runtime import run_cli
@@ -16,17 +17,17 @@ FILE_EXTS = ", ".join(FILE_TYPE_BY_EXTENSION)
def search_cmd(
- query: str = typer.Argument(..., help="Search query"),
- file_type: str | None = typer.Option(None, "--type", help=f"File type filter: {FILE_TYPES}"),
- tier: Tier | None = typer.Option(None, "--tier", help="Exact search index tier: flash, basic, standard, advanced"),
+ query: str = typer.Argument(..., help=t("Search query")),
+ file_type: str | None = typer.Option(None, "--type", help=t("File type filter: {types}", types=FILE_TYPES)),
+ tier: Tier | None = typer.Option(None, "--tier", help=t("Exact search index tier: flash, basic, standard, advanced")),
min_tier: Tier | None = typer.Option(
None,
"--min-tier",
- help="Minimum search index tier: flash, basic, standard, advanced",
+ help=t("Minimum search index tier: flash, basic, standard, advanced"),
),
- limit: int = typer.Option(20, "--limit", "-n", help="Max results"),
- offset: int = typer.Option(0, "--offset", help="Result offset"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ limit: int = typer.Option(20, "--limit", "-n", help=t("Max results")),
+ offset: int = typer.Option(0, "--offset", help=t("Result offset")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Search parsed document content."""
run_cli(
@@ -44,10 +45,10 @@ def search_cmd(
def find_cmd(
- query: str = typer.Argument(..., help="Filename search query"),
- ext: str | None = typer.Option(None, "--ext", help=f"File extension filter: {FILE_EXTS}"),
- limit: int = typer.Option(50, "--limit", "-n", help="Max results"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ query: str = typer.Argument(..., help=t("Filename search query")),
+ ext: str | None = typer.Option(None, "--ext", help=t("File extension filter: {exts}", exts=FILE_EXTS)),
+ limit: int = typer.Option(50, "--limit", "-n", help=t("Max results")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Search filenames only (not document content)."""
run_cli(
@@ -59,24 +60,24 @@ def find_cmd(
def _render_search_results(data: SearchResponse) -> str:
if not data.results:
- return "No results found."
+ return t("No results found.")
- lines = [f"Search results ({data.total} total)"]
+ lines = [t("Search results ({total} total)", total=data.total)]
for index, result in enumerate(data.results, start=1):
- label = result.title or f"Document {result.short_id}"
+ label = result.title or t("Document {short_id}", short_id=result.short_id)
item_line = f"{index}. {label}"
if result.tier:
- item_line += f" Tier: {result.tier}"
+ item_line += " " + t("Tier: {tier}", tier=result.tier)
lines.append(item_line)
active_files = [file for file in result.files if file.status == "active"]
display_files = active_files or result.files
if display_files:
- lines.append(" Files:")
+ lines.append(f" {t('Files:')}")
for file in display_files:
suffix = f" ({file.status})" if file.status != "active" else ""
lines.append(f" {file.path}{suffix}")
else:
- lines.append(" File no longer exists.")
+ lines.append(f" {t('File no longer exists.')}")
snippet = _format_snippet(result.snippet)
if snippet:
lines.append(f" {snippet}")
@@ -87,9 +88,9 @@ def _render_search_results(data: SearchResponse) -> str:
def _render_find_results(data: FindResponse) -> str:
if not data.results:
- return "No results found."
+ return t("No results found.")
- lines = [f"Search results ({data.total} total)"]
+ lines = [t("Search results ({total} total)", total=data.total)]
for index, result in enumerate(data.results, start=1):
path = _format_result_path(result.paths)
lines.append(f"{index}. {result.filename}{path}")
diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.py
index e8b9fa12..a70fc967 100644
--- a/mineru/cli/commands/server.py
+++ b/mineru/cli/commands/server.py
@@ -21,12 +21,13 @@ from ...doclib.endpoint import read_endpoint_file
from ...doclib.instance_lock import DoclibLockUnavailable, build_doclib_home_owned_message, doclib_home_lock
from ...doclib.types import ServerStatusResponse, TCPServerStatus
from ...errors import MineruError
+from ...utils.i18n import t
from ...utils.stdio import utf8_subprocess_env
from ...version import __version__
from ..contracts import CliContext, RenderableObject
from ..runtime import run_cli
-app = typer.Typer(help="Server lifecycle management", no_args_is_help=True)
+app = typer.Typer(help=t("Server lifecycle management"), no_args_is_help=True)
SERVER_START_TIMEOUT_SEC = 30.0
@@ -95,7 +96,7 @@ class _ServerStartLock:
if _server_running():
return self
- raise RuntimeError("Another mineru server start is already in progress.")
+ raise RuntimeError(t("Another mineru server start is already in progress."))
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
if self.acquired:
@@ -203,7 +204,7 @@ def _wait_for_server_stop(timeout: float = 15.0) -> bool:
return False
[email protected](help=t("Start the mineru server in the background."))
def start() -> None:
"""Start the mineru server in the background."""
run_cli(CliContext(json_mode=False), _start)
@@ -211,7 +212,7 @@ def start() -> None:
def _start() -> str:
if _server_running():
- return "Server is already running."
+ return t("Server is already running.")
log_path = _server_log_path()
stdout_log_path = _server_stdout_log_path()
@@ -223,7 +224,7 @@ def _start() -> str:
try:
with _ServerStartLock(_server_start_lock_path()) as start_lock:
if not start_lock.acquired or _server_running():
- return "Server is already running."
+ return t("Server is already running.")
if not _doclib_lock_available():
raise _home_owner_unavailable_error()
@@ -248,24 +249,36 @@ def _start() -> str:
if not _wait_for_started_server(proc):
if proc.poll() is None:
- return f"Server is still starting (PID {proc.pid}).\nCheck status: mineru server status"
+ return f"{t('Server is still starting (PID {pid}).', pid=proc.pid)}\nCheck status: mineru server status"
raise MineruError(
"service_unavailable",
- f"Server failed to start within {int(SERVER_START_TIMEOUT_SEC)} seconds. "
- f"See log: {log_path}; stdout: {stdout_log_path}; stderr: {stderr_log_path}",
+ t(
+ "Server failed to start within {seconds} seconds. "
+ "See log: {log}; stdout: {stdout}; stderr: {stderr}",
+ seconds=int(SERVER_START_TIMEOUT_SEC),
+ log=log_path,
+ stdout=stdout_log_path,
+ stderr=stderr_log_path,
+ ),
)
except MineruError:
raise
except Exception as exc:
raise MineruError(
"service_unavailable",
- f"Server failed to start: {exc}. See log: {log_path}; stdout: {stdout_log_path}; stderr: {stderr_log_path}",
+ t(
+ "Server failed to start: {error}. See log: {log}; stdout: {stdout}; stderr: {stderr}",
+ error=exc,
+ log=log_path,
+ stdout=stdout_log_path,
+ stderr=stderr_log_path,
+ ),
) from exc
- return f"Server started (PID {proc.pid})."
+ return t("Server started (PID {pid}).", pid=proc.pid)
[email protected](help=t("Stop the mineru server gracefully."))
def stop() -> None:
"""Stop the mineru server gracefully."""
run_cli(CliContext(json_mode=False), _stop)
@@ -275,7 +288,7 @@ def _stop() -> str:
if not _server_running():
if not _doclib_lock_available():
raise _home_owner_unavailable_error()
- return "Server is not running."
+ return t("Server is not running.")
try:
from ...doclib.client import DoclibClient
@@ -283,18 +296,18 @@ def _stop() -> str:
c = DoclibClient(timeout=5)
c.shutdown_server()
except Exception as exc:
- raise MineruError("service_unavailable", f"Failed to request MinerU server shutdown: {exc}") from exc
+ raise MineruError("service_unavailable", t("Failed to request MinerU server shutdown: {error}", error=exc)) from exc
if not _wait_for_server_stop():
raise MineruError(
"service_unavailable",
- "MinerU server did not stop within 15 seconds. The server was not restarted.",
+ t("MinerU server did not stop within 15 seconds. The server was not restarted."),
)
- return "Server stopped."
+ return t("Server stopped.")
[email protected](help=t("Restart the mineru server."))
def restart() -> None:
"""Restart the mineru server."""
run_cli(CliContext(json_mode=False), _restart)
@@ -308,8 +321,8 @@ def _restart() -> str:
return _start()
-def status(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected](help=t("Show server status."))
+def status(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Show server status."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, _server_status, render=_render_server_status)
@@ -330,98 +343,98 @@ def _server_status() -> ServerStatusResponse | _ServerStartingStatus:
def _render_server_status(data: ServerStatusResponse | _ServerStartingStatus) -> Iterator[RenderableObject]:
if isinstance(data, _ServerStartingStatus):
if data.pid is None:
- yield "Server is still starting."
+ yield t("Server is still starting.")
else:
- yield f"Server is still starting (PID {data.pid})."
+ yield t("Server is still starting (PID {pid}).", pid=data.pid)
yield "Check again: mineru server status"
return
if not _get(data, "running"):
- yield "Server is not running."
+ yield t("Server is not running.")
return
- table = Table(title="MinerU Server")
- table.add_column("Field", style="cyan")
- table.add_column("Current", style="green")
- table.add_row("PID", str(_get(data, "pid", "?")))
- table.add_row("Uptime", f"{_get(data, 'uptime_seconds', 0):.0f}s")
- table.add_row("Home", _get(data, "mineru_home", ""))
- table.add_row("Version", _get(data, "version", ""))
- table.add_row("Python", _get(data, "python_version", ""))
- table.add_row("Socket", _get(data, "socket_path", ""))
- table.add_row("Data dir", _get(data, "data_dir", ""))
- table.add_row("SQLite", _get(data, "sqlite_path", ""))
- table.add_row("SQLite size", _format_bytes(_get(data, "sqlite_size_bytes")))
- table.add_row("Log", _get(data, "log_path", ""))
+ table = Table(title=t("MinerU Server"))
+ table.add_column(t("Field"), style="cyan")
+ table.add_column(t("Current"), style="green")
+ table.add_row(t("PID"), str(_get(data, "pid", "?")))
+ table.add_row(t("Uptime"), f"{_get(data, 'uptime_seconds', 0):.0f}s")
+ table.add_row(t("Home"), _get(data, "mineru_home", ""))
+ table.add_row(t("Version"), _get(data, "version", ""))
+ table.add_row(t("Python"), _get(data, "python_version", ""))
+ table.add_row(t("Socket"), _get(data, "socket_path", ""))
+ table.add_row(t("Data dir"), _get(data, "data_dir", ""))
+ table.add_row(t("SQLite"), _get(data, "sqlite_path", ""))
+ table.add_row(t("SQLite size"), _format_bytes(_get(data, "sqlite_size_bytes")))
+ table.add_row(t("Log"), _get(data, "log_path", ""))
tcp_data = _get(data, "tcp")
tcp_enabled = bool(_get(tcp_data, "enabled", False))
tcp_host = _get(tcp_data, "host", "") or "-"
tcp_port = _get(tcp_data, "port")
if tcp_enabled:
- tcp_value = f"http://{tcp_host}:{tcp_port}" if tcp_port is not None else f"http://{tcp_host}:(pending)"
+ tcp_value = f"http://{tcp_host}:{tcp_port}" if tcp_port is not None else f"http://{tcp_host}:{t('(pending)')}"
else:
- tcp_value = "disabled"
- table.add_row("TCP", tcp_value)
- table.add_row("Files tracked", str(_get(data, "files_total", 0)))
- table.add_row("Docs indexed", str(_get(data, "docs_total", 0)))
- table.add_row("Active scans", str(_get(data, "active_scan_count", 0)))
- table.add_row("Last scan", _format_timestamp_ms(_get(data, "last_scan_at")))
- table.add_row("Parse queue", str(_get(data, "parse_queue_length", 0)))
- table.add_row("Ingest queue", str(_get(data, "ingest_queue_length", 0)))
- table.add_row("Watches", str(_get(data, "watch_count", 0)))
+ tcp_value = t("disabled")
+ table.add_row(t("TCP"), tcp_value)
+ table.add_row(t("Files tracked"), str(_get(data, "files_total", 0)))
+ table.add_row(t("Docs indexed"), str(_get(data, "docs_total", 0)))
+ table.add_row(t("Active scans"), str(_get(data, "active_scan_count", 0)))
+ table.add_row(t("Last scan"), _format_timestamp_ms(_get(data, "last_scan_at")))
+ table.add_row(t("Parse queue"), str(_get(data, "parse_queue_length", 0)))
+ table.add_row(t("Ingest queue"), str(_get(data, "ingest_queue_length", 0)))
+ table.add_row(t("Watches"), str(_get(data, "watch_count", 0)))
yield table
workers = _get(data, "workers")
if workers:
- worker_table = Table(title="Workers")
- worker_table.add_column("Component", style="cyan")
- worker_table.add_column("Running", style="green")
- worker_table.add_column("Workers", justify="right")
- worker_table.add_row("Watch", "yes" if _get(workers, "watch_running", False) else "no", "-")
+ worker_table = Table(title=t("Workers"))
+ worker_table.add_column(t("Component"), style="cyan")
+ worker_table.add_column(t("Running"), style="green")
+ worker_table.add_column(t("Workers"), justify="right")
+ worker_table.add_row(t("Watch"), t("yes") if _get(workers, "watch_running", False) else t("no"), "-")
worker_table.add_row(
- "Scan",
- "yes" if _get(workers, "scan_running", False) else "no",
+ t("Scan"),
+ t("yes") if _get(workers, "scan_running", False) else t("no"),
str(_get(workers, "scan_workers", 0)),
)
worker_table.add_row(
- "Ingest",
- "yes" if _get(workers, "ingest_running", False) else "no",
+ t("Ingest"),
+ t("yes") if _get(workers, "ingest_running", False) else t("no"),
str(_get(workers, "ingest_workers", 0)),
)
worker_table.add_row(
- "Parse",
- "yes" if _get(workers, "parse_running", False) else "no",
+ t("Parse"),
+ t("yes") if _get(workers, "parse_running", False) else t("no"),
str(_get(workers, "parse_workers", 0)),
)
worker_table.add_row(
- "Device monitor",
- "yes" if _get(workers, "device_monitor_running", False) else "no",
+ t("Device monitor"),
+ t("yes") if _get(workers, "device_monitor_running", False) else t("no"),
"-",
)
worker_table.add_row(
- "Compaction",
- "yes" if _get(workers, "compaction_running", False) else "no",
+ t("Compaction"),
+ t("yes") if _get(workers, "compaction_running", False) else t("no"),
"-",
)
worker_table.add_row(
- "Health check",
- "yes" if _get(workers, "health_check_running", False) else "no",
+ t("Health check"),
+ t("yes") if _get(workers, "health_check_running", False) else t("no"),
"-",
)
yield worker_table
watch_stats = _get(data, "watch_stats", [])
if watch_stats:
- watch_table = Table(title="Watch Stats")
- watch_table.add_column("Path", style="cyan", no_wrap=True)
- watch_table.add_column("Status", style="green")
- watch_table.add_column("Files", justify="right")
- watch_table.add_column("Active", justify="right")
- watch_table.add_column("Deleted", justify="right")
- watch_table.add_column("Unreachable", justify="right")
- watch_table.add_column("Pending ingest", justify="right")
- watch_table.add_column("Errors", justify="right")
- watch_table.add_column("Docs", justify="right")
- watch_table.add_column("Parses done/pending/parsing/failed", justify="right")
+ watch_table = Table(title=t("Watch Stats"))
+ watch_table.add_column(t("Path"), style="cyan", no_wrap=True)
+ watch_table.add_column(t("Status"), style="green")
+ watch_table.add_column(t("Files"), justify="right")
+ watch_table.add_column(t("Active"), justify="right")
+ watch_table.add_column(t("Deleted"), justify="right")
+ watch_table.add_column(t("Unreachable"), justify="right")
+ watch_table.add_column(t("Pending ingest"), justify="right")
+ watch_table.add_column(t("Errors"), justify="right")
+ watch_table.add_column(t("Docs"), justify="right")
+ watch_table.add_column(t("Parses done/pending/parsing/failed"), justify="right")
for item in watch_stats:
parse_counts = (
f"{_get(item, 'parse_done_count', 0)}/"
@@ -445,28 +458,28 @@ def _render_server_status(data: ServerStatusResponse | _ServerStartingStatus) ->
error_rows = _error_summary_rows(_get(data, "error_summary"))
if error_rows:
- error_table = Table(title="Error Summary")
- error_table.add_column("Scope", style="cyan")
- error_table.add_column("Code", style="red")
- error_table.add_column("Count", justify="right")
+ error_table = Table(title=t("Error Summary"))
+ error_table.add_column(t("Scope"), style="cyan")
+ error_table.add_column(t("Code"), style="red")
+ error_table.add_column(t("Count"), justify="right")
for scope, code, count in error_rows:
error_table.add_row(scope, code, str(count))
yield error_table
recent_scans = _get(data, "recent_scans", [])
if recent_scans:
- scan_table = Table(title="Recent Scans")
- scan_table.add_column("ID", justify="right")
- scan_table.add_column("Kind", style="cyan")
- scan_table.add_column("Source")
- scan_table.add_column("Status", style="green")
- scan_table.add_column("Path", no_wrap=True)
- scan_table.add_column("Seen", justify="right")
- scan_table.add_column("New", justify="right")
- scan_table.add_column("Changed", justify="right")
- scan_table.add_column("Deleted", justify="right")
- scan_table.add_column("Errors", justify="right")
- scan_table.add_column("Error code", style="red")
+ scan_table = Table(title=t("Recent Scans"))
+ scan_table.add_column(t("ID"), justify="right")
+ scan_table.add_column(t("Kind"), style="cyan")
+ scan_table.add_column(t("Source"))
+ scan_table.add_column(t("Status"), style="green")
+ scan_table.add_column(t("Path"), no_wrap=True)
+ scan_table.add_column(t("Seen"), justify="right")
+ scan_table.add_column(t("New"), justify="right")
+ scan_table.add_column(t("Changed"), justify="right")
+ scan_table.add_column(t("Deleted"), justify="right")
+ scan_table.add_column(t("Errors"), justify="right")
+ scan_table.add_column(t("Error code"), style="red")
for item in recent_scans:
scan_table.add_row(
str(_get(item, "id", "")),
@@ -485,24 +498,24 @@ def _render_server_status(data: ServerStatusResponse | _ServerStartingStatus) ->
ps_data = _get(data, "parse_server")
if ps_data:
- ps_table = Table(title="Parse Server")
- ps_table.add_column("Target", style="cyan")
- ps_table.add_column("Healthy", style="green")
- ps_table.add_column("Endpoint", style="dim")
- ps_table.add_column("Managed", style="dim")
- ps_table.add_column("Restart", justify="right")
- ps_table.add_column("Last probe", style="dim")
- ps_table.add_column("Last ok", style="dim")
- ps_table.add_column("Last fail", style="dim")
- ps_table.add_column("Tiers", style="green")
- for label, key in [("Local", "local"), ("Remote", "remote")]:
+ ps_table = Table(title=t("Parse Server"))
+ ps_table.add_column(t("Target"), style="cyan")
+ ps_table.add_column(t("Healthy"), style="green")
+ ps_table.add_column(t("Endpoint"), style="dim")
+ ps_table.add_column(t("Managed"), style="dim")
+ ps_table.add_column(t("Restart"), justify="right")
+ ps_table.add_column(t("Last probe"), style="dim")
+ ps_table.add_column(t("Last ok"), style="dim")
+ ps_table.add_column(t("Last fail"), style="dim")
+ ps_table.add_column(t("Tiers"), style="green")
+ for label, key in [(t("Local"), "local"), (t("Remote"), "remote")]:
ps = _get(ps_data, key, {})
if _get(ps, "starting"):
- healthy_str = "starting"
+ healthy_str = t("starting")
elif _get(ps, "healthy"):
- healthy_str = "yes"
+ healthy_str = t("yes")
else:
- healthy_str = "no"
+ healthy_str = t("no")
tiers_str = ", ".join(_get(ps, "supported_tiers", [])) or "-"
mode = _get(ps, "mode", "")
label_str = f"{label} ({mode})" if mode else label
@@ -514,7 +527,7 @@ def _render_server_status(data: ServerStatusResponse | _ServerStartingStatus) ->
if mode_text == "managed":
managed_tier = _get(ps, "managed_tier", "") or "-"
managed_pid = _get(ps, "managed_pid")
- managed_running = "yes" if _get(ps, "managed_running", False) else "no"
+ managed_running = t("yes") if _get(ps, "managed_running", False) else t("no")
managed_str = f"tier={managed_tier}, pid={managed_pid or '-'}, running={managed_running}"
elif mode_text == "self_hosted":
managed_str = _get(ps, "self_hosted_url", "") or "-"
@@ -533,17 +546,17 @@ def _render_server_status(data: ServerStatusResponse | _ServerStartingStatus) ->
yield ps_table
for title, key in (
- ("Recent App Logs", "app_logs"),
- ("Recent Access Logs", "access_logs"),
- ("Recent Stderr Logs", "stderr_logs"),
- ("Recent Stdout Logs", "stdout_logs"),
- ("Recent Parse Server Stderr Logs", "parse_server_stderr_logs"),
- ("Recent Parse Server Stdout Logs", "parse_server_stdout_logs"),
+ (t("Recent App Logs"), "app_logs"),
+ (t("Recent Access Logs"), "access_logs"),
+ (t("Recent Stderr Logs"), "stderr_logs"),
+ (t("Recent Stdout Logs"), "stdout_logs"),
+ (t("Recent Parse Server Stderr Logs"), "parse_server_stderr_logs"),
+ (t("Recent Parse Server Stdout Logs"), "parse_server_stdout_logs"),
):
logs = _get(data, key, [])
if logs:
log_text = "".join(logs)
- panel = Panel(Text(log_text.strip() or "(empty)"), title=title, border_style="dim")
+ panel = Panel(Text(log_text.strip() or t("(empty)")), title=title, border_style="dim")
yield panel
@@ -595,12 +608,12 @@ def _format_age_ms(ts: int | None) -> str:
return "-"
age = max(0.0, time.time() - ts / 1000)
if age < 60:
- return f"{age:.0f}s ago"
+ return t("{age}s ago", age=f"{age:.0f}")
if age < 3600:
- return f"{age / 60:.0f}m ago"
+ return t("{age}m ago", age=f"{age / 60:.0f}")
if age < 86400:
- return f"{age / 3600:.0f}h ago"
- return f"{age / 86400:.0f}d ago"
+ return t("{age}h ago", age=f"{age / 3600:.0f}")
+ return t("{age}d ago", age=f"{age / 86400:.0f}")
def _error_summary_rows(error_summary: Any) -> list[tuple[str, str, int]]:
diff --git a/mineru/cli/commands/show.py b/mineru/cli/commands/show.py
index 47dcecea..6f933cde 100644
--- a/mineru/cli/commands/show.py
+++ b/mineru/cli/commands/show.py
@@ -7,17 +7,18 @@ from rich.table import Table
from ...doclib.client import DoclibClient
from ...doclib.types import DocInfo, FileInfoResponse, ParseInfo, ScanInfo
+from ...utils.i18n import t
from ..contracts import CliContext
from ..path_utils import normalize_cli_path
from ..runtime import run_cli
-app = typer.Typer(help="Show doclib resource details", no_args_is_help=True)
+app = typer.Typer(help=t("Show doclib resource details"), no_args_is_help=True)
[email protected]("parse", help=t("Show one parse task."))
def show_parse(
- parse_id: int = typer.Argument(..., help="Parse task id"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ parse_id: int = typer.Argument(..., help=t("Parse task id")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Show one parse task."""
run_cli(
@@ -27,10 +28,10 @@ def show_parse(
)
[email protected]("scan", help=t("Show one scan task."))
def show_scan(
- scan_id: int = typer.Argument(..., help="Scan task id"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ scan_id: int = typer.Argument(..., help=t("Scan task id")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Show one scan task."""
run_cli(
@@ -40,10 +41,10 @@ def show_scan(
)
[email protected]("file", help=t("Show file, doc, and parse state for a local path."))
def show_file(
- path: str = typer.Argument(..., help="File path"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ path: str = typer.Argument(..., help=t("File path")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Show file, doc, and parse state for a local path."""
run_cli(
@@ -53,10 +54,10 @@ def show_file(
)
[email protected]("doc", help=t("Show one doc by Doc ID or content hash."))
def show_doc(
- doc_ref: str = typer.Argument(..., help="Document Doc ID or SHA-256"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ doc_ref: str = typer.Argument(..., help=t("Document Doc ID or SHA-256")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Show one doc by Doc ID or content hash."""
run_cli(
@@ -71,53 +72,53 @@ def _client() -> DoclibClient:
def _render_parse_info(data: ParseInfo) -> Table:
- table = Table(title=f"Parse {data.id}: {data.status}")
- table.add_column("Field", style="cyan")
- table.add_column("Value", style="green")
- table.add_row("SHA-256", data.sha256)
- table.add_row("Tier", data.tier)
- table.add_row("Pages", data.page_range)
- table.add_row("Privacy", data.privacy)
+ table = Table(title=t("Parse {id}: {status}", id=data.id, status=data.status))
+ table.add_column(t("Field"), style="cyan")
+ table.add_column(t("Value"), style="green")
+ table.add_row(t("SHA-256"), data.sha256)
+ table.add_row(t("Tier"), data.tier)
+ table.add_row(t("Pages"), data.page_range)
+ table.add_row(t("Privacy"), data.privacy)
if data.error_code or data.error_msg:
- table.add_row("Error", f"{data.error_code or ''} {data.error_msg or ''}".rstrip())
+ table.add_row(t("Error"), f"{data.error_code or ''} {data.error_msg or ''}".rstrip())
return table
def _render_scan(data: ScanInfo) -> Table | str:
if data.status == "failed":
- return f"Scan failed: {data.error_code or ''} {data.error_msg or ''}"
- table = Table(title=f"Scan {data.id}: {data.status}")
- table.add_column("Metric", style="cyan")
- table.add_column("Value", style="green", justify="right")
- table.add_row("Seen", str(data.files_seen))
- table.add_row("Refreshed", str(data.files_refreshed))
- table.add_row("New", str(data.files_new))
- table.add_row("Changed", str(data.files_changed))
- table.add_row("Deleted", str(data.files_deleted))
- table.add_row("Unreachable", str(data.files_unreachable))
- table.add_row("Excluded", str(data.files_excluded))
- table.add_row("Unsupported", str(data.files_unsupported))
+ return t("Scan failed: {code} {msg}", code=data.error_code or "", msg=data.error_msg or "")
+ table = Table(title=t("Scan {id}: {status}", id=data.id, status=data.status))
+ table.add_column(t("Metric"), style="cyan")
+ table.add_column(t("Value"), style="green", justify="right")
+ table.add_row(t("Seen"), str(data.files_seen))
+ table.add_row(t("Refreshed"), str(data.files_refreshed))
+ table.add_row(t("New"), str(data.files_new))
+ table.add_row(t("Changed"), str(data.files_changed))
+ table.add_row(t("Deleted"), str(data.files_deleted))
+ table.add_row(t("Unreachable"), str(data.files_unreachable))
+ table.add_row(t("Excluded"), str(data.files_excluded))
+ table.add_row(t("Unsupported"), str(data.files_unsupported))
return table
def _render_file_info(data: FileInfoResponse) -> Table | str:
if not data.file:
- return "File not found in database."
-
- table = Table(title=f"File Info: {data.file.filename or '?'}")
- table.add_column("Field", style="cyan")
- table.add_column("Value", style="green")
- table.add_row("Path", data.file.path or "?")
- table.add_row("Type", data.file.ext or "?")
- table.add_row("Size", _format_info_bytes(data.file.size_bytes))
- table.add_row("Doc ID", data.file.short_id or "-")
- table.add_row("Page count", str(data.doc.page_count if data.doc else "?"))
- table.add_row("Title", (data.doc.title if data.doc else None) or "—")
- table.add_row("Author", (data.doc.author if data.doc else None) or "—")
+ return t("File not found in database.")
+
+ table = Table(title=t("File Info: {name}", name=data.file.filename or "?"))
+ table.add_column(t("Field"), style="cyan")
+ table.add_column(t("Value"), style="green")
+ table.add_row(t("Path"), data.file.path or "?")
+ table.add_row(t("Type"), data.file.ext or "?")
+ table.add_row(t("Size"), _format_info_bytes(data.file.size_bytes))
+ table.add_row(t("Doc ID"), data.file.short_id or "-")
+ table.add_row(t("Page count"), str(data.doc.page_count if data.doc else "?"))
+ table.add_row(t("Title"), (data.doc.title if data.doc else None) or "—")
+ table.add_row(t("Author"), (data.doc.author if data.doc else None) or "—")
if data.parsed_tiers:
tier_str = ", ".join(f"{tier.tier}={tier.status}" for tier in data.parsed_tiers)
- table.add_row("Tiers", tier_str)
+ table.add_row(t("Tiers"), tier_str)
return table
@@ -133,15 +134,15 @@ def _format_info_bytes(n: int | None) -> str:
def _render_doc_info(data: DocInfo) -> Table:
- table = Table(title=f"Doc {data.short_id}")
- table.add_column("Field", style="cyan")
- table.add_column("Value", style="green")
- table.add_row("SHA-256", data.sha256)
- table.add_row("Type", data.file_type or "-")
- table.add_row("Title", data.title or "-")
- table.add_row("Pages", str(data.page_count if data.page_count is not None else "-"))
- table.add_row("Image based", str(data.is_image_based))
+ table = Table(title=t("Doc {short_id}", short_id=data.short_id))
+ table.add_column(t("Field"), style="cyan")
+ table.add_column(t("Value"), style="green")
+ table.add_row(t("SHA-256"), data.sha256)
+ table.add_row(t("Type"), data.file_type or "-")
+ table.add_row(t("Title"), data.title or "-")
+ table.add_row(t("Pages"), str(data.page_count if data.page_count is not None else "-"))
+ table.add_row(t("Image based"), str(data.is_image_based))
if data.files:
files = "\n".join(f"[{file_info.status}] {file_info.path}" for file_info in data.files)
- table.add_row("Files", files)
+ table.add_row(t("Files"), files)
return table
diff --git a/mineru/cli/commands/telemetry.py b/mineru/cli/commands/telemetry.py
index 2c42e32a..15629c23 100644
--- a/mineru/cli/commands/telemetry.py
+++ b/mineru/cli/commands/telemetry.py
@@ -9,40 +9,41 @@ import typer
from ...doclib.client import DoclibClient
from ...doclib.types import TelemetryActionResponse, TelemetryPayload, TelemetryStatusResponse
+from ...utils.i18n import t
from ..contracts import CliContext
from ..runtime import run_cli
-app = typer.Typer(help="Telemetry management", no_args_is_help=True)
+app = typer.Typer(help=t("Telemetry management"), no_args_is_help=True)
-def telemetry_status(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("status", help=t("Show telemetry status."))
+def telemetry_status(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Show telemetry status."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().get_telemetry_status(), render=_render_telemetry_status)
-def telemetry_preview(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("preview", help=t("Print the next telemetry request body without sending it."))
+def telemetry_preview(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Print the next telemetry request body without sending it."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().get_telemetry_preview().body, render=_render_telemetry_preview)
-def telemetry_enable(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("enable", help=t("Enable telemetry."))
+def telemetry_enable(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Enable telemetry."""
_run_action("enable", json_mode=json_mode)
-def telemetry_disable(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("disable", help=t("Disable telemetry and clear pending local aggregates."))
+def telemetry_disable(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Disable telemetry and clear pending local aggregates."""
_run_action("disable", json_mode=json_mode)
-def telemetry_flush(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("flush", help=t("Flush pending telemetry now when telemetry is enabled (or unset during prerelease)."))
+def telemetry_flush(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Flush pending telemetry now when telemetry is enabled (or unset during prerelease)."""
_run_action("flush", json_mode=json_mode)
@@ -57,22 +58,22 @@ def _client() -> DoclibClient:
def _render_telemetry_status(data: TelemetryStatusResponse) -> str:
- last_flush = data.last_flush_at if data.last_flush_at is not None else "never"
+ last_flush = data.last_flush_at if data.last_flush_at is not None else t("never")
return "\n".join(
[
- f"state: {data.state}",
- f"installation_id: {data.installation_id}",
- f"pending_periods: {data.pending_periods}",
- f"pending_metrics: {data.pending_metrics}",
- f"last_flush_at: {last_flush}",
+ t("state: {state}", state=data.state),
+ t("installation_id: {id}", id=data.installation_id),
+ t("pending_periods: {n}", n=data.pending_periods),
+ t("pending_metrics: {n}", n=data.pending_metrics),
+ t("last_flush_at: {value}", value=last_flush),
]
)
def _render_telemetry_action(data: TelemetryActionResponse) -> str:
if data.action == "flush":
- return f"telemetry flush: {data.reason or 'success'}"
- return f"telemetry {data.state}"
+ return t("telemetry flush: {reason}", reason=data.reason or "success")
+ return t("telemetry {state}", state=data.state)
def _render_telemetry_preview(data: TelemetryPayload) -> str:
diff --git a/mineru/cli/commands/usage.py b/mineru/cli/commands/usage.py
index d1fc8ddb..68b045e5 100644
--- a/mineru/cli/commands/usage.py
+++ b/mineru/cli/commands/usage.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field
from ...doclib.client import DoclibClient
from ...doclib.types import RemoteUsageResponse
+from ...utils.i18n import t
from ..contracts import CliContext, RenderableOutput
from ..guidance import (
REMOTE_API_URL_CONFIG,
@@ -25,7 +26,7 @@ class RemoteUsageOutput(BaseModel):
guidance_text: str | None = Field(default=None, exclude=True, repr=False)
-def usage_cmd(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
+def usage_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Show Remote API usage and limits."""
run_cli(
CliContext(json_mode=json_mode),
@@ -51,23 +52,23 @@ def _get_remote_usage() -> RemoteUsageOutput:
def _render_remote_usage(view: RemoteUsageOutput) -> RenderableOutput:
usage = view.usage
lines = [
- "Remote API Usage",
+ t("Remote API Usage"),
"",
- f"Remote URL: {view.remote_url}",
- f"Access level: {usage.access_level}",
- f"Billing period: {_format_billing_period(usage.billing_period.start, usage.billing_period.end)}",
+ t("Remote URL: {url}", url=view.remote_url),
+ t("Access level: {level}", level=usage.access_level),
+ t("Billing period: {period}", period=_format_billing_period(usage.billing_period.start, usage.billing_period.end)),
"",
- "Current",
- f" Pages processed: {usage.current.pages_processed}",
- f" Files processed: {usage.current.files_processed}",
- f" Jobs created: {usage.current.jobs_created}",
+ t("Current"),
+ " " + t("Pages processed: {count}", count=usage.current.pages_processed),
+ " " + t("Files processed: {count}", count=usage.current.files_processed),
+ " " + t("Jobs created: {count}", count=usage.current.jobs_created),
"",
- "Limits",
- f" Max pages per file: {usage.limits.max_pages_per_file}",
- f" Max file size: {_format_bytes(usage.limits.max_file_size_bytes)}",
- f" Max files per job: {usage.limits.max_files_per_job}",
- f" Max concurrent jobs: {usage.limits.max_concurrent_jobs}",
- f" File retention: {_format_retention(usage.limits.max_file_retention_days)}",
+ t("Limits"),
+ " " + t("Max pages per file: {count}", count=usage.limits.max_pages_per_file),
+ " " + t("Max file size: {size}", size=_format_bytes(usage.limits.max_file_size_bytes)),
+ " " + t("Max files per job: {count}", count=usage.limits.max_files_per_job),
+ " " + t("Max concurrent jobs: {count}", count=usage.limits.max_concurrent_jobs),
+ " " + t("File retention: {retention}", retention=_format_retention(usage.limits.max_file_retention_days)),
]
output: list[str] = ["\n".join(lines)]
if view.guidance_text is not None:
@@ -78,7 +79,7 @@ def _render_remote_usage(view: RemoteUsageOutput) -> RenderableOutput:
def _format_billing_period(start: str, end: str | None) -> str:
formatted_start = _format_utc_timestamp(start)
if end is None:
- return f"{formatted_start} - ongoing"
+ return t("{start} - ongoing", start=formatted_start)
return f"{formatted_start} - {_format_utc_timestamp(end)}"
@@ -97,8 +98,8 @@ def _format_bytes(value: int) -> str:
def _format_retention(days: int | None) -> str:
if days is None:
- return "not specified"
- return f"{days} day" if days == 1 else f"{days} days"
+ return t("not specified")
+ return t("{days} day", days=days) if days == 1 else t("{days} days", days=days)
__all__ = ["usage_cmd"]
diff --git a/mineru/cli/commands/watch.py b/mineru/cli/commands/watch.py
index 0b87736a..6f49a0e3 100644
--- a/mineru/cli/commands/watch.py
+++ b/mineru/cli/commands/watch.py
@@ -8,43 +8,42 @@ from rich.table import Table
from ...doclib.client import DoclibClient
from ...doclib.types import RemoveWatchResponse, ScanInfo, ScanRequest, WatchInfo, WatchListResponse, WatchRequest
from ...errors import MineruError
+from ...utils.i18n import t
from ..contracts import CliContext, CliTaskResult
from ..path_utils import normalize_cli_path
from ..runtime import cli_task, run_cli
from .scan import _render_scan, _wait_for_scan
-app = typer.Typer(help="Watch target management", no_args_is_help=True)
+app = typer.Typer(help=t("Watch target management"), no_args_is_help=True)
[email protected]("add", help=t("Add a directory to watch."))
def watch_add(
- path: str = typer.Argument(..., help="Directory path to watch"),
- removable: bool = typer.Option(False, "--removable", help="Removable device"),
- label: str = typer.Option(None, "--label", help="Label for this watch"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ path: str = typer.Argument(..., help=t("Directory path to watch")),
+ removable: bool = typer.Option(False, "--removable", help=t("Removable device")),
+ label: str = typer.Option(None, "--label", help=t("Label for this watch")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Add a directory to watch."""
ctx = CliContext(json_mode=json_mode)
run_cli(
ctx,
- lambda: _client().add_watch(
- WatchRequest(path=normalize_cli_path(path), removable=removable, label=label)
- ),
+ lambda: _client().add_watch(WatchRequest(path=normalize_cli_path(path), removable=removable, label=label)),
render=_render_watch_added,
)
-def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
[email protected]("list", help=t("List watched directories."))
+def watch_list(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""List watched directories."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, lambda: _client().list_watches(), render=_render_watch_list)
[email protected]("remove", help=t("Remove a watched directory."))
def watch_remove(
- target: str = typer.Argument(..., help="Watch id or exact watch root path to remove"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ target: str = typer.Argument(..., help=t("Watch id or exact watch root path to remove")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Remove a watched directory."""
ctx = CliContext(json_mode=json_mode)
@@ -57,12 +56,12 @@ def watch_remove(
run_cli(ctx, remove_watch, render=_render_watch_removed)
[email protected]("rescan", help=t("Create a watch scan task for an existing watch target."))
def watch_rescan(
- target: str = typer.Argument(..., help="Watch id or exact watch root path"),
- wait: int = typer.Option(30, "--wait", help="Max seconds to wait for scan completion"),
- no_wait: bool = typer.Option(False, "--no-wait", help="Return immediately after creating the scan"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
+ target: str = typer.Argument(..., help=t("Watch id or exact watch root path")),
+ wait: int = typer.Option(30, "--wait", help=t("Max seconds to wait for scan completion")),
+ no_wait: bool = typer.Option(False, "--no-wait", help=t("Return immediately after creating the scan")),
+ json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
"""Create a watch scan task for an existing watch target."""
ctx = CliContext(json_mode=json_mode)
@@ -83,32 +82,33 @@ def _client() -> DoclibClient:
def _render_watch_added(data: WatchInfo) -> str:
- return f"Watch added: {data.path} (id={data.id})"
+ return t("Watch added: {path} (id={id})", path=data.path, id=data.id)
def _render_watch_list(data: WatchListResponse) -> Table | str:
if not data.watches:
- return "No watches configured."
- table = Table(title="Watches")
- table.add_column("ID", justify="right")
- table.add_column("Path", style="cyan")
- table.add_column("Status", style="green")
- table.add_column("Removable")
- table.add_column("Label")
+ return t("No watches configured.")
+ table = Table(title=t("Watches"))
+ table.add_column(t("ID"), justify="right")
+ table.add_column(t("Path"), style="cyan")
+ table.add_column(t("Status"), style="green")
+ table.add_column(t("Removable"))
+ table.add_column(t("Label"))
for watch in data.watches:
table.add_row(
str(watch.id),
watch.path,
watch.status,
- "yes" if watch.removable else "no",
+ t("yes") if watch.removable else t("no"),
watch.label or "-",
)
return table
def _render_watch_removed(data: RemoveWatchResponse) -> str:
- action = "removed" if data.removed else "unchanged"
- return f"Watch {data.watch_id} {action}."
+ if data.removed:
+ return t("Watch {watch_id} removed.", watch_id=data.watch_id)
+ return t("Watch {watch_id} unchanged.", watch_id=data.watch_id)
def _resolve_watch(client: DoclibClient, target: str) -> WatchInfo:
@@ -118,10 +118,10 @@ def _resolve_watch(client: DoclibClient, target: str) -> WatchInfo:
for watch in watches:
if watch.id == watch_id:
return watch
- raise MineruError("watch_not_found", f"Watch id {watch_id} not found.", "watch_id")
+ raise MineruError("watch_not_found", t("Watch id {watch_id} not found.", watch_id=watch_id), "watch_id")
normalized = normalize_cli_path(target)
for watch in watches:
if normalize_cli_path(watch.path) == normalized:
return watch
- raise MineruError("watch_not_found", f"Watch path {normalized} not found.", "path")
+ raise MineruError("watch_not_found", t("Watch path {path} not found.", path=normalized), "path")
diff --git a/mineru/cli/guidance.py b/mineru/cli/guidance.py
index 7b82f766..bcb385d4 100644
--- a/mineru/cli/guidance.py
+++ b/mineru/cli/guidance.py
@@ -7,6 +7,7 @@ from urllib.parse import urlsplit
from ..doclib.client import DoclibClient
from ..errors import MineruError
+from ..utils.i18n import t
from .contracts import CliGuidance
OFFICIAL_REMOTE_API_URL = "https://mineru.net/api"
@@ -60,19 +61,19 @@ def api_key_guidance_for_error(error: MineruError) -> CliGuidance | None:
return None
if error.code == "invalid_api_key":
- return _api_key_guidance(required=True, message="Configure a valid Official API Key to continue.")
+ return _api_key_guidance(required=True, message=t("Configure a valid Official API Key to continue."))
if error.code == "feature_requires_api_key":
- return _api_key_guidance(required=True, message="This Remote API feature requires an Official API Key.")
+ return _api_key_guidance(required=True, message=t("This Remote API feature requires an Official API Key."))
if context.api_key_configured:
return None
if error.code == "rate_limit_exceeded":
return _api_key_guidance(
required=False,
- message="An Official API Key is optional and may provide registered rate limits.",
+ message=t("An Official API Key is optional and may provide registered rate limits."),
)
return _api_key_guidance(
required=False,
- message="An Official API Key is optional and enables registered access.",
+ message=t("An Official API Key is optional and enables registered access."),
)
@@ -81,7 +82,7 @@ def api_key_guidance_for_anonymous_usage(remote_url: str) -> CliGuidance | None:
return None
return _api_key_guidance(
required=False,
- message="An Official API Key is optional and enables registered access.",
+ message=t("An Official API Key is optional and enables registered access."),
)
@@ -94,7 +95,10 @@ def _api_key_guidance(*, required: bool, message: str) -> CliGuidance:
"url": OFFICIAL_API_KEY_URL,
"command": SET_API_KEY_COMMAND,
},
- text=(f"{message}\n\nManage or create an API Key:\n{OFFICIAL_API_KEY_URL}\n\nSet the API Key:\n{SET_API_KEY_COMMAND}"),
+ text=(
+ f"{message}\n\n{t('Manage or create an API Key:')}\n{OFFICIAL_API_KEY_URL}\n\n"
+ f"{t('Set the API Key:')}\n{SET_API_KEY_COMMAND}"
+ ),
)
diff --git a/mineru/cli/main.py b/mineru/cli/main.py
index f6c0aefe..f5758034 100644
--- a/mineru/cli/main.py
+++ b/mineru/cli/main.py
@@ -6,6 +6,7 @@ import typer
from click.core import Context
from typer.core import TyperGroup
+from ..utils.i18n import t
from ..utils.logger import configure_global_log_level
from ..utils.stdio import configure_standard_streams
from .commands import cleanup, config, list_resources, server, show, telemetry, usage, watch
@@ -54,7 +55,7 @@ class OrderedRootGroup(TyperGroup):
app = typer.Typer(
name="mineru",
cls=OrderedRootGroup,
- help="MinerU — your personal document center, built for agents",
+ help=t("MinerU — your personal document center, built for agents"),
no_args_is_help=True,
add_completion=False,
)
@@ -68,28 +69,28 @@ def root(
"--version",
callback=show_version,
is_eager=True,
- help="Show the version and exit.",
+ help=t("Show the version and exit."),
),
) -> None:
prepare_cli_telemetry(ctx)
-app.command("parse")(parse_cmd)
-app.command("read")(read_cmd)
+app.command("parse", help=t("Parse a document file."))(parse_cmd)
+app.command("read", help=t("Read parsed doclib content by locator."))(read_cmd)
app.command("scan")(scan_cmd)
app.add_typer(watch.app, name="watch")
-app.command("search")(search_cmd)
-app.command("find")(find_cmd)
-app.command("usage")(usage.usage_cmd)
+app.command("search", help=t("Search parsed document content."))(search_cmd)
+app.command("find", help=t("Search filenames only (not document content)."))(find_cmd)
+app.command("usage", help=t("Show Remote API usage and limits."))(usage.usage_cmd)
app.add_typer(list_resources.app, name="list")
app.add_typer(show.app, name="show")
app.add_typer(telemetry.app, name="telemetry")
app.add_typer(server.app, name="server")
app.add_typer(config.app, name="config")
-app.command("invalidate")(invalidate_cmd)
+app.command("invalidate", help=t("Mark done parse results as superseded."))(invalidate_cmd)
app.command("forget")(forget_cmd)
app.add_typer(cleanup.app, name="cleanup")
-app.command("version")(version_cmd)
+app.command("version", help=t("Print MinerU and Python versions."))(version_cmd)
def main() -> None:
diff --git a/mineru/cli/output.py b/mineru/cli/output.py
index df9624db..4e5675c6 100644
--- a/mineru/cli/output.py
+++ b/mineru/cli/output.py
@@ -12,6 +12,7 @@ from pydantic_core import to_json
from rich.console import Console
from rich.text import Text
+from ..utils.i18n import t
from .contracts import RenderableObject
console = Console(markup=False)
@@ -45,7 +46,7 @@ def print_notice(msg: str) -> None:
def print_error(msg: str) -> None:
- text = Text("Error:", style="red")
+ text = Text(t("Error:"), style="red")
text.append(f" {msg}")
stderr_console.print(text)
diff --git a/mineru/cli/telemetry.py b/mineru/cli/telemetry.py
index bd10065e..1c0d3b92 100644
--- a/mineru/cli/telemetry.py
+++ b/mineru/cli/telemetry.py
@@ -9,6 +9,7 @@ import typer
from ..doclib.client import DoclibClient
from ..doclib.telemetry import TelemetryContext, infer_default_client_context, reset_telemetry_context, set_telemetry_context
+from ..utils.i18n import t
PROMPT_COMMANDS = {
"parse",
@@ -64,8 +65,8 @@ def maybe_prompt_telemetry_consent() -> None:
if status.state != "unset":
return
- typer.echo(TELEMETRY_CONSENT_MESSAGE)
- enabled = typer.confirm("Enable telemetry?", default=True)
+ typer.echo(t(TELEMETRY_CONSENT_MESSAGE))
+ enabled = typer.confirm(t("Enable telemetry?"), default=True)
try:
client.telemetry_action("enable" if enabled else "disable")
except Exception:
diff --git a/mineru/cli/version_command.py b/mineru/cli/version_command.py
index f3c69b1d..ee26becf 100644
--- a/mineru/cli/version_command.py
+++ b/mineru/cli/version_command.py
@@ -7,6 +7,7 @@ from dataclasses import dataclass
import typer
+from ..utils.i18n import t
from .contracts import CliContext
from .runtime import run_cli
@@ -28,8 +29,8 @@ def version_info() -> VersionInfo:
def render_version(data: VersionInfo) -> str:
return "\n".join(
[
- f"MinerU version: {data.mineru_version}",
- f"Python version: {data.python_version}",
+ t("MinerU version: {version}", version=data.mineru_version),
+ t("Python version: {version}", version=data.python_version),
]
)
@@ -41,7 +42,7 @@ def show_version(ctx: typer.Context, value: bool) -> None:
ctx.exit()
-def version_cmd(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
+def version_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
"""Print MinerU and Python versions."""
ctx = CliContext(json_mode=json_mode)
run_cli(ctx, version_info, render=render_version)
diff --git a/mineru/errors.py b/mineru/errors.py
index 38c538c0..9aa9a4f1 100644
--- a/mineru/errors.py
+++ b/mineru/errors.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from typing import Literal
+from .utils.i18n import t
+
ErrorType = Literal[
"invalid_request_error",
"authentication_error",
@@ -194,12 +196,12 @@ class EngineError(MineruError):
class ServerNotRunningError(MineruError):
def __init__(self) -> None:
- super().__init__("server_not_running", "Local mineru server is not running. Run 'mineru server start'.")
+ super().__init__("server_not_running", t("Local mineru server is not running. Run 'mineru server start'."))
class ServerBusyError(MineruError):
- def __init__(self, message: str = "MinerU server is busy. Retry the request.") -> None:
- super().__init__("server_busy", message)
+ def __init__(self, message: str = "") -> None:
+ super().__init__("server_busy", message or t("MinerU server is busy. Retry the request."))
# ── FastAPI error response builder ─────────────────────────────────
diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.py
index f980d6ec..32ee2bca 100644
--- a/mineru/kit/commands/api_server.py
+++ b/mineru/kit/commands/api_server.py
@@ -8,6 +8,7 @@ import typer
from ...parser import api_server as parser_api_server
from ...types import SERVER_TIERS, ServerTier
from ...model.ocr.language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
+from ...utils.i18n import t
from ...utils.logger import configure_global_log_level
from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
@@ -22,53 +23,59 @@ def _normalize_tier_option(tier: str | None) -> ServerTier | None:
if tier not in SERVER_TIERS:
exit_with_message(
"invalid_request",
- f"Unsupported server tier '{tier}'. Supported server tiers: {', '.join(SERVER_TIERS)}",
+ t(
+ "Unsupported server tier '{tier}'. Supported server tiers: {tiers}",
+ tier=tier,
+ tiers=", ".join(SERVER_TIERS),
+ ),
"tier",
)
return cast(ServerTier, tier)
def api_server_cmd(
- host: str = typer.Option("127.0.0.1", "--host", help="Server host"),
- port: int = typer.Option(8000, "--port", help="Server port"),
- upload_dir: str = typer.Option("", "--upload-dir", help="Upload directory"),
+ host: str = typer.Option("127.0.0.1", "--host", help=t("Server host")),
+ port: int = typer.Option(8000, "--port", help=t("Server port")),
+ upload_dir: str = typer.Option("", "--upload-dir", help=t("Upload directory")),
tier: str | None = typer.Option(
None,
"--tier",
- help="Server capability tier: flash, basic, or standard",
+ help=t("Server capability tier: flash, basic, or standard"),
),
- no_flash: bool = typer.Option(False, "--no-flash", help="Disable Flash tier advertisement and execution"),
- no_advanced: bool = typer.Option(False, "--no-advanced", help="Disable Advanced tier advertisement and execution"),
- concurrency: int = typer.Option(1, "--concurrency", help="Maximum concurrent parse jobs"),
- url_timeout: int = typer.Option(60, "--url-timeout", help="Timeout for URL source downloads"),
- allow_local_source: bool = typer.Option(False, "--allow-local-source", help="Allow local source paths"),
- max_inline_bytes: int = typer.Option(1024 * 1024, "--max-inline-bytes", help="Maximum decoded bytes for inline sources"),
- allow_http_source: bool = typer.Option(False, "--allow-http-source", help="Allow URL sources to use plain HTTP"),
+ no_flash: bool = typer.Option(False, "--no-flash", help=t("Disable Flash tier advertisement and execution")),
+ no_advanced: bool = typer.Option(False, "--no-advanced", help=t("Disable Advanced tier advertisement and execution")),
+ concurrency: int = typer.Option(1, "--concurrency", help=t("Maximum concurrent parse jobs")),
+ url_timeout: int = typer.Option(60, "--url-timeout", help=t("Timeout for URL source downloads")),
+ allow_local_source: bool = typer.Option(False, "--allow-local-source", help=t("Allow local source paths")),
+ max_inline_bytes: int = typer.Option(1024 * 1024, "--max-inline-bytes", help=t("Maximum decoded bytes for inline sources")),
+ allow_http_source: bool = typer.Option(False, "--allow-http-source", help=t("Allow URL sources to use plain HTTP")),
language: str = typer.Option(
"ch",
"--language",
- help="Hybrid medium OCR language hint; accepted by other efforts for compatibility",
+ help=t("Hybrid medium OCR language hint; accepted by other efforts for compatibility"),
),
- disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help="Disable image analysis"),
+ disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help=t("Disable image analysis")),
preload_models: bool = typer.Option(
- False, "--preload-models", help="Initialize VLM client and local Hybrid models at startup"
+ False, "--preload-models", help=t("Initialize VLM client and local Hybrid models at startup")
),
- api_key: str | None = typer.Option(None, "--api-key", help="Optional fixed API key"),
- vlm_server_url: str | None = typer.Option(None, "--vlm-server-url", help="Remote VLM URL; empty value selects local VLM"),
- vlm_api_key: str | None = typer.Option(None, "--vlm-api-key", help="Bearer key for the remote VLM server"),
- vlm_model: str | None = typer.Option(None, "--vlm-model", help="Remote VLM model name; empty value enables discovery"),
+ api_key: str | None = typer.Option(None, "--api-key", help=t("Optional fixed API key")),
+ vlm_server_url: str | None = typer.Option(
+ None, "--vlm-server-url", help=t("Remote VLM URL; empty value selects local VLM")
+ ),
+ vlm_api_key: str | None = typer.Option(None, "--vlm-api-key", help=t("Bearer key for the remote VLM server")),
+ vlm_model: str | None = typer.Option(None, "--vlm-model", help=t("Remote VLM model name; empty value enables discovery")),
vlm_http_timeout: int | None = typer.Option(
- None, "--vlm-http-timeout", min=1, help="VLM HTTP timeout in seconds (default: 600)"
+ None, "--vlm-http-timeout", min=1, help=t("VLM HTTP timeout in seconds (default: 600)")
),
vlm_max_concurrency: int | None = typer.Option(
- None, "--vlm-max-concurrency", min=1, help="VLM inference concurrency (default: 100)"
+ None, "--vlm-max-concurrency", min=1, help=t("VLM inference concurrency (default: 100)")
),
log_level: str | None = typer.Option(
None,
"--log-level",
- help=(
- "API service log level: critical, error, warning, info, debug, trace; "
- "default: global log.level. Also filters the Loguru default model-log sink"
+ help=t(
+ "API service log level: critical, error, warning, info, debug, trace; default: global log.level. "
+ "Also filters the Loguru default model-log sink"
),
),
) -> None:
@@ -130,7 +137,11 @@ def main() -> None:
"""配置标准流后,以独立命令运行新版 API 服务入口。"""
configure_standard_streams()
configure_global_log_level()
- typer.run(api_server_cmd)
+ app = typer.Typer(add_completion=False)
+ app.command(help=t("Forward explicit startup options and launch the self-hosted MinerU parsing API service."))(
+ api_server_cmd
+ )
+ app()
__all__ = ["API_SERVER_LANGUAGES", "api_server_cmd", "main"]
diff --git a/mineru/kit/commands/models.py b/mineru/kit/commands/models.py
index 5de990cb..61a36f3d 100644
--- a/mineru/kit/commands/models.py
+++ b/mineru/kit/commands/models.py
@@ -22,12 +22,13 @@ from ...model.registry import (
from ...model.runtime.device import resolve_small_model_backend
from ...model.vlm.selector import resolve_vlm_engine
from ...types import DEPLOYMENT_TIERS
+from ...utils.i18n import t
from ...utils.logger import configure_global_log_level
from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
from ..output import print_info, print_success
-app = typer.Typer(help="Download, inspect, and verify local MinerU models.", no_args_is_help=True)
+app = typer.Typer(help=t("Download, inspect, and verify local MinerU models."), no_args_is_help=True)
def _validate_download_source(source: str | None) -> str | None:
@@ -37,7 +38,11 @@ def _validate_download_source(source: str | None) -> str | None:
normalized = source.strip().lower()
if normalized not in DOWNLOAD_MODEL_SOURCES:
expected = ", ".join(DOWNLOAD_MODEL_SOURCES)
- exit_with_message("invalid_request", f"Unsupported source '{source}'. Expected one of: {expected}.", "source")
+ exit_with_message(
+ "invalid_request",
+ t("Unsupported source '{source}'. Expected one of: {expected}.", source=source, expected=expected),
+ "source",
+ )
return normalized
@@ -50,9 +55,9 @@ def _select_target_repos(
) -> tuple[ModelRepo, ...]:
"""选择显式仓库或按独立后端组合档位资源。"""
if repo_name and tier:
- exit_with_message("invalid_request", "Pass either a model repo name or --tier, not both.")
+ exit_with_message("invalid_request", t("Pass either a model repo name or --tier, not both."))
if not repo_name and tier is None:
- exit_with_message("invalid_request", "Pass a model repo name or --tier.")
+ exit_with_message("invalid_request", t("Pass a model repo name or --tier."))
if tier is not None:
try:
@@ -73,26 +78,26 @@ def _select_target_repos(
def _format_repo_status(repo: ModelRepo) -> str:
"""格式化仓库的本地就绪状态。"""
result = verify_model_repo(repo)
- status = "ready" if result.ready else "missing"
+ status = t("ready") if result.ready else t("missing")
return f"{repo.name}: {status} ({repo.local_dir()})"
[email protected]("download")
[email protected]("download", help=t("Download an explicit repo or the tier resources required by the current backend combination."))
def download_cmd(
- repo: str | None = typer.Argument(None, help="Model repo: MinerU-4_models_torch, MinerU-4_models_onnx, or a VLM repo"),
- tier: str | None = typer.Option(None, "--tier", help="Model tier to prepare: basic or standard"),
+ repo: str | None = typer.Argument(None, help=t("Model repo: MinerU-4_models_torch, MinerU-4_models_onnx, or a VLM repo")),
+ tier: str | None = typer.Option(None, "--tier", help=t("Model tier to prepare: basic or standard")),
small_backend: str | None = typer.Option(
None,
"--small-backend",
- help="Small model backend: auto, onnx, torch. Ignored when REPO is given.",
+ help=t("Small model backend: auto, onnx, torch. Ignored when REPO is given."),
),
vlm_engine: str | None = typer.Option(
None,
"--vlm-engine",
- help="Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given.",
+ help=t("Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given."),
),
- source: str | None = typer.Option(None, "--source", "-s", help="Model source: auto, huggingface, or modelscope"),
- verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
+ source: str | None = typer.Option(None, "--source", "-s", help=t("Model source: auto, huggingface, or modelscope")),
+ verbose: bool = typer.Option(False, "--verbose", "-v", help=t("Verbose output")),
) -> None:
"""下载显式仓库或当前后端组合所需的档位资源。"""
normalized_source = _validate_download_source(source)
@@ -102,25 +107,25 @@ def download_cmd(
try:
root = download_model_repo(target_repo, source=normalized_source, local_as_auto=True)
except Exception as exc:
- exit_with_message("api_error", f"Failed to download {target_repo.name}: {exc}")
+ exit_with_message("api_error", t("Failed to download {repo}: {error}", repo=target_repo.name, error=exc))
if verbose:
print_info(f"{target_repo.name}: {root}")
- label = f"tier {tier}" if tier is not None else repos[0].name
- print_success(f"Downloaded models for {label}.")
+ label = t("tier {tier}", tier=tier) if tier is not None else repos[0].name
+ print_success(t("Downloaded models for {label}.", label=label))
[email protected]("show", help=t("Show configuration sources, effective backends, and tier resources."))
def show_cmd(
small_backend: str | None = typer.Option(
None,
"--small-backend",
- help="Small model backend: auto, onnx, torch. Ignored when REPO is given.",
+ help=t("Small model backend: auto, onnx, torch. Ignored when REPO is given."),
),
vlm_engine: str | None = typer.Option(
None,
"--vlm-engine",
- help="Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given.",
+ help=t("Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given."),
),
) -> None:
"""显示配置来源、有效后端与档位资源。"""
@@ -134,8 +139,8 @@ def show_cmd(
config_file = get_config_file_path()
lines = [
- f"Config: {config_file}",
- f"Config exists: {str(get_config_file_exists()).lower()}",
+ t("Config: {path}", path=config_file),
+ t("Config exists: {value}", value=str(get_config_file_exists()).lower()),
f"MINERU_MODEL_SOURCE={os.getenv(MODEL_SOURCE_ENV_VAR, '') or '(unset)'}",
f"model.base_dir: {config.model.base_dir}",
f"model.base_dir.source: {get_config_source('model.base_dir')}",
@@ -145,9 +150,9 @@ def show_cmd(
f"model.small_backend.source: {get_config_source('model.small_backend')}",
f"model.vlm.engine: {config.model.vlm.engine}",
f"model.vlm.engine.source: {get_config_source('model.vlm.engine')}",
- f"Effective small backend: {effective_small_backend}",
- f"Effective VLM engine: {effective_vlm_engine}",
- "Repos:",
+ t("Effective small backend: {backend}", backend=effective_small_backend),
+ t("Effective VLM engine: {engine}", engine=effective_vlm_engine),
+ t("Repos:"),
]
for line in lines:
print_info(line)
@@ -155,26 +160,26 @@ def show_cmd(
for repo in MODEL_REPOS:
print_info(f" {_format_repo_status(repo)}")
- print_info("Model tiers:")
+ print_info(t("Model tiers:"))
for tier in DEPLOYMENT_TIERS:
repos = model_repos_for_tier(tier, small_backend=effective_small_backend, vlm_engine=vlm_engine)
- names = ", ".join(repo.name for repo in repos) or "(none)"
+ names = ", ".join(repo.name for repo in repos) or t("(none)")
print_info(f" {tier}: {names}")
[email protected]("verify", help=t("Verify local resources for an explicit repo or the current backend combination."))
def verify_cmd(
- repo: str | None = typer.Argument(None, help="Optional model repo name"),
- tier: str | None = typer.Option(None, "--tier", help="Optional model tier: basic or standard"),
+ repo: str | None = typer.Argument(None, help=t("Optional model repo name")),
+ tier: str | None = typer.Option(None, "--tier", help=t("Optional model tier: basic or standard")),
small_backend: str | None = typer.Option(
None,
"--small-backend",
- help="Small model backend: auto, onnx, torch. Ignored when REPO is given.",
+ help=t("Small model backend: auto, onnx, torch. Ignored when REPO is given."),
),
vlm_engine: str | None = typer.Option(
None,
"--vlm-engine",
- help="Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given.",
+ help=t("Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given."),
),
) -> None:
"""校验显式仓库或当前后端组合所需的本地资源。"""
@@ -190,11 +195,11 @@ def verify_cmd(
for target_repo in repos:
result = verify_model_repo(target_repo)
if result.ready:
- print_success(f"{target_repo.name}: ok")
+ print_success(t("{repo}: ok", repo=target_repo.name))
continue
failures += 1
missing = ", ".join(result.missing_paths)
- print_info(f"{target_repo.name}: missing key paths: {missing}")
+ print_info(t("{repo}: missing key paths: {missing}", repo=target_repo.name, missing=missing))
if failures:
raise typer.Exit(1)
@@ -204,7 +209,11 @@ def download_main() -> None:
"""配置标准流后直接运行模型下载命令,无需再输入 download 子命令。"""
configure_standard_streams()
configure_global_log_level()
- typer.run(download_cmd)
+ app = typer.Typer(add_completion=False)
+ app.command(help=t("Download an explicit repo or the tier resources required by the current backend combination."))(
+ download_cmd
+ )
+ app()
__all__ = ["app", "download_cmd", "download_main", "show_cmd", "verify_cmd", "model_repo_names"]
diff --git a/mineru/kit/commands/parse.py b/mineru/kit/commands/parse.py
index 34731d7c..6e2a0688 100644
--- a/mineru/kit/commands/parse.py
+++ b/mineru/kit/commands/parse.py
@@ -14,6 +14,7 @@ from ...parser.api_client import _V1APIError
from ...parser.page_range import normalize_page_range_input
from ...parser.tier import normalize_backend
from ...types import Tier
+from ...utils.i18n import t
from ..common import (
build_remote_api_url,
effective_local_tier_and_backend,
@@ -28,23 +29,23 @@ from ..output import print_info, print_success
def parse_cmd(
- inputs: list[str] = typer.Argument(..., help="Input files or directories"),
- output: str = typer.Option(..., "-o", "--output", help="Output path; required"),
- pages: str | None = typer.Option(None, "-p", "--pages", help="PDF pages: '1-5,8,r3-r1' or 'all'; default: all pages"),
+ inputs: list[str] = typer.Argument(..., help=t("Input files or directories")),
+ output: str = typer.Option(..., "-o", "--output", help=t("Output path; required")),
+ pages: str | None = typer.Option(None, "-p", "--pages", help=t("PDF pages: '1-5,8,r3-r1' or 'all'; default: all pages")),
format: str = typer.Option(
"markdown",
"-f",
"--format",
- help="Output format: markdown, middle_json, zip",
+ help=t("Output format: markdown, middle_json, zip"),
),
- verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),
- tier: str | None = typer.Option(None, "--tier", help="Parse tier: flash, basic, standard, advanced"),
- backend: str | None = typer.Option(None, "--backend", help="Expert backend override"),
- remote: bool = typer.Option(False, "--remote", help="Use mineru.net official remote parse service"),
- remote_url: str | None = typer.Option(None, "--remote-url", help="Use a custom remote parse service URL"),
- api_key: str | None = typer.Option(None, "--api-key", help="API key for remote parse service"),
- ocr_mode: str = typer.Option("auto", "--ocr-mode", help="OCR mode: auto, txt, ocr"),
- disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help="Disable image analysis"),
+ verbose: bool = typer.Option(False, "-v", "--verbose", help=t("Verbose output")),
+ tier: str | None = typer.Option(None, "--tier", help=t("Parse tier: flash, basic, standard, advanced")),
+ backend: str | None = typer.Option(None, "--backend", help=t("Expert backend override")),
+ remote: bool = typer.Option(False, "--remote", help=t("Use mineru.net official remote parse service")),
+ remote_url: str | None = typer.Option(None, "--remote-url", help=t("Use a custom remote parse service URL")),
+ api_key: str | None = typer.Option(None, "--api-key", help=t("API key for remote parse service")),
+ ocr_mode: str = typer.Option("auto", "--ocr-mode", help=t("OCR mode: auto, txt, ocr")),
+ disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help=t("Disable image analysis")),
) -> None:
"""Parse files or directories into markdown, middle JSON, or zip outputs."""
try:
@@ -55,22 +56,22 @@ def parse_cmd(
parse_tier = cast(Tier | None, tier)
parse_ocr_mode = cast(Literal["auto", "txt", "ocr"], ocr_mode)
if not inputs:
- exit_with_message("invalid_request", "At least one input path is required.", "inputs")
+ exit_with_message("invalid_request", t("At least one input path is required."), "inputs")
if remote and backend is not None:
- exit_with_message("invalid_request", "--backend is not allowed in remote mode.", "backend")
+ exit_with_message("invalid_request", t("--backend is not allowed in remote mode."), "backend")
api_url = build_remote_api_url(remote, remote_url)
raw_paths = [Path(raw).expanduser() for raw in inputs]
if any(path.is_dir() for path in raw_paths) and Path(output).expanduser().suffix:
exit_with_message(
"invalid_request",
- "When input is multiple files or directories, --output must be a directory path.",
+ t("When input is multiple files or directories, --output must be a directory path."),
"output",
)
has_directory_input = any(path.is_dir() for path in raw_paths)
if len(raw_paths) > 1 and Path(output).expanduser().suffix:
exit_with_message(
"invalid_request",
- "When input is multiple files or directories, --output must be a directory path.",
+ t("When input is multiple files or directories, --output must be a directory path."),
"output",
)
paths = expand_input_paths(inputs)
@@ -117,5 +118,5 @@ def parse_cmd(
except (MineruError, _V1APIError) as exc:
exit_with_message(exc.code, str(exc), exc.param)
except Exception as exc:
- exit_with_message("parse_failed", f"Failed to parse {path}: {exc}")
- print_success(f"Parsed {len(paths)} input(s).")
+ exit_with_message("parse_failed", t("Failed to parse {path}: {error}", path=path, error=exc))
+ print_success(t("Parsed {count} input(s).", count=len(paths)))
diff --git a/mineru/kit/commands/vlm_server.py b/mineru/kit/commands/vlm_server.py
index 684a4c6b..56c6327e 100644
--- a/mineru/kit/commands/vlm_server.py
+++ b/mineru/kit/commands/vlm_server.py
@@ -12,6 +12,7 @@ import typer
from loguru import logger
from ...model.runtime.platform import is_mac_os_version_supported
+from ...utils.i18n import t
from ...utils.logger import configure_global_log_level
from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
@@ -33,17 +34,20 @@ def _module_available(module_name: str) -> bool:
def _mlx_server_error() -> str | None:
"""检查平台与发布版本,不导入 MLX 重依赖。"""
if platform.system() != "Darwin" or platform.machine() != "arm64" or not is_mac_os_version_supported("14.0"):
- return "MLX server requires Apple Silicon and macOS 14 or newer."
+ return t("MLX server requires Apple Silicon and macOS 14 or newer.")
try:
from packaging.version import Version
version = Version(importlib.metadata.version("mlx-vlm"))
if not Version("0.7.0") <= version < Version("0.8.0"):
- return f"MLX server requires mlx-vlm>=0.7.0,<0.8.0; installed: {version}. Install 'mlx-vlm>=0.7.0,<0.8.0'."
+ return t(
+ "MLX server requires mlx-vlm>=0.7.0,<0.8.0; installed: {version}. Install 'mlx-vlm>=0.7.0,<0.8.0'.",
+ version=version,
+ )
if importlib.util.find_spec("mlx_vlm.server") is None:
- return "mlx_vlm.server is unavailable. Install 'mlx-vlm>=0.7.0,<0.8.0'."
+ return t("mlx_vlm.server is unavailable. Install 'mlx-vlm>=0.7.0,<0.8.0'.")
except (importlib.metadata.PackageNotFoundError, ModuleNotFoundError):
- return "MLX-VLM is not installed. Install 'mlx-vlm>=0.7.0,<0.8.0'."
+ return t("MLX-VLM is not installed. Install 'mlx-vlm>=0.7.0,<0.8.0'.")
return None
@@ -67,22 +71,22 @@ def _run_with_forwarded_argv(main_fn: Callable[[], None], args: list[str]) -> No
def _resolve_auto_engine() -> Literal["vllm", "lmdeploy"]:
"""自动服务仅选择 vLLM 或 LMDeploy,MLX 必须显式指定。"""
if _module_available("vllm"):
- logger.info("Using vLLM as the inference engine for VLM server.")
+ logger.info(t("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.")
+ logger.info(t("Using LMDeploy as the inference engine for VLM server."))
return "lmdeploy"
- logger.info("No automatic VLM server engine is installed. Install vLLM/LMDeploy or explicitly choose --engine mlx.")
+ logger.info(t("No automatic VLM server engine is installed. Install vLLM/LMDeploy or explicitly choose --engine mlx."))
raise typer.Exit(1) from None
def vlm_server_cmd(
ctx: typer.Context,
- engine: str = typer.Option("auto", "--engine", help="VLM serving engine: auto, vllm, lmdeploy, mlx"),
+ engine: str = typer.Option("auto", "--engine", help=t("VLM serving engine: auto, vllm, lmdeploy, mlx")),
) -> None:
"""Start the local VLM server with OpenAI-compatible chat completions."""
if engine not in {"auto", "vllm", "lmdeploy", "mlx"}:
- exit_with_message("invalid_request", f"Unsupported engine '{engine}'.", "engine")
+ exit_with_message("invalid_request", t("Unsupported engine '{engine}'.", engine=engine), "engine")
extra_args = list(ctx.args)
if engine == "auto":
@@ -90,7 +94,7 @@ def vlm_server_cmd(
if engine == "vllm":
if not _module_available("vllm"):
- logger.error("vLLM is not installed. Please install vLLM or choose lmdeploy/mlx as the engine.")
+ logger.error(t("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
@@ -98,7 +102,7 @@ def vlm_server_cmd(
elif engine == "lmdeploy":
if not _module_available("lmdeploy"):
- logger.error("LMDeploy is not installed. Please install LMDeploy or choose vllm/mlx as the engine.")
+ logger.error(t("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
@@ -106,7 +110,7 @@ def vlm_server_cmd(
elif engine == "mlx":
if not _mlx_server_available():
- logger.error(_mlx_server_error() or "MLX server is unavailable.")
+ logger.error(_mlx_server_error() or t("MLX server is unavailable."))
raise typer.Exit(1) from None
from ..vlm_server import mlx_vlm_server
@@ -122,7 +126,10 @@ def main() -> None:
configure_standard_streams()
configure_global_log_level()
app = typer.Typer(add_completion=False)
- app.command(context_settings=FORWARD_CONTEXT_SETTINGS)(vlm_server_cmd)
+ app.command(
+ context_settings=FORWARD_CONTEXT_SETTINGS,
+ help=t("Start the local VLM server with OpenAI-compatible chat completions."),
+ )(vlm_server_cmd)
app()
diff --git a/mineru/kit/commands/webui.py b/mineru/kit/commands/webui.py
index 96b4754d..ea110dcf 100644
--- a/mineru/kit/commands/webui.py
+++ b/mineru/kit/commands/webui.py
@@ -12,6 +12,7 @@ from packaging.specifiers import SpecifierSet
from ...model.ocr.language import validate_public_ocr_lang
from ...types import SERVER_TIERS, ServerTier
+from ...utils.i18n import t
from ...utils.logger import configure_global_log_level
from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
@@ -22,12 +23,12 @@ def _require_gradio_dependencies() -> None:
if importlib.util.find_spec("gradio") is None:
exit_with_message(
"dependency_missing",
- "Gradio is a base dependency; repair the installation with `pip install 'mineru'`.",
+ t("Gradio is a base dependency; repair the installation with `pip install 'mineru'`."),
)
if version("gradio") not in SpecifierSet(">=6.8,<7"):
exit_with_message(
"dependency_incompatible",
- "Gradio >=6.8,<7 is required; upgrade with `pip install --upgrade 'mineru'`.",
+ t("Gradio >=6.8,<7 is required; upgrade with `pip install --upgrade 'mineru'`."),
)
@@ -36,7 +37,11 @@ def _validate_server_tier(value: str) -> ServerTier:
if value not in SERVER_TIERS:
exit_with_message(
"invalid_request",
- f"Unsupported API server tier '{value}'. Supported tiers: {', '.join(SERVER_TIERS)}",
+ t(
+ "Unsupported API server tier '{tier}'. Supported tiers: {tiers}",
+ tier=value,
+ tiers=", ".join(SERVER_TIERS),
+ ),
"api_server_tier",
)
return value # type: ignore[return-value]
@@ -45,45 +50,47 @@ def _validate_server_tier(value: str) -> ServerTier:
def _validate_positive_option(value: int, *, name: str) -> int:
"""校验本地托管服务使用的正整数参数。"""
if value <= 0:
- exit_with_message("invalid_request", f"{name} must be greater than zero", name)
+ exit_with_message("invalid_request", t("{name} must be greater than zero", name=name), name)
return value
def _validate_server_port(value: int) -> int:
"""校验 Gradio 监听端口处于 TCP 有效范围。"""
if value < 1 or value > 65535:
- exit_with_message("invalid_request", "server_port must be between 1 and 65535", "server_port")
+ exit_with_message("invalid_request", t("server_port must be between 1 and 65535"), "server_port")
return value
def webui_cmd(
- api_url: str | None = typer.Option(None, "--api-url", help="External MinerU V1 API base URL"),
- api_key: str | None = typer.Option(None, "--api-key", help="Bearer API key; falls back to MINERU_API_KEY"),
- server_name: str = typer.Option("127.0.0.1", "--server-name", help="Web UI bind host"),
+ api_url: str | None = typer.Option(None, "--api-url", help=t("External MinerU V1 API base URL")),
+ api_key: str | None = typer.Option(None, "--api-key", help=t("Bearer API key; falls back to MINERU_API_KEY")),
+ server_name: str = typer.Option("127.0.0.1", "--server-name", help=t("Web UI bind host")),
server_port: int | None = typer.Option(
- None, "--server-port", help="Web UI bind port; omitted: auto-select from 7860 or GRADIO_SERVER_PORT"
+ None, "--server-port", help=t("Web UI bind port; omitted: auto-select from 7860 or GRADIO_SERVER_PORT")
),
- output_dir: str = typer.Option("./output", "--output-dir", help="Directory for Web UI artifacts"),
+ output_dir: str = typer.Option("./output", "--output-dir", help=t("Directory for Web UI artifacts")),
max_pages: int | None = typer.Option(
- None, "--max-pages", help="Maximum pages per non-Flash PDF conversion; omitted: unlimited"
+ None, "--max-pages", help=t("Maximum pages per non-Flash PDF conversion; omitted: unlimited")
),
- enable_example: bool = typer.Option(True, "--enable-example/--no-enable-example", help="Show local examples"),
- enable_api: bool = typer.Option(True, "--enable-api/--no-enable-api", help="Expose the Gradio event API"),
+ enable_example: bool = typer.Option(True, "--enable-example/--no-enable-example", help=t("Show local examples")),
+ enable_api: bool = typer.Option(True, "--enable-api/--no-enable-api", help=t("Expose the Gradio event API")),
latex_delimiters_type: Literal["a", "b", "all"] = typer.Option(
- "all", "--latex-delimiters-type", help="LaTeX delimiters used by the Markdown preview"
+ "all", "--latex-delimiters-type", help=t("LaTeX delimiters used by the Markdown preview")
+ ),
+ api_server_tier: str = typer.Option(
+ "standard", "--api-server-tier", "--tier", help=t("Managed API server capability tier")
),
- api_server_tier: str = typer.Option("standard", "--api-server-tier", "--tier", help="Managed API server capability tier"),
api_server_concurrency: int = typer.Option(
- 1, "--api-server-concurrency", "--concurrency", help="Managed server job concurrency"
+ 1, "--api-server-concurrency", "--concurrency", help=t("Managed server job concurrency")
),
- api_server_language: str = typer.Option("ch", "--api-server-language", "--language", help="Managed server OCR language"),
+ api_server_language: str = typer.Option("ch", "--api-server-language", "--language", help=t("Managed server OCR language")),
api_server_disable_image_analysis: bool = typer.Option(
False,
"--api-server-disable-image-analysis/--disable-image-analysis",
- help="Disable managed server image analysis",
+ help=t("Disable managed server image analysis"),
),
api_server_preload_models: bool = typer.Option(
- False, "--api-server-preload-models/--preload-models", help="Preload managed server models"
+ False, "--api-server-preload-models/--preload-models", help=t("Preload managed server models")
),
) -> None:
"""启动基于 MinerU V1 API 的 Gradio 文档解析界面。"""
@@ -127,7 +134,9 @@ def main() -> None:
"""以独立 console script 运行Web UI 命令。"""
configure_standard_streams()
configure_global_log_level()
- typer.run(webui_cmd)
+ app = typer.Typer(add_completion=False)
+ app.command(help=t("Start the Gradio document parsing web UI backed by the MinerU V1 API."))(webui_cmd)
+ app()
__all__ = ["webui_cmd", "main"]
diff --git a/mineru/kit/common.py b/mineru/kit/common.py
index 19838993..577f80f5 100644
--- a/mineru/kit/common.py
+++ b/mineru/kit/common.py
@@ -10,6 +10,7 @@ from ..filetypes import PARSEABLE_EXTENSIONS
from ..parser.base import ParseResult
from ..parser.writer import FileBasedDataWriter
from ..types import Tier
+from ..utils.i18n import t
KitFormat = Literal["markdown", "middle_json", "zip"]
LocalTier: TypeAlias = Tier
@@ -38,14 +39,14 @@ def expand_input_paths(inputs: list[str]) -> list[Path]:
def ensure_supported_inputs(paths: list[Path]) -> None:
if not paths:
- raise ValueError("No input files found.")
+ raise ValueError(t("No input files found."))
for path in paths:
if not path.exists():
raise FileNotFoundError(path)
if path.is_dir():
- raise ValueError(f"Directory input must be expanded before validation: {path}")
+ raise ValueError(t("Directory input must be expanded before validation: {path}", path=path))
if path.suffix.lower() not in PARSEABLE_SUFFIXES:
- raise ValueError(f"Unsupported file type: {path}")
+ raise ValueError(t("Unsupported file type: {path}", path=path))
def is_output_path_file_like(path: Path) -> bool:
@@ -64,16 +65,16 @@ def resolve_single_output_path(source: Path, output: Path, format: KitFormat) ->
def resolve_batch_output_paths(paths: list[Path], output: Path, format: KitFormat) -> dict[Path, Path]:
if any(path.parent == path for path in paths):
- raise ValueError("Invalid input path.")
+ raise ValueError(t("Invalid input path."))
multi_input = len(paths) > 1
has_directory_input = False
if multi_input or has_directory_input:
if is_output_path_file_like(output):
- raise ValueError("When input is multiple files or directories, --output must be a directory path.")
+ raise ValueError(t("When input is multiple files or directories, --output must be a directory path."))
output_dir = output
if output.exists() and output.is_file():
- raise ValueError("When input is multiple files or directories, --output must be a directory path.")
+ raise ValueError(t("When input is multiple files or directories, --output must be a directory path."))
destinations: dict[Path, Path] = {}
seen: dict[Path, Path] = {}
@@ -85,7 +86,14 @@ def resolve_batch_output_paths(paths: list[Path], output: Path, format: KitForma
)
existing = seen.get(dest)
if existing is not None:
- raise ValueError(f"Output name collision: {existing.name} and {source.name} both map to {dest}")
+ raise ValueError(
+ t(
+ "Output name collision: {existing} and {source} both map to {dest}",
+ existing=existing.name,
+ source=source.name,
+ dest=dest,
+ )
+ )
seen[dest] = source
destinations[source] = dest
return destinations
@@ -104,7 +112,7 @@ def effective_local_tier_and_backend(tier: Tier | None, backend: str | None) ->
def build_remote_api_url(remote: bool, remote_url: str | None) -> str | None:
if remote and remote_url:
- raise ValueError("--remote and --remote-url are mutually exclusive.")
+ raise ValueError(t("--remote and --remote-url are mutually exclusive."))
if remote_url:
return remote_url
if remote:
@@ -136,7 +144,7 @@ def save_parse_result(result: ParseResult, dest: Path, format: KitFormat) -> Non
if tmp_dir.exists():
tmp_dir.rmdir()
return
- raise ValueError(f"Unsupported format: {format}")
+ raise ValueError(t("Unsupported format: {format}", format=format))
def _write_utf8_text(path: Path, content: str) -> None:
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index 7aa1ba04..fcb5918e 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -7,6 +7,7 @@ from click.core import Context
from typer.core import TyperGroup
from ..cli.version_command import show_version, version_cmd
+from ..utils.i18n import t
from ..utils.logger import configure_global_log_level
from ..utils.stdio import configure_standard_streams
from .commands import api_server, models, parse, router, vlm_server, webui
@@ -31,7 +32,7 @@ class OrderedRootGroup(TyperGroup):
app = typer.Typer(
name="mineru-kit",
cls=OrderedRootGroup,
- help="MinerU Kit — parsing and service tools",
+ help=t("MinerU Kit — parsing and service tools"),
no_args_is_help=True,
add_completion=False,
)
@@ -44,19 +45,25 @@ def root(
"--version",
callback=show_version,
is_eager=True,
- help="Show the version and exit.",
+ help=t("Show the version and exit."),
),
) -> None:
pass
app.add_typer(models.app, name="models")
-app.command("parse")(parse.parse_cmd)
-app.command("webui")(webui.webui_cmd)
-app.command("api-server")(api_server.api_server_cmd)
-app.command("vlm-server", context_settings=vlm_server.FORWARD_CONTEXT_SETTINGS)(vlm_server.vlm_server_cmd)
-app.command("router")(router.router_cmd)
-app.command("version")(version_cmd)
+app.command("parse", help=t("Parse files or directories into markdown, middle JSON, or zip outputs."))(parse.parse_cmd)
+app.command("webui", help=t("Start the Gradio document parsing web UI backed by the MinerU V1 API."))(webui.webui_cmd)
+app.command("api-server", help=t("Forward explicit startup options and launch the self-hosted MinerU parsing API service."))(
+ api_server.api_server_cmd
+)
+app.command(
+ "vlm-server",
+ context_settings=vlm_server.FORWARD_CONTEXT_SETTINGS,
+ help=t("Start the local VLM server with OpenAI-compatible chat completions."),
+)(vlm_server.vlm_server_cmd)
+app.command("router", help=t("Start a standalone Router service exposing only the MinerU V1 API."))(router.router_cmd)
+app.command("version", help=t("Print MinerU and Python versions."))(version_cmd)
def main() -> None:
diff --git a/mineru/kit/router/cli.py b/mineru/kit/router/cli.py
index c5ea92af..335ce6f4 100644
--- a/mineru/kit/router/cli.py
+++ b/mineru/kit/router/cli.py
@@ -9,6 +9,7 @@ import typer
import uvicorn
from ...types import SERVER_TIERS, ServerTier
+from ...utils.i18n import t
from ...utils.logger import configure_global_log_level
from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
@@ -17,25 +18,29 @@ from .workers import RouterSettings
def router_cmd(
- host: str = typer.Option("127.0.0.1", "--host", help="Server host"),
- port: int = typer.Option(8002, "--port", help="Server port"),
- reload: bool = typer.Option(False, "--reload", help="Enable auto-reload"),
+ host: str = typer.Option("127.0.0.1", "--host", help=t("Server host")),
+ port: int = typer.Option(8002, "--port", help=t("Server port")),
+ reload: bool = typer.Option(False, "--reload", help=t("Enable auto-reload")),
upstream_url: list[str] | None = typer.Option(
None,
"--upstream-url",
- help="Existing MinerU V1 API base URL; repeat to add upstreams",
+ help=t("Existing MinerU V1 API base URL; repeat to add upstreams"),
),
- local_gpus: str = typer.Option("auto", "--local-gpus", help="Local workers: auto, none, or GPU CSV"),
- worker_host: str = typer.Option("127.0.0.1", "--worker-host", help="Host for managed api-server workers"),
- worker_tier: str = typer.Option("standard", "--worker-tier", help="Managed worker tier: flash, basic, standard"),
- worker_concurrency: int = typer.Option(1, "--worker-concurrency", help="Concurrency per managed worker"),
- preload_models: bool = typer.Option(False, "--preload-models", help="Preload models in managed workers"),
+ local_gpus: str = typer.Option("auto", "--local-gpus", help=t("Local workers: auto, none, or GPU CSV")),
+ worker_host: str = typer.Option("127.0.0.1", "--worker-host", help=t("Host for managed api-server workers")),
+ worker_tier: str = typer.Option("standard", "--worker-tier", help=t("Managed worker tier: flash, basic, standard")),
+ worker_concurrency: int = typer.Option(1, "--worker-concurrency", help=t("Concurrency per managed worker")),
+ preload_models: bool = typer.Option(False, "--preload-models", help=t("Preload models in managed workers")),
) -> None:
"""启动只暴露 MinerU V1 API 的独立 Router 服务。"""
if worker_tier not in SERVER_TIERS:
exit_with_message(
"invalid_request",
- f"Unsupported worker tier '{worker_tier}'. Supported tiers: {', '.join(SERVER_TIERS)}",
+ t(
+ "Unsupported worker tier '{tier}'. Supported tiers: {tiers}",
+ tier=worker_tier,
+ tiers=", ".join(SERVER_TIERS),
+ ),
"worker_tier",
)
try:
@@ -66,7 +71,9 @@ def main() -> None:
"""配置标准流后运行过渡 `mineru-router` 单命令入口。"""
configure_standard_streams()
configure_global_log_level()
- typer.run(router_cmd)
+ app = typer.Typer(add_completion=False)
+ app.command(help=t("Start a standalone Router service exposing only the MinerU V1 API."))(router_cmd)
+ app()
__all__ = ["main", "router_cmd"]
diff --git a/mineru/utils/i18n.py b/mineru/utils/i18n.py
new file mode 100644
index 00000000..9308200e
--- /dev/null
+++ b/mineru/utils/i18n.py
@@ -0,0 +1,80 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""CLI 双语文案:按系统语言自动选择英文或简体中文。
+
+英文原文即词条 key,漏译时回退英文原文,不会报错。语言在首次使用时
+通过环境变量检测并缓存;Typer 的 help 文案在装饰期求值,属于已知的
+只读查询例外(见 AGENTS.md 副作用隔离一节的实现取舍)。
+"""
+
+from __future__ import annotations
+
+import locale
+import os
+import sys
+from collections.abc import Mapping
+from typing import Any, Literal
+
+from .translations import ZH_MESSAGES
+
+Language = Literal["en", "zh"]
+
+# POSIX 语义:LC_ALL 覆盖 LC_MESSAGES 覆盖 LANG;MINERU_LANG 是产品级强制覆盖。
+LANGUAGE_ENV_VARS = ("MINERU_LANG", "LC_ALL", "LC_MESSAGES", "LANG")
+
+_cached_language: Language | None = None
+
+
+def _normalize_locale_code(raw: str) -> str:
+ code = raw.split("@", 1)[0].split(".", 1)[0]
+ return code.strip().lower().replace("-", "_")
+
+
+def _windows_default_language() -> str:
+ import ctypes
+
+ windll = getattr(ctypes, "windll", None)
+ if windll is None:
+ return ""
+ try:
+ lang_id = windll.kernel32.GetUserDefaultUILanguage()
+ except Exception: # noqa: BLE001 — Windows API 探测失败时静默回退英文
+ return ""
+ return locale.windows_locale.get(int(lang_id), "")
+
+
+def detect_language(env: Mapping[str, str] | None = None) -> Language:
+ """按 MINERU_LANG > LC_ALL > LC_MESSAGES > LANG 检测界面语言,纯函数。
+
+ 第一个非空变量即决定结果(``C``/``POSIX`` 也视为该层决定,结果为英文);
+ 全部未设置时 Windows 上回退到系统 UI 语言,其余平台为英文。
+ """
+ source: Mapping[str, str] = os.environ if env is None else env
+ for name in LANGUAGE_ENV_VARS:
+ raw = source.get(name, "").strip()
+ if not raw:
+ continue
+ if _normalize_locale_code(raw).startswith("zh"):
+ return "zh"
+ return "en"
+ if sys.platform == "win32" and env is None:
+ if _normalize_locale_code(_windows_default_language()).startswith("zh"):
+ return "zh"
+ return "en"
+
+
+def current_language() -> Language:
+ global _cached_language
+ if _cached_language is None:
+ _cached_language = detect_language()
+ return _cached_language
+
+
+def reset_language_cache() -> None:
+ global _cached_language
+ _cached_language = None
+
+
+def t(key: str, /, **fmt: Any) -> str:
+ """返回 key 的当前语言文案;未收录时原样返回英文 key,有 fmt 时做 format。"""
+ text = ZH_MESSAGES.get(key, key) if current_language() == "zh" else key
+ return text.format(**fmt) if fmt else text
diff --git a/mineru/utils/translations.py b/mineru/utils/translations.py
new file mode 100644
index 00000000..bcdd4287
--- /dev/null
+++ b/mineru/utils/translations.py
@@ -0,0 +1,586 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""CLI 双语词典:mineru 与 mineru-kit 的用户可见文案,英文原文 -> 简体中文。
+
+key 为英文原文(gettext 约定),调用点漏译时自动回退英文。含 ``{name}``
+占位符的词条,中文值必须保留同名占位符(test_cli_i18n.py 有占位符一致性守卫)。
+不收录:click/typer 脚手架词、JSON 字段名、`<!-- Next: ... -->` 等协议串。
+"""
+
+from __future__ import annotations
+
+ZH_MESSAGES: dict[str, str] = {
+ # ------------------------------------------------------------------ 共享
+ "JSON output": "JSON 输出",
+ "Verbose output": "详细输出",
+ "Max rows": "最大行数",
+ "Result offset": "结果偏移量",
+ "yes": "是",
+ "no": "否",
+ "Error:": "错误:",
+ "Output path; creates parent directories": "输出路径;自动创建父目录",
+ "Soft character limit for STDOUT content": "STDOUT 内容的软字符上限",
+ "File not found: {path}": "文件不存在: {path}",
+ "File or directory not found: {path}": "文件或目录不存在: {path}",
+ "Show the version and exit.": "显示版本并退出。",
+ "Print MinerU and Python versions.": "显示 MinerU 与 Python 版本。",
+ "MinerU version: {version}": "MinerU 版本: {version}",
+ "Python version: {version}": "Python 版本: {version}",
+ "Written to {path}": "已写入 {path}",
+ "No renderable content in requested pages.": "请求的页面中没有可渲染内容。",
+ "Parse tier: flash, basic, standard, advanced": "解析档位: flash、basic、standard、advanced",
+ "Scan failed: {code} {msg}": "扫描失败: {code} {msg}",
+ # ------------------------------------------------------------- mineru 根
+ "MinerU — your personal document center, built for agents": "MinerU — 你的个人文档中心,为 agent 而建",
+ "Parse a document file.": "解析一个文档文件。",
+ "Read parsed doclib content by locator.": "按定位符读取已解析的 doclib 内容。",
+ "Search parsed document content.": "搜索已解析的文档内容。",
+ "Search filenames only (not document content).": "仅搜索文件名(不搜索文档内容)。",
+ "Show Remote API usage and limits.": "显示 Remote API 用量与限额。",
+ "Mark done parse results as superseded.": "将已完成的解析结果标记为已作废。",
+ # ----------------------------------------------------------------- parse
+ "Path to the document file": "文档文件路径",
+ "Parse tier: flash, basic, standard, advanced (default: server decides)": (
+ "解析档位: flash、basic、standard、advanced(默认由服务端决定)"
+ ),
+ "PDF pages: '1-5,8,r3-r1' or 'all'; default: first 10 pages": "PDF 页码: '1-5,8,r3-r1' 或 'all';默认前 10 页",
+ "Continue reading after a content cursor": "从内容游标之后继续读取",
+ "Output format: markdown": "输出格式: markdown",
+ "Force re-parse, ignore cache": "强制重新解析,忽略缓存",
+ "Use remote parse-server": "使用远程 parse-server",
+ "Max seconds to wait for parse to complete": "等待解析完成的最长秒数",
+ "Don't wait — return immediately": "不等待,立即返回",
+ "Omit document structure markers from output": "输出中省略文档结构标记",
+ "Cache hit — returning cached result.": "命中缓存,返回缓存结果。",
+ "Parse queued (tier={tier}). Waiting up to {wait}s...": "解析已排队(tier={tier})。最多等待 {wait} 秒…",
+ " Parse status: {status}": " 解析状态: {status}",
+ "Parse failed.": "解析失败。",
+ "Parse did not finish within {seconds} seconds.": "解析未在 {seconds} 秒内完成。",
+ "Re-run the same command to continue waiting.": "重新运行同一命令可继续等待。",
+ "No content returned from parse.": "解析未返回内容。",
+ "Parse complete (tier={tier}) {tip}": "解析完成(tier={tier}) {tip}",
+ "Parse still in progress{elapsed} (tier={tier}).": "解析仍在进行中{elapsed}(tier={tier})。",
+ "after {seconds}s": "已等待 {seconds} 秒",
+ "Parse ID": "解析任务 ID",
+ "Parse IDs": "解析任务 ID",
+ "{label}: {ids}": "{label}: {ids}",
+ # ------------------------------------------------------------------ read
+ "Doclib locator, e.g. doc:ab12cd3/tier:basic/page:4": "doclib 定位符,如 doc:ab12cd3/tier:basic/page:4",
+ "Read N pages/blocks before and after the locator": "在定位符前后各读取 N 页/块",
+ "Output format: markdown, image": "输出格式: markdown、image",
+ "Omit continuation marker from output": "输出中省略续读标记",
+ "No image asset returned.": "未返回图片素材。",
+ "Image output requires a file path ending with .png, .jpg, .jpeg, or .webp; stdout is not supported.": (
+ "图片输出需要以 .png、.jpg、.jpeg 或 .webp 结尾的文件路径,不支持 stdout。"
+ ),
+ "Image output path must end with .png, .jpg, .jpeg, or .webp.": "图片输出路径必须以 .png、.jpg、.jpeg 或 .webp 结尾。",
+ # ------------------------------------------------------------------ scan
+ "File or directory path to scan": "要扫描的文件或目录路径",
+ "Max seconds to wait for scan completion": "等待扫描完成的最长秒数",
+ "Return immediately after creating the scan": "创建扫描任务后立即返回",
+ "Scan {id} {status}: seen={seen}, refreshed={refreshed}, new={new}, changed={changed}, deleted={deleted}, "
+ "unreachable={unreachable}, excluded={excluded}, unsupported={unsupported}": (
+ "扫描 {id} {status}: seen={seen}, refreshed={refreshed}, new={new}, changed={changed}, deleted={deleted}, "
+ "unreachable={unreachable}, excluded={excluded}, unsupported={unsupported}"
+ ),
+ # ----------------------------------------------------------------- watch
+ "Watch target management": "监视目标管理",
+ "Add a directory to watch.": "添加要监视的目录。",
+ "List watched directories.": "列出被监视的目录。",
+ "Remove a watched directory.": "移除一个被监视的目录。",
+ "Create a watch scan task for an existing watch target.": "为既有监视目标创建扫描任务。",
+ "Directory path to watch": "要监视的目录路径",
+ "Removable device": "可移动设备",
+ "Label for this watch": "此监视的标签",
+ "Watch id or exact watch root path to remove": "要移除的监视 id 或精确的监视根路径",
+ "Watch id or exact watch root path": "监视 id 或精确的监视根路径",
+ "Watch added: {path} (id={id})": "已添加监视: {path}(id={id})",
+ "No watches configured.": "未配置任何监视。",
+ "Watches": "监视列表",
+ "ID": "ID",
+ "Path": "路径",
+ "Status": "状态",
+ "Removable": "可移动",
+ "Label": "标签",
+ "Watch {watch_id} removed.": "监视 {watch_id} 已移除。",
+ "Watch {watch_id} unchanged.": "监视 {watch_id} 无变化。",
+ "Watch id {watch_id} not found.": "监视 id {watch_id} 不存在。",
+ "Watch path {path} not found.": "监视路径 {path} 不存在。",
+ # ---------------------------------------------------------------- search
+ "Search query": "搜索词",
+ "File type filter: {types}": "文件类型过滤: {types}",
+ "Exact search index tier: flash, basic, standard, advanced": "精确的搜索索引档位: flash、basic、standard、advanced",
+ "Minimum search index tier: flash, basic, standard, advanced": "最低搜索索引档位: flash、basic、standard、advanced",
+ "Max results": "最大结果数",
+ "Filename search query": "文件名搜索词",
+ "File extension filter: {exts}": "文件扩展名过滤: {exts}",
+ "No results found.": "未找到结果。",
+ "Search results ({total} total)": "搜索结果(共 {total} 条)",
+ "Document {short_id}": "文档 {short_id}",
+ "Tier: {tier}": "档位: {tier}",
+ "Files:": "文件:",
+ "File no longer exists.": "文件已不存在。",
+ # ----------------------------------------------------------------- usage
+ "Remote API Usage": "Remote API 用量",
+ "Remote URL: {url}": "Remote URL: {url}",
+ "Access level: {level}": "访问级别: {level}",
+ "Billing period: {period}": "计费周期: {period}",
+ "Current": "当前",
+ "Pages processed: {count}": "已处理页数: {count}",
+ "Files processed: {count}": "已处理文件数: {count}",
+ "Jobs created: {count}": "已创建任务数: {count}",
+ "Limits": "限额",
+ "Max pages per file: {count}": "单文件最大页数: {count}",
+ "Max file size: {size}": "单文件最大体积: {size}",
+ "Max files per job: {count}": "单任务最大文件数: {count}",
+ "Max concurrent jobs: {count}": "最大并发任务数: {count}",
+ "File retention: {retention}": "文件保留期: {retention}",
+ "{start} - ongoing": "{start} - 进行中",
+ "not specified": "未指定",
+ "{days} day": "{days} 天",
+ "{days} days": "{days} 天",
+ # ------------------------------------------------------------------ list
+ "List doclib resources": "列出 doclib 资源",
+ "List parse tasks.": "列出解析任务。",
+ "List scan tasks.": "列出扫描任务。",
+ "List file path records.": "列出文件路径记录。",
+ "List active docs.": "列出活跃文档。",
+ "Parse status filter": "解析状态过滤",
+ "Parse tier filter": "解析档位过滤",
+ "Scan status filter": "扫描状态过滤",
+ "Scan kind filter": "扫描类型过滤",
+ "Watch id filter": "监视 id 过滤",
+ "File status filter": "文件状态过滤",
+ "File extension filter, e.g. pdf": "文件扩展名过滤,如 pdf",
+ "Document file type filter, e.g. pdf": "文档文件类型过滤,如 pdf",
+ "No parses found.": "未找到解析任务。",
+ "Parses ({total} total)": "解析任务(共 {total} 条)",
+ "Tier": "档位",
+ "Pages": "页码",
+ "Doc ID": "文档 ID",
+ "No scans found.": "未找到扫描任务。",
+ "Scans ({total} total)": "扫描任务(共 {total} 条)",
+ "Kind": "类型",
+ "Seen": "已发现",
+ "Refreshed": "已刷新",
+ "Errors": "错误数",
+ "No files found.": "未找到文件。",
+ "Files ({total} total)": "文件(共 {total} 条)",
+ "Ext": "扩展名",
+ "No docs found.": "未找到文档。",
+ "Docs ({total} total)": "文档(共 {total} 条)",
+ "Type": "类型",
+ "Title": "标题",
+ # ------------------------------------------------------------------ show
+ "Show doclib resource details": "显示 doclib 资源详情",
+ "Show one parse task.": "显示单个解析任务。",
+ "Show one scan task.": "显示单个扫描任务。",
+ "Show file, doc, and parse state for a local path.": "显示某个本地路径的文件、文档与解析状态。",
+ "Show one doc by Doc ID or content hash.": "按 Doc ID 或内容哈希显示单个文档。",
+ "Parse task id": "解析任务 id",
+ "Scan task id": "扫描任务 id",
+ "File path": "文件路径",
+ "Document Doc ID or SHA-256": "文档 Doc ID 或 SHA-256",
+ "Parse {id}: {status}": "解析 {id}: {status}",
+ "Field": "字段",
+ "Value": "值",
+ "SHA-256": "SHA-256",
+ "Privacy": "隐私",
+ "Error": "错误",
+ "Scan {id}: {status}": "扫描 {id}: {status}",
+ "Metric": "指标",
+ "New": "新增",
+ "Changed": "已变更",
+ "Deleted": "已删除",
+ "Unreachable": "不可达",
+ "Excluded": "已排除",
+ "Unsupported": "不支持",
+ "File not found in database.": "数据库中未找到该文件。",
+ "File Info: {name}": "文件信息: {name}",
+ "Size": "大小",
+ "Page count": "页数",
+ "Author": "作者",
+ "Tiers": "档位",
+ "Doc {short_id}": "文档 {short_id}",
+ "Image based": "是否图片型",
+ "Files": "文件",
+ # -------------------------------------------------------- telemetry 命令
+ "Telemetry management": "遥测管理",
+ "Show telemetry status.": "显示遥测状态。",
+ "Print the next telemetry request body without sending it.": "打印下一次遥测请求体,但不发送。",
+ "Enable telemetry.": "启用遥测。",
+ "Disable telemetry and clear pending local aggregates.": "禁用遥测并清除待发送的本地聚合数据。",
+ "Flush pending telemetry now when telemetry is enabled (or unset during prerelease).": (
+ "当遥测已启用(或预发布期未设置)时,立即上报待发送遥测。"
+ ),
+ "never": "从未",
+ "state: {state}": "状态(state): {state}",
+ "installation_id: {id}": "installation_id: {id}",
+ "pending_periods: {n}": "待发送周期数: {n}",
+ "pending_metrics: {n}": "待发送指标数: {n}",
+ "last_flush_at: {value}": "上次上报时间: {value}",
+ "telemetry flush: {reason}": "遥测已上报: {reason}",
+ "telemetry {state}": "遥测 {state}",
+ # ---------------------------------------------------------------- server
+ "Server lifecycle management": "服务生命周期管理",
+ "Start the mineru server in the background.": "在后台启动 mineru 服务。",
+ "Stop the mineru server gracefully.": "优雅停止 mineru 服务。",
+ "Restart the mineru server.": "重启 mineru 服务。",
+ "Show server status.": "显示服务状态。",
+ "Server is already running.": "服务已在运行。",
+ "Another mineru server start is already in progress.": "另一个 mineru 服务启动操作正在进行中。",
+ "Server is still starting (PID {pid}).": "服务仍在启动中(PID {pid})。",
+ "Server failed to start within {seconds} seconds. See log: {log}; stdout: {stdout}; stderr: {stderr}": (
+ "服务未在 {seconds} 秒内启动完成。日志: {log};stdout: {stdout};stderr: {stderr}"
+ ),
+ "Server failed to start: {error}. See log: {log}; stdout: {stdout}; stderr: {stderr}": (
+ "服务启动失败: {error}。日志: {log};stdout: {stdout};stderr: {stderr}"
+ ),
+ "Server started (PID {pid}).": "服务已启动(PID {pid})。",
+ "Server is not running.": "服务未在运行。",
+ "Failed to request MinerU server shutdown: {error}": "请求 MinerU 服务关闭失败: {error}",
+ "MinerU server did not stop within 15 seconds. The server was not restarted.": (
+ "MinerU 服务未在 15 秒内停止。服务未被重启。"
+ ),
+ "Server stopped.": "服务已停止。",
+ "Server is still starting.": "服务仍在启动中。",
+ "MinerU Server": "MinerU 服务",
+ "PID": "PID",
+ "Uptime": "运行时长",
+ "Home": "主目录",
+ "Version": "版本",
+ "Python": "Python",
+ "Socket": "Socket",
+ "Data dir": "数据目录",
+ "SQLite": "SQLite",
+ "SQLite size": "SQLite 体积",
+ "Log": "日志",
+ "TCP": "TCP",
+ "Files tracked": "已跟踪文件",
+ "Docs indexed": "已索引文档",
+ "Active scans": "进行中的扫描",
+ "Last scan": "上次扫描",
+ "Parse queue": "解析队列",
+ "Ingest queue": "入库队列",
+ "(pending)": "(未分配)",
+ "disabled": "已禁用",
+ "Workers": "工作进程",
+ "Component": "组件",
+ "Running": "运行中",
+ "Watch": "监视",
+ "Scan": "扫描",
+ "Ingest": "入库",
+ "Parse": "解析",
+ "Device monitor": "设备监视器",
+ "Compaction": "压缩整理",
+ "Health check": "健康检查",
+ "Watch Stats": "监视统计",
+ "Docs": "文档数",
+ "Active": "活跃",
+ "Pending ingest": "待入库",
+ "Parses done/pending/parsing/failed": "解析 完成/排队/解析中/失败",
+ "Error Summary": "错误汇总",
+ "Scope": "范围",
+ "Code": "错误码",
+ "Count": "数量",
+ "Recent Scans": "最近的扫描",
+ "Source": "来源",
+ "Error code": "错误码",
+ "Parse Server": "Parse Server",
+ "Target": "目标",
+ "Healthy": "健康",
+ "Endpoint": "端点",
+ "Managed": "托管",
+ "Restart": "重启",
+ "Last probe": "上次探测",
+ "Last ok": "上次成功",
+ "Last fail": "上次失败",
+ "Local": "本地",
+ "Remote": "远程",
+ "starting": "启动中",
+ "Recent App Logs": "最近的应用日志",
+ "Recent Access Logs": "最近的访问日志",
+ "Recent Stderr Logs": "最近的 stderr 日志",
+ "Recent Stdout Logs": "最近的 stdout 日志",
+ "Recent Parse Server Stderr Logs": "最近的 Parse Server stderr 日志",
+ "Recent Parse Server Stdout Logs": "最近的 Parse Server stdout 日志",
+ "(empty)": "(空)",
+ "{age}s ago": "{age} 秒前",
+ "{age}m ago": "{age} 分钟前",
+ "{age}h ago": "{age} 小时前",
+ "{age}d ago": "{age} 天前",
+ # ---------------------------------------------------------------- config
+ "Configuration management": "配置管理",
+ "Exclude rule management": "排除规则管理",
+ "Parsing rule management": "解析规则管理",
+ "Show effective configuration values.": "显示生效的配置值。",
+ "Show one effective configuration value.": "显示单个生效配置值。",
+ "Set a configuration override.": "设置一个配置覆盖。",
+ "Remove a configuration override and fall back to the default.": "移除配置覆盖并回退到默认值。",
+ "Configuration key": "配置键",
+ "Configuration value": "配置值",
+ "Config": "配置",
+ "Key": "键",
+ "default": "默认",
+ "{key} = {value} [{source}]": "{key} = {value} [{source}]",
+ "removed": "已移除",
+ "unchanged": "无变化",
+ "{key} = {value} [{source}] ({action})": "{key} = {value} [{source}]({action})",
+ "Glob pattern to exclude": "要排除的 glob 模式",
+ "Rule priority": "规则优先级",
+ "Add an exclusion rule.": "添加一条排除规则。",
+ "List exclusion rules.": "列出排除规则。",
+ "Rule id to remove": "要移除的规则 id",
+ "Remove an exclusion rule.": "移除一条排除规则。",
+ "Exclude rule added: id={id}": "已添加排除规则: id={id}",
+ "No exclude rules configured.": "未配置任何排除规则。",
+ "Exclude Rules": "排除规则",
+ "Pattern": "模式",
+ "Priority": "优先级",
+ "Exclude rule {rule_id} removed.": "排除规则 {rule_id} 已移除。",
+ "Exclude rule {rule_id} unchanged.": "排除规则 {rule_id} 无变化。",
+ "Glob pattern to match": "要匹配的 glob 模式",
+ "PDF pages, e.g. all, 1-10 or r3-r1": "PDF 页码,如 all、1-10 或 r3-r1",
+ "Allow remote parsing": "允许远程解析",
+ "Rule name": "规则名称",
+ "Add a parsing rule.": "添加一条解析规则。",
+ "List parsing rules.": "列出解析规则。",
+ "Remove a parsing rule.": "移除一条解析规则。",
+ "Parsing rule added: id={id}": "已添加解析规则: id={id}",
+ "No parsing rules configured.": "未配置任何解析规则。",
+ "Parsing Rules": "解析规则",
+ "Name": "名称",
+ "Parsing rule {rule_id} removed.": "解析规则 {rule_id} 已移除。",
+ "Parsing rule {rule_id} unchanged.": "解析规则 {rule_id} 无变化。",
+ # --------------------------------------------------------------- cleanup
+ "Clean up local doclib records and temp files.": "清理本地 doclib 记录与临时文件。",
+ "Preview only": "仅预览",
+ "Days threshold for temp cleanup": "临时文件清理的天数阈值",
+ "Remove all file rows already marked as deleted.": "移除所有已标记为删除的文件记录。",
+ "Remove docs that are no longer referenced by any file row.": "移除不再被任何文件记录引用的文档。",
+ "Remove old process temp files.": "移除过期的进程临时文件。",
+ "Would remove {count} deleted file record(s). Use --no-dry-run to proceed.": (
+ "将移除 {count} 条已删除的文件记录。加 --no-dry-run 执行。"
+ ),
+ "Removed {count} deleted file record(s).": "已移除 {count} 条已删除的文件记录。",
+ "Would remove {count} orphan doc(s). Use --no-dry-run to proceed.": "将移除 {count} 个孤儿文档。加 --no-dry-run 执行。",
+ "Removed {count} orphan doc(s).": "已移除 {count} 个孤儿文档。",
+ "Removed {count} temp file(s).": "已移除 {count} 个临时文件。",
+ # ---------------------------------------------------------------- forget
+ "File or directory path to forget from doclib": "要从 doclib 移除记录的文件或目录路径",
+ "Would forget {count} file record(s) (matched_as={matched_as}). Use --no-dry-run to proceed.": (
+ "将移除 {count} 条文件记录(matched_as={matched_as})。加 --no-dry-run 执行。"
+ ),
+ "Forgot {count} file record(s) (matched_as={matched_as}).": "已移除 {count} 条文件记录(matched_as={matched_as})。",
+ # ------------------------------------------------------------ invalidate
+ "Parse tier to invalidate (omit = all tiers)": "要作废的解析档位(省略 = 全部档位)",
+ "Invalidated {count} batch(es) for {doc_id}{tier_label}. Use 'mineru parse' to re-parse.": (
+ "已作废 {doc_id}{tier_label} 的 {count} 个批次。使用 'mineru parse' 重新解析。"
+ ),
+ "No done batches found for {doc_id}{tier_label}.": "未找到 {doc_id}{tier_label} 的已完成批次。",
+ # ------------------------------------------------------ errors.py 字面量
+ "Local mineru server is not running. Run 'mineru server start'.": (
+ "本地 mineru 服务未运行。请先运行 'mineru server start'。"
+ ),
+ "MinerU server is busy. Retry the request.": "MinerU 服务繁忙。请重试请求。",
+ # -------------------------------------------------------------- guidance
+ "Configure a valid Official API Key to continue.": "请配置有效的官方 API Key 后继续。",
+ "This Remote API feature requires an Official API Key.": "此 Remote API 功能需要官方 API Key。",
+ "An Official API Key is optional and may provide registered rate limits.": (
+ "官方 API Key 为可选项,配置后可获得注册用户的速率限制。"
+ ),
+ "An Official API Key is optional and enables registered access.": "官方 API Key 为可选项,配置后可启用注册访问。",
+ "Manage or create an API Key:": "管理或创建 API Key:",
+ "Set the API Key:": "设置 API Key:",
+ # --------------------------------------------------- 遥测首次运行同意文案
+ "Help improve MinerU by sending anonymous, locally aggregated usage and diagnostic data.\n"
+ "\n"
+ "Collected:\n"
+ " command names, MinerU version, OS, architecture, Python version, install channel,\n"
+ " coarse CPU/GPU categories, success/failure status, error categories, tiers,\n"
+ " and performance timing buckets.\n"
+ "\n"
+ "NOT collected:\n"
+ " document contents, extracted text/images, file names, file paths, raw URLs,\n"
+ " search queries, prompts, snippets, tracebacks, exception messages, hostnames,\n"
+ " usernames, account IDs, API keys, or exact CPU/GPU models.\n"
+ "\n"
+ "Press Enter or type Y to enable, or type N to disable.\n"
+ "You can change this later with `mineru telemetry enable` or `mineru telemetry disable`.\n"
+ "Preview what would be sent with `mineru telemetry preview`.": (
+ "帮助改进 MinerU:发送匿名且本地聚合的使用与诊断数据。\n"
+ "\n"
+ "收集内容:\n"
+ " 命令名、MinerU 版本、操作系统、架构、Python 版本、安装渠道、\n"
+ " 粗粒度 CPU/GPU 类别、成功/失败状态、错误类别、档位,以及性能耗时分桶。\n"
+ "\n"
+ "不收集的内容:\n"
+ " 文档内容、提取的文本/图片、文件名、文件路径、原始 URL、搜索词、提示词、\n"
+ " 片段、堆栈、异常消息、主机名、用户名、账号 ID、API 密钥,或精确 CPU/GPU 型号。\n"
+ "\n"
+ "按回车或输入 Y 启用,输入 N 禁用。\n"
+ "之后可通过 `mineru telemetry enable` 或 `mineru telemetry disable` 修改。\n"
+ "使用 `mineru telemetry preview` 预览将发送的内容。"
+ ),
+ "Enable telemetry?": "启用遥测?",
+ # ------------------------------------------------------------- kit 根
+ "MinerU Kit — parsing and service tools": "MinerU Kit — 解析与服务工具",
+ "Parse files or directories into markdown, middle JSON, or zip outputs.": (
+ "将文件或目录解析为 markdown、middle JSON 或 zip 输出。"
+ ),
+ "Start the Gradio document parsing web UI backed by the MinerU V1 API.": "启动基于 MinerU V1 API 的 Gradio 文档解析界面。",
+ "Forward explicit startup options and launch the self-hosted MinerU parsing API service.": (
+ "转发显式启动参数,启动 self-hosted MinerU 解析 API 服务。"
+ ),
+ "Start the local VLM server with OpenAI-compatible chat completions.": (
+ "启动本地 VLM 服务,提供 OpenAI 兼容的 chat completions。"
+ ),
+ "Start a standalone Router service exposing only the MinerU V1 API.": "启动只暴露 MinerU V1 API 的独立 Router 服务。",
+ # ------------------------------------------------------------ kit parse
+ "Input files or directories": "输入文件或目录",
+ "Output path; required": "输出路径;必填",
+ "PDF pages: '1-5,8,r3-r1' or 'all'; default: all pages": "PDF 页码: '1-5,8,r3-r1' 或 'all';默认全部页面",
+ "Output format: markdown, middle_json, zip": "输出格式: markdown、middle_json、zip",
+ "Expert backend override": "专家后端覆盖",
+ "Use mineru.net official remote parse service": "使用 mineru.net 官方远程解析服务",
+ "Use a custom remote parse service URL": "使用自定义远程解析服务 URL",
+ "API key for remote parse service": "远程解析服务的 API key",
+ "OCR mode: auto, txt, ocr": "OCR 模式: auto、txt、ocr",
+ "Disable image analysis": "禁用图像分析",
+ "At least one input path is required.": "至少需要一个输入路径。",
+ "--backend is not allowed in remote mode.": "远程模式下不允许使用 --backend。",
+ "When input is multiple files or directories, --output must be a directory path.": (
+ "当输入为多个文件或目录时,--output 必须是目录路径。"
+ ),
+ "Failed to parse {path}: {error}": "解析 {path} 失败: {error}",
+ "Parsed {count} input(s).": "已解析 {count} 个输入。",
+ # ------------------------------------------------------------ kit webui
+ "Gradio is a base dependency; repair the installation with `pip install 'mineru'`.": (
+ "Gradio 是基础依赖;请用 `pip install 'mineru'` 修复安装。"
+ ),
+ "Gradio >=6.8,<7 is required; upgrade with `pip install --upgrade 'mineru'`.": (
+ "需要 Gradio >=6.8,<7;请用 `pip install --upgrade 'mineru'` 升级。"
+ ),
+ "Unsupported API server tier '{tier}'. Supported tiers: {tiers}": "不支持的 API server 档位 '{tier}'。支持的档位: {tiers}",
+ "{name} must be greater than zero": "{name} 必须大于零",
+ "server_port must be between 1 and 65535": "server_port 必须在 1 到 65535 之间",
+ "External MinerU V1 API base URL": "外部 MinerU V1 API 基础 URL",
+ "Bearer API key; falls back to MINERU_API_KEY": "Bearer API key;未提供时回退到 MINERU_API_KEY",
+ "Web UI bind host": "Web UI 绑定主机",
+ "Web UI bind port; omitted: auto-select from 7860 or GRADIO_SERVER_PORT": (
+ "Web UI 绑定端口;省略时从 7860 或 GRADIO_SERVER_PORT 自动选择"
+ ),
+ "Directory for Web UI artifacts": "Web UI 产物目录",
+ "Maximum pages per non-Flash PDF conversion; omitted: unlimited": "非 Flash PDF 单次转换的最大页数;省略时不限制",
+ "Show local examples": "显示本地示例",
+ "Expose the Gradio event API": "开放 Gradio 事件 API",
+ "LaTeX delimiters used by the Markdown preview": "Markdown 预览使用的 LaTeX 定界符",
+ "Managed API server capability tier": "托管 API server 的能力档位",
+ "Managed server job concurrency": "托管服务的任务并发数",
+ "Managed server OCR language": "托管服务的 OCR 语言",
+ "Disable managed server image analysis": "禁用托管服务的图像分析",
+ "Preload managed server models": "预加载托管服务的模型",
+ # ------------------------------------------------------- kit api-server
+ "Unsupported server tier '{tier}'. Supported server tiers: {tiers}": "不支持的服务档位 '{tier}'。支持的档位: {tiers}",
+ "Server host": "服务监听主机",
+ "Server port": "服务监听端口",
+ "Upload directory": "上传目录",
+ "Server capability tier: flash, basic, or standard": "服务能力档位: flash、basic 或 standard",
+ "Disable Flash tier advertisement and execution": "禁用 Flash 档位的广播与执行",
+ "Disable Advanced tier advertisement and execution": "禁用 Advanced 档位的广播与执行",
+ "Maximum concurrent parse jobs": "最大并发解析任务数",
+ "Timeout for URL source downloads": "URL 来源下载超时",
+ "Allow local source paths": "允许本地来源路径",
+ "Maximum decoded bytes for inline sources": "内联来源的最大解码字节数",
+ "Allow URL sources to use plain HTTP": "允许 URL 来源使用明文 HTTP",
+ "Hybrid medium OCR language hint; accepted by other efforts for compatibility": (
+ "Hybrid 中档 OCR 语言提示;为兼容性也接受其他档位传入"
+ ),
+ "Initialize VLM client and local Hybrid models at startup": "启动时初始化 VLM 客户端与本地 Hybrid 模型",
+ "Optional fixed API key": "可选的固定 API key",
+ "Remote VLM URL; empty value selects local VLM": "远程 VLM URL;留空选择本地 VLM",
+ "Bearer key for the remote VLM server": "远程 VLM 服务的 Bearer key",
+ "Remote VLM model name; empty value enables discovery": "远程 VLM 模型名;留空启用自动发现",
+ "VLM HTTP timeout in seconds (default: 600)": "VLM HTTP 超时秒数(默认 600)",
+ "VLM inference concurrency (default: 100)": "VLM 推理并发数(默认 100)",
+ "API service log level: critical, error, warning, info, debug, trace; default: global log.level. "
+ "Also filters the Loguru default model-log sink": (
+ "API 服务日志级别: critical、error、warning、info、debug、trace;默认取全局 log.level。同时过滤 Loguru 默认模型日志 sink"
+ ),
+ # ------------------------------------------------------- kit vlm-server
+ "VLM serving engine: auto, vllm, lmdeploy, mlx": "VLM 推理服务引擎: auto、vllm、lmdeploy、mlx",
+ "Unsupported engine '{engine}'.": "不支持的引擎 '{engine}'。",
+ "Using vLLM as the inference engine for VLM server.": "使用 vLLM 作为 VLM 服务的推理引擎。",
+ "Using LMDeploy as the inference engine for VLM server.": "使用 LMDeploy 作为 VLM 服务的推理引擎。",
+ "No automatic VLM server engine is installed. Install vLLM/LMDeploy or explicitly choose --engine mlx.": (
+ "未安装可自动选择的 VLM 服务引擎。请安装 vLLM/LMDeploy,或显式指定 --engine mlx。"
+ ),
+ "vLLM is not installed. Please install vLLM or choose lmdeploy/mlx as the engine.": (
+ "未安装 vLLM。请安装 vLLM,或选择 lmdeploy/mlx 作为引擎。"
+ ),
+ "LMDeploy is not installed. Please install LMDeploy or choose vllm/mlx as the engine.": (
+ "未安装 LMDeploy。请安装 LMDeploy,或选择 vllm/mlx 作为引擎。"
+ ),
+ "MLX server is unavailable.": "MLX 服务不可用。",
+ "MLX server requires Apple Silicon and macOS 14 or newer.": "MLX 服务需要 Apple Silicon 和 macOS 14 及以上。",
+ "MLX server requires mlx-vlm>=0.7.0,<0.8.0; installed: {version}. Install 'mlx-vlm>=0.7.0,<0.8.0'.": (
+ "MLX 服务需要 mlx-vlm>=0.7.0,<0.8.0;当前安装: {version}。请安装 'mlx-vlm>=0.7.0,<0.8.0'。"
+ ),
+ "mlx_vlm.server is unavailable. Install 'mlx-vlm>=0.7.0,<0.8.0'.": (
+ "mlx_vlm.server 不可用。请安装 'mlx-vlm>=0.7.0,<0.8.0'。"
+ ),
+ "MLX-VLM is not installed. Install 'mlx-vlm>=0.7.0,<0.8.0'.": "未安装 MLX-VLM。请安装 'mlx-vlm>=0.7.0,<0.8.0'。",
+ # ---------------------------------------------------------- kit models
+ "Download, inspect, and verify local MinerU models.": "下载、查看与校验本地 MinerU 模型。",
+ "Download an explicit repo or the tier resources required by the current backend combination.": (
+ "下载显式仓库或当前后端组合所需的档位资源。"
+ ),
+ "Show configuration sources, effective backends, and tier resources.": "显示配置来源、有效后端与档位资源。",
+ "Verify local resources for an explicit repo or the current backend combination.": (
+ "校验显式仓库或当前后端组合所需的本地资源。"
+ ),
+ "Unsupported source '{source}'. Expected one of: {expected}.": "不支持的来源 '{source}'。可选值: {expected}。",
+ "Pass either a model repo name or --tier, not both.": "请只传模型仓库名或 --tier 其中之一。",
+ "Pass a model repo name or --tier.": "请传入模型仓库名或 --tier。",
+ "ready": "就绪",
+ "missing": "缺失",
+ "Failed to download {repo}: {error}": "下载 {repo} 失败: {error}",
+ "Downloaded models for {label}.": "已下载 {label} 的模型。",
+ "tier {tier}": "档位 {tier}",
+ "Config: {path}": "配置文件: {path}",
+ "Config exists: {value}": "配置文件存在: {value}",
+ "Effective small backend: {backend}": "生效的小模型后端: {backend}",
+ "Effective VLM engine: {engine}": "生效的 VLM 引擎: {engine}",
+ "Repos:": "仓库:",
+ "Model tiers:": "模型档位:",
+ "(none)": "(无)",
+ "Model repo: MinerU-4_models_torch, MinerU-4_models_onnx, or a VLM repo": (
+ "模型仓库: MinerU-4_models_torch、MinerU-4_models_onnx 或 VLM 仓库"
+ ),
+ "Model tier to prepare: basic or standard": "要准备的模型档位: basic 或 standard",
+ "Small model backend: auto, onnx, torch. Ignored when REPO is given.": "小模型后端: auto、onnx、torch。指定 REPO 时忽略。",
+ "Local VLM engine: auto, llama-cpp, vllm, lmdeploy, mlx. Ignored when REPO is given.": (
+ "本地 VLM 引擎: auto、llama-cpp、vllm、lmdeploy、mlx。指定 REPO 时忽略。"
+ ),
+ "Model source: auto, huggingface, or modelscope": "模型来源: auto、huggingface 或 modelscope",
+ "Optional model repo name": "可选的模型仓库名",
+ "Optional model tier: basic or standard": "可选的模型档位: basic 或 standard",
+ "{repo}: ok": "{repo}: 正常",
+ "{repo}: missing key paths: {missing}": "{repo}: 缺少关键路径: {missing}",
+ # --------------------------------------------------------- kit router
+ "Unsupported worker tier '{tier}'. Supported tiers: {tiers}": "不支持的 worker 档位 '{tier}'。支持的档位: {tiers}",
+ "Enable auto-reload": "启用自动重载",
+ "Existing MinerU V1 API base URL; repeat to add upstreams": "既有的 MinerU V1 API 基础 URL;可重复传入以添加多个上游",
+ "Local workers: auto, none, or GPU CSV": "本地 worker: auto、none 或 GPU 列表(CSV)",
+ "Host for managed api-server workers": "托管 api-server worker 的主机",
+ "Managed worker tier: flash, basic, standard": "托管 worker 档位: flash、basic、standard",
+ "Concurrency per managed worker": "每个托管 worker 的并发数",
+ "Preload models in managed workers": "在托管 worker 中预加载模型",
+ # -------------------------------------------------------- kit common
+ "No input files found.": "未找到输入文件。",
+ "Directory input must be expanded before validation: {path}": "目录输入必须先展开再校验: {path}",
+ "Unsupported file type: {path}": "不支持的文件类型: {path}",
+ "Invalid input path.": "无效的输入路径。",
+ "Output name collision: {existing} and {source} both map to {dest}": "输出名称冲突: {existing} 与 {source} 都映射到 {dest}",
+ "--remote and --remote-url are mutually exclusive.": "--remote 与 --remote-url 互斥。",
+ "Unsupported format: {format}": "不支持的格式: {format}",
+}
diff --git a/tests/conftest.py b/tests/conftest.py
index 83c3aaf8..58c983bf 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,9 +3,22 @@
from __future__ import annotations
import importlib
+import os
import pytest
+# Typer 的 help 文案在 import 期求值,必须在任何 mineru 模块导入前固定 CLI 语言,
+# 否则中文 locale 机器上既有的英文输出断言会失败。i18n 专项测试自行 monkeypatch 覆盖。
+os.environ["MINERU_LANG"] = "en"
+
+
[email protected](autouse=True)
+def pin_cli_language() -> None:
+ """每个测试前重置语言缓存,保证运行期 t() 调用也固定为英文。"""
+ from mineru.utils import i18n
+
+ i18n.reset_language_cache()
+
@pytest.fixture(autouse=True)
def isolate_optional_llm_configuration(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unittest/test_cli_i18n.py b/tests/unittest/test_cli_i18n.py
new file mode 100644
index 00000000..e1aa5f00
--- /dev/null
+++ b/tests/unittest/test_cli_i18n.py
@@ -0,0 +1,135 @@
+"""mineru / mineru-kit CLI 双语文案:语言检测、t() 语义与词典完整性守卫。"""
+
+from __future__ import annotations
+
+import ast
+import string
+from pathlib import Path
+
+import pytest
+
+from mineru.cli.telemetry import TELEMETRY_CONSENT_MESSAGE
+from mineru.utils.i18n import detect_language, reset_language_cache, t
+from mineru.utils.translations import ZH_MESSAGES
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+# 两个 CLI 工具的用户可见表层;gradio(自带 i18n)与 vlm_server 透传服务不在范围内。
+SCAN_FILES = sorted(
+ {
+ *REPO_ROOT.glob("mineru/cli/**/*.py"),
+ REPO_ROOT / "mineru/kit/main.py",
+ REPO_ROOT / "mineru/kit/common.py",
+ *REPO_ROOT.glob("mineru/kit/commands/*.py"),
+ REPO_ROOT / "mineru/kit/router/cli.py",
+ }
+)
+
+
+def _use_language(monkeypatch: pytest.MonkeyPatch, language: str) -> None:
+ monkeypatch.setenv("MINERU_LANG", language)
+ reset_language_cache()
+
+
+class TestDetectLanguage:
+ def test_mineru_lang_overrides_everything(self) -> None:
+ assert detect_language({"MINERU_LANG": "zh", "LC_ALL": "en_US.UTF-8", "LANG": "en_US.UTF-8"}) == "zh"
+ assert detect_language({"MINERU_LANG": "en", "LC_ALL": "zh_CN.UTF-8"}) == "en"
+
+ def test_posix_priority_chain(self) -> None:
+ assert detect_language({"LC_ALL": "zh_CN.UTF-8", "LC_MESSAGES": "en_US.UTF-8", "LANG": "en_US.UTF-8"}) == "zh"
+ assert detect_language({"LC_MESSAGES": "zh_TW.UTF-8", "LANG": "en_US.UTF-8"}) == "zh"
+ assert detect_language({"LANG": "en_US.UTF-8"}) == "en"
+
+ def test_c_locale_decides_english(self) -> None:
+ assert detect_language({"LC_ALL": "C", "LANG": "zh_CN.UTF-8"}) == "en"
+ assert detect_language({"LC_ALL": "POSIX", "LANG": "zh_CN.UTF-8"}) == "en"
+
+ def test_chinese_variants(self) -> None:
+ for value in ("zh", "zh_CN.UTF-8", "zh_TW", "zh-HK", "zh_Hans@pinyin", "ZH_CN.UTF-8"):
+ assert detect_language({"LANG": value}) == "zh", value
+
+ def test_unset_falls_back_to_english(self) -> None:
+ assert detect_language({}) == "en"
+ assert detect_language({"LANG": ""}) == "en"
+
+ def test_reads_process_env_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("MINERU_LANG", "zh")
+ reset_language_cache()
+ try:
+ assert t("JSON output") == "JSON 输出"
+ finally:
+ reset_language_cache()
+
+
+class TestTranslationFunction:
+ def test_english_passthrough(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _use_language(monkeypatch, "en")
+ assert t("JSON output") == "JSON output"
+ assert t("Never translated key.") == "Never translated key."
+
+ def test_chinese_lookup_and_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _use_language(monkeypatch, "zh")
+ assert t("JSON output") == "JSON 输出"
+ assert t("Never translated key.") == "Never translated key."
+
+ def test_format_kwargs(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _use_language(monkeypatch, "zh")
+ assert t("Written to {path}", path="out/a.md") == "已写入 out/a.md"
+ _use_language(monkeypatch, "en")
+ assert t("Written to {path}", path="out/a.md") == "Written to out/a.md"
+
+
+class TestCatalogIntegrity:
+ def test_every_entry_keeps_placeholders(self) -> None:
+ formatter = string.Formatter()
+ for key, value in ZH_MESSAGES.items():
+ expected = {name for _, name, _, _ in formatter.parse(key) if name is not None}
+ actual = {name for _, name, _, _ in formatter.parse(value) if name is not None}
+ assert expected == actual, f"占位符不一致: {key!r}"
+
+ def test_telemetry_consent_block_is_translated(self) -> None:
+ assert TELEMETRY_CONSENT_MESSAGE in ZH_MESSAGES
+
+ def test_every_t_literal_has_catalog_entry(self) -> None:
+ keys = {key for path, key in _iter_t_literals()}
+ missing = keys - set(ZH_MESSAGES)
+ assert not missing, f"t() 字面量缺少中文词条: {sorted(missing)}"
+
+ def test_no_raw_help_literals(self) -> None:
+ violations = [f"{path.relative_to(REPO_ROOT)}:{node.lineno}" for path, node in _iter_raw_help_keywords()]
+ assert not violations, f"发现未包 t() 的 help= 字面量: {violations}"
+
+
+def _iter_ast() -> list[tuple[Path, ast.AST]]:
+ trees: list[tuple[Path, ast.AST]] = []
+ for path in SCAN_FILES:
+ trees.append((path, ast.parse(path.read_text(encoding="utf-8"), filename=str(path))))
+ return trees
+
+
+def _iter_t_literals() -> list[tuple[Path, str]]:
+ literals: list[tuple[Path, str]] = []
+ for path, tree in _iter_ast():
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ if not (isinstance(node.func, ast.Name) and node.func.id == "t"):
+ continue
+ if node.args and isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str):
+ literals.append((path, node.args[0].value))
+ return literals
+
+
+def _iter_raw_help_keywords() -> list[tuple[Path, ast.keyword]]:
+ hits: list[tuple[Path, ast.keyword]] = []
+ for path, tree in _iter_ast():
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ for keyword in node.keywords:
+ if keyword.arg != "help" or not isinstance(keyword.value, ast.Constant):
+ continue
+ if isinstance(keyword.value.value, str):
+ hits.append((path, keyword))
+ return hits
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index c545526d..9ed556c0 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -45,11 +45,12 @@ def test_webui_main_runs_modern_command(monkeypatch: pytest.MonkeyPatch) -> None
"""校验独立入口复用 Web UI 命令且先配置标准流。"""
calls: list[object] = []
monkeypatch.setattr(webui, "configure_standard_streams", lambda: calls.append("configure"))
- monkeypatch.setattr(webui.typer, "run", lambda command: calls.append(command))
+ monkeypatch.setattr(webui, "webui_cmd", lambda: calls.append("command"))
- webui.main()
+ code = _invoke_standalone_command(monkeypatch, webui.main, "mineru-webui", [])
- assert calls == ["configure", webui.webui_cmd]
+ assert code == 0
+ assert calls == ["configure", "command"]
def test_webui_console_script_targets_modern_command() -> None:
@@ -103,11 +104,12 @@ def test_standalone_main_configures_streams_before_typer_run(
"""校验 API 和下载入口先配置标准流,再直接复用现有回调。"""
calls: list[object] = []
monkeypatch.setattr(module, "configure_standard_streams", lambda: calls.append("configure"))
- monkeypatch.setattr(typer, "run", lambda command: calls.append(command))
+ monkeypatch.setattr(module, callback.__name__, lambda: calls.append("command"))
- entrypoint()
+ code = _invoke_standalone_command(monkeypatch, entrypoint, "standalone-entry", [])
- assert calls == ["configure", callback]
+ assert code == 0
+ assert calls == ["configure", "command"]
def test_standalone_vlm_main_configures_streams_and_forwards_extra_args(monkeypatch: pytest.MonkeyPatch) -> None: