Files
genshin-tcg/src/genshin_tcg/cli.py
T
V d651455499
CI / quality (3.11) (push) Has been cancelled
CI / quality (3.12) (push) Has been cancelled
First version
2026-10-15 17:37:05 +02:00

199 lines
6.5 KiB
Python

"""Command line interface (Typer + Rich)."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, NoReturn
import typer
from rich.console import Console
from rich.table import Table
from genshin_tcg import __version__
from genshin_tcg.config import CardSettings, Settings
from genshin_tcg.data.catalog import load_catalog
from genshin_tcg.data.paimon import SourceError
from genshin_tcg.logging_setup import configure_logging
from genshin_tcg.pipeline import build as build_pipeline
from genshin_tcg.pipeline import fetch as fetch_pipeline
from genshin_tcg.pipeline import impose as impose_pipeline
from genshin_tcg.pipeline import render as render_pipeline
from genshin_tcg.rendering.converters import RenderError
app = typer.Typer(
add_completion=False,
no_args_is_help=True,
help="Generate printable Genshin Impact TCG cards (HTML -> PNG -> A4 PDF).",
)
console = Console()
__all__ = ["app"]
@dataclass(slots=True)
class CliState:
settings: Settings
def _version_callback(value: bool) -> None:
if value:
console.print(f"genshin-tcg {__version__}")
raise typer.Exit
@app.callback()
def main(
ctx: typer.Context,
version: Annotated[
bool,
typer.Option(
"--version", callback=_version_callback, is_eager=True, help="Show version and exit."
),
] = False,
verbose: Annotated[
int, typer.Option("-v", "--verbose", count=True, help="Increase log verbosity (-v, -vv).")
] = 0,
language: Annotated[str, typer.Option(help="Dataset language, e.g. 'fr' or 'en'.")] = "fr",
assets_dir: Annotated[
Path, typer.Option(help="Directory for downloaded assets.")
] = Path("assets"),
build_dir: Annotated[
Path, typer.Option(help="Directory for generated output.")
] = Path("build"),
dpi: Annotated[int | None, typer.Option(help="Output resolution (>= 300).")] = None,
) -> None:
"""Configure logging and shared settings for all sub-commands."""
configure_logging(verbose)
card = CardSettings() if dpi is None else CardSettings(dpi=dpi)
settings = Settings(
language=language,
assets_dir=assets_dir,
build_dir=build_dir,
card=card,
)
ctx.obj = CliState(settings=settings)
@app.command()
def fetch(
ctx: typer.Context,
force: Annotated[bool, typer.Option(help="Re-download files even if cached.")] = False,
assets: Annotated[
bool, typer.Option("--assets/--no-assets", help="Download card images.")
] = True,
only: Annotated[
list[str] | None, typer.Option("--only", help="Restrict to card id(s).")
] = None,
) -> None:
"""Stage 1: download the dataset (+ assets) and build the local catalogue."""
state = _state(ctx)
try:
result = fetch_pipeline(state.settings, only=only, force=force, with_assets=assets)
except (SourceError, FileNotFoundError) as exc:
_fail(exc)
console.print(
f"[green]Catalogue:[/green] {len(result.catalog)} cards "
f"({len(result.catalog.characters)} characters, {len(result.catalog.actions)} actions)"
)
console.print(f"[green]Written:[/green] {state.settings.catalog_path}")
@app.command()
def render(
ctx: typer.Context,
screenshot: Annotated[
bool, typer.Option("--screenshot/--no-screenshot", help="Rasterise HTML to PNG.")
] = True,
only: Annotated[
list[str] | None, typer.Option("--only", help="Restrict to card id(s).")
] = None,
) -> None:
"""Stage 2: emit standalone HTML (and PNG) for each card."""
state = _state(ctx)
try:
rendered = render_pipeline(state.settings, only=only, screenshot=screenshot)
except (FileNotFoundError, RenderError) as exc:
_fail(exc)
console.print(f"[green]Rendered:[/green] {len(rendered)} card(s) -> {state.settings.html_dir}")
if screenshot:
console.print(f"[green]PNG:[/green] {state.settings.png_dir}")
@app.command()
def impose(
ctx: typer.Context,
output: Annotated[Path | None, typer.Option(help="PDF output path.")] = None,
only: Annotated[
list[str] | None, typer.Option("--only", help="Restrict to card id(s).")
] = None,
) -> None:
"""Stage 3: lay the generated PNGs out on A4 sheets and write a PDF."""
state = _state(ctx)
try:
result = impose_pipeline(state.settings, only=only, output=output)
except FileNotFoundError as exc:
_fail(exc)
console.print(
f"[green]PDF:[/green] {result.output} ({result.cards} cards, {result.pages} page(s))"
)
@app.command()
def build(
ctx: typer.Context,
force: Annotated[bool, typer.Option(help="Re-download files even if cached.")] = False,
assets: Annotated[
bool, typer.Option("--assets/--no-assets", help="Download card images.")
] = True,
screenshot: Annotated[
bool, typer.Option("--screenshot/--no-screenshot", help="Rasterise HTML to PNG.")
] = True,
only: Annotated[
list[str] | None, typer.Option("--only", help="Restrict to card id(s).")
] = None,
) -> None:
"""Run all three stages: fetch -> render -> impose."""
state = _state(ctx)
try:
result = build_pipeline(
state.settings, only=only, force=force, with_assets=assets, screenshot=screenshot
)
except (SourceError, FileNotFoundError, RenderError) as exc:
_fail(exc)
console.print(
f"[bold green]Done:[/bold green] {len(result.rendered)} cards -> {result.imposition.output}"
)
@app.command(name="list")
def list_cards(ctx: typer.Context) -> None:
"""Print the locally built catalogue."""
state = _state(ctx)
catalog_path = state.settings.catalog_path
if not catalog_path.is_file():
_fail(FileNotFoundError(f"No catalogue at {catalog_path}. Run 'fetch' first."))
catalog = load_catalog(catalog_path)
table = Table(title=f"{len(catalog)} card(s)", header_style="bold")
table.add_column("id")
table.add_column("name")
table.add_column("type")
for card in catalog:
table.add_row(card.id, card.name, card.type.value)
console.print(table)
def _state(ctx: typer.Context) -> CliState:
if not isinstance(ctx.obj, CliState): # pragma: no cover - defensive
raise RuntimeError("CLI state was not initialised.")
return ctx.obj
def _fail(exc: BaseException) -> NoReturn:
console.print(f"[bold red]Error:[/bold red] {exc}")
raise typer.Exit(code=1)
if __name__ == "__main__": # pragma: no cover
app()