Sorts : relevé à partir des règles réparé, objets écartés, écoles remises en ordre
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 2m18s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 2m49s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m10s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 2m18s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 2m49s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m10s
Presque tous les sorts proposés étaient écartés : la description reprise du livre commençait par une ligne trop courte (« 1 Action ») pour servir de passage cité. Relevé de sorts - Le passage cité prend le début de la description sur plusieurs lignes quand la première est trop courte. - La ligne de niveau placée au-dessus du nom (« TIER 2 ») ouvre la description du sort au lieu de finir celle du précédent ; le niveau y est lu avant celui du modèle. - Un objet magique n'est pas un sort : texte qui s'ouvre sur une rareté, « nom » qui n'est qu'un niveau, consigne au modèle ; les sections d'équipement ne sont plus cochées d'office. - Le modèle est relancé quand des titres de sorts restent sans réponse. - L'école se lit aussi dans un titre traduit ; la traduction des titres garde « › ». Lecture du PDF - Un grand titre dessiné après le texte qu'il coiffe est remis à sa place : les sorts d'une école n'étaient plus rangés sous le titre de l'école précédente. - Des lignes de blocs différents ne forment une rangée de tableau que si leurs cellules se touchent presque ou si une rangée voisine est alignée ; deux intertitres à la même hauteur ne sont pas une rangée.
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
"""Catalogue de sorts : relevé des sorts décrits dans un morceau de règles."""
|
"""Catalogue de sorts : relevé des sorts décrits dans un morceau de règles."""
|
||||||
|
import logging
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
@@ -8,10 +9,16 @@ from app.api.deps import get_llm_provider
|
|||||||
from app.application.llm_json import load_json_object
|
from app.application.llm_json import load_json_object
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import spell_extraction as spell_prompts
|
from app.application.prompts import spell_extraction as spell_prompts
|
||||||
from app.application.spell_location import locate_spells
|
from app.application.spell_location import locate_spells, named_by_a_heading, unclaimed_headings
|
||||||
from app.domain.ports import LLMProvider, LLMProviderError
|
from app.domain.ports import LLMProvider, LLMProviderError
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Un petit modèle s'arrête parfois après quelques sorts. Quand les sorts du morceau sont des
|
||||||
|
# intertitres et qu'une bonne part reste sans sort, il est relancé sur ceux qui manquent.
|
||||||
|
MAX_PASSES = 3
|
||||||
|
_MISSING_SHARE = 0.25
|
||||||
|
|
||||||
# Schéma de sortie : passé tel quel aux modèles locaux (sortie structurée), traduit en mode
|
# Schéma de sortie : passé tel quel aux modèles locaux (sortie structurée), traduit en mode
|
||||||
# JSON par les fournisseurs cloud.
|
# JSON par les fournisseurs cloud.
|
||||||
@@ -86,20 +93,43 @@ async def generate_spell_extraction(
|
|||||||
"""
|
"""
|
||||||
if not body.text.strip():
|
if not body.text.strip():
|
||||||
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
||||||
|
fields = [f.model_dump() for f in body.fields]
|
||||||
|
entries: list = []
|
||||||
|
spells = []
|
||||||
|
for attempt in range(MAX_PASSES):
|
||||||
|
avoid = [*body.avoid, *(spell.name for spell in spells)]
|
||||||
prompt = spell_prompts.spell_extraction_prompt(
|
prompt = spell_prompts.spell_extraction_prompt(
|
||||||
body.system_name, body.section_title, body.text,
|
body.system_name, body.section_title, body.text, fields, avoid)
|
||||||
[f.model_dump() for f in body.fields], body.avoid)
|
|
||||||
try:
|
try:
|
||||||
# Température basse : on relève ce qui est écrit, on n'écrit rien.
|
# Température basse : on relève ce qui est écrit, on n'écrit rien.
|
||||||
raw = await generate_with_retry(llm, prompt, output_format=_SPELLS_SCHEMA, temperature=0.1)
|
raw = await generate_with_retry(llm, prompt, output_format=_SPELLS_SCHEMA, temperature=0.1)
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
if attempt == 0:
|
||||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
break # une relance en échec ne retire rien à ce qui est déjà relevé
|
||||||
parsed, _ = load_json_object(raw)
|
parsed, _ = load_json_object(raw)
|
||||||
if not isinstance(parsed, dict):
|
if not isinstance(parsed, dict):
|
||||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de liste de sorts exploitable.")
|
if attempt == 0:
|
||||||
|
raise HTTPException(status_code=502,
|
||||||
|
detail="Le modèle n'a pas renvoyé de liste de sorts exploitable.")
|
||||||
|
break
|
||||||
|
answer = parsed.get("spells")
|
||||||
|
# D'une relance, seuls comptent les sorts que nomme un intertitre encore sans sort : le
|
||||||
|
# modèle, poussé à en trouver d'autres, ne doit pas découper les sorts déjà relevés.
|
||||||
|
fresh = answer if attempt == 0 else named_by_a_heading(answer, unclaimed_headings(body.text, spells))
|
||||||
|
before = len(spells)
|
||||||
|
entries.extend(fresh if isinstance(fresh, list) else [])
|
||||||
|
spells = locate_spells(entries, body.text, body.section_title)
|
||||||
|
missing = unclaimed_headings(body.text, spells)
|
||||||
|
headings = len(missing) + len(spells)
|
||||||
|
if not spells or len(spells) <= before and attempt > 0:
|
||||||
|
break
|
||||||
|
if len(missing) < 2 or len(missing) < _MISSING_SHARE * headings:
|
||||||
|
break
|
||||||
|
logger.info("Relevé de sorts « %s » : %s sort(s) relevé(s), %s intertitre(s) sans sort — relance.",
|
||||||
|
body.section_title, len(spells), len(missing))
|
||||||
return SpellExtractionResponseDTO(spells=[
|
return SpellExtractionResponseDTO(spells=[
|
||||||
ExtractedSpellDTO(name=spell.name, level=spell.level, school=spell.school,
|
ExtractedSpellDTO(name=spell.name, level=spell.level, school=spell.school,
|
||||||
description=spell.description, values=spell.values, excerpt=spell.excerpt)
|
description=spell.description, values=spell.values, excerpt=spell.excerpt)
|
||||||
for spell in locate_spells(parsed.get("spells"), body.text, body.section_title)
|
for spell in spells
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -75,6 +75,8 @@ def spell_extraction_prompt(system_name: str, section_title: str, text: str,
|
|||||||
"seulement cité, sans que le texte décrive son effet, n'est pas relevé.\n"
|
"seulement cité, sans que le texte décrive son effet, n'est pas relevé.\n"
|
||||||
"- Ne relève pas les règles générales de magie (comment lancer un sort, ce que coûte la "
|
"- Ne relève pas les règles générales de magie (comment lancer un sort, ce que coûte la "
|
||||||
"magie) : seulement les sorts eux-mêmes.\n"
|
"magie) : seulement les sorts eux-mêmes.\n"
|
||||||
|
"- Un OBJET n'est pas un sort, même s'il permet d'en lancer un : ne relève ni parchemin, "
|
||||||
|
"ni baguette, ni potion, ni flacon, ni anneau, ni aucun autre objet magique.\n"
|
||||||
'- Si le texte ne décrit aucun sort, renvoie {"spells": []}.\n'
|
'- Si le texte ne décrit aucun sort, renvoie {"spells": []}.\n'
|
||||||
"- Garde la langue du texte : ne traduis pas les noms.\n"
|
"- Garde la langue du texte : ne traduis pas les noms.\n"
|
||||||
"Renvoie maintenant le JSON."
|
"Renvoie maintenant le JSON."
|
||||||
|
|||||||
@@ -202,7 +202,11 @@ class RulesTranslator:
|
|||||||
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||||
for title in batch:
|
for title in batch:
|
||||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||||
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
translated = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||||
|
# Le séparateur des niveaux d'un titre (« Magic › Fire Spells ») reste le même.
|
||||||
|
if " › " in title and " › " not in translated:
|
||||||
|
translated = translated.replace(" > ", " › ")
|
||||||
|
out[title] = translated
|
||||||
return out
|
return out
|
||||||
|
|
||||||
async def translate_content(self, text: str, source: str, target: str) -> str:
|
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||||
|
|||||||
@@ -16,7 +16,31 @@ from dataclasses import dataclass, field
|
|||||||
|
|
||||||
# Longueur maximale du passage cité (le début de la description), que le Core vérifie.
|
# Longueur maximale du passage cité (le début de la description), que le Core vérifie.
|
||||||
EXCERPT_CHARS = 160
|
EXCERPT_CHARS = 160
|
||||||
|
# Le Core écarte un sort dont le passage cité fait moins de 25 caractères utiles. Une première
|
||||||
|
# ligne plus courte que ce seuil (« 1 Action », « Rituel ») est donc prolongée par les suivantes.
|
||||||
|
MIN_EXCERPT_CHARS = 40
|
||||||
_LEADING = " \t:—–-·|"
|
_LEADING = " \t:—–-·|"
|
||||||
|
# Ce qui précède le nom dans son bloc (sa ligne de niveau : « TIER 1 », « Tour de magie ») est
|
||||||
|
# gardé en tête de la description, tant que c'est court.
|
||||||
|
_PREFIX_CHARS = 80
|
||||||
|
# Ligne de niveau placée juste au-dessus du nom d'un sort.
|
||||||
|
_LEVEL_LINE = re.compile(
|
||||||
|
r"^(?:tier|niveau|level|lvl|rang|rank|cercle|circle|cantrip|tours? de magie|sorts? mineurs?)\b",
|
||||||
|
re.IGNORECASE)
|
||||||
|
_LEVEL_LINE_CHARS = 40
|
||||||
|
# Un objet magique se reconnaît à sa rareté, donnée dès le début de son texte (« Very rare
|
||||||
|
# flask », « Flacon très rare ») : un sort n'en a pas.
|
||||||
|
_RARITY = re.compile(
|
||||||
|
r"\b(?:common|uncommon|rare|very rare|legendary|artifact|commune?s?|peu commune?s?|tr[eè]s rares?"
|
||||||
|
r"|l[ée]gendaires?|art[ée]fact)\b", re.IGNORECASE)
|
||||||
|
_RARITY_WITHIN = 40
|
||||||
|
# Un « nom » qui n'est qu'un niveau : la ligne d'un tableau (prix des parchemins par niveau).
|
||||||
|
_LEVEL_NAME = re.compile(
|
||||||
|
r"^(?:(?:sorts?|spells?)\s+(?:de\s+|du\s+|of\s+)?)?"
|
||||||
|
r"(?:tier|niveau|level|lvl|rang|rank|cercle|circle|cantrips?|tours? de magie|sorts? mineurs?)\b"
|
||||||
|
r"(?:\s*\d+)?(?:\s+(?:spells?|sorts?))?\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
_HEADING = re.compile(r"^#{2,4}\s+(.+?)\s*$", re.MULTILINE)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -54,14 +78,54 @@ def _line_start(text: str, position: int) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def _excerpt(description: str) -> str:
|
def _excerpt(description: str) -> str:
|
||||||
"""Début de la description, sur sa première ligne : le passage que le Core retrouve dans
|
"""Début de la description : le passage que le Core retrouve dans le texte envoyé.
|
||||||
le texte envoyé."""
|
|
||||||
first = next((line.strip() for line in description.splitlines() if line.strip()), "")
|
C'est sa première ligne — prolongée par les suivantes tant qu'elle est trop courte pour
|
||||||
first = first.lstrip("#>*- ").strip() or first
|
faire foi (« 1 Action » ne prouve rien, « 1 Action Reaction: When an enemy… » si). Les
|
||||||
if len(first) <= EXCERPT_CHARS:
|
lignes sont réunies par une espace : le Core compare aux espaces près."""
|
||||||
return first
|
lines = [line.strip() for line in description.splitlines() if line.strip()]
|
||||||
cut = first.rfind(" ", 0, EXCERPT_CHARS)
|
if not lines:
|
||||||
return first[:cut if cut > 0 else EXCERPT_CHARS]
|
return ""
|
||||||
|
excerpt = lines[0].lstrip("#>*- ").strip() or lines[0]
|
||||||
|
for line in lines[1:]:
|
||||||
|
if len(excerpt) >= MIN_EXCERPT_CHARS:
|
||||||
|
break
|
||||||
|
excerpt = f"{excerpt} {line}"
|
||||||
|
if len(excerpt) <= EXCERPT_CHARS:
|
||||||
|
return excerpt
|
||||||
|
cut = excerpt.rfind(" ", 0, EXCERPT_CHARS)
|
||||||
|
return excerpt[:cut if cut > 0 else EXCERPT_CHARS]
|
||||||
|
|
||||||
|
|
||||||
|
def _level_line_above(text: str, line_start: int) -> int:
|
||||||
|
"""Début du bloc d'un sort dont le nom ouvre la ligne `line_start` : la ligne de niveau
|
||||||
|
placée juste au-dessus (« TIER 1 », « CANTRIP », « Tour de magie ») en fait partie."""
|
||||||
|
above = text[:line_start].rstrip()
|
||||||
|
start = above.rfind("\n") + 1
|
||||||
|
line = above[start:].strip()
|
||||||
|
if not line or len(line) > _LEVEL_LINE_CHARS or line.startswith(("#", "|", "-")):
|
||||||
|
return line_start
|
||||||
|
return start if _LEVEL_LINE.match(line) else line_start
|
||||||
|
|
||||||
|
|
||||||
|
def _level_from(prefix: str) -> str:
|
||||||
|
"""Niveau que donne la ligne placée au-dessus du nom : « TIER 2, AOE » → « 2 »,
|
||||||
|
« CANTRIP » → « Cantrip », « TOUR DE MAGIE » → « Tour de magie ». '' si ce n'en est pas une."""
|
||||||
|
line = prefix.splitlines()[0].strip() if prefix.strip() else ""
|
||||||
|
match = _LEVEL_LINE.match(line)
|
||||||
|
if not match:
|
||||||
|
return ""
|
||||||
|
number = re.search(r"\d+", line)
|
||||||
|
if number:
|
||||||
|
return number.group()
|
||||||
|
label = match.group(0) # « TOUR DE MAGIE UTILITÉ DE FEU » → « Tour de magie »
|
||||||
|
return label[:1].upper() + label[1:].lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _is_item(description: str) -> bool:
|
||||||
|
"""Le texte est-il celui d'un objet magique (rareté annoncée d'emblée) plutôt que d'un sort ?"""
|
||||||
|
first = next((line for line in description.splitlines() if line.strip()), "")
|
||||||
|
return bool(_RARITY.search(first[:_RARITY_WITHIN]))
|
||||||
|
|
||||||
|
|
||||||
_SCHOOL_IN_TITLE = (
|
_SCHOOL_IN_TITLE = (
|
||||||
@@ -73,7 +137,8 @@ _SCHOOL_IN_TITLE = (
|
|||||||
|
|
||||||
def school_from_title(section_title: str) -> str:
|
def school_from_title(section_title: str) -> str:
|
||||||
"""École que nomme le titre de la section (« Magic › Fire Spells » → « Fire »), ou ''."""
|
"""École que nomme le titre de la section (« Magic › Fire Spells » → « Fire »), ou ''."""
|
||||||
last = section_title.split("›")[-1].strip()
|
# « › » sépare les niveaux d'un titre ; un titre traduit par l'IA porte parfois « > ».
|
||||||
|
last = re.split(r"[›>]", section_title)[-1].strip()
|
||||||
for pattern in _SCHOOL_IN_TITLE:
|
for pattern in _SCHOOL_IN_TITLE:
|
||||||
match = pattern.match(last)
|
match = pattern.match(last)
|
||||||
if match:
|
if match:
|
||||||
@@ -82,6 +147,23 @@ def school_from_title(section_title: str) -> str:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def unclaimed_headings(text: str, spells: list[LocatedSpell]) -> list[str]:
|
||||||
|
"""Intertitres du texte qu'aucun sort relevé ne nomme : dans une section de sorts, ce sont
|
||||||
|
ceux que le modèle a laissés de côté."""
|
||||||
|
names = [spell.name.casefold() for spell in spells]
|
||||||
|
return [heading for heading in _HEADING.findall(text)
|
||||||
|
if not any(name in heading.casefold() for name in names)]
|
||||||
|
|
||||||
|
|
||||||
|
def named_by_a_heading(entries: object, headings: list[str]) -> list[dict]:
|
||||||
|
"""Entrées du modèle dont le nom est celui d'un de ces intertitres."""
|
||||||
|
folded = [heading.casefold() for heading in headings]
|
||||||
|
return [entry for entry in entries if isinstance(entry, dict)
|
||||||
|
and len(_text(entry.get("name"))) >= 3
|
||||||
|
and any(_text(entry.get("name")).casefold() in heading for heading in folded)
|
||||||
|
] if isinstance(entries, list) else []
|
||||||
|
|
||||||
|
|
||||||
def locate_spells(entries: object, text: str, section_title: str = "") -> list[LocatedSpell]:
|
def locate_spells(entries: object, text: str, section_title: str = "") -> list[LocatedSpell]:
|
||||||
"""Sorts désignés par le modèle, avec leur description reprise du texte.
|
"""Sorts désignés par le modèle, avec leur description reprise du texte.
|
||||||
|
|
||||||
@@ -89,15 +171,16 @@ def locate_spells(entries: object, text: str, section_title: str = "") -> list[L
|
|||||||
|
|
||||||
`entries` : la liste renvoyée par le modèle, des objets {name, level, school, values, start}.
|
`entries` : la liste renvoyée par le modèle, des objets {name, level, school, values, start}.
|
||||||
Un sort dont le nom ne figure pas dans le texte est écarté (inventé, traduit, ou venu d'un
|
Un sort dont le nom ne figure pas dans le texte est écarté (inventé, traduit, ou venu d'un
|
||||||
autre jeu), de même qu'un sort seulement cité, sans texte après son nom."""
|
autre jeu), de même qu'un sort seulement cité, sans texte après son nom, et qu'un objet
|
||||||
|
magique (son texte s'ouvre sur sa rareté)."""
|
||||||
if not isinstance(entries, list):
|
if not isinstance(entries, list):
|
||||||
return []
|
return []
|
||||||
found: list[tuple[int, int, dict]] = [] # (début du bloc, fin du nom, entrée)
|
found: list[tuple[int, int, int, dict]] = [] # (début du bloc, début du nom, fin du nom, entrée)
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
if not isinstance(entry, dict):
|
if not isinstance(entry, dict):
|
||||||
continue
|
continue
|
||||||
name = _text(entry.get("name"))
|
name = _text(entry.get("name"))
|
||||||
if not name:
|
if not name or _LEVEL_NAME.match(name):
|
||||||
continue
|
continue
|
||||||
# Le nom est cherché à partir des premiers mots du bloc quand le modèle les donne :
|
# Le nom est cherché à partir des premiers mots du bloc quand le modèle les donne :
|
||||||
# un sort cité plus haut dans le texte (dans une liste, un sommaire) n'est pas son bloc.
|
# un sort cité plus haut dans le texte (dans une liste, un sommaire) n'est pas son bloc.
|
||||||
@@ -113,28 +196,37 @@ def locate_spells(entries: object, text: str, section_title: str = "") -> list[L
|
|||||||
if name_span is None:
|
if name_span is None:
|
||||||
continue
|
continue
|
||||||
block_start = _line_start(text, start[0] if start is not None else name_span[0])
|
block_start = _line_start(text, start[0] if start is not None else name_span[0])
|
||||||
found.append((block_start, name_span[1], entry))
|
if start is None:
|
||||||
|
block_start = _level_line_above(text, block_start)
|
||||||
|
found.append((block_start, name_span[0], name_span[1], entry))
|
||||||
|
|
||||||
found.sort(key=lambda item: item[0])
|
found.sort(key=lambda item: item[0])
|
||||||
fallback_school = school_from_title(section_title)
|
fallback_school = school_from_title(section_title)
|
||||||
out: list[LocatedSpell] = []
|
out: list[LocatedSpell] = []
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
for position, (block_start, name_end, entry) in enumerate(found):
|
for position, (block_start, name_start, name_end, entry) in enumerate(found):
|
||||||
name = _text(entry.get("name"))
|
name = _text(entry.get("name"))
|
||||||
if name.lower() in seen:
|
if name.lower() in seen:
|
||||||
continue
|
continue
|
||||||
block_end = next((nxt[0] for nxt in found[position + 1:] if nxt[0] > block_start), len(text))
|
block_end = next((nxt[0] for nxt in found[position + 1:] if nxt[0] > block_start), len(text))
|
||||||
description = text[name_end:max(name_end, block_end)].strip().lstrip(_LEADING).strip()
|
body = text[name_end:max(name_end, block_end)].strip().lstrip(_LEADING).strip()
|
||||||
if not description:
|
if not body or _is_item(body):
|
||||||
continue
|
continue
|
||||||
|
# Ce qui précède le nom dans son bloc — sa ligne de niveau — ouvre la description.
|
||||||
|
prefix = text[block_start:name_start].strip().strip("#").strip()
|
||||||
|
description = f"{prefix}\n\n{body}" if prefix and len(prefix) <= _PREFIX_CHARS else body
|
||||||
values = entry.get("values")
|
values = entry.get("values")
|
||||||
seen.add(name.lower())
|
seen.add(name.lower())
|
||||||
out.append(LocatedSpell(
|
out.append(LocatedSpell(
|
||||||
name=name,
|
name=name,
|
||||||
level=_text(entry.get("level")),
|
# Le niveau se lit d'abord sur la ligne de niveau du livre : elle fait foi. À
|
||||||
|
# défaut, c'est celui que donne le modèle.
|
||||||
|
level=_level_from(prefix) or _text(entry.get("level")),
|
||||||
school=_text(entry.get("school")) or fallback_school,
|
school=_text(entry.get("school")) or fallback_school,
|
||||||
description=description,
|
description=description,
|
||||||
excerpt=_excerpt(description),
|
# Le passage cité part de ce qui suit le nom : dans le livre, le nom sépare la
|
||||||
|
# ligne de niveau du reste, et le Core cherche un passage d'un seul tenant.
|
||||||
|
excerpt=_excerpt(body),
|
||||||
values={str(k).strip(): _text(v) for k, v in values.items() if str(k).strip() and _text(v)}
|
values={str(k).strip(): _text(v) for k, v in values.items() if str(k).strip() and _text(v)}
|
||||||
if isinstance(values, dict) else {},
|
if isinstance(values, dict) else {},
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -45,6 +45,21 @@ COLUMN_SPILL = 0.1
|
|||||||
# Un blanc horizontal d'au moins cette part de la hauteur de page, commun à toutes les
|
# Un blanc horizontal d'au moins cette part de la hauteur de page, commun à toutes les
|
||||||
# colonnes, sépare deux bandes (l'espace entre deux paragraphes est bien plus petit).
|
# colonnes, sépare deux bandes (l'espace entre deux paragraphes est bien plus petit).
|
||||||
BAND_GAP = 0.03
|
BAND_GAP = 0.03
|
||||||
|
# Un « grand titre » : un bloc court dont les caractères font au moins cette fois la taille du
|
||||||
|
# texte courant de la page.
|
||||||
|
TITLE_RATIO = 1.5
|
||||||
|
TITLE_CHARS = 80
|
||||||
|
# Une ligne plus grosse que le texte courant dans ce rapport est un intertitre, pas une cellule :
|
||||||
|
# deux intertitres à la même hauteur dans deux colonnes ne font pas une rangée de tableau.
|
||||||
|
SUBTITLE_RATIO = 1.25
|
||||||
|
# Deux rangées d'un même tableau se suivent de près (en tailles de caractères) et leurs
|
||||||
|
# premières cellules sont alignées (en points).
|
||||||
|
ROW_PITCH = 3.0
|
||||||
|
ROW_ALIGN = 6.0
|
||||||
|
# Blanc maximal (en tailles de caractères) entre deux cellules d'une rangée isolée.
|
||||||
|
LONE_ROW_GAP = 5.0
|
||||||
|
# Une page plus large que haute dans ce rapport est une double page : chaque moitié a ses titres.
|
||||||
|
SPREAD_RATIO = 1.2
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -120,6 +135,7 @@ def _gather_rows(blocks: list[LayoutBlock], height: float) -> list[LayoutBlock]:
|
|||||||
la même colonne. La rangée prend la place de sa cellule de gauche ; les blocs vidés de
|
la même colonne. La rangée prend la place de sa cellule de gauche ; les blocs vidés de
|
||||||
leurs lignes disparaissent."""
|
leurs lignes disparaissent."""
|
||||||
columns = _columns(blocks, height)
|
columns = _columns(blocks, height)
|
||||||
|
body = _body_size(blocks)
|
||||||
entries = [
|
entries = [
|
||||||
(b, i, line) for b, block in enumerate(blocks) for i, line in enumerate(block.lines)
|
(b, i, line) for b, block in enumerate(blocks) for i, line in enumerate(block.lines)
|
||||||
if not _is_edge(line.y0, line.y1, height)
|
if not _is_edge(line.y0, line.y1, height)
|
||||||
@@ -139,7 +155,8 @@ def _gather_rows(blocks: list[LayoutBlock], height: float) -> list[LayoutBlock]:
|
|||||||
def zone(block_rank: int, line: LayoutLine) -> int:
|
def zone(block_rank: int, line: LayoutLine) -> int:
|
||||||
"""Zone où chercher les cellules voisines : la colonne de la ligne si son bloc est une
|
"""Zone où chercher les cellules voisines : la colonne de la ligne si son bloc est une
|
||||||
rangée, sinon son seul bloc (cellules d'un même bloc, tableau hors des colonnes)."""
|
rangée, sinon son seul bloc (cellules d'un même bloc, tableau hors des colonnes)."""
|
||||||
column = (_column_of(line, columns) if columns else 0) if single_row[block_rank] else -1
|
subtitle = body > 0 and line.size >= SUBTITLE_RATIO * body
|
||||||
|
column = (_column_of(line, columns) if columns else 0) if single_row[block_rank] and not subtitle else -1
|
||||||
return column if column != -1 else -(block_rank + 2)
|
return column if column != -1 else -(block_rank + 2)
|
||||||
|
|
||||||
keyed = sorted(((zone(b, line), line.y1, b, i, line) for b, i, line in entries), key=lambda e: (e[0], e[1]))
|
keyed = sorted(((zone(b, line), line.y1, b, i, line) for b, i, line in entries), key=lambda e: (e[0], e[1]))
|
||||||
@@ -157,12 +174,16 @@ def _gather_rows(blocks: list[LayoutBlock], height: float) -> list[LayoutBlock]:
|
|||||||
merged: dict[tuple[int, int], LayoutLine] = {} # (bloc, ligne) de gauche → rangée
|
merged: dict[tuple[int, int], LayoutLine] = {} # (bloc, ligne) de gauche → rangée
|
||||||
removed: set[tuple[int, int]] = set()
|
removed: set[tuple[int, int]] = set()
|
||||||
widened: dict[int, float] = {}
|
widened: dict[int, float] = {}
|
||||||
for cells in groups:
|
rows = [sorted(cells, key=lambda c: c[2].x0) for cells in groups if len(cells) >= 2]
|
||||||
if len(cells) < 2:
|
for cells in rows:
|
||||||
continue
|
|
||||||
cells.sort(key=lambda c: c[2].x0)
|
|
||||||
if any(right[2].x0 < left[2].x1 + MIN_CELL_GAP for left, right in zip(cells, cells[1:])):
|
if any(right[2].x0 < left[2].x1 + MIN_CELL_GAP for left, right in zip(cells, cells[1:])):
|
||||||
continue # des lignes qui se chevauchent ne sont pas des cellules
|
continue # des lignes qui se chevauchent ne sont pas des cellules
|
||||||
|
# Des lignes de blocs différents à la même hauteur sont une rangée si leurs cellules se
|
||||||
|
# touchent presque, ou si le tableau continue. Éloignées et seules, ce sont deux bouts
|
||||||
|
# de texte de deux colonnes (l'étiquette d'un sort à gauche, celle d'un autre à droite).
|
||||||
|
if (len({b for b, _, _ in cells}) > 1 and not _close_cells(cells)
|
||||||
|
and not any(_neighbour_rows(cells, other) for other in rows)):
|
||||||
|
continue
|
||||||
b, i, first = cells[0]
|
b, i, first = cells[0]
|
||||||
texts = [c[2].text for c in cells]
|
texts = [c[2].text for c in cells]
|
||||||
if len(cells) == 2 and len(texts[0]) <= 3 and all(c[2].cells == 1 for c in cells):
|
if len(cells) == 2 and len(texts[0]) <= 3 and all(c[2].cells == 1 for c in cells):
|
||||||
@@ -184,6 +205,30 @@ def _gather_rows(blocks: list[LayoutBlock], height: float) -> list[LayoutBlock]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _close_cells(row: list[tuple[int, int, LayoutLine]]) -> bool:
|
||||||
|
"""Cellules assez proches pour former une rangée à elles seules (« 15-16 | Texte »)."""
|
||||||
|
return all(right[2].x0 - left[2].x1 <= LONE_ROW_GAP * max(left[2].size, right[2].size)
|
||||||
|
for left, right in zip(row, row[1:]))
|
||||||
|
|
||||||
|
|
||||||
|
def _neighbour_rows(row: list[tuple[int, int, LayoutLine]], other: list[tuple[int, int, LayoutLine]]) -> bool:
|
||||||
|
"""Deux rangées voisines d'un même tableau : l'une près de l'autre, leurs deux premières
|
||||||
|
cellules alignées (à gauche, à droite ou au centre : une colonne de nombres s'aligne à droite).
|
||||||
|
Le titre d'un sort et son coût, sur une ligne, ne font pas un tableau avec les étiquettes
|
||||||
|
de niveau des colonnes voisines."""
|
||||||
|
if row is other:
|
||||||
|
return False
|
||||||
|
first, second = row[0][2], other[0][2]
|
||||||
|
if not 0 < abs(first.y0 - second.y0) <= ROW_PITCH * max(first.size, second.size):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def aligned(a: LayoutLine, b: LayoutLine) -> bool:
|
||||||
|
return (abs(a.x0 - b.x0) <= ROW_ALIGN or abs(a.x1 - b.x1) <= ROW_ALIGN
|
||||||
|
or abs((a.x0 + a.x1) - (b.x0 + b.x1)) <= 2 * ROW_ALIGN)
|
||||||
|
|
||||||
|
return all(aligned(mine[2], theirs[2]) for mine, theirs in zip(row[:2], other[:2]))
|
||||||
|
|
||||||
|
|
||||||
def _goes_backward(blocks: list[LayoutBlock], width: float) -> bool:
|
def _goes_backward(blocks: list[LayoutBlock], width: float) -> bool:
|
||||||
"""La suite de blocs revient-elle en arrière ? Même colonne et plus haut, ou plus à gauche
|
"""La suite de blocs revient-elle en arrière ? Même colonne et plus haut, ou plus à gauche
|
||||||
et plus haut. Passer à la colonne suivante (à droite, plus haut) est l'ordre normal."""
|
et plus haut. Passer à la colonne suivante (à droite, plus haut) est l'ordre normal."""
|
||||||
@@ -322,12 +367,65 @@ def without_margin_tabs(blocks: list[LayoutBlock], width: float) -> list[LayoutB
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _body_size(blocks: list[LayoutBlock]) -> float:
|
||||||
|
"""Taille de caractères du texte courant : celle qui porte le plus de texte sur la page."""
|
||||||
|
weight: dict[float, int] = {}
|
||||||
|
for block in blocks:
|
||||||
|
for line in block.lines:
|
||||||
|
weight[line.size] = weight.get(line.size, 0) + len(line.text)
|
||||||
|
return max(weight, key=lambda size: weight[size]) if weight else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def hoist_titles(blocks: list[LayoutBlock], width: float, height: float) -> list[LayoutBlock]:
|
||||||
|
"""Remet à sa place un grand titre dessiné après le texte qu'il coiffe.
|
||||||
|
|
||||||
|
Certains PDF tracent d'abord le contenu d'une page, puis ses grands titres par-dessus : lus
|
||||||
|
dans cet ordre, le titre arrive après son texte, qui se retrouve rangé sous le titre
|
||||||
|
précédent (les sorts nécrotiques sous « Radiant Spells »). Un grand titre remonte donc
|
||||||
|
devant les blocs qui le précèdent dans le PDF alors qu'ils sont SOUS lui dans la page, à
|
||||||
|
son aplomb. On s'arrête au premier bloc qui est au-dessus de lui, ou qui barre la page.
|
||||||
|
Dans une double page, un titre ne sort pas de sa moitié."""
|
||||||
|
body = _body_size(blocks)
|
||||||
|
if not body or width <= 0:
|
||||||
|
return blocks
|
||||||
|
spread = width >= SPREAD_RATIO * height
|
||||||
|
out = list(blocks)
|
||||||
|
for title in blocks:
|
||||||
|
if _is_edge(title.y0, title.y1, height) or title.chars > TITLE_CHARS or not title.lines \
|
||||||
|
or min(line.size for line in title.lines) < TITLE_RATIO * body:
|
||||||
|
continue
|
||||||
|
low, high = 0.0, width
|
||||||
|
if spread:
|
||||||
|
low, high = (0.0, width / 2) if (title.x0 + title.x1) / 2 < width / 2 else (width / 2, width)
|
||||||
|
zone = [title.x0, title.x1]
|
||||||
|
position = next(i for i, block in enumerate(out) if block is title)
|
||||||
|
target = None
|
||||||
|
for index in range(position - 1, -1, -1):
|
||||||
|
other = out[index]
|
||||||
|
if _is_edge(other.y0, other.y1, height):
|
||||||
|
continue
|
||||||
|
if other.x1 - other.x0 >= WIDE_RATIO * (high - low):
|
||||||
|
break # un bloc qui barre la page : une autre bande
|
||||||
|
center = (other.x0 + other.x1) / 2
|
||||||
|
if other.x1 <= zone[0] or other.x0 >= zone[1] or not low <= center <= high:
|
||||||
|
continue # ailleurs dans la page
|
||||||
|
# La boîte d'un gros titre déborde sous ses lettres : un bloc est « sous » le titre
|
||||||
|
# dès qu'il commence sous son milieu.
|
||||||
|
if other.y0 < (title.y0 + title.y1) / 2:
|
||||||
|
break # au-dessus du titre : il est à sa place
|
||||||
|
target = index
|
||||||
|
zone = [max(low, min(zone[0], other.x0)), min(high, max(zone[1], other.x1))]
|
||||||
|
if target is not None:
|
||||||
|
out.insert(target, out.pop(position))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def place_lines(blocks: list[LayoutBlock], width: float, height: float) -> list[PlacedLine]:
|
def place_lines(blocks: list[LayoutBlock], width: float, height: float) -> list[PlacedLine]:
|
||||||
"""Lignes d'une page dans l'ordre de lecture, rangées de tableau réunies."""
|
"""Lignes d'une page dans l'ordre de lecture, rangées de tableau réunies."""
|
||||||
blocks = without_overprints(without_margin_tabs([b for b in blocks if b.lines], width))
|
blocks = without_overprints(without_margin_tabs([b for b in blocks if b.lines], width))
|
||||||
if not blocks:
|
if not blocks:
|
||||||
return []
|
return []
|
||||||
ordered = reading_order(_gather_rows(blocks, height), width, height)
|
ordered = hoist_titles(reading_order(_gather_rows(blocks, height), width, height), width, height)
|
||||||
out: list[PlacedLine] = []
|
out: list[PlacedLine] = []
|
||||||
for rank, block in enumerate(ordered):
|
for rank, block in enumerate(ordered):
|
||||||
for line in block.lines:
|
for line in block.lines:
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from app.infrastructure.pdf_layout import (
|
from app.infrastructure.pdf_layout import (
|
||||||
CELL_SEPARATOR, LayoutBlock, LayoutLine, place_lines, reading_order, split_cells, without_overprints,
|
CELL_SEPARATOR, LayoutBlock, LayoutLine, hoist_titles, place_lines, reading_order, split_cells,
|
||||||
|
without_overprints,
|
||||||
)
|
)
|
||||||
|
|
||||||
WIDTH, HEIGHT = 600.0, 800.0
|
WIDTH, HEIGHT = 600.0, 800.0
|
||||||
@@ -105,9 +106,31 @@ def test_cells_of_a_row_spread_over_several_blocks_are_gathered():
|
|||||||
block(40, 400, 120, 410, line(40, 400, 120, "Wooden Buckler")),
|
block(40, 400, 120, 410, line(40, 400, 120, "Wooden Buckler")),
|
||||||
block(300, 400, 320, 410, line(300, 400, 320, "+2")),
|
block(300, 400, 320, 410, line(300, 400, 320, "+2")),
|
||||||
block(500, 400, 540, 410, line(500, 400, 540, "5 gp")),
|
block(500, 400, 540, 410, line(500, 400, 540, "5 gp")),
|
||||||
|
block(40, 415, 120, 425, line(40, 415, 120, "Iron Shield")),
|
||||||
|
block(300, 415, 320, 425, line(300, 415, 320, "+3")),
|
||||||
|
block(500, 415, 540, 425, line(500, 415, 540, "20 gp")),
|
||||||
]
|
]
|
||||||
placed = place_lines(blocks, WIDTH, HEIGHT)
|
placed = place_lines(blocks, WIDTH, HEIGHT)
|
||||||
assert placed[-1].text == "Wooden Buckler | +2 | 5 gp" and placed[-1].cells == 3
|
assert [p.text for p in placed[-2:]] == ["Wooden Buckler | +2 | 5 gp", "Iron Shield | +3 | 20 gp"]
|
||||||
|
assert placed[-1].cells == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_lone_labels_at_the_same_height_are_not_a_table_row():
|
||||||
|
"""Double colonne de sorts : « CANTRIP » ouvre un sort à gauche, « TIER 4 » un autre à droite."""
|
||||||
|
blocks = [
|
||||||
|
paragraph(40, 100, 560, 300),
|
||||||
|
block(40, 400, 80, 408, line(40, 400, 80, "CANTRIP", 8.0)),
|
||||||
|
block(40, 410, 260, 450, line(40, 410, 260, "Rebuke : la cible subit 1d8 dégâts radiants,"),
|
||||||
|
line(40, 422, 260, "et ne peut plus attaquer ce tour.")),
|
||||||
|
block(300, 400, 335, 408, line(300, 400, 335, "TIER 4", 8.0)),
|
||||||
|
block(300, 410, 540, 450, line(300, 410, 540, "Shield of Justice : vos attaquants sont aveuglés"),
|
||||||
|
line(300, 422, 540, "jusqu'à la fin de leur prochain tour.")),
|
||||||
|
block(40, 520, 80, 528, line(40, 520, 80, "TIER 1", 8.0)),
|
||||||
|
block(300, 520, 335, 528, line(300, 520, 335, "TIER 6", 8.0)),
|
||||||
|
]
|
||||||
|
read = [p.text for p in place_lines(blocks, WIDTH, HEIGHT)]
|
||||||
|
assert "CANTRIP" in read and "TIER 4" in read and "TIER 1" in read and "TIER 6" in read
|
||||||
|
assert not any(" | " in text for text in read)
|
||||||
|
|
||||||
|
|
||||||
def test_lines_of_a_paragraph_are_never_pulled_into_a_neighbouring_row():
|
def test_lines_of_a_paragraph_are_never_pulled_into_a_neighbouring_row():
|
||||||
@@ -118,6 +141,8 @@ def test_lines_of_a_paragraph_are_never_pulled_into_a_neighbouring_row():
|
|||||||
paragraph(40, 100, 560, 300),
|
paragraph(40, 100, 560, 300),
|
||||||
block(40, 395, 120, 405, line(40, 395, 120, "Wooden Buckler")),
|
block(40, 395, 120, 405, line(40, 395, 120, "Wooden Buckler")),
|
||||||
block(200, 395, 220, 405, line(200, 395, 220, "+2")),
|
block(200, 395, 220, 405, line(200, 395, 220, "+2")),
|
||||||
|
block(40, 410, 120, 420, line(40, 410, 120, "Iron Shield")),
|
||||||
|
block(200, 410, 220, 420, line(200, 410, 220, "+3")),
|
||||||
sidebar,
|
sidebar,
|
||||||
]
|
]
|
||||||
placed = place_lines(blocks, WIDTH, HEIGHT)
|
placed = place_lines(blocks, WIDTH, HEIGHT)
|
||||||
@@ -146,6 +171,77 @@ def test_lines_at_the_top_and_bottom_of_the_page_are_flagged():
|
|||||||
assert [p.edge for p in place_lines(blocks, WIDTH, HEIGHT)] == [True, False, True]
|
assert [p.edge for p in place_lines(blocks, WIDTH, HEIGHT)] == [True, False, True]
|
||||||
|
|
||||||
|
|
||||||
|
# --- grands titres dessinés après leur texte ---------------------------------------------------
|
||||||
|
|
||||||
|
def _spell(x0: float, y0: float, name: str) -> LayoutBlock:
|
||||||
|
return block(x0, y0, x0 + 160, y0 + 60, LayoutLine(x0, y0, x0 + 160, y0 + 12, name, 12.0),
|
||||||
|
line(x0, y0 + 14, x0 + 160, "Portée 8. Dégâts 2d12, puis la cible est entravée jusqu'à la fin."))
|
||||||
|
|
||||||
|
|
||||||
|
def _big_title(x0: float, y0: float, text: str) -> LayoutBlock:
|
||||||
|
return block(x0, y0, x0 + 150, y0 + 30, LayoutLine(x0, y0, x0 + 150, y0 + 30, text, 25.0))
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_big_title_drawn_after_the_text_it_heads_is_put_back_above_it():
|
||||||
|
"""Double page d'un livre de sorts : chaque moitié a deux colonnes de sorts sous son titre,
|
||||||
|
mais le PDF trace les sorts d'abord, le titre de l'école ensuite."""
|
||||||
|
width, height = 840.0, 600.0
|
||||||
|
radiant = [_spell(30, 80, "Rebuke"), _spell(30, 200, "Heal"), _spell(220, 80, "Vengeance")]
|
||||||
|
necrotic = [block(450, 100, 475, 110, line(450, 100, 475, "CANTRIP", 7.5)),
|
||||||
|
_spell(450, 115, "Entice"), _spell(640, 115, "Vigor Mortis")]
|
||||||
|
radiant_title, necrotic_title = _big_title(150, 30, "Radiant Spells"), _big_title(570, 60, "Necrotic Spells")
|
||||||
|
redeem = _spell(80, 520, "Redeem")
|
||||||
|
drawn = [*radiant, radiant_title, redeem, *necrotic, necrotic_title]
|
||||||
|
ordered = hoist_titles(drawn, width, height)
|
||||||
|
assert ordered == [radiant_title, *radiant, redeem, necrotic_title, *necrotic]
|
||||||
|
# Par place_lines, le texte suit : le titre de l'école précède ses sorts.
|
||||||
|
read = [placed.text for placed in place_lines(drawn, width, height)]
|
||||||
|
assert read.index("Radiant Spells") < read.index("Rebuke") < read.index("Redeem")
|
||||||
|
assert read.index("Redeem") < read.index("Necrotic Spells") < read.index("CANTRIP") < read.index("Entice")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_label_brushing_the_bottom_of_a_big_title_is_still_below_it():
|
||||||
|
"""La boîte d'un titre de 25 points descend sous ses lettres : l'étiquette « CANTRIP » du
|
||||||
|
premier sort la frôle, sans être au-dessus du titre."""
|
||||||
|
title = _big_title(150, 30, "Radiant Spells") # boîte de 30 à 60
|
||||||
|
label = block(30, 57, 60, 66, line(30, 57, 60, "CANTRIP", 7.5))
|
||||||
|
spell = _spell(30, 70, "Rebuke")
|
||||||
|
assert hoist_titles([label, spell, title], 840.0, 600.0) == [title, label, spell]
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_subheadings_at_the_same_height_in_two_columns_are_not_a_table_row():
|
||||||
|
left = block(30, 200, 190, 212, LayoutLine(30, 200, 190, 212, "Heal | 1 Action", 12.0, 2))
|
||||||
|
right = block(220, 200, 380, 212, LayoutLine(220, 200, 380, 212, "Sacrifice | 1 Action", 12.0, 2))
|
||||||
|
texts_ = [paragraph(30, 216, 190, 260), paragraph(220, 216, 380, 260)]
|
||||||
|
read = [placed.text for placed in place_lines([left, texts_[0], right, texts_[1]], 840.0, 600.0)]
|
||||||
|
assert "Heal | 1 Action" in read and "Sacrifice | 1 Action" in read
|
||||||
|
# Des cellules à la taille du texte courant restent une rangée.
|
||||||
|
cells = [block(30, 300, 80, 310, line(30, 300, 80, "Épée")), block(110, 300, 160, 310, line(110, 300, 160, "1d8")),
|
||||||
|
block(30, 314, 80, 324, line(30, 314, 80, "Dague")), block(110, 314, 160, 324, line(110, 314, 160, "1d4"))]
|
||||||
|
assert "Épée | 1d8" in [placed.text for placed in place_lines([*texts_, *cells], 840.0, 600.0)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_title_already_in_place_or_heading_another_column_does_not_move():
|
||||||
|
# Page simple, deux colonnes : le titre en tête de la seconde ne passe pas devant la première.
|
||||||
|
first = [paragraph(40, 60, 280, 300), paragraph(40, 320, 280, 560)]
|
||||||
|
title = _big_title(320, 60, "Magie")
|
||||||
|
second = [paragraph(320, 100, 560, 300)]
|
||||||
|
drawn = [*first, title, *second]
|
||||||
|
assert hoist_titles(drawn, WIDTH, HEIGHT) == drawn
|
||||||
|
# Un titre placé plus bas que ce qui le précède reste où il est.
|
||||||
|
lower = [paragraph(40, 60, 560, 200), _big_title(40, 240, "Combat"), paragraph(40, 290, 560, 400)]
|
||||||
|
assert hoist_titles(lower, WIDTH, HEIGHT) == lower
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_title_does_not_climb_over_a_block_that_spans_the_page():
|
||||||
|
banner = paragraph(40, 200, 560, 240) # barre la page, sous le titre
|
||||||
|
below = paragraph(40, 260, 280, 400)
|
||||||
|
title = _big_title(40, 150, "Rituels")
|
||||||
|
drawn = [paragraph(40, 60, 560, 120), banner, below, title]
|
||||||
|
# Le titre remonte devant le bloc qu'il coiffe, pas au-delà de la bande qui barre la page.
|
||||||
|
assert hoist_titles(drawn, WIDTH, HEIGHT) == [drawn[0], banner, title, below]
|
||||||
|
|
||||||
|
|
||||||
def test_a_title_drawn_twice_at_the_same_place_is_read_once():
|
def test_a_title_drawn_twice_at_the_same_place_is_read_once():
|
||||||
title = line(50, 100, 120, "Notes", 18.0)
|
title = line(50, 100, 120, "Notes", 18.0)
|
||||||
twice = block(50, 100, 300, 140, title, LayoutLine(50.2, 100.1, 120.1, 118.0, "Notes", 18.0),
|
twice = block(50, 100, 300, 140, title, LayoutLine(50.2, 100.1, 120.1, 118.0, "Notes", 18.0),
|
||||||
|
|||||||
@@ -208,6 +208,18 @@ async def test_translate_titles_sends_a_long_list_in_several_calls():
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def test_translated_titles_keep_the_path_separator():
|
||||||
|
class TitlesLLM:
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
return ('{"titles": {"Magic › Fire Spells": "Magie > Sorts de feu", "Combat": "Combat",'
|
||||||
|
' "Gear › A > B": "Équipement › A > B"}}')
|
||||||
|
|
||||||
|
titles = await rules_translation.RulesTranslator(TitlesLLM()).translate_titles(
|
||||||
|
["Magic › Fire Spells", "Combat", "Gear › A > B"], "en", "fr")
|
||||||
|
assert titles == {"Magic › Fire Spells": "Magie › Sorts de feu", "Combat": "Combat",
|
||||||
|
"Gear › A > B": "Équipement › A > B"}
|
||||||
|
|
||||||
|
|
||||||
# --- glossaire des termes de jeu ---------------------------------------------------------------
|
# --- glossaire des termes de jeu ---------------------------------------------------------------
|
||||||
|
|
||||||
_STAT_BLOCK = ("Tiny beast, unaligned\n\nArmor Class 12 Hit Points 22 (4d6 + 8) Speed 10 ft., fly 40 ft.\n\n"
|
_STAT_BLOCK = ("Tiny beast, unaligned\n\nArmor Class 12 Hit Points 22 (4d6 + 8) Speed 10 ft., fly 40 ft.\n\n"
|
||||||
|
|||||||
@@ -92,14 +92,21 @@ def test_the_description_of_a_spell_is_the_slice_of_the_book_that_follows_its_na
|
|||||||
], _BOOK)
|
], _BOOK)
|
||||||
|
|
||||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite", "Enchant Weapon"]
|
assert [s.name for s in spells] == ["Flame Dart", "Ignite", "Enchant Weapon"]
|
||||||
# Mot pour mot, jusqu'à la ligne qui ouvre le sort suivant : rien n'est réécrit.
|
# Mot pour mot, de la ligne de niveau qui ouvre le sort à celle qui ouvre le suivant :
|
||||||
|
# rien n'est réécrit, seul le nom (déjà dans le titre de la fiche) est retiré.
|
||||||
assert spells[0].description == (
|
assert spells[0].description == (
|
||||||
"1 Action\n\nRange: 10. Damage: 1d10. On crit: Smoldering.\n\nHigh Levels: +5 damage every 5th level.")
|
"CANTRIP\n\n1 Action\n\nRange: 10. Damage: 1d10. On crit: Smoldering.\n\n"
|
||||||
assert spells[1].description == "2 Actions\n\nRange: 10. Damage: 4d10 to a Smoldering target.\n\nUpcast: +10 damage."
|
"High Levels: +5 damage every 5th level.")
|
||||||
assert spells[2].description == "1 Action\n\nConcentration: 1 min. Reach: 8."
|
assert spells[1].description == (
|
||||||
assert all(spell.description in _BOOK for spell in spells)
|
"TIER 1\n\n2 Actions\n\nRange: 10. Damage: 4d10 to a Smoldering target.\n\nUpcast: +10 damage.")
|
||||||
# Le passage cité est le début de la description : le Core le retrouve dans le texte.
|
assert spells[2].description == "TIER 2\n\n1 Action\n\nConcentration: 1 min. Reach: 8."
|
||||||
assert [s.excerpt for s in spells] == ["1 Action", "2 Actions", "1 Action"]
|
assert all(part in _BOOK for spell in spells for part in spell.description.split("\n\n"))
|
||||||
|
# Le passage cité est le début de ce qui suit le nom, assez long pour faire foi : le Core
|
||||||
|
# le retrouve dans le texte, aux espaces près.
|
||||||
|
assert [s.excerpt for s in spells] == [
|
||||||
|
"1 Action Range: 10. Damage: 1d10. On crit: Smoldering.",
|
||||||
|
"2 Actions Range: 10. Damage: 4d10 to a Smoldering target.",
|
||||||
|
"1 Action Concentration: 1 min. Reach: 8."]
|
||||||
assert (spells[1].level, spells[1].school, spells[2].school) == ("1", "Fire", "")
|
assert (spells[1].level, spells[1].school, spells[2].school) == ("1", "Fire", "")
|
||||||
|
|
||||||
|
|
||||||
@@ -115,9 +122,10 @@ def test_spells_are_put_back_in_the_order_of_the_book_whatever_the_order_of_the_
|
|||||||
def test_without_its_first_words_a_spell_is_found_by_its_name():
|
def test_without_its_first_words_a_spell_is_found_by_its_name():
|
||||||
spells = locate_spells([{"name": "Flame Dart"}, {"name": "ignite", "start": "des mots absents du texte"}], _BOOK)
|
spells = locate_spells([{"name": "Flame Dart"}, {"name": "ignite", "start": "des mots absents du texte"}], _BOOK)
|
||||||
assert [s.name for s in spells] == ["Flame Dart", "ignite"]
|
assert [s.name for s in spells] == ["Flame Dart", "ignite"]
|
||||||
# Sans la ligne du niveau comme repère, elle reste en fin de la description précédente.
|
# Même sans repère donné par le modèle, la ligne de niveau placée au-dessus du nom ouvre
|
||||||
assert spells[0].description.endswith("every 5th level.\n\nTIER 1")
|
# le sort : elle ne reste pas en fin de la description précédente.
|
||||||
assert spells[1].description.startswith("2 Actions")
|
assert spells[0].description.endswith("every 5th level.")
|
||||||
|
assert spells[1].description.startswith("TIER 1\n\n2 Actions")
|
||||||
|
|
||||||
|
|
||||||
def test_a_spell_whose_name_is_not_in_the_text_is_left_out():
|
def test_a_spell_whose_name_is_not_in_the_text_is_left_out():
|
||||||
@@ -144,7 +152,8 @@ def test_malformed_entries_values_and_duplicates():
|
|||||||
"pas un objet",
|
"pas un objet",
|
||||||
], _BOOK)
|
], _BOOK)
|
||||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite"]
|
assert [s.name for s in spells] == ["Flame Dart", "Ignite"]
|
||||||
assert spells[0].level == "0"
|
# Le niveau écrit dans le livre (« CANTRIP ») prime sur celui du modèle (0).
|
||||||
|
assert spells[0].level == "Cantrip"
|
||||||
assert spells[0].values == {"Portée": "10", "Coût": "2"}
|
assert spells[0].values == {"Portée": "10", "Coût": "2"}
|
||||||
assert spells[1].values == {}
|
assert spells[1].values == {}
|
||||||
assert locate_spells(None, _BOOK) == []
|
assert locate_spells(None, _BOOK) == []
|
||||||
@@ -165,6 +174,132 @@ def test_a_spell_without_school_takes_the_one_named_by_the_section_title():
|
|||||||
assert [s.school for s in spells] == ["Fire", "Pyromancie"]
|
assert [s.school for s in spells] == ["Fire", "Pyromancie"]
|
||||||
|
|
||||||
|
|
||||||
|
_NIMBLE = (
|
||||||
|
"Upcast: +10 damage.\n\nCANTRIP\n\n### Withering Touch 1 Action\n\n"
|
||||||
|
"Reach: 1. Damage: 1d12. On damage, target is considered undead for 1 round.\n\n"
|
||||||
|
"High Levels: +6 damage every 5th level.\n\nTIER 1\n\n### Shadow Trap 1 Action\n\n"
|
||||||
|
"Reaction: When an enemy moves next to an ally within Reach 8.\n\nDamage: 2d12.\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_short_first_line_is_extended_so_that_the_excerpt_proves_something():
|
||||||
|
"""« 1 Action » seul ne passe pas la vérification du Core (25 caractères au moins)."""
|
||||||
|
spells = locate_spells([{"name": "Withering Touch"}, {"name": "Shadow Trap"}], _NIMBLE)
|
||||||
|
assert spells[0].excerpt == "1 Action Reach: 1. Damage: 1d12. On damage, target is considered undead for 1 round."
|
||||||
|
assert spells[1].excerpt == "1 Action Reaction: When an enemy moves next to an ally within Reach 8."
|
||||||
|
# Le passage se retrouve dans le texte, aux espaces près — ce que compare le Core.
|
||||||
|
flat = " ".join(_NIMBLE.replace("#", " ").split())
|
||||||
|
assert all(spell.excerpt in flat and len(spell.excerpt) >= 25 for spell in spells)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_level_line_above_the_name_opens_the_spell_instead_of_closing_the_previous_one():
|
||||||
|
by_name = locate_spells([{"name": "Withering Touch"}, {"name": "Shadow Trap"}], _NIMBLE)
|
||||||
|
by_start = locate_spells([{"name": "Withering Touch", "start": "CANTRIP"},
|
||||||
|
{"name": "Shadow Trap", "start": "TIER 1"}], _NIMBLE)
|
||||||
|
for spells in (by_name, by_start):
|
||||||
|
assert spells[0].description == (
|
||||||
|
"CANTRIP\n\n1 Action\n\nReach: 1. Damage: 1d12. On damage, target is considered undead for 1 round.\n\n"
|
||||||
|
"High Levels: +6 damage every 5th level.")
|
||||||
|
assert spells[1].description.startswith("TIER 1\n\n1 Action\n\nReaction: When an enemy")
|
||||||
|
# Une ligne ordinaire au-dessus du nom reste au sort précédent.
|
||||||
|
plain = "### Brume\n\nLa brume se lève sur la lande.\n\nDurée : 1 min\n\n### Givre\n\nLe sol gèle sous vos pas, d'un coup."
|
||||||
|
brume, givre = locate_spells([{"name": "Brume"}, {"name": "Givre"}], plain)
|
||||||
|
assert brume.description.endswith("Durée : 1 min") and givre.description.startswith("Le sol gèle")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_level_is_read_on_the_level_line_of_the_book_before_the_answer_of_the_model():
|
||||||
|
text = ("TIER 2, AOE\n\n### Enchant Weapon 1 Action\n\nConcentration: 1 min. Reach: 8. A weapon you choose glows.\n\n"
|
||||||
|
"TOUR DE MAGIE\n\n### Souffle de vie 1 Action\n\nPortée : 6. Restaure 1d4 PV à une créature mourante.\n\n"
|
||||||
|
"CANTRIP\n\n### Zap 1 Action\n\nRange: 8. Damage: 2d8 lightning to one target you can see.\n")
|
||||||
|
spells = locate_spells([{"name": "Enchant Weapon"}, {"name": "Souffle de vie", "level": "1"},
|
||||||
|
{"name": "Zap", "level": ""}], text)
|
||||||
|
assert [spell.level for spell in spells] == ["2", "Tour de magie", "Cantrip"]
|
||||||
|
# Sans ligne de niveau au-dessus du nom, le niveau est celui que donne le modèle.
|
||||||
|
plain = "### Brume\n\nLa brume se lève sur la lande et cache tout ce qui s'y trouve."
|
||||||
|
assert locate_spells([{"name": "Brume", "level": "3"}], plain)[0].level == "3"
|
||||||
|
utility = "TOUR DE MAGIE UTILITÉ DE FOUDRE\n\n### Zap\n\nPortée : 8. Une étincelle frappe la cible."
|
||||||
|
assert locate_spells([{"name": "Zap"}], utility)[0].level == "Tour de magie"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_school_is_read_in_a_translated_title_too():
|
||||||
|
from app.application.spell_location import school_from_title
|
||||||
|
assert school_from_title("Magie > Sorts de feu") == "Feu"
|
||||||
|
assert school_from_title("Magie › Sorts radiants") == "Radiants"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_magic_item_is_not_a_spell():
|
||||||
|
text = ("### Flacon de Coup de Glaçage\n\nFlacon très rare, Niveau 8 (1 charge) Recharge : laisser le flacon "
|
||||||
|
"au fond d'un lac.\n\n### Wand of Sparks\n\nUncommon wand, Tier 1 (3 charges). Cast Spark.\n\n"
|
||||||
|
"### Étincelle\n\nUne étincelle jaillit de vos doigts et frappe une cible à portée, rarement deux.\n")
|
||||||
|
spells = locate_spells([{"name": "Flacon de Coup de Glaçage"}, {"name": "Wand of Sparks"},
|
||||||
|
{"name": "Étincelle"}], text)
|
||||||
|
assert [spell.name for spell in spells] == ["Étincelle"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_level_is_not_the_name_of_a_spell():
|
||||||
|
"""Tableau des prix de parchemins : « Tour de magie | 10 po », « Sort de Niveau 1 | 35 po »."""
|
||||||
|
table = ("| Tour de magie | 10 po | Sort de Niveau 5 | 3 000 po |\n| Sort de Niveau 1 | 35 po | Tier 6 | 10 000 po |\n\n"
|
||||||
|
"### Étincelle\n\nUne étincelle jaillit de vos doigts et frappe une cible à portée.\n")
|
||||||
|
spells = locate_spells([{"name": "Tour de magie"}, {"name": "Sort de Niveau 1"}, {"name": "Tier 6"},
|
||||||
|
{"name": "Cantrip"}, {"name": "Level 3 spell"}, {"name": "Étincelle"}], table)
|
||||||
|
assert [spell.name for spell in spells] == ["Étincelle"]
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptedLLM:
|
||||||
|
def __init__(self, *responses: str) -> None:
|
||||||
|
self.responses = list(responses)
|
||||||
|
self.prompts: list[str] = []
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompts.append(prompt)
|
||||||
|
return self.responses[min(len(self.prompts), len(self.responses)) - 1]
|
||||||
|
|
||||||
|
|
||||||
|
_SIX = "".join(f"### Sort {n}\n\nLe sort numéro {n} frappe une cible à portée et lui inflige des dégâts.\n\n"
|
||||||
|
for n in range(1, 7))
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_asks_again_when_most_headings_have_no_spell(client):
|
||||||
|
llm = ScriptedLLM(
|
||||||
|
json.dumps({"spells": [{"name": "Sort 1"}, {"name": "Sort 2"}]}),
|
||||||
|
# Relance : les sorts manquants, et un « sort » qui n'est pas un intertitre (écarté).
|
||||||
|
json.dumps({"spells": [{"name": "Sort 3"}, {"name": "Sort 4"}, {"name": "Sort 5"}, {"name": "Sort 6"},
|
||||||
|
{"name": "dégâts"}]}))
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
|
response = client.post("/generate/spell-extraction", json={"system_name": "Jeu", "text": _SIX})
|
||||||
|
|
||||||
|
assert [spell["name"] for spell in response.json()["spells"]] == [f"Sort {n}" for n in range(1, 7)]
|
||||||
|
assert len(llm.prompts) == 2
|
||||||
|
assert "- Sort 1" in llm.prompts[1] and "- Sort 2" in llm.prompts[1]
|
||||||
|
# Les sorts déjà relevés ne sont pas découpés par la relance.
|
||||||
|
assert response.json()["spells"][0]["description"] == "Le sort numéro 1 frappe une cible à portée et lui inflige des dégâts."
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_does_not_ask_again_when_the_answer_is_complete_or_empty(client):
|
||||||
|
complete = ScriptedLLM(json.dumps({"spells": [{"name": f"Sort {n}"} for n in range(1, 7)]}))
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: complete
|
||||||
|
assert len(client.post("/generate/spell-extraction", json={"text": _SIX}).json()["spells"]) == 6
|
||||||
|
assert len(complete.prompts) == 1
|
||||||
|
|
||||||
|
none = ScriptedLLM(json.dumps({"spells": []}))
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: none
|
||||||
|
assert client.post("/generate/spell-extraction", json={"text": _SIX}).json() == {"spells": []}
|
||||||
|
assert len(none.prompts) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_stops_asking_when_a_pass_finds_nothing_new(client):
|
||||||
|
llm = ScriptedLLM(json.dumps({"spells": [{"name": "Sort 1"}]}), json.dumps({"spells": []}))
|
||||||
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
assert len(client.post("/generate/spell-extraction", json={"text": _SIX}).json()["spells"]) == 1
|
||||||
|
assert len(llm.prompts) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_says_that_an_item_is_not_a_spell():
|
||||||
|
prompt = spell_extraction_prompt("Nimble", "Équipement", "Texte.", [], [])
|
||||||
|
assert "Un OBJET n'est pas un sort" in prompt and "parchemin" in prompt and "baguette" in prompt
|
||||||
|
|
||||||
|
|
||||||
def test_a_long_first_line_gives_a_short_excerpt():
|
def test_a_long_first_line_gives_a_short_excerpt():
|
||||||
text = "### Mur de feu\n\n" + "Un mur de flammes se dresse devant vous " * 12
|
text = "### Mur de feu\n\n" + "Un mur de flammes se dresse devant vous " * 12
|
||||||
spell = locate_spells([{"name": "Mur de feu"}], text)[0]
|
spell = locate_spells([{"name": "Mur de feu"}], text)[0]
|
||||||
@@ -189,7 +324,8 @@ def test_route_returns_the_text_of_the_rules_not_the_words_of_the_model(client):
|
|||||||
assert response.json() == {"spells": [{
|
assert response.json() == {"spells": [{
|
||||||
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||||
"description": "Niveau 1 — Évocation. Portée : 18 m.\nUn trait de givre frappe une cible : 2d6 dégâts de froid.",
|
"description": "Niveau 1 — Évocation. Portée : 18 m.\nUn trait de givre frappe une cible : 2d6 dégâts de froid.",
|
||||||
"values": {"Portée": "18 m"}, "excerpt": "Niveau 1 — Évocation. Portée : 18 m."}]}
|
"values": {"Portée": "18 m"},
|
||||||
|
"excerpt": "Niveau 1 — Évocation. Portée : 18 m. Un trait de givre frappe une cible : 2d6 dégâts de froid."}]}
|
||||||
assert llm.temperature == 0.1
|
assert llm.temperature == 0.1
|
||||||
assert llm.output_format["required"] == ["spells"]
|
assert llm.output_format["required"] == ["spells"]
|
||||||
assert "description" not in llm.output_format["properties"]["spells"]["items"]["properties"]
|
assert "description" not in llm.output_format["properties"]["spells"]["items"]["properties"]
|
||||||
|
|||||||
+18
@@ -94,6 +94,24 @@ class SpellProposalServiceTest {
|
|||||||
assertThat(proposal.dropped()).isEqualTo(5);
|
assertThat(proposal.dropped()).isEqualTo(5);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validate_accepteUnPassageQuiCourtSurPlusieursLignesDuTexte() {
|
||||||
|
// Un sort dont le titre porte aussi son coût (« Shadow Trap 1 Action ») : sa description
|
||||||
|
// s'ouvre sur « 1 Action », trop court pour faire foi. Le Brain cite donc le début de la
|
||||||
|
// description sur plusieurs lignes, réunies par une espace.
|
||||||
|
String rules = "TIER 1\n\n### Shadow Trap 1 Action\n\n"
|
||||||
|
+ "Reaction: When an enemy moves next to an ally within Reach 8.\n\nDamage: 2d12.";
|
||||||
|
List<SpellCandidate> candidates = List.of(
|
||||||
|
new SpellCandidate("Shadow Trap", "1", "", "TIER 1\n\n1 Action\n\nReaction: When an enemy moves.",
|
||||||
|
Map.of(), "1 Action Reaction: When an enemy moves next to an ally within Reach 8."),
|
||||||
|
new SpellCandidate("Shadow Trap bis", "1", "", "1 Action", Map.of(), "1 Action"));
|
||||||
|
|
||||||
|
Proposal proposal = SpellProposalService.validate(candidates, rules, List.of(), List.of());
|
||||||
|
|
||||||
|
assertThat(proposal.spells()).extracting(ProposedSpell::name).containsExactly("Shadow Trap");
|
||||||
|
assertThat(proposal.dropped()).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void validate_neReproposePasUnSortConnuOuRepete_sansLeCompterCommeEcarte() {
|
void validate_neReproposePasUnSortConnuOuRepete_sansLeCompterCommeEcarte() {
|
||||||
Proposal proposal = SpellProposalService.validate(
|
Proposal proposal = SpellProposalService.validate(
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ describe('spell-proposal.util', () => {
|
|||||||
expect(looksLikeMagic('SPELLS')).toBe(true);
|
expect(looksLikeMagic('SPELLS')).toBe(true);
|
||||||
expect(looksLikeMagic('Prières et miracles')).toBe(true);
|
expect(looksLikeMagic('Prières et miracles')).toBe(true);
|
||||||
expect(looksLikeMagic('Combat')).toBe(false);
|
expect(looksLikeMagic('Combat')).toBe(false);
|
||||||
|
// Un parchemin ou une baguette permet de lancer un sort, mais n'en est pas un.
|
||||||
|
expect(looksLikeMagic('Équipement › Parchemins de sorts et Baguettes')).toBe(false);
|
||||||
|
expect(looksLikeMagic('Equipment › Spell Scrolls & Wands')).toBe(false);
|
||||||
|
expect(looksLikeMagic('Equipment › Magical Items')).toBe(false);
|
||||||
|
expect(looksLikeMagic('Magie › Sorts radiants')).toBe(true);
|
||||||
expect(suggestedSections([{ title: 'Combat', content: 'x' }, { title: 'Cast Spell', content: 'x' },
|
expect(suggestedSections([{ title: 'Combat', content: 'x' }, { title: 'Cast Spell', content: 'x' },
|
||||||
{ title: 'Mage', content: 'x' }])).toEqual(['Cast Spell', 'Mage']);
|
{ title: 'Mage', content: 'x' }])).toEqual(['Cast Spell', 'Mage']);
|
||||||
expect(suggestedSections([{ title: 'Combat', content: 'x' }])).toEqual([]);
|
expect(suggestedSections([{ title: 'Combat', content: 'x' }])).toEqual([]);
|
||||||
|
|||||||
@@ -29,12 +29,19 @@ export const MAX_CHUNK_CHARS = 8_000;
|
|||||||
const MAGIC_WORDS = ['magie', 'magic', 'sort', 'spell', 'incantation', 'grimoire', 'pouvoir', 'power', 'prière',
|
const MAGIC_WORDS = ['magie', 'magic', 'sort', 'spell', 'incantation', 'grimoire', 'pouvoir', 'power', 'prière',
|
||||||
'priere', 'prayer', 'rituel', 'ritual', 'arcane', 'miracle', 'enchantement', 'mage', 'wizard', 'sorcier', 'cantrip'];
|
'priere', 'prayer', 'rituel', 'ritual', 'arcane', 'miracle', 'enchantement', 'mage', 'wizard', 'sorcier', 'cantrip'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mots qui signalent une section d'équipement : un parchemin ou une baguette permet de lancer un
|
||||||
|
* sort, mais n'en est pas un. Ces sections ne sont pas cochées d'office (on peut les cocher).
|
||||||
|
*/
|
||||||
|
const ITEM_WORDS = ['équipement', 'equipement', 'equipment', 'objet', 'item', 'parchemin', 'scroll', 'baguette',
|
||||||
|
'wand', 'potion', 'trésor', 'tresor', 'treasure', 'butin', 'loot'];
|
||||||
|
|
||||||
const key = (name: string | null | undefined): string => (name ?? '').trim().toLowerCase();
|
const key = (name: string | null | undefined): string => (name ?? '').trim().toLowerCase();
|
||||||
|
|
||||||
/** Le titre de cette section laisse-t-il penser qu'elle décrit des sorts ? */
|
/** Le titre de cette section laisse-t-il penser qu'elle décrit des sorts ? */
|
||||||
export function looksLikeMagic(title: string): boolean {
|
export function looksLikeMagic(title: string): boolean {
|
||||||
const lower = key(title);
|
const lower = key(title);
|
||||||
return MAGIC_WORDS.some(word => lower.includes(word));
|
return MAGIC_WORDS.some(word => lower.includes(word)) && !ITEM_WORDS.some(word => lower.includes(word));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Sections cochées d'office : celles qui parlent de magie ; à défaut, aucune. */
|
/** Sections cochées d'office : celles qui parlent de magie ; à défaut, aucune. */
|
||||||
|
|||||||
Reference in New Issue
Block a user