Files
fotoplaner/venv/lib/python3.12/site-packages/docling/cli/models.py
T
anders 16c54c6653 Tilføjet venv med docling og afhængigheder
Testfiler opdelt i PNG og previews
2026-10-27 12:20:23 +01:00

404 lines
15 KiB
Python

# SPDX-FileCopyrightText: The Docling Contributors
# SPDX-License-Identifier: MIT
import logging
import sys
import warnings
from enum import Enum
from pathlib import Path
from typing import Annotated, Literal, Optional
# Check for CLI dependencies
try:
import typer
from rich.console import Console
from rich.logging import RichHandler
except ImportError as e:
missing_package = str(e).split("'")[1] if "'" in str(e) else "typer or rich"
print(
f"Error: Missing required CLI dependency '{missing_package}'", file=sys.stderr
)
print("\nThe docling-tools CLI requires additional dependencies.", file=sys.stderr)
print("Please install them using one of the following options:\n", file=sys.stderr)
print(" 1. Install the full docling package (recommended):", file=sys.stderr)
print(" pip install docling\n", file=sys.stderr)
print(" 2. Install docling-slim with CLI support:", file=sys.stderr)
print(" pip install docling-slim[cli]\n", file=sys.stderr)
print(" 3. Install just the missing dependencies:", file=sys.stderr)
print(" pip install typer rich\n", file=sys.stderr)
sys.exit(1)
from docling.datamodel.asr_model_specs import (
_DISTIL_WHISPER_OPENAI_CHECKPOINTS,
_distil_whisper_prefetch_name,
)
from docling.datamodel.settings import settings
from docling.exceptions import RapidOcrModelSizeNotSupportedError
from docling.models.stages.ocr.easyocr_model import (
resolve_easyocr_codes,
)
from docling.models.stages.ocr.rapid_ocr_model import (
_RAPIDOCR_DEFAULT_LANGUAGE,
_parse_rapidocr_model_spec,
_resolve_rapidocr,
_validate_rapidocr_model_size,
)
from docling.models.utils.hf_model_download import download_hf_model
from docling.utils.model_downloader import _DEFAULT_RAPIDOCR_MODELS, download_models
warnings.filterwarnings(action="ignore", category=UserWarning, module="pydantic|torch")
warnings.filterwarnings(action="ignore", category=FutureWarning, module="easyocr")
console = Console()
err_console = Console(stderr=True)
app = typer.Typer(
name="Docling models helper",
no_args_is_help=True,
add_completion=False,
pretty_exceptions_enable=False,
)
class _AvailableModels(str, Enum):
LAYOUT = "layout"
TABLEFORMER = "tableformer"
TABLEFORMERV2 = "tableformerv2"
CODE_FORMULA = "code_formula"
PICTURE_CLASSIFIER = "picture_classifier"
SMOLVLM = "smolvlm"
GRANITEDOCLING = "granitedocling"
GRANITEDOCLING_MLX = "granitedocling_mlx"
SMOLDOCLING = "smoldocling"
SMOLDOCLING_MLX = "smoldocling_mlx"
GRANITE_VISION = "granite_vision"
GRANITE_CHART_EXTRACTION = "granite_chart_extraction"
GRANITE_CHART_EXTRACTION_V3_3 = "granite_chart_extraction_v3_3"
GRANITE_CHART_EXTRACTION_V4 = "granite_chart_extraction_v4"
RAPIDOCR = "rapidocr"
EASYOCR = "easyocr"
NEMOTRON_OCR_V2 = "nemotron_ocr_v2"
WHISPER_TINY = "whisper_tiny"
WHISPER_TINY_EN = "whisper_tiny_en"
WHISPER_BASE = "whisper_base"
WHISPER_BASE_EN = "whisper_base_en"
WHISPER_SMALL = "whisper_small"
WHISPER_SMALL_EN = "whisper_small_en"
WHISPER_MEDIUM = "whisper_medium"
WHISPER_MEDIUM_EN = "whisper_medium_en"
WHISPER_LARGE = "whisper_large"
WHISPER_TURBO = "whisper_turbo"
WHISPER_DISTIL_SMALL_EN = "whisper_distil_small_en"
WHISPER_DISTIL_MEDIUM_EN = "whisper_distil_medium_en"
WHISPER_DISTIL_LARGE_V3 = "whisper_distil_large_v3"
WHISPER_DISTIL_LARGE_V3_5 = "whisper_distil_large_v3_5"
_WHISPER_MODELS = {
_AvailableModels.WHISPER_TINY: "tiny",
_AvailableModels.WHISPER_TINY_EN: "tiny.en",
_AvailableModels.WHISPER_BASE: "base",
_AvailableModels.WHISPER_BASE_EN: "base.en",
_AvailableModels.WHISPER_SMALL: "small",
_AvailableModels.WHISPER_SMALL_EN: "small.en",
_AvailableModels.WHISPER_MEDIUM: "medium",
_AvailableModels.WHISPER_MEDIUM_EN: "medium.en",
_AvailableModels.WHISPER_LARGE: "large",
_AvailableModels.WHISPER_TURBO: "turbo",
}
_WHISPER_DISTIL_MODELS = {
_AvailableModels(_distil_whisper_prefetch_name(model_name)): model_name
for model_name in _DISTIL_WHISPER_OPENAI_CHECKPOINTS
}
_default_models = [
_AvailableModels.LAYOUT,
_AvailableModels.TABLEFORMER,
_AvailableModels.CODE_FORMULA,
_AvailableModels.PICTURE_CLASSIFIER,
_AvailableModels.RAPIDOCR,
]
@app.command("download")
def download(
output_dir: Annotated[
Path,
typer.Option(
...,
"-o",
"--output-dir",
help="The directory where to download the models.",
),
] = (settings.cache_dir / "models"),
force: Annotated[
bool, typer.Option(..., help="If true, the download will be forced.")
] = False,
models: Annotated[
Optional[list[_AvailableModels]],
typer.Argument(
help="Models to download (default behavior: a predefined set of models will be downloaded).",
),
] = None,
all: Annotated[
bool,
typer.Option(
...,
"--all",
help="If true, all available models will be downloaded (mutually exclusive with passing specific models).",
show_default=True,
),
] = False,
asr: Annotated[
bool,
typer.Option(
...,
"--asr",
help=(
"With --all, also download native Whisper ASR models, including "
"the Distil-Whisper presets."
),
),
] = False,
quiet: Annotated[
bool,
typer.Option(
...,
"-q",
"--quiet",
help="No extra output is generated, the CLI prints only the directory with the cached models.",
),
] = False,
easyocr_lang: Annotated[
Optional[list[str]],
typer.Option(
...,
"--easyocr-lang",
help=(
"OCR language to prefetch for EasyOCR, as a BCP-47 tag "
"(e.g. 'de', 'zh-Hant', 'ru'). EasyOCR's own codes are accepted "
"too and mean what EasyOCR means by them, so 'ch_sim' is "
"Simplified Chinese. Repeat for multiple."
),
),
] = None,
rapidocr_backend_lang: Annotated[
Optional[list[str]],
typer.Option(
...,
"--rapidocr-backend-lang",
help=(
"RapidOCR checkpoint set to prefetch, as '<backend>:<lang>' "
"with a BCP-47 language (e.g. 'onnxruntime:el', 'torch:ko'). "
"PP-OCR's own codes are accepted too, including its script "
"recognizers, which no language tag can name: "
"'onnxruntime:cyrillic', 'torch:ch'. Repeat for multiple. "
"Replaces the default set."
),
),
] = None,
rapidocr_model_size: Annotated[
Literal["tiny", "small", "medium"],
typer.Option(
...,
"--rapidocr-model-size",
help=(
"Detection/recognition model size, applied to every selected "
"--rapidocr-backend-lang pair (or the default set) -- one scalar "
"for the whole command, unlike the repeatable "
"--rapidocr-backend-lang. Only affects pairs resolving to "
"PP-OCRv6; `tiny` is not available for every PP-OCRv6 language "
"(e.g. Japanese), and an unsupported combination is rejected "
"before any download starts."
),
),
] = "small",
):
if models and all:
raise typer.BadParameter(
"Cannot simultaneously set 'all' parameter and specify models to download."
)
if asr and not all:
raise typer.BadParameter("--asr requires --all", param_hint="--asr")
if not quiet:
logging.basicConfig(
level=logging.INFO,
format="[blue]%(message)s[/blue]",
datefmt="[%X]",
handlers=[RichHandler(show_level=False, show_time=False, markup=True)],
)
to_download = models or (
[
model
for model in _AvailableModels
if asr
or (model not in _WHISPER_MODELS and model not in _WHISPER_DISTIL_MODELS)
]
if all
else _default_models
)
if easyocr_lang is not None:
if _AvailableModels.EASYOCR not in to_download:
raise typer.BadParameter(
"--easyocr-lang requires the 'easyocr' model",
param_hint="--easyocr-lang",
)
try:
resolve_easyocr_codes(easyocr_lang)
except ValueError as error:
raise typer.BadParameter(str(error), param_hint="--easyocr-lang") from error
if rapidocr_backend_lang is not None:
if _AvailableModels.RAPIDOCR not in to_download:
raise typer.BadParameter(
"--rapidocr-backend-lang requires the 'rapidocr' model",
param_hint="--rapidocr-backend-lang",
)
try:
for value in rapidocr_backend_lang:
_parse_rapidocr_model_spec(value)
except ValueError as error:
raise typer.BadParameter(
str(error), param_hint="--rapidocr-backend-lang"
) from error
if rapidocr_model_size != "small":
if _AvailableModels.RAPIDOCR not in to_download:
raise typer.BadParameter(
"--rapidocr-model-size requires the 'rapidocr' model",
param_hint="--rapidocr-model-size",
)
# Checked against every pair that will actually be prefetched, so a bad
# combination (e.g. onnxruntime:japan + tiny) fails here, not mid-download.
try:
for value in rapidocr_backend_lang or _DEFAULT_RAPIDOCR_MODELS:
spec = _parse_rapidocr_model_spec(value)
lang = spec.user_lang or _RAPIDOCR_DEFAULT_LANGUAGE
resolved = _resolve_rapidocr(lang, spec.backend)
assert resolved.ppocr_version is not None
assert resolved.rapidocr_code is not None
_validate_rapidocr_model_size(
backend=spec.backend,
language=lang,
ppocr_version=resolved.ppocr_version,
rec_code=resolved.rapidocr_code,
model_size=rapidocr_model_size,
)
except (ValueError, RapidOcrModelSizeNotSupportedError) as error:
raise typer.BadParameter(
str(error), param_hint="--rapidocr-model-size"
) from error
output_dir = download_models(
output_dir=output_dir,
force=force,
progress=(not quiet),
with_layout=_AvailableModels.LAYOUT in to_download,
with_tableformer=_AvailableModels.TABLEFORMER in to_download,
with_tableformer_v2=_AvailableModels.TABLEFORMERV2 in to_download,
with_code_formula=_AvailableModels.CODE_FORMULA in to_download,
with_picture_classifier=_AvailableModels.PICTURE_CLASSIFIER in to_download,
with_smolvlm=_AvailableModels.SMOLVLM in to_download,
with_granitedocling=_AvailableModels.GRANITEDOCLING in to_download,
with_granitedocling_mlx=_AvailableModels.GRANITEDOCLING_MLX in to_download,
with_smoldocling=_AvailableModels.SMOLDOCLING in to_download,
with_smoldocling_mlx=_AvailableModels.SMOLDOCLING_MLX in to_download,
with_granite_vision=_AvailableModels.GRANITE_VISION in to_download,
with_granite_chart_extraction=_AvailableModels.GRANITE_CHART_EXTRACTION
in to_download,
with_granite_chart_extraction_v3_3=_AvailableModels.GRANITE_CHART_EXTRACTION_V3_3
in to_download,
with_granite_chart_extraction_v4=_AvailableModels.GRANITE_CHART_EXTRACTION_V4
in to_download,
with_rapidocr=_AvailableModels.RAPIDOCR in to_download,
rapidocr_models=rapidocr_backend_lang,
rapidocr_model_size=rapidocr_model_size,
with_easyocr=_AvailableModels.EASYOCR in to_download,
easyocr_languages=easyocr_lang,
with_nemotron_ocr=_AvailableModels.NEMOTRON_OCR_V2 in to_download,
whisper_models=[
_WHISPER_MODELS[model] for model in to_download if model in _WHISPER_MODELS
],
whisper_distil_models=[
_WHISPER_DISTIL_MODELS[model]
for model in to_download
if model in _WHISPER_DISTIL_MODELS
],
)
if quiet:
typer.echo(output_dir)
else:
typer.secho(f"\nModels downloaded into: {output_dir}.", fg="green")
console.print(
"\n",
"Docling can now be configured for running offline using the local artifacts.\n\n",
"Using the CLI:",
f"`docling --artifacts-path={output_dir} FILE`",
"\n",
"Using Python: see the documentation at <https://docling-project.github.io/docling/usage>.",
)
@app.command("download-hf-repo")
def download_hf_repo(
models: Annotated[
list[str],
typer.Argument(
help="Specific models to download from HuggingFace identified by their repo id. For example: docling-project/docling-models .",
),
],
output_dir: Annotated[
Path,
typer.Option(
...,
"-o",
"--output-dir",
help="The directory where to download the models.",
),
] = (settings.cache_dir / "models"),
force: Annotated[
bool, typer.Option(..., help="If true, the download will be forced.")
] = False,
quiet: Annotated[
bool,
typer.Option(
...,
"-q",
"--quiet",
help="No extra output is generated, the CLI prints only the directory with the cached models.",
),
] = False,
):
if not quiet:
logging.basicConfig(
level=logging.INFO,
format="[blue]%(message)s[/blue]",
datefmt="[%X]",
handlers=[RichHandler(show_level=False, show_time=False, markup=True)],
)
for item in models:
if not quiet:
typer.secho(f"\nDownloading {item} model from HuggingFace...")
download_hf_model(
repo_id=item,
# would be better to reuse "repo_cache_folder" property: https://github.com/docling-project/docling/blob/main/docling/datamodel/pipeline_options_vlm_model.py#L76
# but creating options objects seams like an overkill
local_dir=output_dir / item.replace("/", "--"),
force=force,
progress=(not quiet),
)
if quiet:
typer.echo(output_dir)
else:
typer.secho(f"\nModels downloaded into: {output_dir}.", fg="green")
click_app = typer.main.get_command(app)
if __name__ == "__main__":
app()