First version
This commit is contained in:
@@ -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 %}
|
||||
Reference in New Issue
Block a user