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

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:
2026-11-14 12:07:33 +01:00
parent 4998ac3849
commit cd54f05b78
11 changed files with 554 additions and 54 deletions
+98 -2
View File
@@ -2,7 +2,8 @@
from __future__ import annotations
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
@@ -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(300, 400, 320, 410, line(300, 400, 320, "+2")),
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)
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():
@@ -118,6 +141,8 @@ def test_lines_of_a_paragraph_are_never_pulled_into_a_neighbouring_row():
paragraph(40, 100, 560, 300),
block(40, 395, 120, 405, line(40, 395, 120, "Wooden Buckler")),
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,
]
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]
# --- 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():
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),
+12
View File
@@ -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 ---------------------------------------------------------------
_STAT_BLOCK = ("Tiny beast, unaligned\n\nArmor Class 12 Hit Points 22 (4d6 + 8) Speed 10 ft., fly 40 ft.\n\n"
+148 -12
View File
@@ -92,14 +92,21 @@ def test_the_description_of_a_spell_is_the_slice_of_the_book_that_follows_its_na
], _BOOK)
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 == (
"1 Action\n\nRange: 10. Damage: 1d10. On crit: Smoldering.\n\nHigh Levels: +5 damage every 5th level.")
assert spells[1].description == "2 Actions\n\nRange: 10. Damage: 4d10 to a Smoldering target.\n\nUpcast: +10 damage."
assert spells[2].description == "1 Action\n\nConcentration: 1 min. Reach: 8."
assert all(spell.description in _BOOK for spell in spells)
# Le passage cité est le début de la description : le Core le retrouve dans le texte.
assert [s.excerpt for s in spells] == ["1 Action", "2 Actions", "1 Action"]
"CANTRIP\n\n1 Action\n\nRange: 10. Damage: 1d10. On crit: Smoldering.\n\n"
"High Levels: +5 damage every 5th level.")
assert spells[1].description == (
"TIER 1\n\n2 Actions\n\nRange: 10. Damage: 4d10 to a Smoldering target.\n\nUpcast: +10 damage.")
assert spells[2].description == "TIER 2\n\n1 Action\n\nConcentration: 1 min. Reach: 8."
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", "")
@@ -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():
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"]
# Sans la ligne du niveau comme repère, elle reste en fin de la description précédente.
assert spells[0].description.endswith("every 5th level.\n\nTIER 1")
assert spells[1].description.startswith("2 Actions")
# Même sans repère donné par le modèle, la ligne de niveau placée au-dessus du nom ouvre
# le sort : elle ne reste pas en fin de la description précédente.
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():
@@ -144,7 +152,8 @@ def test_malformed_entries_values_and_duplicates():
"pas un objet",
], _BOOK)
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[1].values == {}
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"]
_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():
text = "### Mur de feu\n\n" + "Un mur de flammes se dresse devant vous " * 12
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": [{
"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.",
"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.output_format["required"] == ["spells"]
assert "description" not in llm.output_format["properties"]["spells"]["items"]["properties"]