|
| 1 | +# |
| 2 | +# Copyright IBM Corp. 2024 - 2024 |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# |
| 5 | + |
| 6 | +"""CLI for docling viewer.""" |
| 7 | +import importlib |
| 8 | +import tempfile |
| 9 | +import webbrowser |
| 10 | +from pathlib import Path |
| 11 | +from typing import Annotated, Optional |
| 12 | + |
| 13 | +import typer |
| 14 | + |
| 15 | +from docling_core.types.doc import DoclingDocument |
| 16 | +from docling_core.types.doc.base import ImageRefMode |
| 17 | +from docling_core.utils.file import resolve_source_to_path |
| 18 | + |
| 19 | +app = typer.Typer( |
| 20 | + name="Docling", |
| 21 | + no_args_is_help=True, |
| 22 | + add_completion=False, |
| 23 | + pretty_exceptions_enable=False, |
| 24 | +) |
| 25 | + |
| 26 | + |
| 27 | +def version_callback(value: bool): |
| 28 | + """Callback for version inspection.""" |
| 29 | + if value: |
| 30 | + docling_core_version = importlib.metadata.version("docling-core") |
| 31 | + print(f"Docling Core version: {docling_core_version}") |
| 32 | + raise typer.Exit() |
| 33 | + |
| 34 | + |
| 35 | +@app.command(no_args_is_help=True) |
| 36 | +def view( |
| 37 | + source: Annotated[ |
| 38 | + str, |
| 39 | + typer.Argument( |
| 40 | + ..., |
| 41 | + metavar="source", |
| 42 | + help="Docling JSON file to view.", |
| 43 | + ), |
| 44 | + ], |
| 45 | + version: Annotated[ |
| 46 | + Optional[bool], |
| 47 | + typer.Option( |
| 48 | + "--version", |
| 49 | + callback=version_callback, |
| 50 | + is_eager=True, |
| 51 | + help="Show version information.", |
| 52 | + ), |
| 53 | + ] = None, |
| 54 | +): |
| 55 | + """Display a Docling JSON file on the default browser.""" |
| 56 | + path = resolve_source_to_path(source=source) |
| 57 | + doc = DoclingDocument.load_from_json(filename=path) |
| 58 | + target_path = Path(tempfile.mkdtemp()) / "out.html" |
| 59 | + html_output = doc.export_to_html(image_mode=ImageRefMode.EMBEDDED) |
| 60 | + with open(target_path, "w") as f: |
| 61 | + f.write(html_output) |
| 62 | + webbrowser.open(url=f"file://{target_path.absolute().resolve()}") |
| 63 | + |
| 64 | + |
| 65 | +click_app = typer.main.get_command(app) |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + app() |
0 commit comments