First version
This commit is contained in:
@@ -0,0 +1,35 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
quality:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
python-version: ["3.11", "3.12"]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
cache: pip
|
||||||
|
|
||||||
|
- name: Install
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: ruff check .
|
||||||
|
|
||||||
|
- name: Type-check
|
||||||
|
run: mypy
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: pytest --cov --cov-report=term-missing
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
# Byte-compiled / optimized
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# Virtual environments
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# Packaging / build artefacts
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
*.egg-info/
|
||||||
|
.eggs/
|
||||||
|
|
||||||
|
# Tooling caches
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
|
htmlcov/
|
||||||
|
|
||||||
|
# Project outputs
|
||||||
|
output/
|
||||||
|
*.pdf
|
||||||
|
|
||||||
|
# Downloaded / generated assets (data & images are fetched at build time)
|
||||||
|
assets/source/
|
||||||
|
assets/tcg/
|
||||||
|
|
||||||
|
# Editors / OS
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# Genshin TCG Generator
|
||||||
|
|
||||||
|
Turn the [paimon-moe](https://github.com/MadeBaruna/paimon-moe) Genshin Impact
|
||||||
|
TCG data into **printable cards**: standalone HTML per card, high-resolution PNGs
|
||||||
|
and an A4 imposition PDF ready for a home printer or a print shop.
|
||||||
|
|
||||||
|
The pipeline is deliberately split into three inspectable stages.
|
||||||
|
|
||||||
|
```
|
||||||
|
fetch render impose
|
||||||
|
┌───────────────┐ ┌───────────────────┐ ┌────────────────────┐
|
||||||
|
│ fr.json │ │ Jinja2 templates │ │ ReportLab A4 grid │
|
||||||
|
│ + PNG assets │ ───► │ → HTML per card │ ───► │ 3x3, 9 cards/page │
|
||||||
|
│ → catalog.json│ │ → PNG (Playwright)│ │ + crop marks │
|
||||||
|
└───────────────┘ └───────────────────┘ └────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Data mining** – downloads `src/data/tcg/<lang>.json` and every required image
|
||||||
|
from `paimon-moe` into a local `assets/` cache, then parses it into typed
|
||||||
|
[Pydantic](https://docs.pydantic.dev) models (`character` vs `action` cards).
|
||||||
|
- **Modular rendering** – each card is written as a *self-contained* `.html` file
|
||||||
|
(CSS inlined, images referenced relatively) so a badly laid-out card can be
|
||||||
|
tweaked by hand and re-rasterised without re-running the earlier stages.
|
||||||
|
- **Print-ready output** – cards are rendered at the classic 63x88 mm poker
|
||||||
|
format at 300 DPI (configurable) and imposed 3x3 on A4 with optional crop marks.
|
||||||
|
- **Typed and tested** – strict `mypy`, `ruff`, and a `pytest` suite.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.11+
|
||||||
|
- [Playwright](https://playwright.dev/python/)'s Chromium build (installed below)
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m venv .venv
|
||||||
|
.venv\Scripts\Activate.ps1 # or: source .venv/bin/activate
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
playwright install chromium # one-off browser download
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Run the full pipeline (download → render → PDF):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
genshin-tcg build
|
||||||
|
# identical to:
|
||||||
|
python -m genshin_tcg build
|
||||||
|
```
|
||||||
|
|
||||||
|
Or run the stages individually:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
genshin-tcg fetch # download data + assets, write build/catalog.json
|
||||||
|
genshin-tcg render # build/html/<id>.html and build/png/<id>.png
|
||||||
|
genshin-tcg impose # build/cards-fr.pdf
|
||||||
|
```
|
||||||
|
|
||||||
|
Useful flags:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
genshin-tcg --language en build # English dataset
|
||||||
|
genshin-tcg --dpi 600 build # 600 DPI output
|
||||||
|
genshin-tcg render --only ganyu --only diluc # a subset of cards
|
||||||
|
genshin-tcg render --no-screenshot # only regenerate the HTML
|
||||||
|
genshin-tcg list # browse the local catalogue
|
||||||
|
```
|
||||||
|
|
||||||
|
Output layout:
|
||||||
|
|
||||||
|
```
|
||||||
|
build/
|
||||||
|
├── catalog.json # the intermediate "source of truth"
|
||||||
|
├── html/ganyu.html # self-contained, hand-editable
|
||||||
|
├── png/ganyu.png # 744x1039 px @ 300 DPI
|
||||||
|
└── cards-fr.pdf # A4 imposition
|
||||||
|
assets/ # cached downloads (git-ignored)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Settings can be set through the CLI or environment variables (prefix `GTCG_`,
|
||||||
|
nested keys separated by `__`), or a `.env` file:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
GTCG_LANGUAGE=fr
|
||||||
|
GTCG_CARD__DPI=300
|
||||||
|
GTCG_PAGE__CUT_MARKS=true
|
||||||
|
GTCG_RENDER__KEEP_HTML=true
|
||||||
|
```
|
||||||
|
|
||||||
|
| Setting | Default | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `language` | `fr` | Dataset language code |
|
||||||
|
| `assets_dir` | `assets` | Where downloads are cached |
|
||||||
|
| `build_dir` | `build` | Where output is written |
|
||||||
|
| `card.width_mm` / `card.height_mm` | `63` / `88` | Card size (poker format) |
|
||||||
|
| `card.dpi` | `300` | Output resolution |
|
||||||
|
| `page.columns` / `page.rows` | `3` / `3` | Imposition grid |
|
||||||
|
| `page.cut_marks` | `true` | Draw crop marks on the PDF |
|
||||||
|
| `render.keep_html` | `true` | Keep generated HTML after rasterising |
|
||||||
|
|
||||||
|
### Factions / nations
|
||||||
|
|
||||||
|
The upstream dataset does not ship faction artwork, so nation tags are supplied
|
||||||
|
locally. Drop icons into `assets/tcg/icons/factions/<faction>.png` and map cards
|
||||||
|
to them in `assets/overrides/factions.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "ganyu": "liyue", "diluc": "mondstadt", "rhodeia_of_loch": "fatui" }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
ruff check .
|
||||||
|
mypy
|
||||||
|
pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project layout
|
||||||
|
|
||||||
|
```
|
||||||
|
src/genshin_tcg/
|
||||||
|
├── cli.py # Typer entry point
|
||||||
|
├── config.py # pydantic-settings configuration
|
||||||
|
├── constants.py # domain enums + asset path helpers
|
||||||
|
├── models.py # typed domain models (Pydantic)
|
||||||
|
├── markup.py # description normalisation + sanitisation
|
||||||
|
├── pipeline.py # fetch / render / impose orchestration
|
||||||
|
├── data/ # remote source, catalogue, asset download
|
||||||
|
├── rendering/ # Jinja environment, view models, converter, renderer
|
||||||
|
│ └── templates/ # base/character/action templates + stylesheet
|
||||||
|
└── pdf/ # ReportLab imposition
|
||||||
|
```
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
This tool only downloads publicly available assets from `paimon-moe`; all game
|
||||||
|
assets and texts remain the property of HoYoverse. Use for personal printing.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{}
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["hatchling>=1.25"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "genshin-tcg"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Pipeline to generate printable Genshin Impact TCG cards (PNG + A4 imposition PDF) from paimon-moe data."
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
license = { text = "MIT" }
|
||||||
|
authors = [{ name = "Genshin TCG Tool" }]
|
||||||
|
keywords = ["genshin", "tcg", "cards", "pdf", "print", "playwright", "reportlab"]
|
||||||
|
classifiers = [
|
||||||
|
"Development Status :: 4 - Beta",
|
||||||
|
"Environment :: Console",
|
||||||
|
"Intended Audience :: End Users/Desktop",
|
||||||
|
"Programming Language :: Python :: 3",
|
||||||
|
"Programming Language :: Python :: 3.11",
|
||||||
|
"Programming Language :: Python :: 3.12",
|
||||||
|
"Topic :: Multimedia :: Graphics :: Graphics Conversion",
|
||||||
|
]
|
||||||
|
dependencies = [
|
||||||
|
"beautifulsoup4>=4.12",
|
||||||
|
"httpx>=0.27",
|
||||||
|
"jinja2>=3.1",
|
||||||
|
"pillow>=10.4",
|
||||||
|
"playwright>=1.47",
|
||||||
|
"pydantic>=2.9",
|
||||||
|
"pydantic-settings>=2.5",
|
||||||
|
"reportlab>=4.2",
|
||||||
|
"rich>=13.9",
|
||||||
|
"typer>=0.12",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"mypy>=1.11",
|
||||||
|
"pytest>=8.3",
|
||||||
|
"pytest-cov>=6.0",
|
||||||
|
"ruff>=0.7",
|
||||||
|
"types-beautifulsoup4>=4.12",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
genshin-tcg = "genshin_tcg.cli:app"
|
||||||
|
|
||||||
|
[project.urls]
|
||||||
|
Homepage = "https://github.com/example/genshin-tcg"
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["src/genshin_tcg"]
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------------------
|
||||||
|
# Tooling
|
||||||
|
# --------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py311"
|
||||||
|
src = ["src", "tests"]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = [
|
||||||
|
"E", # pycodestyle errors
|
||||||
|
"W", # pycodestyle warnings
|
||||||
|
"F", # pyflakes
|
||||||
|
"I", # isort
|
||||||
|
"N", # pep8-naming
|
||||||
|
"UP", # pyupgrade
|
||||||
|
"B", # flake8-bugbear
|
||||||
|
"C4", # flake8-comprehensions
|
||||||
|
"SIM", # flake8-simplify
|
||||||
|
"TID", # flake8-tidy-imports
|
||||||
|
"RUF", # ruff-specific
|
||||||
|
"PTH", # flake8-use-pathlib
|
||||||
|
"ANN", # flake8-annotations
|
||||||
|
]
|
||||||
|
ignore = [
|
||||||
|
"ANN401", # allow Any where genuinely needed (rare)
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
"tests/**" = ["ANN201", "ANN001"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.isort]
|
||||||
|
known-first-party = ["genshin_tcg"]
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.11"
|
||||||
|
plugins = ["pydantic.mypy"]
|
||||||
|
strict = true
|
||||||
|
warn_unreachable = true
|
||||||
|
warn_unused_ignores = true
|
||||||
|
disallow_any_generics = true
|
||||||
|
disallow_untyped_defs = true
|
||||||
|
no_implicit_reexport = true
|
||||||
|
files = ["src", "tests"]
|
||||||
|
|
||||||
|
[[tool.mypy.overrides]]
|
||||||
|
module = ["reportlab.*", "pil.*"]
|
||||||
|
ignore_missing_imports = true
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
addopts = "-ra --strict-markers --strict-config"
|
||||||
|
filterwarnings = ["error"]
|
||||||
|
|
||||||
|
[tool.coverage.run]
|
||||||
|
source = ["genshin_tcg"]
|
||||||
|
branch = true
|
||||||
|
|
||||||
|
[tool.coverage.report]
|
||||||
|
show_missing = true
|
||||||
|
exclude_lines = ["if TYPE_CHECKING:", "raise NotImplementedError"]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"""Package metadata for :mod:`genshin_tcg`."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
__all__ = ["__version__"]
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
"""Command line entry point (``python -m genshin_tcg``)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from genshin_tcg.cli import app
|
||||||
|
|
||||||
|
if __name__ == "__main__": # pragma: no cover - exercised through the console script
|
||||||
|
app()
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""Runtime configuration.
|
||||||
|
|
||||||
|
Settings can be supplied through (in increasing priority):
|
||||||
|
|
||||||
|
1. the defaults declared below,
|
||||||
|
2. a ``.env`` file / process environment using the ``GTCG_`` prefix, e.g.
|
||||||
|
``GTCG_LANGUAGE=fr`` or ``GTCG_CARD__DPI=600`` (nested keys use ``__``).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
__all__ = ["BASE_DPI", "CardSettings", "PageSettings", "RenderSettings", "Settings"]
|
||||||
|
|
||||||
|
MM_PER_INCH = 25.4
|
||||||
|
#: The reference resolution the card templates are designed against (63x88mm).
|
||||||
|
BASE_DPI = 300
|
||||||
|
|
||||||
|
DEFAULT_SOURCE_BASE_URL = "https://raw.githubusercontent.com/MadeBaruna/paimon-moe/main"
|
||||||
|
|
||||||
|
|
||||||
|
class CardSettings(BaseModel):
|
||||||
|
"""Physical and pixel geometry of a single card."""
|
||||||
|
|
||||||
|
width_mm: float = Field(default=63.0, gt=0)
|
||||||
|
height_mm: float = Field(default=88.0, gt=0)
|
||||||
|
dpi: int = Field(default=BASE_DPI, ge=BASE_DPI)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def design_width_px(self) -> int:
|
||||||
|
"""Template pixel width (always computed at :data:`BASE_DPI`)."""
|
||||||
|
return round(self.width_mm / MM_PER_INCH * BASE_DPI)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def design_height_px(self) -> int:
|
||||||
|
return round(self.height_mm / MM_PER_INCH * BASE_DPI)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def output_width_px(self) -> int:
|
||||||
|
return round(self.design_width_px * self.scale_factor)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def output_height_px(self) -> int:
|
||||||
|
return round(self.design_height_px * self.scale_factor)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def scale_factor(self) -> float:
|
||||||
|
"""Playwright ``deviceScaleFactor`` needed to hit :attr:`dpi`."""
|
||||||
|
return self.dpi / BASE_DPI
|
||||||
|
|
||||||
|
|
||||||
|
class PageSettings(BaseModel):
|
||||||
|
"""A4 sheet geometry and grid."""
|
||||||
|
|
||||||
|
width_mm: float = Field(default=210.0, gt=0)
|
||||||
|
height_mm: float = Field(default=297.0, gt=0)
|
||||||
|
columns: int = Field(default=3, ge=1)
|
||||||
|
rows: int = Field(default=3, ge=1)
|
||||||
|
margin_mm: float = Field(default=0.0, ge=0, description="0 = auto-centre the grid")
|
||||||
|
gutter_mm: float = Field(default=0.0, ge=0)
|
||||||
|
cut_marks: bool = True
|
||||||
|
mark_length_mm: float = Field(default=4.0, gt=0)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def capacity(self) -> int:
|
||||||
|
return self.columns * self.rows
|
||||||
|
|
||||||
|
|
||||||
|
class RenderSettings(BaseModel):
|
||||||
|
"""Browser-based rendering knobs."""
|
||||||
|
|
||||||
|
timeout_ms: int = Field(default=30_000, gt=0)
|
||||||
|
keep_html: bool = True
|
||||||
|
max_concurrency: int = Field(default=1, ge=1)
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
"""Top-level application settings."""
|
||||||
|
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_prefix="GTCG_",
|
||||||
|
env_nested_delimiter="__",
|
||||||
|
env_file=".env",
|
||||||
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
|
language: str = Field(default="fr", min_length=2, max_length=8)
|
||||||
|
source_base_url: str = Field(default=DEFAULT_SOURCE_BASE_URL)
|
||||||
|
assets_dir: Path = Field(default=Path("assets"))
|
||||||
|
build_dir: Path = Field(default=Path("build"))
|
||||||
|
|
||||||
|
card: CardSettings = Field(default_factory=CardSettings)
|
||||||
|
page: PageSettings = Field(default_factory=PageSettings)
|
||||||
|
render: RenderSettings = Field(default_factory=RenderSettings)
|
||||||
|
|
||||||
|
@field_validator("source_base_url")
|
||||||
|
@classmethod
|
||||||
|
def _strip_trailing_slash(cls, value: str) -> str:
|
||||||
|
return value.rstrip("/")
|
||||||
|
|
||||||
|
# -- Derived paths ---------------------------------------------------------
|
||||||
|
|
||||||
|
@property
|
||||||
|
def source_dir(self) -> Path:
|
||||||
|
return self.assets_dir / "source"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def source_json(self) -> Path:
|
||||||
|
return self.source_dir / f"{self.language}.json"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tags_json(self) -> Path:
|
||||||
|
return self.source_dir / f"tags_{self.language}.json"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tcg_dir(self) -> Path:
|
||||||
|
return self.assets_dir / "tcg"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def factions_override(self) -> Path:
|
||||||
|
return self.assets_dir / "overrides" / "factions.json"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def html_dir(self) -> Path:
|
||||||
|
return self.build_dir / "html"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def png_dir(self) -> Path:
|
||||||
|
return self.build_dir / "png"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def catalog_path(self) -> Path:
|
||||||
|
return self.build_dir / "catalog.json"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pdf_path(self) -> Path:
|
||||||
|
return self.build_dir / f"cards-{self.language}.pdf"
|
||||||
|
|
||||||
|
def ensure_directories(self) -> None:
|
||||||
|
"""Create every directory the pipeline writes to."""
|
||||||
|
for directory in (
|
||||||
|
self.source_dir,
|
||||||
|
self.tcg_dir,
|
||||||
|
self.html_dir,
|
||||||
|
self.png_dir,
|
||||||
|
self.build_dir,
|
||||||
|
):
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""Domain vocabulary for the Genshin TCG dataset.
|
||||||
|
|
||||||
|
The string values mirror the tokens used by ``paimon-moe`` (``src/data/tcg``), so
|
||||||
|
they can be serialised to / deserialised from the upstream JSON without loss.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"AssetPaths",
|
||||||
|
"CardType",
|
||||||
|
"CostType",
|
||||||
|
"Element",
|
||||||
|
"Faction",
|
||||||
|
"SkillKind",
|
||||||
|
"WeaponType",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class Element(StrEnum):
|
||||||
|
"""Playable / enemy elements that can appear on a character card."""
|
||||||
|
|
||||||
|
ANEMO = "anemo"
|
||||||
|
GEO = "geo"
|
||||||
|
ELECTRO = "electro"
|
||||||
|
DENDRO = "dendro"
|
||||||
|
HYDRO = "hydro"
|
||||||
|
PYRO = "pyro"
|
||||||
|
CRYO = "cryo"
|
||||||
|
|
||||||
|
|
||||||
|
class WeaponType(StrEnum):
|
||||||
|
"""Weapon categories. ``NONE`` is used by non-weapon-wielding characters."""
|
||||||
|
|
||||||
|
SWORD = "sword"
|
||||||
|
CLAYMORE = "claymore"
|
||||||
|
POLEARM = "pole"
|
||||||
|
BOW = "bow"
|
||||||
|
CATALYST = "catalyst"
|
||||||
|
NONE = "none"
|
||||||
|
|
||||||
|
|
||||||
|
class CardType(StrEnum):
|
||||||
|
"""Every card category present in the dataset."""
|
||||||
|
|
||||||
|
CHARACTER = "character"
|
||||||
|
TALENT = "talent"
|
||||||
|
ARTIFACT = "artifact"
|
||||||
|
WEAPON = "weapon"
|
||||||
|
NONE = "none"
|
||||||
|
RESONANCE = "resonance"
|
||||||
|
ALLY = "ally"
|
||||||
|
FOOD = "food"
|
||||||
|
PLACE = "place"
|
||||||
|
ITEM = "item"
|
||||||
|
|
||||||
|
|
||||||
|
class CostType(StrEnum):
|
||||||
|
"""Token types found inside a skill/action ``cost`` array.
|
||||||
|
|
||||||
|
``VOID`` is the unaligned (any) die, ``SAME`` requires dice of the same
|
||||||
|
element and ``ENERGY`` is the energy cost.
|
||||||
|
"""
|
||||||
|
|
||||||
|
ANEMO = "anemo"
|
||||||
|
GEO = "geo"
|
||||||
|
ELECTRO = "electro"
|
||||||
|
DENDRO = "dendro"
|
||||||
|
HYDRO = "hydro"
|
||||||
|
PYRO = "pyro"
|
||||||
|
CRYO = "cryo"
|
||||||
|
VOID = "void"
|
||||||
|
ENERGY = "energy"
|
||||||
|
SAME = "same"
|
||||||
|
|
||||||
|
|
||||||
|
class SkillKind(StrEnum):
|
||||||
|
"""Localised (French) skill headers as shipped by the dataset."""
|
||||||
|
|
||||||
|
NORMAL_ATTACK = "Attaque normale"
|
||||||
|
ELEMENTAL_SKILL = "Compétence élémentaire"
|
||||||
|
ELEMENTAL_BURST = "Déchaînement élémentaire"
|
||||||
|
PASSIVE = "Capacité passive"
|
||||||
|
|
||||||
|
|
||||||
|
class Faction(StrEnum):
|
||||||
|
"""Best-effort faction vocabulary used to tag cards (see ``overrides``)."""
|
||||||
|
|
||||||
|
MONDSTADT = "mondstadt"
|
||||||
|
LIYUE = "liyue"
|
||||||
|
INAZUMA = "inazuma"
|
||||||
|
SUMERU = "sumeru"
|
||||||
|
FONTAINE = "fontaine"
|
||||||
|
NATLAN = "natlan"
|
||||||
|
SNEZHNAYA = "snezhnaya"
|
||||||
|
KHAENRIAH = "khaenriah"
|
||||||
|
FATUI = "fatui"
|
||||||
|
HILICHURL = "hilichurl"
|
||||||
|
MONSTER = "monster"
|
||||||
|
|
||||||
|
|
||||||
|
class AssetPaths:
|
||||||
|
"""Relative asset locations inside the local ``assets/`` directory.
|
||||||
|
|
||||||
|
They mirror the ``paimon-moe`` ``static/images/tcg`` layout so the downloader
|
||||||
|
can derive remote URLs from the same relative strings.
|
||||||
|
"""
|
||||||
|
|
||||||
|
ILLUSTRATIONS: Final = "tcg"
|
||||||
|
SKILLS: Final = "tcg/skills"
|
||||||
|
ICONS: Final = "tcg/icons"
|
||||||
|
ELEMENTS: Final = "tcg/icons/elements"
|
||||||
|
WEAPONS: Final = "tcg/icons/weapons"
|
||||||
|
TYPES: Final = "tcg/icons/types"
|
||||||
|
|
||||||
|
HP_ICON: Final = "tcg/icons/hp.png"
|
||||||
|
ENERGY_CARD_ICON: Final = "tcg/icons/energy_card.png"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def illustration(card_id: str) -> str:
|
||||||
|
return f"{AssetPaths.ILLUSTRATIONS}/{card_id}.png"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def skill(character_id: str, index: int) -> str:
|
||||||
|
"""``index`` is the 0-based position of the skill in the character's list."""
|
||||||
|
return f"{AssetPaths.SKILLS}/{character_id}/skill_{index + 1}.png"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def cost_die(cost: CostType) -> str:
|
||||||
|
return f"{AssetPaths.ICONS}/{cost.value}.png"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def element(element: Element) -> str:
|
||||||
|
return f"{AssetPaths.ELEMENTS}/{element.value}.png"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def weapon(weapon: WeaponType) -> str:
|
||||||
|
return f"{AssetPaths.WEAPONS}/{weapon.value}.png"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def card_type(card_type: CardType) -> str:
|
||||||
|
return f"{AssetPaths.TYPES}/{card_type.value}.png"
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""Data acquisition and modelling (pipeline stage 1)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from genshin_tcg.data.catalog import Catalog, load_catalog, load_raw_source, save_catalog
|
||||||
|
from genshin_tcg.data.paimon import DownloadReport, PaimonSource, SourceError
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Catalog",
|
||||||
|
"DownloadReport",
|
||||||
|
"PaimonSource",
|
||||||
|
"SourceError",
|
||||||
|
"load_catalog",
|
||||||
|
"load_raw_source",
|
||||||
|
"save_catalog",
|
||||||
|
]
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Asset discovery and download helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from genshin_tcg.constants import AssetPaths, CardType, CostType, Element, WeaponType
|
||||||
|
from genshin_tcg.data.paimon import DownloadReport, PaimonSource
|
||||||
|
from genshin_tcg.models import Card, CharacterCard
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"download_required_assets",
|
||||||
|
"illustration_key",
|
||||||
|
"iter_required_keys",
|
||||||
|
"skill_keys",
|
||||||
|
"static_icon_keys",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def illustration_key(card: Card) -> str:
|
||||||
|
"""Asset key of a card's full artwork."""
|
||||||
|
return AssetPaths.illustration(card.id)
|
||||||
|
|
||||||
|
|
||||||
|
def skill_keys(card: CharacterCard) -> list[str]:
|
||||||
|
"""Asset keys of a character's skill icons, in skill order."""
|
||||||
|
return [AssetPaths.skill(card.id, index) for index in range(len(card.skills))]
|
||||||
|
|
||||||
|
|
||||||
|
def static_icon_keys() -> list[str]:
|
||||||
|
"""Asset keys of every generic icon the templates may reference."""
|
||||||
|
keys: list[str] = [AssetPaths.HP_ICON, AssetPaths.ENERGY_CARD_ICON]
|
||||||
|
keys += [AssetPaths.cost_die(cost) for cost in CostType]
|
||||||
|
keys += [AssetPaths.element(element) for element in Element]
|
||||||
|
keys += [AssetPaths.weapon(weapon) for weapon in WeaponType]
|
||||||
|
keys += [
|
||||||
|
AssetPaths.card_type(card_type)
|
||||||
|
for card_type in CardType
|
||||||
|
if card_type is not CardType.CHARACTER
|
||||||
|
]
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def iter_required_keys(cards: Sequence[Card]) -> list[str]:
|
||||||
|
"""Return every asset key required to render *cards* (deduplicated, sorted)."""
|
||||||
|
keys = set(static_icon_keys())
|
||||||
|
for card in cards:
|
||||||
|
keys.add(illustration_key(card))
|
||||||
|
if isinstance(card, CharacterCard):
|
||||||
|
keys.update(skill_keys(card))
|
||||||
|
return sorted(keys)
|
||||||
|
|
||||||
|
|
||||||
|
def download_required_assets(
|
||||||
|
cards: Sequence[Card],
|
||||||
|
*,
|
||||||
|
assets_dir: Path,
|
||||||
|
base_url: str,
|
||||||
|
force: bool = False,
|
||||||
|
max_workers: int = 8,
|
||||||
|
) -> DownloadReport:
|
||||||
|
"""Download every asset required to render *cards* into ``assets_dir``."""
|
||||||
|
with PaimonSource(base_url) as source:
|
||||||
|
return source.download_assets(
|
||||||
|
iter_required_keys(cards),
|
||||||
|
assets_dir=assets_dir,
|
||||||
|
force=force,
|
||||||
|
max_workers=max_workers,
|
||||||
|
)
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Loading, classifying and persisting the card catalogue (pipeline stage 1)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from collections.abc import Iterator, Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
from genshin_tcg.models import ActionCard, Card, CharacterCard, parse_catalog
|
||||||
|
|
||||||
|
__all__ = ["Catalog", "load_catalog", "load_raw_source", "save_catalog"]
|
||||||
|
|
||||||
|
_logger = get_logger("data.catalog")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Catalog:
|
||||||
|
"""An immutable, queryable collection of parsed cards."""
|
||||||
|
|
||||||
|
cards: tuple[Card, ...] = ()
|
||||||
|
_by_id: dict[str, Card] = field(init=False, repr=False, compare=False)
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
by_id: dict[str, Card] = {}
|
||||||
|
for card in self.cards:
|
||||||
|
if card.id in by_id:
|
||||||
|
_logger.warning("Duplicate card id %r; the last entry wins", card.id)
|
||||||
|
by_id[card.id] = card
|
||||||
|
object.__setattr__(self, "_by_id", by_id)
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return len(self.cards)
|
||||||
|
|
||||||
|
def __iter__(self) -> Iterator[Card]:
|
||||||
|
return iter(self.cards)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def characters(self) -> tuple[CharacterCard, ...]:
|
||||||
|
return tuple(card for card in self.cards if isinstance(card, CharacterCard))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def actions(self) -> tuple[ActionCard, ...]:
|
||||||
|
return tuple(card for card in self.cards if isinstance(card, ActionCard))
|
||||||
|
|
||||||
|
def get(self, card_id: str) -> Card:
|
||||||
|
try:
|
||||||
|
return self._by_id[card_id]
|
||||||
|
except KeyError as exc:
|
||||||
|
raise KeyError(f"Unknown card id: {card_id!r}") from exc
|
||||||
|
|
||||||
|
def select(self, ids: Sequence[str]) -> Catalog:
|
||||||
|
"""Return a sub-catalogue restricted to *ids* (order preserved)."""
|
||||||
|
return Catalog(cards=tuple(self.get(card_id) for card_id in ids))
|
||||||
|
|
||||||
|
|
||||||
|
def load_raw_source(path: Path) -> list[dict[str, Any]]:
|
||||||
|
"""Read the raw localised JSON payload."""
|
||||||
|
if not path.is_file():
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"Source data not found at {path}. Run the 'fetch' command first."
|
||||||
|
)
|
||||||
|
with path.open(encoding="utf-8") as handle:
|
||||||
|
payload = json.load(handle)
|
||||||
|
if not isinstance(payload, list):
|
||||||
|
raise ValueError(f"Expected a JSON array in {path}, got {type(payload).__name__}")
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def save_catalog(catalog: Catalog, path: Path) -> None:
|
||||||
|
"""Persist *catalog* as pretty JSON, atomically."""
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
payload = [card.model_dump(mode="json", by_alias=True, exclude_none=True) for card in catalog]
|
||||||
|
temporary = path.with_suffix(path.suffix + ".tmp")
|
||||||
|
temporary.write_text(
|
||||||
|
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
temporary.replace(path)
|
||||||
|
_logger.info("Wrote catalogue with %d cards to %s", len(catalog), path)
|
||||||
|
|
||||||
|
|
||||||
|
def load_catalog(path: Path) -> Catalog:
|
||||||
|
"""Load a catalogue previously written by :func:`save_catalog`."""
|
||||||
|
cards = parse_catalog(load_raw_source(path))
|
||||||
|
return Catalog(cards=tuple(cards))
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"""Remote transport for the ``paimon-moe`` GitHub repository.
|
||||||
|
|
||||||
|
All network access funnels through :class:`PaimonSource`, which resolves
|
||||||
|
project-relative asset keys (see :class:`~genshin_tcg.constants.AssetPaths`) to
|
||||||
|
raw GitHub URLs and caches the downloaded bytes on disk.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
|
||||||
|
__all__ = ["DownloadReport", "PaimonSource", "SourceError"]
|
||||||
|
|
||||||
|
_DATA_PREFIX = "src/data/tcg"
|
||||||
|
_IMAGE_PREFIX = "static/images"
|
||||||
|
|
||||||
|
|
||||||
|
class SourceError(RuntimeError):
|
||||||
|
"""Raised when the remote source cannot be reached or a file is missing."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class DownloadReport:
|
||||||
|
"""Outcome of a batch download."""
|
||||||
|
|
||||||
|
downloaded: list[str] = field(default_factory=list)
|
||||||
|
skipped: list[str] = field(default_factory=list)
|
||||||
|
failed: dict[str, str] = field(default_factory=dict)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ok(self) -> bool:
|
||||||
|
return not self.failed
|
||||||
|
|
||||||
|
|
||||||
|
class PaimonSource:
|
||||||
|
"""A caching HTTP client for the paimon-moe data repository."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: str,
|
||||||
|
*,
|
||||||
|
client: httpx.Client | None = None,
|
||||||
|
logger: logging.Logger | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._base_url = base_url.rstrip("/")
|
||||||
|
self._logger = logger or get_logger("data.paimon")
|
||||||
|
self._owns_client = client is None
|
||||||
|
self._client = client or httpx.Client(
|
||||||
|
timeout=httpx.Timeout(30.0, connect=15.0),
|
||||||
|
follow_redirects=True,
|
||||||
|
transport=httpx.HTTPTransport(retries=3),
|
||||||
|
headers={"User-Agent": "genshin-tcg/0.1 (+https://github.com/)"},
|
||||||
|
)
|
||||||
|
|
||||||
|
# -- Context manager -------------------------------------------------------
|
||||||
|
|
||||||
|
def __enter__(self) -> PaimonSource:
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc: object) -> None:
|
||||||
|
self.close()
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._owns_client:
|
||||||
|
self._client.close()
|
||||||
|
|
||||||
|
# -- URL helpers -----------------------------------------------------------
|
||||||
|
|
||||||
|
def data_url(self, language: str) -> str:
|
||||||
|
return self._url(f"{_DATA_PREFIX}/{language}.json")
|
||||||
|
|
||||||
|
def tags_url(self, language: str) -> str:
|
||||||
|
return self._url(f"{_DATA_PREFIX}/tags/{language}.json")
|
||||||
|
|
||||||
|
def asset_url(self, relative: str) -> str:
|
||||||
|
"""Map an asset key such as ``tcg/ganyu.png`` to its raw URL."""
|
||||||
|
return self._url(f"{_IMAGE_PREFIX}/{relative}")
|
||||||
|
|
||||||
|
def _url(self, path: str) -> str:
|
||||||
|
return f"{self._base_url}/{quote(path, safe='/')}"
|
||||||
|
|
||||||
|
# -- Downloads -------------------------------------------------------------
|
||||||
|
|
||||||
|
def fetch_text(self, url: str) -> str:
|
||||||
|
"""Download *url* and decode it as UTF-8."""
|
||||||
|
try:
|
||||||
|
response = self._client.get(url)
|
||||||
|
response.raise_for_status()
|
||||||
|
except httpx.HTTPError as exc: # pragma: no cover - network dependent
|
||||||
|
raise SourceError(f"Failed to fetch {url}: {exc}") from exc
|
||||||
|
return response.text
|
||||||
|
|
||||||
|
def save_to(self, url: str, destination: Path, *, force: bool = False) -> bool:
|
||||||
|
"""Download *url* into *destination* unless it already exists.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``True`` when a download happened, ``False`` when cached.
|
||||||
|
"""
|
||||||
|
if not force and destination.is_file() and destination.stat().st_size > 0:
|
||||||
|
return False
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
try:
|
||||||
|
response = self._client.get(url)
|
||||||
|
response.raise_for_status()
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise SourceError(f"Failed to fetch {url}: {exc}") from exc
|
||||||
|
destination.write_bytes(response.content)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def download_assets(
|
||||||
|
self,
|
||||||
|
relative_keys: list[str],
|
||||||
|
*,
|
||||||
|
assets_dir: Path,
|
||||||
|
force: bool = False,
|
||||||
|
max_workers: int = 8,
|
||||||
|
) -> DownloadReport:
|
||||||
|
"""Download a batch of asset keys concurrently into ``assets_dir``."""
|
||||||
|
report = DownloadReport()
|
||||||
|
unique = sorted(set(relative_keys))
|
||||||
|
self._logger.debug("Resolving %d asset keys", len(unique))
|
||||||
|
|
||||||
|
def _one(relative: str) -> tuple[str, str | None]:
|
||||||
|
try:
|
||||||
|
changed = self.save_to(
|
||||||
|
self.asset_url(relative),
|
||||||
|
assets_dir / relative,
|
||||||
|
force=force,
|
||||||
|
)
|
||||||
|
except SourceError as exc:
|
||||||
|
return relative, str(exc)
|
||||||
|
return relative, "downloaded" if changed else "skipped"
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
||||||
|
for relative, outcome in pool.map(_one, unique):
|
||||||
|
if outcome == "downloaded":
|
||||||
|
report.downloaded.append(relative)
|
||||||
|
elif outcome == "skipped":
|
||||||
|
report.skipped.append(relative)
|
||||||
|
else:
|
||||||
|
assert outcome is not None
|
||||||
|
report.failed[relative] = outcome
|
||||||
|
self._logger.warning("Asset unavailable: %s (%s)", relative, outcome)
|
||||||
|
|
||||||
|
self._logger.info(
|
||||||
|
"Assets: %d downloaded, %d cached, %d missing",
|
||||||
|
len(report.downloaded),
|
||||||
|
len(report.skipped),
|
||||||
|
len(report.failed),
|
||||||
|
)
|
||||||
|
return report
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Centralised logging configuration using :mod:`rich`."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from rich.logging import RichHandler
|
||||||
|
|
||||||
|
__all__ = ["configure_logging", "get_logger"]
|
||||||
|
|
||||||
|
_ROOT_LOGGER_NAME = "genshin_tcg"
|
||||||
|
|
||||||
|
|
||||||
|
def get_logger(name: str | None = None) -> logging.Logger:
|
||||||
|
"""Return a namespaced logger (``genshin_tcg`` when *name* is omitted)."""
|
||||||
|
if not name:
|
||||||
|
return logging.getLogger(_ROOT_LOGGER_NAME)
|
||||||
|
if name == _ROOT_LOGGER_NAME or name.startswith(f"{_ROOT_LOGGER_NAME}."):
|
||||||
|
return logging.getLogger(name)
|
||||||
|
return logging.getLogger(f"{_ROOT_LOGGER_NAME}.{name}")
|
||||||
|
|
||||||
|
|
||||||
|
def configure_logging(verbosity: int = 0) -> None:
|
||||||
|
"""Attach a single :class:`RichHandler` to the package logger.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
verbosity: 0 -> WARNING, 1 -> INFO, >=2 -> DEBUG.
|
||||||
|
"""
|
||||||
|
level = logging.WARNING if verbosity <= 0 else logging.INFO if verbosity == 1 else logging.DEBUG
|
||||||
|
logger = logging.getLogger(_ROOT_LOGGER_NAME)
|
||||||
|
logger.setLevel(level)
|
||||||
|
logger.handlers.clear()
|
||||||
|
logger.propagate = False
|
||||||
|
|
||||||
|
handler = RichHandler(rich_tracebacks=True, show_path=level <= logging.DEBUG, markup=False)
|
||||||
|
handler.setFormatter(logging.Formatter("%(message)s", datefmt="[%X]"))
|
||||||
|
logger.addHandler(handler)
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""Normalisation and sanitisation of the upstream card markup.
|
||||||
|
|
||||||
|
The dataset ships rich markup inside descriptions:
|
||||||
|
|
||||||
|
* ``<span style="color: #RRGGBBAA;">…</span>`` for coloured keywords, and
|
||||||
|
* escaped line breaks written as the two characters ``\\n``.
|
||||||
|
|
||||||
|
Older Genshin exports use ``<color=#RRGGBB>…</color>`` instead, so both forms
|
||||||
|
are supported. Everything is finally run through :func:`sanitize` which keeps a
|
||||||
|
small allow-list of tags/styles, making the output safe to inject with Jinja's
|
||||||
|
``| safe`` filter.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
from bs4 import BeautifulSoup, Tag
|
||||||
|
|
||||||
|
__all__ = ["clean_markup", "inline_symbols", "sanitize", "strip_markup"]
|
||||||
|
|
||||||
|
# ``<color=#RRGGBB>`` / ``<color=#RRGGBBAA>`` -> span with an inline style.
|
||||||
|
_COLOR_OPEN = re.compile(r"<color=(#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?)>", re.IGNORECASE)
|
||||||
|
_COLOR_CLOSE = re.compile(r"</color\s*>", re.IGNORECASE)
|
||||||
|
|
||||||
|
# Allow-list: tag name -> permitted attribute names.
|
||||||
|
_ALLOWED_TAGS: dict[str, frozenset[str]] = {
|
||||||
|
"span": frozenset({"style"}),
|
||||||
|
"b": frozenset(),
|
||||||
|
"strong": frozenset(),
|
||||||
|
"i": frozenset(),
|
||||||
|
"em": frozenset(),
|
||||||
|
"u": frozenset(),
|
||||||
|
"br": frozenset(),
|
||||||
|
}
|
||||||
|
|
||||||
|
# Allow-list of inline CSS properties we are willing to render.
|
||||||
|
_ALLOWED_STYLE_PROPS: frozenset[str] = frozenset({"color", "text-decoration", "font-weight"})
|
||||||
|
|
||||||
|
# Disallowed tags whose *contents* must be dropped rather than unwrapped.
|
||||||
|
_DROP_CONTENT_TAGS: tuple[str, ...] = (
|
||||||
|
"script",
|
||||||
|
"style",
|
||||||
|
"template",
|
||||||
|
"iframe",
|
||||||
|
"object",
|
||||||
|
"embed",
|
||||||
|
"head",
|
||||||
|
"title",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_style(style: str) -> str:
|
||||||
|
"""Keep only the allow-listed declarations of an inline ``style`` attribute."""
|
||||||
|
declarations: list[str] = []
|
||||||
|
for raw in style.split(";"):
|
||||||
|
declaration = raw.strip()
|
||||||
|
if not declaration or ":" not in declaration:
|
||||||
|
continue
|
||||||
|
prop, _, value = declaration.partition(":")
|
||||||
|
prop = prop.strip().lower()
|
||||||
|
value = value.strip()
|
||||||
|
if prop in _ALLOWED_STYLE_PROPS and value:
|
||||||
|
declarations.append(f"{prop}: {value}")
|
||||||
|
return "; ".join(declarations)
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare(text: str) -> str:
|
||||||
|
"""Rewrite ``<color=…>`` tags and escaped newlines before sanitising."""
|
||||||
|
text = _COLOR_CLOSE.sub("</span>", _COLOR_OPEN.sub(r'<span style="color:\1">', text))
|
||||||
|
# The dataset stores line breaks as a literal backslash followed by 'n'.
|
||||||
|
text = text.replace("\\n", "<br/>").replace("\r\n", "<br/>").replace("\n", "<br/>")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize(fragment: str) -> str:
|
||||||
|
"""Return ``fragment`` restricted to the allow-listed subset of HTML."""
|
||||||
|
soup = BeautifulSoup(fragment, "html.parser")
|
||||||
|
for dangerous in soup.find_all(list(_DROP_CONTENT_TAGS)):
|
||||||
|
dangerous.decompose()
|
||||||
|
for tag in soup.find_all(True):
|
||||||
|
allowed_attrs = _ALLOWED_TAGS.get(tag.name)
|
||||||
|
if allowed_attrs is None:
|
||||||
|
tag.unwrap()
|
||||||
|
continue
|
||||||
|
_filter_attributes(tag, allowed_attrs)
|
||||||
|
return "".join(str(child) for child in soup.children)
|
||||||
|
|
||||||
|
|
||||||
|
def _filter_attributes(tag: Tag, allowed_attrs: frozenset[str]) -> None:
|
||||||
|
for name in list(tag.attrs):
|
||||||
|
if name not in allowed_attrs:
|
||||||
|
del tag.attrs[name]
|
||||||
|
|
||||||
|
style = tag.get("style")
|
||||||
|
if isinstance(style, str):
|
||||||
|
cleaned = _clean_style(style)
|
||||||
|
if cleaned:
|
||||||
|
tag["style"] = cleaned
|
||||||
|
else:
|
||||||
|
del tag["style"]
|
||||||
|
|
||||||
|
|
||||||
|
def clean_markup(text: str) -> str:
|
||||||
|
"""Full pipeline: colour tags -> ``<br/>`` -> sanitised HTML string."""
|
||||||
|
return sanitize(_prepare(text))
|
||||||
|
|
||||||
|
|
||||||
|
def strip_markup(text: str) -> str:
|
||||||
|
"""Return the plain-text content, with ``<br/>`` collapsed to spaces."""
|
||||||
|
soup = BeautifulSoup(_prepare(text), "html.parser")
|
||||||
|
return soup.get_text(" ", strip=True)
|
||||||
|
|
||||||
|
|
||||||
|
#: Splits an HTML fragment into alternating text / tag chunks (tags captured).
|
||||||
|
_HTML_CHUNKS = re.compile(r"(<[^>]*>)")
|
||||||
|
#: Characters treated as "word" characters for boundary detection (incl. accents).
|
||||||
|
_WORD_CHARS = r"\w\u00C0-\u024F"
|
||||||
|
|
||||||
|
|
||||||
|
def inline_symbols(html: str, symbols: Mapping[str, str]) -> str:
|
||||||
|
"""Replace whole-word ``keywords`` with inline markup, skipping HTML tags.
|
||||||
|
|
||||||
|
``symbols`` maps a literal keyword (e.g. ``"Cryo"``) to the markup that
|
||||||
|
should be inserted *before* it (e.g. an ``<img>`` tag). Keyword matching is
|
||||||
|
case-sensitive and respects word boundaries, and only text nodes are
|
||||||
|
rewritten so tag names and attribute values are never touched.
|
||||||
|
"""
|
||||||
|
if not symbols:
|
||||||
|
return html
|
||||||
|
alternatives = "|".join(re.escape(key) for key in sorted(symbols, key=len, reverse=True))
|
||||||
|
pattern = re.compile(
|
||||||
|
rf"(?<![{_WORD_CHARS}])({alternatives})(?![{_WORD_CHARS}])"
|
||||||
|
)
|
||||||
|
chunks = _HTML_CHUNKS.split(html)
|
||||||
|
for index in range(0, len(chunks), 2): # even indices hold text, odd hold tags
|
||||||
|
chunks[index] = pattern.sub(
|
||||||
|
lambda match: f"{symbols[match.group(1)]}{match.group(1)}", chunks[index]
|
||||||
|
)
|
||||||
|
return "".join(chunks)
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""Typed domain models for the TCG dataset.
|
||||||
|
|
||||||
|
The models are intentionally frozen (immutable) so a parsed catalogue can be
|
||||||
|
safely shared across threads (e.g. by the concurrent asset downloader) and
|
||||||
|
serialised back to disk as the intermediate "source of truth" JSON.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from typing import Annotated, Any, Literal, TypeAlias
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator
|
||||||
|
|
||||||
|
from genshin_tcg.constants import CardType, CostType, Element, WeaponType
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ActionCard",
|
||||||
|
"ActionCardType",
|
||||||
|
"Card",
|
||||||
|
"CharacterCard",
|
||||||
|
"CostItem",
|
||||||
|
"Skill",
|
||||||
|
"SubSkill",
|
||||||
|
"parse_catalog",
|
||||||
|
]
|
||||||
|
|
||||||
|
NonEmptyStr = Annotated[str, StringConstraints(min_length=1)]
|
||||||
|
|
||||||
|
|
||||||
|
class _Base(BaseModel):
|
||||||
|
"""Shared model configuration."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(frozen=True, populate_by_name=True, extra="ignore")
|
||||||
|
|
||||||
|
|
||||||
|
class CostItem(_Base):
|
||||||
|
"""A single die (or energy) in a skill/action cost."""
|
||||||
|
|
||||||
|
type: CostType
|
||||||
|
count: Annotated[int, Field(ge=0, le=10)]
|
||||||
|
|
||||||
|
|
||||||
|
class SubSkill(_Base):
|
||||||
|
"""An entity summoned / created by a skill (e.g. a "Perle de glace")."""
|
||||||
|
|
||||||
|
id: NonEmptyStr
|
||||||
|
name: NonEmptyStr
|
||||||
|
description: NonEmptyStr = Field(alias="desc")
|
||||||
|
|
||||||
|
|
||||||
|
class Skill(_Base):
|
||||||
|
"""A single skill of a character card."""
|
||||||
|
|
||||||
|
id: NonEmptyStr | None = None
|
||||||
|
kind: NonEmptyStr = Field(alias="type", description="Localised skill header.")
|
||||||
|
name: NonEmptyStr
|
||||||
|
description: NonEmptyStr = Field(alias="desc")
|
||||||
|
cost: tuple[CostItem, ...] = ()
|
||||||
|
sub: SubSkill | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class _CardBase(_Base):
|
||||||
|
"""Fields shared by every card."""
|
||||||
|
|
||||||
|
internal_id: int = Field(alias="_id")
|
||||||
|
id: NonEmptyStr
|
||||||
|
name: NonEmptyStr
|
||||||
|
type: CardType
|
||||||
|
|
||||||
|
|
||||||
|
class CharacterCard(_CardBase):
|
||||||
|
"""A playable character card (portrait layout with skills)."""
|
||||||
|
|
||||||
|
type: Literal[CardType.CHARACTER]
|
||||||
|
hp: Annotated[int, Field(ge=1, le=99)]
|
||||||
|
energy: Annotated[int, Field(ge=0, le=10)]
|
||||||
|
element: Element
|
||||||
|
weapon: WeaponType
|
||||||
|
skills: tuple[Skill, ...] = Field(min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
ActionCardType: TypeAlias = Literal[
|
||||||
|
CardType.TALENT,
|
||||||
|
CardType.ARTIFACT,
|
||||||
|
CardType.WEAPON,
|
||||||
|
CardType.NONE,
|
||||||
|
CardType.RESONANCE,
|
||||||
|
CardType.ALLY,
|
||||||
|
CardType.FOOD,
|
||||||
|
CardType.PLACE,
|
||||||
|
CardType.ITEM,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ActionCard(_CardBase):
|
||||||
|
"""Any non-character card (single cost + description)."""
|
||||||
|
|
||||||
|
type: ActionCardType
|
||||||
|
requirement: NonEmptyStr | None = None
|
||||||
|
cost: tuple[CostItem, ...] = ()
|
||||||
|
description: NonEmptyStr
|
||||||
|
|
||||||
|
@model_validator(mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _flatten_skills(cls, data: Mapping[str, Any]) -> Mapping[str, Any]:
|
||||||
|
"""The upstream format nests cost/description under a ``skills`` object."""
|
||||||
|
if "description" in data or "cost" in data:
|
||||||
|
return data
|
||||||
|
skills = data.get("skills")
|
||||||
|
if isinstance(skills, Mapping):
|
||||||
|
return {**data, "cost": skills.get("cost", []), "description": skills.get("desc")}
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
Card: TypeAlias = CharacterCard | ActionCard
|
||||||
|
|
||||||
|
|
||||||
|
def parse_catalog(raw: Sequence[Mapping[str, Any]]) -> list[Card]:
|
||||||
|
"""Parse the raw ``fr.json`` payload into typed :data:`Card` objects.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
pydantic.ValidationError: if an entry does not match any known card shape.
|
||||||
|
"""
|
||||||
|
cards: list[Card] = []
|
||||||
|
for entry in raw:
|
||||||
|
card_type = entry.get("type")
|
||||||
|
if card_type == CardType.CHARACTER:
|
||||||
|
cards.append(CharacterCard.model_validate(entry))
|
||||||
|
else:
|
||||||
|
cards.append(ActionCard.model_validate(entry))
|
||||||
|
return cards
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"""PDF imposition (pipeline stage 3)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from genshin_tcg.pdf.imposition import ImpositionGrid, ImpositionResult, impose_pdf
|
||||||
|
|
||||||
|
__all__ = ["ImpositionGrid", "ImpositionResult", "impose_pdf"]
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"""A4 imposition: lay card PNGs out on a print sheet and export a PDF.
|
||||||
|
|
||||||
|
The grid is described in millimetres and rendered with ReportLab for precise
|
||||||
|
placement. Optionally short crop marks are drawn at every card corner.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from reportlab.lib.units import mm
|
||||||
|
from reportlab.pdfgen import canvas as pdf_canvas
|
||||||
|
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover
|
||||||
|
from reportlab.pdfgen.canvas import Canvas
|
||||||
|
|
||||||
|
__all__ = ["ImpositionGrid", "ImpositionResult", "impose_pdf"]
|
||||||
|
|
||||||
|
_logger = get_logger("pdf.imposition")
|
||||||
|
|
||||||
|
_CROP_MARK_WIDTH_PT = 0.35
|
||||||
|
_CROP_MARK_COLOR = (0.35, 0.35, 0.35)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ImpositionGrid:
|
||||||
|
"""Physical description of a print sheet and its card grid."""
|
||||||
|
|
||||||
|
page_width_mm: float = 210.0
|
||||||
|
page_height_mm: float = 297.0
|
||||||
|
card_width_mm: float = 63.0
|
||||||
|
card_height_mm: float = 88.0
|
||||||
|
columns: int = 3
|
||||||
|
rows: int = 3
|
||||||
|
margin_mm: float = 0.0
|
||||||
|
gutter_mm: float = 0.0
|
||||||
|
cut_marks: bool = True
|
||||||
|
mark_length_mm: float = 4.0
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if self.columns < 1 or self.rows < 1:
|
||||||
|
raise ValueError("columns and rows must be >= 1")
|
||||||
|
if self.content_width_mm > self.page_width_mm + 1e-6:
|
||||||
|
raise ValueError(
|
||||||
|
f"Grid is too wide: {self.content_width_mm:.1f}mm > {self.page_width_mm:.1f}mm"
|
||||||
|
)
|
||||||
|
if self.content_height_mm > self.page_height_mm + 1e-6:
|
||||||
|
raise ValueError(
|
||||||
|
f"Grid is too tall: {self.content_height_mm:.1f}mm > {self.page_height_mm:.1f}mm"
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def capacity(self) -> int:
|
||||||
|
"""Number of cards that fit on one sheet."""
|
||||||
|
return self.columns * self.rows
|
||||||
|
|
||||||
|
@property
|
||||||
|
def content_width_mm(self) -> float:
|
||||||
|
return self.columns * self.card_width_mm + (self.columns - 1) * self.gutter_mm
|
||||||
|
|
||||||
|
@property
|
||||||
|
def content_height_mm(self) -> float:
|
||||||
|
return self.rows * self.card_height_mm + (self.rows - 1) * self.gutter_mm
|
||||||
|
|
||||||
|
@property
|
||||||
|
def offset_x_mm(self) -> float:
|
||||||
|
if self.margin_mm > 0:
|
||||||
|
return self.margin_mm
|
||||||
|
return (self.page_width_mm - self.content_width_mm) / 2
|
||||||
|
|
||||||
|
@property
|
||||||
|
def offset_y_mm(self) -> float:
|
||||||
|
if self.margin_mm > 0:
|
||||||
|
return self.margin_mm
|
||||||
|
return (self.page_height_mm - self.content_height_mm) / 2
|
||||||
|
|
||||||
|
def cell_top_left_mm(self, index: int) -> tuple[float, float]:
|
||||||
|
"""Return the top-left ``(x, y)`` of the card at ``index`` on the sheet."""
|
||||||
|
if not 0 <= index < self.capacity:
|
||||||
|
raise IndexError(f"Cell index {index} out of range (capacity={self.capacity})")
|
||||||
|
column = index % self.columns
|
||||||
|
row = index // self.columns
|
||||||
|
x = self.offset_x_mm + column * (self.card_width_mm + self.gutter_mm)
|
||||||
|
y = self.offset_y_mm + row * (self.card_height_mm + self.gutter_mm)
|
||||||
|
return x, y
|
||||||
|
|
||||||
|
def page_count(self, card_count: int) -> int:
|
||||||
|
if card_count < 0:
|
||||||
|
raise ValueError("card_count must be >= 0")
|
||||||
|
return math.ceil(card_count / self.capacity) if card_count else 0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ImpositionResult:
|
||||||
|
output: Path
|
||||||
|
pages: int
|
||||||
|
cards: int
|
||||||
|
|
||||||
|
|
||||||
|
def impose_pdf(
|
||||||
|
image_paths: Sequence[Path],
|
||||||
|
output: Path,
|
||||||
|
grid: ImpositionGrid,
|
||||||
|
*,
|
||||||
|
title: str = "Genshin TCG",
|
||||||
|
) -> ImpositionResult:
|
||||||
|
"""Lay *image_paths* out on sheets described by *grid* and write a PDF.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
An :class:`ImpositionResult` describing what was written.
|
||||||
|
"""
|
||||||
|
for path in image_paths:
|
||||||
|
if not path.is_file():
|
||||||
|
raise FileNotFoundError(f"Missing card image: {path}")
|
||||||
|
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
pages = grid.page_count(len(image_paths))
|
||||||
|
|
||||||
|
canvas = pdf_canvas.Canvas(
|
||||||
|
str(output), pagesize=(grid.page_width_mm * mm, grid.page_height_mm * mm)
|
||||||
|
)
|
||||||
|
canvas.setTitle(title)
|
||||||
|
|
||||||
|
for page_index in range(pages):
|
||||||
|
chunk = image_paths[page_index * grid.capacity : (page_index + 1) * grid.capacity]
|
||||||
|
for cell_index, image_path in enumerate(chunk):
|
||||||
|
_draw_card(canvas, image_path, grid, cell_index)
|
||||||
|
if grid.cut_marks:
|
||||||
|
_draw_crop_marks(canvas, grid, len(chunk))
|
||||||
|
canvas.showPage()
|
||||||
|
|
||||||
|
canvas.save()
|
||||||
|
_logger.info("Wrote %d card(s) across %d page(s) to %s", len(image_paths), pages, output)
|
||||||
|
return ImpositionResult(output=output, pages=pages, cards=len(image_paths))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_card(canvas: Canvas, image_path: Path, grid: ImpositionGrid, cell_index: int) -> None:
|
||||||
|
x_mm, y_top_mm = grid.cell_top_left_mm(cell_index)
|
||||||
|
y_bottom_mm = grid.page_height_mm - y_top_mm - grid.card_height_mm
|
||||||
|
canvas.drawImage(
|
||||||
|
str(image_path),
|
||||||
|
x_mm * mm,
|
||||||
|
y_bottom_mm * mm,
|
||||||
|
width=grid.card_width_mm * mm,
|
||||||
|
height=grid.card_height_mm * mm,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_crop_marks(canvas: Canvas, grid: ImpositionGrid, drawn: int) -> None:
|
||||||
|
canvas.saveState()
|
||||||
|
canvas.setStrokeColorRGB(*_CROP_MARK_COLOR)
|
||||||
|
canvas.setLineWidth(_CROP_MARK_WIDTH_PT)
|
||||||
|
length = grid.mark_length_mm
|
||||||
|
for cell_index in range(drawn):
|
||||||
|
x_mm, y_top_mm = grid.cell_top_left_mm(cell_index)
|
||||||
|
right_mm = x_mm + grid.card_width_mm
|
||||||
|
bottom_mm = y_top_mm + grid.card_height_mm
|
||||||
|
corners = (
|
||||||
|
(x_mm, y_top_mm, -1, -1),
|
||||||
|
(right_mm, y_top_mm, 1, -1),
|
||||||
|
(x_mm, bottom_mm, -1, 1),
|
||||||
|
(right_mm, bottom_mm, 1, 1),
|
||||||
|
)
|
||||||
|
for corner_x, corner_y, direction_x, direction_y in corners:
|
||||||
|
# Horizontal tick.
|
||||||
|
canvas.line(
|
||||||
|
corner_x * mm,
|
||||||
|
(grid.page_height_mm - corner_y) * mm,
|
||||||
|
(corner_x + direction_x * length) * mm,
|
||||||
|
(grid.page_height_mm - corner_y) * mm,
|
||||||
|
)
|
||||||
|
# Vertical tick.
|
||||||
|
canvas.line(
|
||||||
|
corner_x * mm,
|
||||||
|
(grid.page_height_mm - corner_y) * mm,
|
||||||
|
corner_x * mm,
|
||||||
|
(grid.page_height_mm - corner_y - direction_y * length) * mm,
|
||||||
|
)
|
||||||
|
canvas.restoreState()
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""Pipeline orchestration.
|
||||||
|
|
||||||
|
The three stages from the design document are exposed both individually
|
||||||
|
(:func:`fetch`, :func:`render`, :func:`impose`) and combined (:func:`build`) so
|
||||||
|
each step can be inspected before continuing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from genshin_tcg.config import Settings
|
||||||
|
from genshin_tcg.data.assets import download_required_assets
|
||||||
|
from genshin_tcg.data.catalog import Catalog, load_catalog, load_raw_source, save_catalog
|
||||||
|
from genshin_tcg.data.paimon import DownloadReport, PaimonSource
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
from genshin_tcg.models import parse_catalog
|
||||||
|
from genshin_tcg.pdf.imposition import ImpositionGrid, ImpositionResult, impose_pdf
|
||||||
|
from genshin_tcg.rendering.converters import HtmlConverter, PlaywrightConverter, Viewport
|
||||||
|
from genshin_tcg.rendering.renderer import CardRenderer, RenderedCard, safe_name
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"BuildResult",
|
||||||
|
"FetchResult",
|
||||||
|
"build",
|
||||||
|
"fetch",
|
||||||
|
"impose",
|
||||||
|
"render",
|
||||||
|
]
|
||||||
|
|
||||||
|
_logger = get_logger("pipeline")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class FetchResult:
|
||||||
|
catalog: Catalog
|
||||||
|
downloads: DownloadReport | None
|
||||||
|
source_json: Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class BuildResult:
|
||||||
|
fetch: FetchResult
|
||||||
|
rendered: list[RenderedCard]
|
||||||
|
imposition: ImpositionResult
|
||||||
|
|
||||||
|
|
||||||
|
def fetch(
|
||||||
|
settings: Settings,
|
||||||
|
*,
|
||||||
|
only: Sequence[str] | None = None,
|
||||||
|
force: bool = False,
|
||||||
|
with_assets: bool = True,
|
||||||
|
) -> FetchResult:
|
||||||
|
"""Stage 1 - download the localised JSON (+ assets) and build the catalogue."""
|
||||||
|
settings.ensure_directories()
|
||||||
|
with PaimonSource(settings.source_base_url) as source:
|
||||||
|
source.save_to(source.data_url(settings.language), settings.source_json, force=force)
|
||||||
|
source.save_to(source.tags_url(settings.language), settings.tags_json, force=force)
|
||||||
|
|
||||||
|
catalog = Catalog(cards=tuple(parse_catalog(load_raw_source(settings.source_json))))
|
||||||
|
_logger.info(
|
||||||
|
"Parsed %d card(s): %d character(s), %d action(s)",
|
||||||
|
len(catalog),
|
||||||
|
len(catalog.characters),
|
||||||
|
len(catalog.actions),
|
||||||
|
)
|
||||||
|
if only:
|
||||||
|
catalog = catalog.select(only)
|
||||||
|
|
||||||
|
save_catalog(catalog, settings.catalog_path)
|
||||||
|
|
||||||
|
downloads: DownloadReport | None = None
|
||||||
|
if with_assets:
|
||||||
|
downloads = download_required_assets(
|
||||||
|
catalog.cards,
|
||||||
|
assets_dir=settings.assets_dir,
|
||||||
|
base_url=settings.source_base_url,
|
||||||
|
force=force,
|
||||||
|
)
|
||||||
|
if not downloads.ok:
|
||||||
|
_logger.warning("%d asset(s) could not be downloaded", len(downloads.failed))
|
||||||
|
|
||||||
|
return FetchResult(catalog=catalog, downloads=downloads, source_json=settings.source_json)
|
||||||
|
|
||||||
|
|
||||||
|
def render(
|
||||||
|
settings: Settings,
|
||||||
|
*,
|
||||||
|
only: Sequence[str] | None = None,
|
||||||
|
screenshot: bool = True,
|
||||||
|
converter: HtmlConverter | None = None,
|
||||||
|
) -> list[RenderedCard]:
|
||||||
|
"""Stage 2 - emit HTML for every card and (optionally) rasterise to PNG.
|
||||||
|
|
||||||
|
*converter* lets callers inject a pre-opened :class:`HtmlConverter` (useful in
|
||||||
|
tests); when omitted a :class:`PlaywrightConverter` is created and closed.
|
||||||
|
"""
|
||||||
|
catalog = _load_catalogue(settings)
|
||||||
|
if only:
|
||||||
|
catalog = catalog.select(only)
|
||||||
|
|
||||||
|
renderer = CardRenderer(settings)
|
||||||
|
rendered = renderer.write_html(renderer.build_views(catalog))
|
||||||
|
if not screenshot:
|
||||||
|
return rendered
|
||||||
|
|
||||||
|
if converter is not None:
|
||||||
|
return renderer.rasterise(rendered, converter)
|
||||||
|
|
||||||
|
card = settings.card
|
||||||
|
viewport = Viewport(
|
||||||
|
width_px=card.design_width_px,
|
||||||
|
height_px=card.design_height_px,
|
||||||
|
scale_factor=card.scale_factor,
|
||||||
|
)
|
||||||
|
with PlaywrightConverter(viewport, timeout_ms=settings.render.timeout_ms) as runner:
|
||||||
|
return renderer.rasterise(rendered, runner)
|
||||||
|
|
||||||
|
|
||||||
|
def impose(
|
||||||
|
settings: Settings,
|
||||||
|
*,
|
||||||
|
only: Sequence[str] | None = None,
|
||||||
|
output: Path | None = None,
|
||||||
|
) -> ImpositionResult:
|
||||||
|
"""Stage 3 - lay every rendered PNG out on A4 sheets and write a PDF."""
|
||||||
|
catalog = _load_catalogue(settings)
|
||||||
|
if only:
|
||||||
|
catalog = catalog.select(only)
|
||||||
|
|
||||||
|
images = [settings.png_dir / f"{safe_name(card.id)}.png" for card in catalog]
|
||||||
|
grid = _grid_from_settings(settings)
|
||||||
|
return impose_pdf(images, output or settings.pdf_path, grid)
|
||||||
|
|
||||||
|
|
||||||
|
def build(
|
||||||
|
settings: Settings,
|
||||||
|
*,
|
||||||
|
only: Sequence[str] | None = None,
|
||||||
|
force: bool = False,
|
||||||
|
with_assets: bool = True,
|
||||||
|
screenshot: bool = True,
|
||||||
|
) -> BuildResult:
|
||||||
|
"""Run all three stages in sequence."""
|
||||||
|
fetch_result = fetch(settings, only=only, force=force, with_assets=with_assets)
|
||||||
|
rendered = render(settings, only=only, screenshot=screenshot)
|
||||||
|
imposition = impose(settings, only=only, output=settings.pdf_path)
|
||||||
|
return BuildResult(fetch=fetch_result, rendered=rendered, imposition=imposition)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_catalogue(settings: Settings) -> Catalog:
|
||||||
|
if not settings.catalog_path.is_file():
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"No catalogue at {settings.catalog_path}. Run the 'fetch' command first."
|
||||||
|
)
|
||||||
|
return load_catalog(settings.catalog_path)
|
||||||
|
|
||||||
|
|
||||||
|
def _grid_from_settings(settings: Settings) -> ImpositionGrid:
|
||||||
|
page = settings.page
|
||||||
|
card = settings.card
|
||||||
|
return ImpositionGrid(
|
||||||
|
page_width_mm=page.width_mm,
|
||||||
|
page_height_mm=page.height_mm,
|
||||||
|
card_width_mm=card.width_mm,
|
||||||
|
card_height_mm=card.height_mm,
|
||||||
|
columns=page.columns,
|
||||||
|
rows=page.rows,
|
||||||
|
margin_mm=page.margin_mm,
|
||||||
|
gutter_mm=page.gutter_mm,
|
||||||
|
cut_marks=page.cut_marks,
|
||||||
|
mark_length_mm=page.mark_length_mm,
|
||||||
|
)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Marker file: this package ships inline type information (PEP 561).
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Templating and rasterisation (pipeline stage 2)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from genshin_tcg.rendering.context import ActionView, CardView, CharacterView, build_view
|
||||||
|
from genshin_tcg.rendering.converters import (
|
||||||
|
HtmlConverter,
|
||||||
|
PlaywrightConverter,
|
||||||
|
RenderError,
|
||||||
|
Viewport,
|
||||||
|
)
|
||||||
|
from genshin_tcg.rendering.environment import build_environment
|
||||||
|
from genshin_tcg.rendering.renderer import CardRenderer, RenderedCard
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ActionView",
|
||||||
|
"CardRenderer",
|
||||||
|
"CardView",
|
||||||
|
"CharacterView",
|
||||||
|
"HtmlConverter",
|
||||||
|
"PlaywrightConverter",
|
||||||
|
"RenderError",
|
||||||
|
"RenderedCard",
|
||||||
|
"Viewport",
|
||||||
|
"build_environment",
|
||||||
|
"build_view",
|
||||||
|
]
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
"""Build the typed template context (view models) for a card.
|
||||||
|
|
||||||
|
This module is the boundary between the *domain* models (:mod:`genshin_tcg.models`)
|
||||||
|
and the *presentation* templates: it resolves asset URLs, localises labels and
|
||||||
|
sanitises descriptions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Literal, TypeAlias
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
from genshin_tcg.constants import AssetPaths, CostType, Element
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
from genshin_tcg.markup import clean_markup, inline_symbols
|
||||||
|
from genshin_tcg.models import ActionCard, Card, CharacterCard, CostItem
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ActionView",
|
||||||
|
"CardView",
|
||||||
|
"CharacterView",
|
||||||
|
"CostView",
|
||||||
|
"SkillView",
|
||||||
|
"TagView",
|
||||||
|
"build_view",
|
||||||
|
"load_faction_overrides",
|
||||||
|
"load_labels",
|
||||||
|
]
|
||||||
|
|
||||||
|
_logger = get_logger("rendering.context")
|
||||||
|
|
||||||
|
#: Fallback labels so the pipeline works offline / in tests.
|
||||||
|
_DEFAULT_LABELS: dict[str, str] = {
|
||||||
|
"character": "Personnage",
|
||||||
|
"talent": "Aptitude",
|
||||||
|
"artifact": "Artéfact",
|
||||||
|
"weapon": "Arme",
|
||||||
|
"none": "Sans élément",
|
||||||
|
"resonance": "Résonance élémentaire",
|
||||||
|
"ally": "Compagnon",
|
||||||
|
"food": "Plat",
|
||||||
|
"place": "Terrain",
|
||||||
|
"item": "Objet",
|
||||||
|
"anemo": "Anémo",
|
||||||
|
"geo": "Géo",
|
||||||
|
"electro": "Électro",
|
||||||
|
"dendro": "Dendro",
|
||||||
|
"hydro": "Hydro",
|
||||||
|
"pyro": "Pyro",
|
||||||
|
"cryo": "Cryo",
|
||||||
|
"sword": "Épée à une main",
|
||||||
|
"claymore": "Épée à deux mains",
|
||||||
|
"pole": "Arme d'hast",
|
||||||
|
"bow": "Arc",
|
||||||
|
"catalyst": "Catalyseur",
|
||||||
|
"void": "Dé indéterminé",
|
||||||
|
"energy": "Énergie",
|
||||||
|
"same": "Dé identique",
|
||||||
|
"mondstadt": "Mondstadt",
|
||||||
|
"liyue": "Liyue",
|
||||||
|
"inazuma": "Inazuma",
|
||||||
|
"sumeru": "Sumeru",
|
||||||
|
"fontaine": "Fontaine",
|
||||||
|
"natlan": "Natlan",
|
||||||
|
"snezhnaya": "Snezhnaya",
|
||||||
|
"khaenriah": "Khaenri'ah",
|
||||||
|
"fatui": "Fatui",
|
||||||
|
"hilichurl": "Brutocollinus",
|
||||||
|
"monster": "Monstre",
|
||||||
|
}
|
||||||
|
|
||||||
|
#: Keywords replaced by an inline element die inside descriptions.
|
||||||
|
_INLINE_SYMBOLS: dict[str, str] = {
|
||||||
|
"Anémo": "anemo",
|
||||||
|
"Géo": "geo",
|
||||||
|
"Électro": "electro",
|
||||||
|
"Dendro": "dendro",
|
||||||
|
"Hydro": "hydro",
|
||||||
|
"Pyro": "pyro",
|
||||||
|
"Cryo": "cryo",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class CostView(BaseModel):
|
||||||
|
model_config = ConfigDict(frozen=True)
|
||||||
|
|
||||||
|
label: str
|
||||||
|
icon: str
|
||||||
|
count: int
|
||||||
|
|
||||||
|
|
||||||
|
class TagView(BaseModel):
|
||||||
|
model_config = ConfigDict(frozen=True)
|
||||||
|
|
||||||
|
kind: Literal["element", "weapon", "faction"]
|
||||||
|
label: str
|
||||||
|
icon: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SkillView(BaseModel):
|
||||||
|
model_config = ConfigDict(frozen=True)
|
||||||
|
|
||||||
|
name: str
|
||||||
|
kind: str
|
||||||
|
description_html: str
|
||||||
|
icon: str | None = None
|
||||||
|
cost: tuple[CostView, ...] = ()
|
||||||
|
sub_name: str | None = None
|
||||||
|
sub_description_html: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class _ViewBase(BaseModel):
|
||||||
|
model_config = ConfigDict(frozen=True)
|
||||||
|
|
||||||
|
card_id: str
|
||||||
|
name: str
|
||||||
|
css_class: str
|
||||||
|
width_px: int
|
||||||
|
height_px: int
|
||||||
|
illustration: str
|
||||||
|
|
||||||
|
|
||||||
|
class CharacterView(_ViewBase):
|
||||||
|
kind: Literal["character"] = "character"
|
||||||
|
hp: int
|
||||||
|
hp_icon: str
|
||||||
|
energy: int
|
||||||
|
energy_icon: str
|
||||||
|
element_icon: str
|
||||||
|
element_label: str
|
||||||
|
weapon_icon: str
|
||||||
|
weapon_label: str
|
||||||
|
tags: tuple[TagView, ...] = ()
|
||||||
|
skills: tuple[SkillView, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
class ActionView(_ViewBase):
|
||||||
|
kind: Literal["action"] = "action"
|
||||||
|
type_label: str
|
||||||
|
type_icon: str
|
||||||
|
cost: tuple[CostView, ...] = ()
|
||||||
|
description_html: str
|
||||||
|
requirement: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
CardView: TypeAlias = CharacterView | ActionView
|
||||||
|
|
||||||
|
|
||||||
|
class AssetUrlResolver:
|
||||||
|
"""Translate asset keys to URLs relative to the generated HTML directory."""
|
||||||
|
|
||||||
|
def __init__(self, assets_dir: Path, html_dir: Path) -> None:
|
||||||
|
self._assets_dir = assets_dir
|
||||||
|
self._html_dir = html_dir
|
||||||
|
|
||||||
|
def url(self, key: str) -> str:
|
||||||
|
absolute = (self._assets_dir / key).resolve()
|
||||||
|
relative = os.path.relpath(absolute, start=self._html_dir.resolve())
|
||||||
|
return Path(relative).as_posix()
|
||||||
|
|
||||||
|
def exists(self, key: str) -> bool:
|
||||||
|
return (self._assets_dir / key).is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def load_labels(path: Path) -> dict[str, str]:
|
||||||
|
"""Merge the localised ``tags`` file (if any) over the built-in labels."""
|
||||||
|
labels = dict(_DEFAULT_LABELS)
|
||||||
|
if path.is_file():
|
||||||
|
try:
|
||||||
|
payload: Any = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
except json.JSONDecodeError as exc: # pragma: no cover - defensive
|
||||||
|
_logger.warning("Invalid tags file %s: %s", path, exc)
|
||||||
|
return labels
|
||||||
|
if isinstance(payload, Mapping):
|
||||||
|
labels.update({str(k): str(v) for k, v in payload.items()})
|
||||||
|
else:
|
||||||
|
_logger.debug("No tags file at %s; using built-in labels", path)
|
||||||
|
return labels
|
||||||
|
|
||||||
|
|
||||||
|
def load_faction_overrides(path: Path) -> dict[str, str]:
|
||||||
|
"""Load an optional ``card id -> faction`` mapping maintained by the user.
|
||||||
|
|
||||||
|
The upstream dataset does not store faction/nation icons, so they are
|
||||||
|
supplied locally (see the design document's "Factions/Nations" note).
|
||||||
|
"""
|
||||||
|
if not path.is_file():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
payload: Any = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
except json.JSONDecodeError as exc: # pragma: no cover - defensive
|
||||||
|
_logger.warning("Invalid faction override file %s: %s", path, exc)
|
||||||
|
return {}
|
||||||
|
if not isinstance(payload, Mapping):
|
||||||
|
_logger.warning("Faction overrides must be a JSON object in %s", path)
|
||||||
|
return {}
|
||||||
|
return {str(k): str(v) for k, v in payload.items()}
|
||||||
|
|
||||||
|
|
||||||
|
class _ViewBuilder:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
assets_dir: Path,
|
||||||
|
html_dir: Path,
|
||||||
|
labels: Mapping[str, str],
|
||||||
|
factions: Mapping[str, str],
|
||||||
|
inline_element_icons: bool = True,
|
||||||
|
) -> None:
|
||||||
|
self._resolver = AssetUrlResolver(assets_dir, html_dir)
|
||||||
|
self._labels = labels
|
||||||
|
self._factions = factions
|
||||||
|
self._inline = inline_element_icons
|
||||||
|
|
||||||
|
# -- Public API ------------------------------------------------------------
|
||||||
|
|
||||||
|
def build(self, card: Card, *, width_px: int, height_px: int) -> CardView:
|
||||||
|
if isinstance(card, CharacterCard):
|
||||||
|
return self._character(card, width_px=width_px, height_px=height_px)
|
||||||
|
return self._action(card, width_px=width_px, height_px=height_px)
|
||||||
|
|
||||||
|
# -- Internals -------------------------------------------------------------
|
||||||
|
|
||||||
|
def _description(self, raw: str) -> str:
|
||||||
|
html = clean_markup(raw)
|
||||||
|
if not self._inline:
|
||||||
|
return html
|
||||||
|
symbols = {
|
||||||
|
keyword: self._inline_icon(icon, keyword)
|
||||||
|
for keyword, icon in _INLINE_SYMBOLS.items()
|
||||||
|
}
|
||||||
|
return inline_symbols(html, symbols)
|
||||||
|
|
||||||
|
def _inline_icon(self, element: str, alt: str) -> str:
|
||||||
|
url = self._resolver.url(AssetPaths.element(Element(element)))
|
||||||
|
return f'<img class="inline-die" src="{url}" alt="{alt}">'
|
||||||
|
|
||||||
|
def _cost(self, items: Sequence[CostItem]) -> tuple[CostView, ...]:
|
||||||
|
if not items:
|
||||||
|
return (
|
||||||
|
CostView(
|
||||||
|
label=self._labels.get(CostType.SAME.value, "Dé identique"),
|
||||||
|
icon=self._resolver.url(AssetPaths.cost_die(CostType.SAME)),
|
||||||
|
count=0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return tuple(
|
||||||
|
CostView(
|
||||||
|
label=self._labels.get(item.type.value, item.type.value),
|
||||||
|
icon=self._resolver.url(AssetPaths.cost_die(item.type)),
|
||||||
|
count=item.count,
|
||||||
|
)
|
||||||
|
for item in items
|
||||||
|
)
|
||||||
|
|
||||||
|
def _character(self, card: CharacterCard, *, width_px: int, height_px: int) -> CharacterView:
|
||||||
|
tags: list[TagView] = [
|
||||||
|
TagView(
|
||||||
|
kind="element",
|
||||||
|
label=self._labels.get(card.element.value, card.element.value),
|
||||||
|
icon=self._resolver.url(AssetPaths.element(card.element)),
|
||||||
|
),
|
||||||
|
TagView(
|
||||||
|
kind="weapon",
|
||||||
|
label=self._labels.get(card.weapon.value, card.weapon.value),
|
||||||
|
icon=self._resolver.url(AssetPaths.weapon(card.weapon)),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
faction = self._factions.get(card.id)
|
||||||
|
if faction:
|
||||||
|
faction_key = f"tcg/icons/factions/{faction}.png"
|
||||||
|
tags.append(
|
||||||
|
TagView(
|
||||||
|
kind="faction",
|
||||||
|
label=self._labels.get(faction, faction),
|
||||||
|
icon=(
|
||||||
|
self._resolver.url(faction_key)
|
||||||
|
if self._resolver.exists(faction_key)
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
skills = tuple(
|
||||||
|
SkillView(
|
||||||
|
name=skill.name,
|
||||||
|
kind=skill.kind,
|
||||||
|
description_html=self._description(skill.description),
|
||||||
|
icon=self._resolver.url(AssetPaths.skill(card.id, index)),
|
||||||
|
cost=self._cost(skill.cost),
|
||||||
|
sub_name=skill.sub.name if skill.sub else None,
|
||||||
|
sub_description_html=(
|
||||||
|
self._description(skill.sub.description) if skill.sub else None
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for index, skill in enumerate(card.skills)
|
||||||
|
)
|
||||||
|
|
||||||
|
return CharacterView(
|
||||||
|
card_id=card.id,
|
||||||
|
name=card.name,
|
||||||
|
css_class=f"el-{card.element.value}",
|
||||||
|
width_px=width_px,
|
||||||
|
height_px=height_px,
|
||||||
|
illustration=self._resolver.url(AssetPaths.illustration(card.id)),
|
||||||
|
hp=card.hp,
|
||||||
|
hp_icon=self._resolver.url(AssetPaths.HP_ICON),
|
||||||
|
energy=card.energy,
|
||||||
|
energy_icon=self._resolver.url(AssetPaths.ENERGY_CARD_ICON),
|
||||||
|
element_icon=self._resolver.url(AssetPaths.element(card.element)),
|
||||||
|
element_label=self._labels.get(card.element.value, card.element.value),
|
||||||
|
weapon_icon=self._resolver.url(AssetPaths.weapon(card.weapon)),
|
||||||
|
weapon_label=self._labels.get(card.weapon.value, card.weapon.value),
|
||||||
|
tags=tuple(tags),
|
||||||
|
skills=skills,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _action(self, card: ActionCard, *, width_px: int, height_px: int) -> ActionView:
|
||||||
|
requirement = (
|
||||||
|
self._labels.get(card.requirement, card.requirement) if card.requirement else None
|
||||||
|
)
|
||||||
|
return ActionView(
|
||||||
|
card_id=card.id,
|
||||||
|
name=card.name,
|
||||||
|
css_class=f"type-{card.type.value}",
|
||||||
|
width_px=width_px,
|
||||||
|
height_px=height_px,
|
||||||
|
illustration=self._resolver.url(AssetPaths.illustration(card.id)),
|
||||||
|
type_label=self._labels.get(card.type.value, card.type.value),
|
||||||
|
type_icon=self._resolver.url(AssetPaths.card_type(card.type)),
|
||||||
|
cost=self._cost(card.cost),
|
||||||
|
description_html=self._description(card.description),
|
||||||
|
requirement=requirement,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_view(
|
||||||
|
card: Card,
|
||||||
|
*,
|
||||||
|
assets_dir: Path,
|
||||||
|
html_dir: Path,
|
||||||
|
labels: Mapping[str, str] | None = None,
|
||||||
|
factions: Mapping[str, str] | None = None,
|
||||||
|
width_px: int,
|
||||||
|
height_px: int,
|
||||||
|
inline_element_icons: bool = True,
|
||||||
|
) -> CardView:
|
||||||
|
"""Convenience wrapper around :class:`_ViewBuilder` for a single card."""
|
||||||
|
builder = _ViewBuilder(
|
||||||
|
assets_dir=assets_dir,
|
||||||
|
html_dir=html_dir,
|
||||||
|
labels=labels if labels is not None else dict(_DEFAULT_LABELS),
|
||||||
|
factions=factions or {},
|
||||||
|
inline_element_icons=inline_element_icons,
|
||||||
|
)
|
||||||
|
return builder.build(card, width_px=width_px, height_px=height_px)
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""Pluggable HTML-to-image converters.
|
||||||
|
|
||||||
|
The rendering stage depends only on the :class:`HtmlConverter` protocol, so an
|
||||||
|
alternative backend (e.g. ``wkhtmltopdf``) can be dropped in without touching the
|
||||||
|
renderer. :class:`PlaywrightConverter` is the default implementation and drives
|
||||||
|
headless Chromium.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from contextlib import suppress
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from types import TracebackType
|
||||||
|
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
||||||
|
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover
|
||||||
|
from playwright.sync_api import Browser, BrowserContext, Page, Playwright
|
||||||
|
|
||||||
|
__all__ = ["HtmlConverter", "PlaywrightConverter", "RenderError", "Viewport"]
|
||||||
|
|
||||||
|
|
||||||
|
class RenderError(RuntimeError):
|
||||||
|
"""Raised when a card cannot be rasterised."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Viewport:
|
||||||
|
"""Pixel geometry handed to the browser."""
|
||||||
|
|
||||||
|
width_px: int
|
||||||
|
height_px: int
|
||||||
|
scale_factor: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class HtmlConverter(Protocol):
|
||||||
|
"""A stateful, reusable HTML rasteriser (use as a context manager)."""
|
||||||
|
|
||||||
|
def convert(self, html_path: Path, image_path: Path) -> None:
|
||||||
|
"""Rasterise ``html_path`` into ``image_path``."""
|
||||||
|
|
||||||
|
def close(self) -> None: ...
|
||||||
|
|
||||||
|
def __enter__(self) -> HtmlConverter: ...
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc: BaseException | None,
|
||||||
|
tb: TracebackType | None,
|
||||||
|
) -> bool | None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class PlaywrightConverter:
|
||||||
|
"""Rasterise HTML with headless Chromium via Playwright."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
viewport: Viewport,
|
||||||
|
*,
|
||||||
|
timeout_ms: int = 30_000,
|
||||||
|
logger: logging.Logger | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._viewport = viewport
|
||||||
|
self._timeout_ms = timeout_ms
|
||||||
|
self._logger = logger or get_logger("rendering.playwright")
|
||||||
|
self._playwright: Playwright | None = None
|
||||||
|
self._browser: Browser | None = None
|
||||||
|
self._context: BrowserContext | None = None
|
||||||
|
self._page: Page | None = None
|
||||||
|
|
||||||
|
# -- Context manager -------------------------------------------------------
|
||||||
|
|
||||||
|
def __enter__(self) -> PlaywrightConverter:
|
||||||
|
try:
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
except ImportError as exc: # pragma: no cover - dependency is declared
|
||||||
|
raise RenderError(
|
||||||
|
"Playwright is not installed. Run `pip install playwright` and "
|
||||||
|
"`playwright install chromium`."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
playwright = sync_playwright().start()
|
||||||
|
browser = playwright.chromium.launch(headless=True)
|
||||||
|
context = browser.new_context(
|
||||||
|
viewport={"width": self._viewport.width_px, "height": self._viewport.height_px},
|
||||||
|
device_scale_factor=self._viewport.scale_factor,
|
||||||
|
reduced_motion="reduce",
|
||||||
|
)
|
||||||
|
context.set_default_timeout(self._timeout_ms)
|
||||||
|
page = context.new_page()
|
||||||
|
except Exception as exc: # pragma: no cover - environment dependent
|
||||||
|
raise RenderError(
|
||||||
|
"Could not launch Chromium. Run `playwright install chromium`."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
self._playwright, self._browser, self._context, self._page = (
|
||||||
|
playwright,
|
||||||
|
browser,
|
||||||
|
context,
|
||||||
|
page,
|
||||||
|
)
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc: BaseException | None,
|
||||||
|
tb: TracebackType | None,
|
||||||
|
) -> bool | None:
|
||||||
|
self.close()
|
||||||
|
return None
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
with suppress(Exception):
|
||||||
|
if self._context is not None:
|
||||||
|
self._context.close()
|
||||||
|
with suppress(Exception):
|
||||||
|
if self._browser is not None:
|
||||||
|
self._browser.close()
|
||||||
|
with suppress(Exception):
|
||||||
|
if self._playwright is not None:
|
||||||
|
self._playwright.stop()
|
||||||
|
self._playwright = self._browser = self._context = self._page = None
|
||||||
|
|
||||||
|
# -- Conversion ------------------------------------------------------------
|
||||||
|
|
||||||
|
def convert(self, html_path: Path, image_path: Path) -> None:
|
||||||
|
if self._page is None:
|
||||||
|
raise RenderError("Converter must be used as a context manager.")
|
||||||
|
|
||||||
|
page = self._page
|
||||||
|
image_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
try:
|
||||||
|
page.goto(html_path.resolve().as_uri(), wait_until="load")
|
||||||
|
page.wait_for_function("() => Array.from(document.images).every((i) => i.complete)")
|
||||||
|
page.screenshot(
|
||||||
|
path=str(image_path),
|
||||||
|
clip={
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"width": self._viewport.width_px,
|
||||||
|
"height": self._viewport.height_px,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except Exception as exc: # pragma: no cover - browser dependent
|
||||||
|
raise RenderError(f"Failed to rasterise {html_path.name}: {exc}") from exc
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""HTML -> server-side renderer environment."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape
|
||||||
|
|
||||||
|
__all__ = ["TEMPLATES_DIR", "build_environment"]
|
||||||
|
|
||||||
|
TEMPLATES_DIR = Path(__file__).parent / "templates"
|
||||||
|
|
||||||
|
|
||||||
|
def build_environment(templates_dir: Path | None = None) -> Environment:
|
||||||
|
"""Create the Jinja environment used to render card templates.
|
||||||
|
|
||||||
|
``autoescape`` is enabled for HTML, so card descriptions (already sanitised
|
||||||
|
upstream) must be injected with the ``| safe`` filter explicitly.
|
||||||
|
"""
|
||||||
|
return Environment(
|
||||||
|
loader=FileSystemLoader(str(templates_dir or TEMPLATES_DIR)),
|
||||||
|
undefined=StrictUndefined,
|
||||||
|
autoescape=select_autoescape(
|
||||||
|
enabled_extensions=("html", "jinja"), default_for_string=False
|
||||||
|
),
|
||||||
|
trim_blocks=True,
|
||||||
|
lstrip_blocks=True,
|
||||||
|
keep_trailing_newline=True,
|
||||||
|
)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""Card rendering: build views, emit self-contained HTML and rasterise to PNG.
|
||||||
|
|
||||||
|
Each generated HTML file is standalone (stylesheet inlined, assets referenced by
|
||||||
|
relative URLs) so it can be opened, hand-tweaked and re-rasterised without
|
||||||
|
re-running the earlier pipeline stages.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from jinja2 import Environment
|
||||||
|
|
||||||
|
from genshin_tcg.config import Settings
|
||||||
|
from genshin_tcg.data.catalog import Catalog
|
||||||
|
from genshin_tcg.logging_setup import get_logger
|
||||||
|
from genshin_tcg.models import Card
|
||||||
|
from genshin_tcg.rendering.context import (
|
||||||
|
CardView,
|
||||||
|
CharacterView,
|
||||||
|
build_view,
|
||||||
|
load_faction_overrides,
|
||||||
|
load_labels,
|
||||||
|
)
|
||||||
|
from genshin_tcg.rendering.converters import HtmlConverter
|
||||||
|
from genshin_tcg.rendering.environment import build_environment
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ACTION_HEADER_RATIO",
|
||||||
|
"BODY_RATIO",
|
||||||
|
"CHARACTER_HEADER_RATIO",
|
||||||
|
"CardRenderer",
|
||||||
|
"RenderedCard",
|
||||||
|
"safe_name",
|
||||||
|
]
|
||||||
|
|
||||||
|
#: Vertical zoning (see the design document, section 4).
|
||||||
|
CHARACTER_HEADER_RATIO = 0.20
|
||||||
|
ACTION_HEADER_RATIO = 0.15
|
||||||
|
BODY_RATIO = 0.40
|
||||||
|
|
||||||
|
_PROGRESS_EVERY = 25
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class RenderedCard:
|
||||||
|
"""A card that has been rendered to HTML and (optionally) rasterised."""
|
||||||
|
|
||||||
|
card_id: str
|
||||||
|
kind: str
|
||||||
|
html_path: Path
|
||||||
|
png_path: Path
|
||||||
|
|
||||||
|
|
||||||
|
class CardRenderer:
|
||||||
|
"""Render a :class:`~genshin_tcg.data.catalog.Catalog` to HTML and PNG files."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
settings: Settings,
|
||||||
|
*,
|
||||||
|
environment: Environment | None = None,
|
||||||
|
labels: Mapping[str, str] | None = None,
|
||||||
|
factions: Mapping[str, str] | None = None,
|
||||||
|
logger: logging.Logger | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._settings = settings
|
||||||
|
self._environment = environment or build_environment()
|
||||||
|
self._labels = (
|
||||||
|
dict(labels) if labels is not None else load_labels(settings.tags_json)
|
||||||
|
)
|
||||||
|
self._factions = (
|
||||||
|
dict(factions)
|
||||||
|
if factions is not None
|
||||||
|
else load_faction_overrides(settings.factions_override)
|
||||||
|
)
|
||||||
|
self._logger = logger or get_logger("rendering.renderer")
|
||||||
|
self._style = self._render_stylesheet()
|
||||||
|
|
||||||
|
# -- Public API ------------------------------------------------------------
|
||||||
|
|
||||||
|
def build_views(self, catalog: Catalog) -> list[CardView]:
|
||||||
|
"""Turn every card of *catalog* into a typed template view."""
|
||||||
|
return [self._build_view(card) for card in catalog]
|
||||||
|
|
||||||
|
def write_html(self, views: Sequence[CardView]) -> list[RenderedCard]:
|
||||||
|
"""Write one standalone HTML file per view."""
|
||||||
|
self._settings.html_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
rendered: list[RenderedCard] = []
|
||||||
|
for view in views:
|
||||||
|
template_name = (
|
||||||
|
"character.html.jinja" if isinstance(view, CharacterView) else "action.html.jinja"
|
||||||
|
)
|
||||||
|
document = self._environment.get_template(template_name).render(
|
||||||
|
view=view,
|
||||||
|
card_class=view.css_class,
|
||||||
|
style_content=self._style,
|
||||||
|
)
|
||||||
|
stem = safe_name(view.card_id)
|
||||||
|
html_path = self._settings.html_dir / f"{stem}.html"
|
||||||
|
html_path.write_text(document, encoding="utf-8")
|
||||||
|
rendered.append(
|
||||||
|
RenderedCard(
|
||||||
|
card_id=view.card_id,
|
||||||
|
kind=view.kind,
|
||||||
|
html_path=html_path,
|
||||||
|
png_path=self._settings.png_dir / f"{stem}.png",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._logger.info("Wrote %d HTML card(s) to %s", len(rendered), self._settings.html_dir)
|
||||||
|
return rendered
|
||||||
|
|
||||||
|
def rasterise(
|
||||||
|
self,
|
||||||
|
rendered: Sequence[RenderedCard],
|
||||||
|
converter: HtmlConverter,
|
||||||
|
) -> list[RenderedCard]:
|
||||||
|
"""Rasterise each rendered HTML file to PNG using *converter*."""
|
||||||
|
self._settings.png_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
total = len(rendered)
|
||||||
|
for index, item in enumerate(rendered, start=1):
|
||||||
|
converter.convert(item.html_path, item.png_path)
|
||||||
|
if index % _PROGRESS_EVERY == 0 or index == total:
|
||||||
|
self._logger.info("Rasterised %d/%d card(s)", index, total)
|
||||||
|
if not self._settings.render.keep_html:
|
||||||
|
for item in rendered:
|
||||||
|
item.html_path.unlink(missing_ok=True)
|
||||||
|
return list(rendered)
|
||||||
|
|
||||||
|
# -- Internals -------------------------------------------------------------
|
||||||
|
|
||||||
|
def _build_view(self, card: Card) -> CardView:
|
||||||
|
card_settings = self._settings.card
|
||||||
|
return build_view(
|
||||||
|
card,
|
||||||
|
assets_dir=self._settings.assets_dir,
|
||||||
|
html_dir=self._settings.html_dir,
|
||||||
|
labels=self._labels,
|
||||||
|
factions=self._factions,
|
||||||
|
width_px=card_settings.design_width_px,
|
||||||
|
height_px=card_settings.design_height_px,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _render_stylesheet(self) -> str:
|
||||||
|
card = self._settings.card
|
||||||
|
template = self._environment.get_template("card.css.jinja")
|
||||||
|
return template.render(
|
||||||
|
width_px=card.design_width_px,
|
||||||
|
height_px=card.design_height_px,
|
||||||
|
header_height_px=round(card.design_height_px * CHARACTER_HEADER_RATIO),
|
||||||
|
header_action_height_px=round(card.design_height_px * ACTION_HEADER_RATIO),
|
||||||
|
body_height_px=round(card.design_height_px * BODY_RATIO),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def safe_name(card_id: str) -> str:
|
||||||
|
"""Map an upstream card id to a filesystem-safe stem."""
|
||||||
|
safe = "".join(ch if ch.isalnum() or ch in "-_" else "_" for ch in card_id)
|
||||||
|
return safe.strip("_") or "card"
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{% extends "base.html.jinja" %}
|
||||||
|
|
||||||
|
{% block card %}
|
||||||
|
<div class="art-bg" style="background-image: url('{{ view.illustration }}')"></div>
|
||||||
|
<img class="art art-contain" src="{{ view.illustration }}" alt="">
|
||||||
|
<div class="shade"></div>
|
||||||
|
|
||||||
|
<header class="header header-action">
|
||||||
|
<div class="cost cost-header">
|
||||||
|
{% for die in view.cost %}
|
||||||
|
<span class="die" style="background-image: url('{{ die.icon }}')">
|
||||||
|
<b>{{ die.count }}</b>
|
||||||
|
</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<h1 class="card-name">{{ view.name }}</h1>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="body body-action">
|
||||||
|
<div class="type-row">
|
||||||
|
<img class="type-icon" src="{{ view.type_icon }}" alt="">
|
||||||
|
<span class="type-label">{{ view.type_label }}</span>
|
||||||
|
</div>
|
||||||
|
<p class="desc">{{ view.description_html | safe }}</p>
|
||||||
|
{% if view.requirement %}
|
||||||
|
<p class="requirement">Requiert : {{ view.requirement }}</p>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="fr">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>{{ view.name }}</title>
|
||||||
|
<style>{{ style_content | safe }}</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="card" class="card {{ card_class }}">
|
||||||
|
{% block card %}{% endblock %}
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
{# Self-contained stylesheet for a single card. Dimensions are injected so the
|
||||||
|
generated HTML can be re-rendered at any DPI without editing the template. #}
|
||||||
|
:root {
|
||||||
|
--card-w: {{ width_px }}px;
|
||||||
|
--card-h: {{ height_px }}px;
|
||||||
|
--header-h: {{ header_height_px }}px;
|
||||||
|
--header-action-h: {{ header_action_height_px }}px;
|
||||||
|
--body-h: {{ body_height_px }}px;
|
||||||
|
--accent: #d9c9a3;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
width: var(--card-w);
|
||||||
|
height: var(--card-h);
|
||||||
|
overflow: hidden;
|
||||||
|
background: #0b0f18;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: "Segoe UI", "Noto Sans", "DejaVu Sans", system-ui, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
position: relative;
|
||||||
|
width: var(--card-w);
|
||||||
|
height: var(--card-h);
|
||||||
|
overflow: hidden;
|
||||||
|
color: #f4f1e8;
|
||||||
|
background: radial-gradient(120% 80% at 50% 0%, #26304a 0%, #0d1220 70%);
|
||||||
|
border-radius: 20px;
|
||||||
|
box-shadow: inset 0 0 0 3px rgba(255, 255, 255, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Element accents ------------------------------------------------------------ */
|
||||||
|
.el-anemo { --accent: #7fe0c3; }
|
||||||
|
.el-geo { --accent: #f0b23a; }
|
||||||
|
.el-electro { --accent: #c9a6ff; }
|
||||||
|
.el-dendro { --accent: #9fdc5b; }
|
||||||
|
.el-hydro { --accent: #6cc6ff; }
|
||||||
|
.el-pyro { --accent: #ff8a5c; }
|
||||||
|
.el-cryo { --accent: #9fd8e8; }
|
||||||
|
|
||||||
|
/* Artwork -------------------------------------------------------------------- */
|
||||||
|
.art {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 0 auto 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 60%;
|
||||||
|
object-fit: cover;
|
||||||
|
object-position: top center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Action cards keep the whole illustration visible, over a blurred backdrop. */
|
||||||
|
.art-bg {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 0 auto 0;
|
||||||
|
height: 60%;
|
||||||
|
background-size: cover;
|
||||||
|
background-position: center;
|
||||||
|
filter: blur(26px) brightness(0.5) saturate(0.9);
|
||||||
|
transform: scale(1.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-contain { object-fit: contain; object-position: center; }
|
||||||
|
|
||||||
|
.shade {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 0 auto 0;
|
||||||
|
height: 60%;
|
||||||
|
background: linear-gradient(
|
||||||
|
180deg,
|
||||||
|
rgba(8, 10, 18, 0.86) 0%,
|
||||||
|
rgba(8, 10, 18, 0.2) 26%,
|
||||||
|
rgba(8, 10, 18, 0) 55%,
|
||||||
|
rgba(8, 10, 18, 0.65) 100%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Header --------------------------------------------------------------------- */
|
||||||
|
.header {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 0 auto 0;
|
||||||
|
height: var(--header-h);
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 20px 22px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hp-bubble {
|
||||||
|
position: relative;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 96px;
|
||||||
|
height: 96px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hp-bubble img { width: 100%; height: 100%; }
|
||||||
|
|
||||||
|
.hp-bubble b {
|
||||||
|
position: absolute;
|
||||||
|
font-size: 40px;
|
||||||
|
color: #fff;
|
||||||
|
-webkit-text-stroke: 3px #1a1a1a;
|
||||||
|
paint-order: stroke fill;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-block { flex: 1 1 auto; min-width: 0; padding-top: 6px; }
|
||||||
|
|
||||||
|
.card-name {
|
||||||
|
font-size: 42px;
|
||||||
|
line-height: 1.02;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: 0.4px;
|
||||||
|
text-shadow: 0 2px 6px rgba(0, 0, 0, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-tags {
|
||||||
|
list-style: none;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-tags li {
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.3px;
|
||||||
|
padding: 3px 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
color: var(--accent);
|
||||||
|
background: rgba(0, 0, 0, 0.45);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 55%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cost dice (action header + skills) ---------------------------------------- */
|
||||||
|
.die {
|
||||||
|
position: relative;
|
||||||
|
display: inline-grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 38px;
|
||||||
|
height: 38px;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: center;
|
||||||
|
background-size: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.die b {
|
||||||
|
font-size: 19px;
|
||||||
|
color: #fff;
|
||||||
|
-webkit-text-stroke: 2px #171717;
|
||||||
|
paint-order: stroke fill;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cost { display: flex; gap: 2px; flex: 0 0 auto; }
|
||||||
|
|
||||||
|
.cost-header { gap: 4px; }
|
||||||
|
.cost-header .die { width: 64px; height: 64px; }
|
||||||
|
.cost-header .die b { font-size: 30px; }
|
||||||
|
|
||||||
|
/* Body / text zone ----------------------------------------------------------- */
|
||||||
|
.body {
|
||||||
|
position: absolute;
|
||||||
|
inset: auto 0 0 0;
|
||||||
|
height: var(--body-h);
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 58px 1fr 58px;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 16px 14px;
|
||||||
|
background: rgba(12, 14, 24, 0.86);
|
||||||
|
border-top: 2px solid color-mix(in srgb, var(--accent) 60%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.energy-col, .tags-col {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.energy { width: 46px; height: 46px; filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.8)); }
|
||||||
|
|
||||||
|
.tag { display: grid; place-items: center; width: 48px; height: 48px; }
|
||||||
|
.tag img { width: 100%; height: 100%; }
|
||||||
|
.tag-faction {
|
||||||
|
width: 46px;
|
||||||
|
height: 46px;
|
||||||
|
border-radius: 50%;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--accent);
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Skills --------------------------------------------------------------------- */
|
||||||
|
.skills { display: flex; flex-direction: column; gap: 6px; overflow: hidden; }
|
||||||
|
|
||||||
|
.skill {
|
||||||
|
background: rgba(0, 0, 0, 0.42);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.09);
|
||||||
|
border-radius: 11px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.skill-head { display: flex; align-items: center; gap: 8px; }
|
||||||
|
|
||||||
|
.skill-icon {
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: rgba(0, 0, 0, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.skill-titles { flex: 1 1 auto; min-width: 0; }
|
||||||
|
|
||||||
|
.skill-name { display: block; font-size: 18px; font-weight: 700; line-height: 1.05; }
|
||||||
|
|
||||||
|
.skill-kind { display: block; font-size: 12px; font-weight: 600; color: #ffd780; }
|
||||||
|
|
||||||
|
.skill-desc { font-size: 14px; line-height: 1.25; margin-top: 4px; }
|
||||||
|
|
||||||
|
.inline-die {
|
||||||
|
width: 17px;
|
||||||
|
height: 17px;
|
||||||
|
vertical-align: -3px;
|
||||||
|
margin: 0 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sub-name { margin-top: 5px; font-size: 13px; font-weight: 700; color: var(--accent); }
|
||||||
|
|
||||||
|
.skill-desc.sub { font-size: 13px; margin-top: 1px; }
|
||||||
|
|
||||||
|
/* Action body ---------------------------------------------------------------- */
|
||||||
|
.body-action {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 18px 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.type-row { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.type-icon { width: 42px; height: 42px; }
|
||||||
|
.type-label { font-size: 20px; font-weight: 700; color: var(--accent); }
|
||||||
|
|
||||||
|
.desc { font-size: 18px; line-height: 1.34; }
|
||||||
|
|
||||||
|
.requirement { margin-top: auto; font-size: 14px; font-style: italic; opacity: 0.75; }
|
||||||
|
|
||||||
|
/* Action header -------------------------------------------------------------- */
|
||||||
|
.header-action {
|
||||||
|
height: var(--header-action-h);
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 16px 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-action .card-name { font-size: 34px; }
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
{% extends "base.html.jinja" %}
|
||||||
|
|
||||||
|
{% block card %}
|
||||||
|
<img class="art" src="{{ view.illustration }}" alt="">
|
||||||
|
<div class="shade"></div>
|
||||||
|
|
||||||
|
<header class="header">
|
||||||
|
<div class="hp-bubble">
|
||||||
|
<img src="{{ view.hp_icon }}" alt="PV">
|
||||||
|
<b>{{ view.hp }}</b>
|
||||||
|
</div>
|
||||||
|
<div class="title-block">
|
||||||
|
<h1 class="card-name">{{ view.name }}</h1>
|
||||||
|
<ul class="header-tags">
|
||||||
|
<li>{{ view.element_label }}</li>
|
||||||
|
<li>{{ view.weapon_label }}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="body">
|
||||||
|
<aside class="energy-col" aria-label="Énergie">
|
||||||
|
{% for _ in range(view.energy) %}
|
||||||
|
<img class="energy" src="{{ view.energy_icon }}" alt="Énergie">
|
||||||
|
{% endfor %}
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div class="skills">
|
||||||
|
{% for skill in view.skills %}
|
||||||
|
<article class="skill">
|
||||||
|
<div class="skill-head">
|
||||||
|
{% if skill.icon %}<img class="skill-icon" src="{{ skill.icon }}" alt="">{% endif %}
|
||||||
|
<div class="skill-titles">
|
||||||
|
<span class="skill-name">{{ skill.name }}</span>
|
||||||
|
<span class="skill-kind">{{ skill.kind }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="cost">
|
||||||
|
{% for die in skill.cost %}
|
||||||
|
<span class="die" style="background-image: url('{{ die.icon }}')">
|
||||||
|
<b>{{ die.count }}</b>
|
||||||
|
</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="skill-desc">{{ skill.description_html | safe }}</p>
|
||||||
|
{% if skill.sub_name %}
|
||||||
|
<p class="sub-name">{{ skill.sub_name }}</p>
|
||||||
|
<p class="skill-desc sub">{{ skill.sub_description_html | safe }}</p>
|
||||||
|
{% endif %}
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="tags-col" aria-label="Attributs">
|
||||||
|
{% for tag in view.tags %}
|
||||||
|
<span class="tag tag-{{ tag.kind }}" title="{{ tag.label }}">
|
||||||
|
{% if tag.icon %}
|
||||||
|
<img src="{{ tag.icon }}" alt="{{ tag.label }}">
|
||||||
|
{% else %}
|
||||||
|
{{ tag.label }}
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
{% endfor %}
|
||||||
|
</aside>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Shared pytest fixtures."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from genshin_tcg.config import Settings
|
||||||
|
from genshin_tcg.data.catalog import Catalog
|
||||||
|
from genshin_tcg.models import parse_catalog
|
||||||
|
|
||||||
|
FIXTURES_DIR = Path(__file__).parent / "fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConverter:
|
||||||
|
"""A stub :class:`~genshin_tcg.rendering.converters.HtmlConverter`."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.calls: list[tuple[Path, Path]] = []
|
||||||
|
|
||||||
|
def convert(self, html_path: Path, image_path: Path) -> None:
|
||||||
|
self.calls.append((html_path, image_path))
|
||||||
|
image_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
image_path.write_bytes(b"fake-png")
|
||||||
|
|
||||||
|
def close(self) -> None: # pragma: no cover - trivial
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __enter__(self) -> FakeConverter:
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc: object) -> None: # pragma: no cover - trivial
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_converter() -> FakeConverter:
|
||||||
|
return FakeConverter()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def sample_payload() -> list[dict[str, object]]:
|
||||||
|
raw = (FIXTURES_DIR / "sample_fr.json").read_text(encoding="utf-8")
|
||||||
|
payload = json.loads(raw)
|
||||||
|
assert isinstance(payload, list)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def sample_catalog(sample_payload: list[dict[str, object]]) -> Catalog:
|
||||||
|
return Catalog(cards=tuple(parse_catalog(sample_payload)))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def settings(tmp_path: Path) -> Iterator[Settings]:
|
||||||
|
yield Settings(
|
||||||
|
language="fr",
|
||||||
|
assets_dir=tmp_path / "assets",
|
||||||
|
build_dir=tmp_path / "build",
|
||||||
|
)
|
||||||
Vendored
+78
@@ -0,0 +1,78 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"_id": 9001,
|
||||||
|
"id": "test_pyro",
|
||||||
|
"type": "character",
|
||||||
|
"name": "Test Pyro",
|
||||||
|
"hp": 10,
|
||||||
|
"energy": 3,
|
||||||
|
"element": "pyro",
|
||||||
|
"weapon": "claymore",
|
||||||
|
"skills": [
|
||||||
|
{
|
||||||
|
"_id": 90011,
|
||||||
|
"type": "Attaque normale",
|
||||||
|
"name": "Frappe de test",
|
||||||
|
"desc": "Inflige 2 pts de <span style=\"color: #FFFFFFFF;\">DGT physiques</span>\\nEt rien d'autre.",
|
||||||
|
"cost": [
|
||||||
|
{ "type": "pyro", "count": 1 },
|
||||||
|
{ "type": "void", "count": 2 }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_id": 90012,
|
||||||
|
"type": "Compétence élémentaire",
|
||||||
|
"name": "Gerbe de flammes",
|
||||||
|
"desc": "Inflige 3 pts de <span style=\"color: #FFFFFFFF;\">DGT Pyro</span>.",
|
||||||
|
"cost": [{ "type": "pyro", "count": 3 }],
|
||||||
|
"sub": {
|
||||||
|
"_id": 900121,
|
||||||
|
"id": "test_summon",
|
||||||
|
"name": "Flamme éternelle",
|
||||||
|
"desc": "<span style=\"color: #FFFFFFFF;\">Phase finale : </span>Inflige 1 pt de <span style=\"color: #99FFFFFF;\">DGT Pyro</span>."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_id": 90013,
|
||||||
|
"type": "Déchaînement élémentaire",
|
||||||
|
"name": "Explosion finale",
|
||||||
|
"desc": "Inflige 5 pts de <span style=\"color: #FFFFFFFF;\">DGT Pyro</span>.",
|
||||||
|
"cost": [
|
||||||
|
{ "type": "pyro", "count": 3 },
|
||||||
|
{ "type": "energy", "count": 3 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_id": 9002,
|
||||||
|
"id": "test_talent",
|
||||||
|
"type": "talent",
|
||||||
|
"name": "Talent de test",
|
||||||
|
"requirement": "test_pyro",
|
||||||
|
"skills": {
|
||||||
|
"cost": [{ "type": "pyro", "count": 4 }],
|
||||||
|
"desc": "<color=#FFD700>Action de combat</color> : équipe cette carte.\\n(Votre deck doit contenir Test Pyro)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_id": 9003,
|
||||||
|
"id": "test_artifact",
|
||||||
|
"type": "artifact",
|
||||||
|
"name": "Artefact de test",
|
||||||
|
"skills": {
|
||||||
|
"cost": [],
|
||||||
|
"desc": "Les <span style=\"color: #FFFFFFFF; text-decoration: underline;\">DGT</span> infligés +1."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_id": 9004,
|
||||||
|
"id": "test_food",
|
||||||
|
"type": "food",
|
||||||
|
"name": "Plat de test",
|
||||||
|
"skills": {
|
||||||
|
"cost": [{ "type": "same", "count": 2 }],
|
||||||
|
"desc": "Soigne 2 pts."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Tests for asset discovery and URL resolution."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from genshin_tcg.constants import AssetPaths, CardType, CostType, Element, WeaponType
|
||||||
|
from genshin_tcg.data.assets import (
|
||||||
|
illustration_key,
|
||||||
|
iter_required_keys,
|
||||||
|
skill_keys,
|
||||||
|
static_icon_keys,
|
||||||
|
)
|
||||||
|
from genshin_tcg.data.catalog import Catalog
|
||||||
|
from genshin_tcg.models import CharacterCard
|
||||||
|
from genshin_tcg.rendering.context import AssetUrlResolver
|
||||||
|
|
||||||
|
|
||||||
|
def test_static_icons_cover_domain_vocabulary() -> None:
|
||||||
|
keys = set(static_icon_keys())
|
||||||
|
assert AssetPaths.HP_ICON in keys
|
||||||
|
assert AssetPaths.ENERGY_CARD_ICON in keys
|
||||||
|
assert AssetPaths.cost_die(CostType.VOID) in keys
|
||||||
|
assert AssetPaths.element(Element.PYRO) in keys
|
||||||
|
assert AssetPaths.weapon(WeaponType.BOW) in keys
|
||||||
|
|
||||||
|
|
||||||
|
def test_static_icons_exclude_character_type_icon() -> None:
|
||||||
|
# No ``types/character.png`` exists upstream.
|
||||||
|
assert AssetPaths.card_type(CardType.CHARACTER) not in static_icon_keys()
|
||||||
|
|
||||||
|
|
||||||
|
def test_required_keys_include_illustration_and_skills(sample_catalog: Catalog) -> None:
|
||||||
|
keys = set(iter_required_keys(sample_catalog.cards))
|
||||||
|
assert "tcg/test_pyro.png" in keys
|
||||||
|
assert "tcg/skills/test_pyro/skill_1.png" in keys
|
||||||
|
assert "tcg/skills/test_pyro/skill_3.png" in keys
|
||||||
|
assert "tcg/skills/test_pyro/skill_4.png" not in keys
|
||||||
|
assert "tcg/test_food.png" in keys
|
||||||
|
|
||||||
|
|
||||||
|
def test_skill_keys_follow_skill_order(sample_catalog: Catalog) -> None:
|
||||||
|
character = next(iter(sample_catalog.characters))
|
||||||
|
assert isinstance(character, CharacterCard)
|
||||||
|
assert skill_keys(character) == [
|
||||||
|
"tcg/skills/test_pyro/skill_1.png",
|
||||||
|
"tcg/skills/test_pyro/skill_2.png",
|
||||||
|
"tcg/skills/test_pyro/skill_3.png",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_illustration_key_uses_card_id(sample_catalog: Catalog) -> None:
|
||||||
|
assert illustration_key(sample_catalog.get("test_food")) == "tcg/test_food.png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_url_resolver_builds_relative_urls(tmp_path: Path) -> None:
|
||||||
|
assets = tmp_path / "assets"
|
||||||
|
html_dir = tmp_path / "build" / "html"
|
||||||
|
resolver = AssetUrlResolver(assets, html_dir)
|
||||||
|
url = resolver.url("tcg/test_pyro.png")
|
||||||
|
assert url == "../../assets/tcg/test_pyro.png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_url_resolver_exists(tmp_path: Path) -> None:
|
||||||
|
assets = tmp_path / "assets"
|
||||||
|
(assets / "tcg").mkdir(parents=True)
|
||||||
|
(assets / "tcg" / "x.png").write_bytes(b"x")
|
||||||
|
resolver = AssetUrlResolver(assets, tmp_path / "build" / "html")
|
||||||
|
assert resolver.exists("tcg/x.png")
|
||||||
|
assert not resolver.exists("tcg/missing.png")
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Tests for the domain models and catalogue."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from genshin_tcg.constants import CardType, Element, WeaponType
|
||||||
|
from genshin_tcg.data.catalog import Catalog, load_catalog, save_catalog
|
||||||
|
from genshin_tcg.models import ActionCard, CharacterCard, parse_catalog
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_catalog_classifies_cards(sample_payload: list[dict[str, object]]) -> None:
|
||||||
|
cards = parse_catalog(sample_payload)
|
||||||
|
assert len(cards) == 4
|
||||||
|
characters = [c for c in cards if isinstance(c, CharacterCard)]
|
||||||
|
actions = [c for c in cards if isinstance(c, ActionCard)]
|
||||||
|
assert len(characters) == 1
|
||||||
|
assert len(actions) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_character_card_parsing(sample_payload: list[dict[str, object]]) -> None:
|
||||||
|
character = next(
|
||||||
|
card for card in parse_catalog(sample_payload) if isinstance(card, CharacterCard)
|
||||||
|
)
|
||||||
|
assert character.id == "test_pyro"
|
||||||
|
assert character.element is Element.PYRO
|
||||||
|
assert character.weapon is WeaponType.CLAYMORE
|
||||||
|
assert character.hp == 10
|
||||||
|
assert character.energy == 3
|
||||||
|
assert len(character.skills) == 3
|
||||||
|
assert character.skills[0].cost[0].count == 1
|
||||||
|
assert character.skills[1].sub is not None
|
||||||
|
assert character.skills[1].sub.name == "Flamme éternelle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_action_card_flattens_skills_object(sample_payload: list[dict[str, object]]) -> None:
|
||||||
|
talent = next(
|
||||||
|
card
|
||||||
|
for card in parse_catalog(sample_payload)
|
||||||
|
if isinstance(card, ActionCard) and card.id == "test_talent"
|
||||||
|
)
|
||||||
|
assert talent.type is CardType.TALENT
|
||||||
|
assert talent.requirement == "test_pyro"
|
||||||
|
assert talent.cost[0].count == 4
|
||||||
|
assert "Action de combat" in talent.description
|
||||||
|
|
||||||
|
|
||||||
|
def test_action_card_with_empty_cost(sample_payload: list[dict[str, object]]) -> None:
|
||||||
|
artifact = next(
|
||||||
|
card
|
||||||
|
for card in parse_catalog(sample_payload)
|
||||||
|
if isinstance(card, ActionCard) and card.id == "test_artifact"
|
||||||
|
)
|
||||||
|
assert artifact.cost == ()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_card_shape_raises() -> None:
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
parse_catalog([{"_id": 1, "id": "x", "type": "character", "name": "x"}])
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_queries(sample_catalog: Catalog) -> None:
|
||||||
|
assert len(sample_catalog) == 4
|
||||||
|
assert len(sample_catalog.characters) == 1
|
||||||
|
assert len(sample_catalog.actions) == 3
|
||||||
|
assert sample_catalog.get("test_food").name == "Plat de test"
|
||||||
|
subset = sample_catalog.select(["test_food", "test_pyro"])
|
||||||
|
assert [card.id for card in subset] == ["test_food", "test_pyro"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_duplicate_ids_warn(sample_payload: list[dict[str, object]]) -> None:
|
||||||
|
duplicated = [*sample_payload, sample_payload[0]]
|
||||||
|
catalog = Catalog(cards=tuple(parse_catalog(duplicated)))
|
||||||
|
assert len(catalog.cards) == 5
|
||||||
|
assert len(catalog._by_id) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_round_trip(sample_catalog: Catalog, tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "catalog.json"
|
||||||
|
save_catalog(sample_catalog, path)
|
||||||
|
reloaded = load_catalog(path)
|
||||||
|
assert [card.id for card in reloaded] == [card.id for card in sample_catalog]
|
||||||
|
assert reloaded.get("test_pyro") == sample_catalog.get("test_pyro")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Tests for the Typer CLI."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from typer.testing import CliRunner
|
||||||
|
|
||||||
|
from genshin_tcg import __version__
|
||||||
|
from genshin_tcg.cli import app
|
||||||
|
from genshin_tcg.data.catalog import Catalog, save_catalog
|
||||||
|
|
||||||
|
runner = CliRunner()
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_flag() -> None:
|
||||||
|
result = runner.invoke(app, ["--version"])
|
||||||
|
assert result.exit_code == 0
|
||||||
|
assert __version__ in result.output
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_without_catalogue_errors(tmp_path: Path) -> None:
|
||||||
|
result = runner.invoke(
|
||||||
|
app,
|
||||||
|
["--build-dir", str(tmp_path / "build"), "--assets-dir", str(tmp_path / "assets"), "list"],
|
||||||
|
)
|
||||||
|
assert result.exit_code == 1
|
||||||
|
assert "Error" in result.output
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_prints_catalogue(tmp_path: Path, sample_catalog: Catalog) -> None:
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir(parents=True)
|
||||||
|
save_catalog(sample_catalog, build_dir / "catalog.json")
|
||||||
|
|
||||||
|
result = runner.invoke(
|
||||||
|
app,
|
||||||
|
["--build-dir", str(build_dir), "--assets-dir", str(tmp_path / "assets"), "list"],
|
||||||
|
)
|
||||||
|
assert result.exit_code == 0
|
||||||
|
assert "test_pyro" in result.output
|
||||||
|
assert "Test Pyro" in result.output
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Tests for :mod:`genshin_tcg.config`."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from genshin_tcg.config import CardSettings, Settings
|
||||||
|
|
||||||
|
|
||||||
|
def test_design_pixels_for_poker_format() -> None:
|
||||||
|
card = CardSettings(width_mm=63, height_mm=88, dpi=300)
|
||||||
|
assert card.design_width_px == 744
|
||||||
|
assert card.design_height_px == 1039
|
||||||
|
assert card.scale_factor == 1.0
|
||||||
|
assert card.output_width_px == 744
|
||||||
|
|
||||||
|
|
||||||
|
def test_scale_factor_tracks_dpi() -> None:
|
||||||
|
card = CardSettings(dpi=600)
|
||||||
|
assert card.scale_factor == 2.0
|
||||||
|
assert card.output_width_px == 1488
|
||||||
|
assert card.output_height_px == 2078
|
||||||
|
|
||||||
|
|
||||||
|
def test_dpi_below_baseline_is_rejected() -> None:
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
CardSettings(dpi=150)
|
||||||
|
|
||||||
|
|
||||||
|
def test_derived_paths(tmp_path: Path) -> None:
|
||||||
|
settings = Settings(language="en", assets_dir=tmp_path / "a", build_dir=tmp_path / "b")
|
||||||
|
assert settings.source_json == tmp_path / "a" / "source" / "en.json"
|
||||||
|
assert settings.tags_json == tmp_path / "a" / "source" / "tags_en.json"
|
||||||
|
assert settings.catalog_path == tmp_path / "b" / "catalog.json"
|
||||||
|
assert settings.pdf_path == tmp_path / "b" / "cards-en.pdf"
|
||||||
|
assert settings.factions_override == tmp_path / "a" / "overrides" / "factions.json"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ensure_directories(tmp_path: Path) -> None:
|
||||||
|
settings = Settings(assets_dir=tmp_path / "a", build_dir=tmp_path / "b")
|
||||||
|
settings.ensure_directories()
|
||||||
|
assert settings.source_dir.is_dir()
|
||||||
|
assert settings.tcg_dir.is_dir()
|
||||||
|
assert settings.html_dir.is_dir()
|
||||||
|
assert settings.png_dir.is_dir()
|
||||||
|
|
||||||
|
|
||||||
|
def test_nested_env_override() -> None:
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.environ["GTCG_CARD__DPI"] = "600"
|
||||||
|
os.environ["GTCG_PAGE__CUT_MARKS"] = "false"
|
||||||
|
try:
|
||||||
|
settings = Settings()
|
||||||
|
assert settings.card.dpi == 600
|
||||||
|
assert settings.page.cut_marks is False
|
||||||
|
finally:
|
||||||
|
os.environ.pop("GTCG_CARD__DPI", None)
|
||||||
|
os.environ.pop("GTCG_PAGE__CUT_MARKS", None)
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
"""Tests for the template view builder."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from genshin_tcg.data.catalog import Catalog
|
||||||
|
from genshin_tcg.rendering.context import (
|
||||||
|
ActionView,
|
||||||
|
CharacterView,
|
||||||
|
build_view,
|
||||||
|
load_faction_overrides,
|
||||||
|
load_labels,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _character(catalog: Catalog) -> CharacterView:
|
||||||
|
view = build_view(
|
||||||
|
catalog.get("test_pyro"),
|
||||||
|
assets_dir=Path("assets"),
|
||||||
|
html_dir=Path("build") / "html",
|
||||||
|
width_px=744,
|
||||||
|
height_px=1039,
|
||||||
|
)
|
||||||
|
assert isinstance(view, CharacterView)
|
||||||
|
return view
|
||||||
|
|
||||||
|
|
||||||
|
def _action(catalog: Catalog) -> ActionView:
|
||||||
|
view = build_view(
|
||||||
|
catalog.get("test_talent"),
|
||||||
|
assets_dir=Path("assets"),
|
||||||
|
html_dir=Path("build") / "html",
|
||||||
|
width_px=744,
|
||||||
|
height_px=1039,
|
||||||
|
)
|
||||||
|
assert isinstance(view, ActionView)
|
||||||
|
return view
|
||||||
|
|
||||||
|
|
||||||
|
def test_character_view_fields(sample_catalog: Catalog) -> None:
|
||||||
|
view = _character(sample_catalog)
|
||||||
|
assert view.kind == "character"
|
||||||
|
assert view.name == "Test Pyro"
|
||||||
|
assert view.hp == 10
|
||||||
|
assert view.energy == 3
|
||||||
|
assert view.css_class == "el-pyro"
|
||||||
|
assert view.width_px == 744
|
||||||
|
assert view.illustration == "../../assets/tcg/test_pyro.png"
|
||||||
|
assert view.energy_icon.endswith("assets/tcg/icons/energy_card.png")
|
||||||
|
assert view.hp_icon.endswith("assets/tcg/icons/hp.png")
|
||||||
|
|
||||||
|
|
||||||
|
def test_character_tags_include_element_and_weapon(sample_catalog: Catalog) -> None:
|
||||||
|
view = _character(sample_catalog)
|
||||||
|
kinds = [tag.kind for tag in view.tags]
|
||||||
|
assert kinds == ["element", "weapon"]
|
||||||
|
assert view.tags[0].label == "Pyro"
|
||||||
|
element_icon = view.tags[0].icon
|
||||||
|
assert element_icon is not None
|
||||||
|
assert element_icon.endswith("assets/tcg/icons/elements/pyro.png")
|
||||||
|
assert view.tags[1].label == "Épée à deux mains"
|
||||||
|
|
||||||
|
|
||||||
|
def test_character_skills_and_costs(sample_catalog: Catalog) -> None:
|
||||||
|
view = _character(sample_catalog)
|
||||||
|
assert len(view.skills) == 3
|
||||||
|
first = view.skills[0]
|
||||||
|
assert first.name == "Frappe de test"
|
||||||
|
assert first.icon is not None and first.icon.endswith("skills/test_pyro/skill_1.png")
|
||||||
|
assert [die.count for die in first.cost] == [1, 2]
|
||||||
|
assert first.cost[0].icon.endswith("assets/tcg/icons/pyro.png")
|
||||||
|
assert first.cost[1].icon.endswith("assets/tcg/icons/void.png")
|
||||||
|
|
||||||
|
|
||||||
|
def test_character_description_is_cleaned_and_highlighted(sample_catalog: Catalog) -> None:
|
||||||
|
view = _character(sample_catalog)
|
||||||
|
assert "<br/>" in view.skills[0].description_html
|
||||||
|
assert '<span style="color: #FFFFFFFF">DGT ' in view.skills[1].description_html
|
||||||
|
assert "inline-die" in view.skills[1].description_html
|
||||||
|
assert view.skills[1].sub_name == "Flamme éternelle"
|
||||||
|
assert view.skills[1].sub_description_html is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_inline_element_icons_can_be_disabled(sample_catalog: Catalog) -> None:
|
||||||
|
with_icons = _character(sample_catalog)
|
||||||
|
assert "inline-die" in with_icons.skills[1].description_html
|
||||||
|
|
||||||
|
without = build_view(
|
||||||
|
sample_catalog.get("test_pyro"),
|
||||||
|
assets_dir=Path("assets"),
|
||||||
|
html_dir=Path("build") / "html",
|
||||||
|
width_px=744,
|
||||||
|
height_px=1039,
|
||||||
|
inline_element_icons=False,
|
||||||
|
)
|
||||||
|
assert isinstance(without, CharacterView)
|
||||||
|
assert "inline-die" not in without.skills[1].description_html
|
||||||
|
|
||||||
|
|
||||||
|
def test_action_view_fields(sample_catalog: Catalog) -> None:
|
||||||
|
view = _action(sample_catalog)
|
||||||
|
assert view.kind == "action"
|
||||||
|
assert view.css_class == "type-talent"
|
||||||
|
assert view.type_label == "Aptitude"
|
||||||
|
assert view.type_icon.endswith("assets/tcg/icons/types/talent.png")
|
||||||
|
assert view.requirement == "test_pyro"
|
||||||
|
assert [die.count for die in view.cost] == [4]
|
||||||
|
assert "<br/>" in view.description_html
|
||||||
|
assert '<span style="color: #FFD700">Action de combat</span>' in view.description_html
|
||||||
|
|
||||||
|
|
||||||
|
def test_action_without_cost_gets_placeholder_die(sample_catalog: Catalog) -> None:
|
||||||
|
view = build_view(
|
||||||
|
sample_catalog.get("test_artifact"),
|
||||||
|
assets_dir=Path("assets"),
|
||||||
|
html_dir=Path("build") / "html",
|
||||||
|
width_px=744,
|
||||||
|
height_px=1039,
|
||||||
|
)
|
||||||
|
assert isinstance(view, ActionView)
|
||||||
|
assert len(view.cost) == 1
|
||||||
|
assert view.cost[0].count == 0
|
||||||
|
assert view.cost[0].icon.endswith("assets/tcg/icons/same.png")
|
||||||
|
|
||||||
|
|
||||||
|
def test_faction_override_without_icon(tmp_path: Path, sample_catalog: Catalog) -> None:
|
||||||
|
view = build_view(
|
||||||
|
sample_catalog.get("test_pyro"),
|
||||||
|
assets_dir=tmp_path / "assets",
|
||||||
|
html_dir=tmp_path / "build" / "html",
|
||||||
|
factions={"test_pyro": "liyue"},
|
||||||
|
width_px=744,
|
||||||
|
height_px=1039,
|
||||||
|
)
|
||||||
|
assert isinstance(view, CharacterView)
|
||||||
|
faction = next(tag for tag in view.tags if tag.kind == "faction")
|
||||||
|
assert faction.label == "Liyue"
|
||||||
|
assert faction.icon is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_faction_override_with_icon(tmp_path: Path, sample_catalog: Catalog) -> None:
|
||||||
|
icon = tmp_path / "assets" / "tcg" / "icons" / "factions" / "liyue.png"
|
||||||
|
icon.parent.mkdir(parents=True)
|
||||||
|
icon.write_bytes(b"x")
|
||||||
|
view = build_view(
|
||||||
|
sample_catalog.get("test_pyro"),
|
||||||
|
assets_dir=tmp_path / "assets",
|
||||||
|
html_dir=tmp_path / "build" / "html",
|
||||||
|
factions={"test_pyro": "liyue"},
|
||||||
|
width_px=744,
|
||||||
|
height_px=1039,
|
||||||
|
)
|
||||||
|
assert isinstance(view, CharacterView)
|
||||||
|
faction = next(tag for tag in view.tags if tag.kind == "faction")
|
||||||
|
assert faction.icon is not None and faction.icon.endswith("factions/liyue.png")
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_labels_merges_file(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "tags_fr.json"
|
||||||
|
path.write_text('{"pyro": "Feu", "unique": "Unique"}', encoding="utf-8")
|
||||||
|
labels = load_labels(path)
|
||||||
|
assert labels["pyro"] == "Feu"
|
||||||
|
assert labels["unique"] == "Unique"
|
||||||
|
assert labels["talent"] == "Aptitude" # built-in fallback retained
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_labels_missing_file_uses_defaults(tmp_path: Path) -> None:
|
||||||
|
labels = load_labels(tmp_path / "nope.json")
|
||||||
|
assert labels["cryo"] == "Cryo"
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_faction_overrides(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "factions.json"
|
||||||
|
path.write_text('{"ganyu": "liyue"}', encoding="utf-8")
|
||||||
|
assert load_faction_overrides(path) == {"ganyu": "liyue"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_faction_overrides_missing(tmp_path: Path) -> None:
|
||||||
|
assert load_faction_overrides(tmp_path / "nope.json") == {}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
"""Tests for A4 imposition."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from genshin_tcg.pdf.imposition import ImpositionGrid, impose_pdf
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_grid_geometry() -> None:
|
||||||
|
grid = ImpositionGrid()
|
||||||
|
assert grid.capacity == 9
|
||||||
|
assert grid.content_width_mm == pytest.approx(189.0)
|
||||||
|
assert grid.content_height_mm == pytest.approx(264.0)
|
||||||
|
assert grid.offset_x_mm == pytest.approx(10.5)
|
||||||
|
assert grid.offset_y_mm == pytest.approx(16.5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cell_positions() -> None:
|
||||||
|
grid = ImpositionGrid()
|
||||||
|
assert grid.cell_top_left_mm(0) == pytest.approx((10.5, 16.5))
|
||||||
|
assert grid.cell_top_left_mm(2) == pytest.approx((10.5 + 2 * 63, 16.5))
|
||||||
|
assert grid.cell_top_left_mm(3) == pytest.approx((10.5, 16.5 + 88))
|
||||||
|
assert grid.cell_top_left_mm(8) == pytest.approx((10.5 + 2 * 63, 16.5 + 2 * 88))
|
||||||
|
|
||||||
|
|
||||||
|
def test_cell_index_bounds() -> None:
|
||||||
|
grid = ImpositionGrid()
|
||||||
|
with pytest.raises(IndexError):
|
||||||
|
grid.cell_top_left_mm(9)
|
||||||
|
|
||||||
|
|
||||||
|
def test_page_count() -> None:
|
||||||
|
grid = ImpositionGrid()
|
||||||
|
assert grid.page_count(0) == 0
|
||||||
|
assert grid.page_count(1) == 1
|
||||||
|
assert grid.page_count(9) == 1
|
||||||
|
assert grid.page_count(10) == 2
|
||||||
|
assert grid.page_count(18) == 2
|
||||||
|
assert grid.page_count(19) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_grid_too_large_raises() -> None:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ImpositionGrid(page_width_mm=100.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_explicit_margin() -> None:
|
||||||
|
grid = ImpositionGrid(margin_mm=5.0)
|
||||||
|
assert grid.offset_x_mm == 5.0
|
||||||
|
assert grid.offset_y_mm == 5.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_gutter_shifts_cells() -> None:
|
||||||
|
grid = ImpositionGrid(gutter_mm=2.0, margin_mm=1.0)
|
||||||
|
assert grid.content_width_mm == pytest.approx(3 * 63 + 2 * 2)
|
||||||
|
assert grid.cell_top_left_mm(1) == pytest.approx((1.0 + 65.0, 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
def _make_pngs(directory: Path, count: int) -> list[Path]:
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
paths: list[Path] = []
|
||||||
|
for index in range(count):
|
||||||
|
path = directory / f"card_{index}.png"
|
||||||
|
Image.new("RGB", (74, 104), (index * 10 % 256, 0, 0)).save(path)
|
||||||
|
paths.append(path)
|
||||||
|
return paths
|
||||||
|
|
||||||
|
|
||||||
|
def test_impose_pdf_writes_multiple_pages(tmp_path: Path) -> None:
|
||||||
|
images = _make_pngs(tmp_path / "png", 10)
|
||||||
|
output = tmp_path / "out.pdf"
|
||||||
|
result = impose_pdf(images, output, ImpositionGrid())
|
||||||
|
assert result.pages == 2
|
||||||
|
assert result.cards == 10
|
||||||
|
assert output.is_file()
|
||||||
|
assert output.stat().st_size > 1000
|
||||||
|
|
||||||
|
|
||||||
|
def test_impose_pdf_single_page(tmp_path: Path) -> None:
|
||||||
|
images = _make_pngs(tmp_path / "png", 3)
|
||||||
|
output = tmp_path / "out.pdf"
|
||||||
|
result = impose_pdf(images, output, ImpositionGrid(cut_marks=False))
|
||||||
|
assert result.pages == 1
|
||||||
|
assert output.is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_impose_pdf_missing_image_raises(tmp_path: Path) -> None:
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
impose_pdf([tmp_path / "nope.png"], tmp_path / "out.pdf", ImpositionGrid())
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""Tests for :mod:`genshin_tcg.markup`."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from genshin_tcg.markup import clean_markup, inline_symbols, sanitize, strip_markup
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_markup_converts_color_tags() -> None:
|
||||||
|
assert clean_markup("<color=#FFD700>Or</color>") == '<span style="color: #FFD700">Or</span>'
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_markup_converts_escaped_newlines() -> None:
|
||||||
|
assert clean_markup("a\\nb") == "a<br/>b"
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_markup_keeps_colour_and_underline_spans() -> None:
|
||||||
|
raw = '<span style="color: #80C0FFFF; text-decoration: underline;">DGT</span>'
|
||||||
|
expected = '<span style="color: #80C0FFFF; text-decoration: underline">DGT</span>'
|
||||||
|
assert clean_markup(raw) == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_sanitize_removes_script_and_event_handlers() -> None:
|
||||||
|
dirty = '<script>alert(1)</script><span onclick="x()" style="color: red;">ok</span>'
|
||||||
|
cleaned = sanitize(dirty)
|
||||||
|
assert "script" not in cleaned
|
||||||
|
assert "alert" not in cleaned
|
||||||
|
assert "onclick" not in cleaned
|
||||||
|
assert cleaned == '<span style="color: red">ok</span>'
|
||||||
|
|
||||||
|
|
||||||
|
def test_sanitize_unwraps_unknown_tags_but_keeps_text() -> None:
|
||||||
|
assert sanitize("<div>hello <em>world</em></div>") == "hello <em>world</em>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_sanitize_drops_non_allowlisted_styles() -> None:
|
||||||
|
cleaned = sanitize('<span style="position: fixed; color: blue;">x</span>')
|
||||||
|
assert cleaned == '<span style="color: blue">x</span>'
|
||||||
|
|
||||||
|
|
||||||
|
def test_strip_markup_returns_plain_text() -> None:
|
||||||
|
assert strip_markup("<span>a</span>\\nb") == "a b"
|
||||||
|
|
||||||
|
|
||||||
|
def test_inline_symbols_prefixes_keyword_only_in_text() -> None:
|
||||||
|
html = 'DGT <span style="color: red;">Pyro</span>'
|
||||||
|
result = inline_symbols(html, {"Pyro": "[ICON]"})
|
||||||
|
assert result == 'DGT <span style="color: red;">[ICON]Pyro</span>'
|
||||||
|
|
||||||
|
|
||||||
|
def test_inline_symbols_respects_word_boundaries_and_attributes() -> None:
|
||||||
|
html = '<span title="Pyro">Pyromane</span>'
|
||||||
|
result = inline_symbols(html, {"Pyro": "[ICON]"})
|
||||||
|
# "Pyro" inside the attribute and inside "Pyromane" must not match.
|
||||||
|
assert result == html
|
||||||
|
|
||||||
|
|
||||||
|
def test_inline_symbols_no_symbols_is_identity() -> None:
|
||||||
|
assert inline_symbols("<b>x</b>", {}) == "<b>x</b>"
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Tests for the pipeline orchestration (offline: no network, no browser)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from genshin_tcg import pipeline
|
||||||
|
from genshin_tcg.config import Settings
|
||||||
|
from genshin_tcg.data.catalog import Catalog, save_catalog
|
||||||
|
from genshin_tcg.rendering.converters import HtmlConverter
|
||||||
|
from genshin_tcg.rendering.renderer import safe_name
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_catalogue(settings: Settings, catalog: Catalog) -> None:
|
||||||
|
settings.ensure_directories()
|
||||||
|
save_catalog(catalog, settings.catalog_path)
|
||||||
|
|
||||||
|
|
||||||
|
def _make_pngs(settings: Settings, catalog: Catalog) -> None:
|
||||||
|
settings.png_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
for card in catalog:
|
||||||
|
Image.new("RGB", (74, 104), (10, 20, 30)).save(
|
||||||
|
settings.png_dir / f"{safe_name(card.id)}.png"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_without_screenshot(settings: Settings, sample_catalog: Catalog) -> None:
|
||||||
|
_prepare_catalogue(settings, sample_catalog)
|
||||||
|
rendered = pipeline.render(settings, screenshot=False)
|
||||||
|
assert len(rendered) == 4
|
||||||
|
assert all(item.html_path.is_file() for item in rendered)
|
||||||
|
assert all(not item.png_path.exists() for item in rendered)
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_with_injected_converter(
|
||||||
|
settings: Settings, sample_catalog: Catalog, fake_converter: HtmlConverter
|
||||||
|
) -> None:
|
||||||
|
_prepare_catalogue(settings, sample_catalog)
|
||||||
|
rendered = pipeline.render(settings, converter=fake_converter)
|
||||||
|
assert len(rendered) == 4
|
||||||
|
assert all(item.png_path.is_file() for item in rendered)
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_only_subset(settings: Settings, sample_catalog: Catalog) -> None:
|
||||||
|
_prepare_catalogue(settings, sample_catalog)
|
||||||
|
rendered = pipeline.render(settings, only=["test_pyro"], screenshot=False)
|
||||||
|
assert [item.card_id for item in rendered] == ["test_pyro"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_impose_from_generated_pngs(settings: Settings, sample_catalog: Catalog) -> None:
|
||||||
|
_prepare_catalogue(settings, sample_catalog)
|
||||||
|
_make_pngs(settings, sample_catalog)
|
||||||
|
result = pipeline.impose(settings)
|
||||||
|
assert result.cards == 4
|
||||||
|
assert result.pages == 1
|
||||||
|
assert result.output.is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_impose_custom_output(settings: Settings, sample_catalog: Catalog) -> None:
|
||||||
|
_prepare_catalogue(settings, sample_catalog)
|
||||||
|
_make_pngs(settings, sample_catalog)
|
||||||
|
output = settings.build_dir / "custom.pdf"
|
||||||
|
result = pipeline.impose(settings, output=output)
|
||||||
|
assert result.output == output
|
||||||
|
assert output.is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_without_catalogue_raises(settings: Settings) -> None:
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
pipeline.render(settings, screenshot=False)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Tests for the HTML renderer (no browser required)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from genshin_tcg.config import Settings
|
||||||
|
from genshin_tcg.data.catalog import Catalog
|
||||||
|
from genshin_tcg.rendering.converters import HtmlConverter, Viewport
|
||||||
|
from genshin_tcg.rendering.renderer import CardRenderer
|
||||||
|
|
||||||
|
|
||||||
|
def test_write_html_creates_standalone_documents(
|
||||||
|
settings: Settings, sample_catalog: Catalog
|
||||||
|
) -> None:
|
||||||
|
renderer = CardRenderer(settings)
|
||||||
|
rendered = renderer.write_html(renderer.build_views(sample_catalog))
|
||||||
|
|
||||||
|
assert len(rendered) == 4
|
||||||
|
character = next(item for item in rendered if item.card_id == "test_pyro")
|
||||||
|
document = character.html_path.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
assert "<style>" in document
|
||||||
|
assert "--card-w: 744px" in document
|
||||||
|
assert 'class="card el-pyro"' in document
|
||||||
|
assert "../../assets/tcg/test_pyro.png" in document
|
||||||
|
|
||||||
|
action = next(item for item in rendered if item.card_id == "test_talent")
|
||||||
|
action_document = action.html_path.read_text(encoding="utf-8")
|
||||||
|
assert 'class="card type-talent"' in action_document
|
||||||
|
|
||||||
|
|
||||||
|
def test_safe_names_for_special_ids() -> None:
|
||||||
|
from genshin_tcg.rendering.renderer import safe_name
|
||||||
|
|
||||||
|
assert safe_name("shaken,_not_purred") == "shaken__not_purred"
|
||||||
|
assert safe_name("the_bestest_travel_companion!") == "the_bestest_travel_companion"
|
||||||
|
assert safe_name("wellspring_of_war-lust") == "wellspring_of_war-lust"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rasterise_writes_png_and_keeps_html(
|
||||||
|
settings: Settings, sample_catalog: Catalog, fake_converter: HtmlConverter
|
||||||
|
) -> None:
|
||||||
|
renderer = CardRenderer(settings)
|
||||||
|
rendered = renderer.write_html(renderer.build_views(sample_catalog))
|
||||||
|
result = renderer.rasterise(rendered, fake_converter)
|
||||||
|
|
||||||
|
assert len(result) == 4
|
||||||
|
assert all(item.png_path.exists() for item in result)
|
||||||
|
assert all(item.html_path.exists() for item in result)
|
||||||
|
assert (result[0].png_path.read_bytes()) == b"fake-png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rasterise_removes_html_when_disabled(
|
||||||
|
settings: Settings, sample_catalog: Catalog, fake_converter: HtmlConverter
|
||||||
|
) -> None:
|
||||||
|
settings.render.keep_html = False
|
||||||
|
renderer = CardRenderer(settings)
|
||||||
|
rendered = renderer.write_html(renderer.build_views(sample_catalog))
|
||||||
|
result = renderer.rasterise(rendered, fake_converter)
|
||||||
|
|
||||||
|
assert all(not item.html_path.exists() for item in result)
|
||||||
|
assert all(item.png_path.exists() for item in result)
|
||||||
|
|
||||||
|
|
||||||
|
def test_viewport_from_settings(settings: Settings) -> None:
|
||||||
|
vp = Viewport(
|
||||||
|
width_px=settings.card.design_width_px,
|
||||||
|
height_px=settings.card.design_height_px,
|
||||||
|
scale_factor=settings.card.scale_factor,
|
||||||
|
)
|
||||||
|
assert (vp.width_px, vp.height_px, vp.scale_factor) == (744, 1039, 1.0)
|
||||||
Reference in New Issue
Block a user