First version
This commit is contained in:
@@ -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