"""Découpage d'un livre par la structure de son PDF (signets, titres), sans IA.""" from __future__ import annotations from app.application.pdf_structure import BOOKMARKS, HEADINGS, NONE, split_by_structure from app.domain.models import ExtractedDocument, ExtractedPage, TextLine, TocEntry BODY = 10.0 TITLE = 24.0 SUBTITLE = 16.0 class Book: """Fabrique un livre ligne par ligne : chaque appel à `para` ouvre un nouveau bloc.""" def __init__(self) -> None: self.lines: list[TextLine] = [] self.page = 0 self._block = 0 def next_page(self) -> "Book": self.page += 1 self._block = 0 return self def title(self, text: str, size: float = TITLE) -> "Book": return self.para(text, size=size) def para(self, *lines: str, size: float = BODY) -> "Book": for text in lines: self.lines.append(TextLine(self.page, self._block, text, size)) self._block += 1 return self def doc(self, toc: list[TocEntry] | None = None) -> ExtractedDocument: pages = [ExtractedPage(index=p, text="texte", used_ocr=False) for p in range(self.page + 1)] return ExtractedDocument(pages=pages, toc=toc or [], lines=self.lines) def _three_chapters() -> Book: return (Book() .title("Combat").para("Le combat se joue en tours.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) def _toc(*entries: tuple[int, str, int]) -> list[TocEntry]: return [TocEntry(level=level, title=title, page=page) for level, title, page in entries] # --- signets -------------------------------------------------------------------------------- def test_bookmarks_give_the_sections_of_the_book(): split = split_by_structure(_three_chapters().doc(_toc((1, "Combat", 1), (1, "Magie", 2), (1, "Repos", 3)))) assert split.method == BOOKMARKS assert split.sections == { "Combat": "Le combat se joue en tours.", "Magie": "La magie coûte du mana.", "Repos": "Une nuit de repos soigne tout.", } def test_a_small_chapter_stays_whole_with_its_subsections_as_subheadings(): book = (Book().title("Combat").para("Le combat se joue en tours.") .title("Attaquer", SUBTITLE).para("Lancez le dé de dégâts.") .title("Défendre", SUBTITLE).para("Réduisez les dégâts.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) toc = _toc((1, "Combat", 1), (2, "Attaquer", 1), (2, "Défendre", 1), (1, "Magie", 2), (1, "Repos", 3)) split = split_by_structure(book.doc(toc)) assert list(split.sections) == ["Combat", "Magie", "Repos"] assert split.sections["Combat"] == ( "Le combat se joue en tours.\n\n### Attaquer\n\nLancez le dé de dégâts.\n\n### Défendre\n\nRéduisez les dégâts.") def test_a_big_chapter_is_given_by_its_subsections(): book = (Book().title("Combat").para("Intro.") .title("Attaquer", SUBTITLE).para("Lancez le dé. " * 30) .title("Défendre", SUBTITLE).para("Réduisez les dégâts. " * 30) .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) toc = _toc((1, "Combat", 1), (2, "Attaquer", 1), (2, "Défendre", 1), (1, "Magie", 2), (1, "Repos", 3)) split = split_by_structure(book.doc(toc), max_section_chars=500) assert list(split.sections) == ["Combat › Attaquer", "Combat › Défendre", "Magie", "Repos"] # L'introduction du chapitre, trop courte pour faire une section, ouvre la première. assert split.sections["Combat › Attaquer"].startswith("Intro.\n\nLancez le dé.") def test_a_substantial_chapter_introduction_is_a_section_of_its_own(): book = (Book().title("Combat").para("Présentation du combat. " * 12) .title("Attaquer", SUBTITLE).para("Lancez le dé. " * 30) .title("Défendre", SUBTITLE).para("Réduisez les dégâts. " * 30) .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) toc = _toc((1, "Combat", 1), (2, "Attaquer", 1), (2, "Défendre", 1), (1, "Magie", 2), (1, "Repos", 3)) split = split_by_structure(book.doc(toc), max_section_chars=500) assert list(split.sections)[:3] == ["Combat", "Combat › Attaquer", "Combat › Défendre"] def test_a_bookmark_missing_from_its_page_starts_at_the_top_of_the_page(): # Titre dessiné dans une illustration : le signet existe, pas la ligne de texte. book = (Book().para("Le combat se joue en tours.") .next_page().para("La magie coûte du mana.") .next_page().para("Une nuit de repos soigne tout.")) split = split_by_structure(book.doc(_toc((1, "Combat", 1), (1, "Magie", 2), (1, "Repos", 3)))) assert split.sections == { "Combat": "Le combat se joue en tours.", "Magie": "La magie coûte du mana.", "Repos": "Une nuit de repos soigne tout.", } def test_titles_found_by_size_detail_what_bookmarks_do_not(): book = (Book().title("Magie").para("La magie coûte du mana.") .title("Sorts de feu", SUBTITLE).para("Dard de flamme. " * 20) .title("Sorts de glace", SUBTITLE).para("Lance de glace. " * 20) .next_page().title("Repos").para("Une nuit de repos soigne tout.") .next_page().title("Glossaire").para("Avantage : lancez un dé de plus.")) split = split_by_structure(book.doc(_toc((1, "Magie", 1), (1, "Repos", 2), (1, "Glossaire", 3))), max_section_chars=400) assert split.method == BOOKMARKS assert list(split.sections) == ["Magie › Sorts de feu", "Magie › Sorts de glace", "Repos", "Glossaire"] # --- titres repérés à leur taille --------------------------------------------------------------- def test_without_bookmarks_big_titles_give_the_sections(): split = split_by_structure(_three_chapters().doc()) assert split.method == HEADINGS assert list(split.sections) == ["Combat", "Magie", "Repos"] def test_a_title_on_two_lines_is_one_title(): book = (Book().para("GARDEN OF", "DEATH", size=TITLE).para("Un jardin mortel.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert list(split_by_structure(book.doc()).sections) == ["GARDEN OF DEATH", "Magie", "Repos"] def test_a_slightly_bigger_line_is_a_subheading_inside_its_section(): book = (Book().title("Combat").para("Le combat se joue en tours.") .para("Surprise", size=11.5).para("La surprise donne l'avantage.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert split_by_structure(book.doc()).sections["Combat"] == ( "Le combat se joue en tours.\n\n#### Surprise\n\nLa surprise donne l'avantage.") # --- mise en forme, sans réécriture ---------------------------------------------------------------- def test_lines_of_a_paragraph_are_joined_and_split_words_reunited(): book = (Book().title("Combat") .para("Le combat se joue en tours et chaque héros agit une fois avec son équi­", "pement. Un mot coupé par un tiret est réuni : atta-", "quer coûte une action.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert split_by_structure(book.doc()).sections["Combat"] == ( "Le combat se joue en tours et chaque héros agit une fois avec son équipement. " "Un mot coupé par un tiret est réuni : attaquer coûte une action.") def test_words_cut_by_a_typographic_hyphen_are_reunited_and_compound_names_keep_theirs(): book = (Book().title("Combat") .para("Cet événement n'intervient que si les joueurs piétinent com‑", "plètement. L'aubergiste Finnlor Trois‑", "Doigts les met sur la piste, pro‐", "gressivement.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert split_by_structure(book.doc()).sections["Combat"] == ( "Cet événement n'intervient que si les joueurs piétinent complètement. " "L'aubergiste Finnlor Trois‑Doigts les met sur la piste, progressivement.") def test_a_paragraph_cut_by_a_page_break_is_joined_again(): book = (Book().title("Combat").para("Le combat se joue en tours et chaque héros") .next_page().para("agit une fois.").title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert split_by_structure(book.doc()).sections["Combat"] == "Le combat se joue en tours et chaque héros agit une fois." def test_bullets_become_a_list(): book = (Book().title("Combat").para("Vous pouvez :", "• attaquer", "• vous déplacer") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert split_by_structure(book.doc()).sections["Combat"] == "Vous pouvez :\n\n- attaquer\n\n- vous déplacer" def test_page_numbers_running_headers_and_printed_contents_are_left_out(): book = Book() for page in range(8): if page: book.next_page() book.para("NIMBLE — RÈGLES").title(f"Chapitre {page + 1}").para(f"Texte du chapitre {page + 1}.").para(str(page + 1)) book.lines.insert(1, TextLine(0, 9, "Combat........................12", BODY)) sections = split_by_structure(book.doc()).sections assert len(sections) == 8 assert sections["Chapitre 3"] == "Texte du chapitre 3." assert all("NIMBLE" not in text and "....." not in text for text in sections.values()) def test_what_comes_before_the_first_title_is_the_preamble(): book = (Book().para("Crédits et remerciements. " * 10) .next_page().title("Combat").para("Le combat se joue en tours.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert list(split_by_structure(book.doc()).sections)[0] == "Préambule" assert list(split_by_structure(book.doc(), preamble_title="Front matter").sections)[0] == "Front matter" def test_a_section_without_subsections_that_is_too_long_is_cut_in_parts(): book = Book().title("Glossaire") for i in range(40): book.para(f"Terme {i} : " + "définition " * 12) book.next_page().title("Magie").para("La magie coûte du mana.") book.next_page().title("Repos").para("Une nuit de repos soigne tout.") sections = split_by_structure(book.doc(), max_section_chars=2000).sections parts = [title for title in sections if title.startswith("Glossaire")] assert parts[0] == "Glossaire (1/3)" and len(parts) == 3 # Rien n'est perdu ni répété d'une partie à l'autre. assert sum(sections[p].count("Terme ") for p in parts) == 40 def test_two_sections_with_the_same_title_do_not_overwrite_each_other(): book = (Book().title("Notes").para("Premières notes.") .next_page().title("Notes").para("Secondes notes.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) assert list(split_by_structure(book.doc()).sections) == ["Notes", "Notes (2)", "Repos"] def test_the_whole_text_of_the_book_is_kept(): book = (Book().title("Combat").para("Alpha bravo.") .title("Attaquer", SUBTITLE).para("Charlie delta.") .next_page().title("Magie").para("Echo foxtrot.") .next_page().title("Repos").para("Golf hotel.")) everything = " ".join(split_by_structure(book.doc()).sections.values()) for word in ("Alpha", "bravo", "Charlie", "delta", "Echo", "foxtrot", "Golf", "hotel", "Attaquer"): assert word in everything # --- pas de structure : à l'appelant de passer par l'IA -------------------------------------------- def test_a_scan_with_text_all_the_same_size_has_no_structure(): book = Book() for page in range(5): if page: book.next_page() book.para("COMBAT", "Le combat se joue en tours.", "MAGIE", "La magie coûte du mana.", size=11.0) assert split_by_structure(book.doc()).method == NONE assert split_by_structure(book.doc()).sections == {} def test_an_ocr_page_has_no_size_and_no_title(): book = Book() for page in range(4): if page: book.next_page() book.para("COMBAT", "Le combat se joue en tours.", size=0.0) assert split_by_structure(book.doc()).method == NONE def test_no_lines_no_structure(): doc = ExtractedDocument(pages=[ExtractedPage(index=0, text="texte", used_ocr=False)]) assert split_by_structure(doc).method == NONE def test_too_few_titles_for_a_long_book_is_not_a_structure(): book = Book().title("Couverture") for _ in range(200): book.next_page().para("Texte d'une page.") book.title("Fin") assert split_by_structure(book.doc()).method == NONE # --- défauts vus sur un corpus de 185 livres ---------------------------------------------------- def test_a_label_repeated_inside_the_text_is_part_of_the_book(): """Bestiaire : « Actions » revient sur chaque page, au milieu de la fiche de la créature.""" book = Book() for page in range(8): if page: book.next_page() (book.title(f"Créature {page + 1}").para("Une créature redoutable.").para("Classe d'armure 12") .para("Actions").para("12").para("Morsure : 1d6 dégâts.").para("Fin de la fiche.") .para("Encore une ligne.").para("Et une dernière.")) sections = split_by_structure(book.doc()).sections assert "Actions" in sections["Créature 3"] # Un nombre seul au milieu de la page (cellule de tableau) n'est pas un numéro de page. assert "\n\n12\n\n" in sections["Créature 3"] def test_a_single_bookmark_over_the_whole_book_does_not_prefix_every_title(): book = (Book().para("Couverture du livre. " * 12) .next_page().title("Combat").para("Le combat se joue en tours.") .next_page().title("Magie").para("La magie coûte du mana.") .next_page().title("Repos").para("Une nuit de repos soigne tout.")) toc = _toc((1, "Cover", 1), (2, "Combat", 2), (2, "Magie", 3), (2, "Repos", 4)) sections = split_by_structure(book.doc(toc)).sections assert list(sections) == ["Préambule", "Combat", "Magie", "Repos"] assert sections["Préambule"].startswith("Couverture du livre.") def test_invisible_characters_are_removed_from_titles(): book = _three_chapters() toc = _toc((1, "​Combat", 1), (1, "Magie", 2), (1, "Repos", 3)) assert list(split_by_structure(book.doc(toc)).sections) == ["Combat", "Magie", "Repos"] # --- tableaux et lignes à cellules --------------------------------------------------------------- def test_a_running_head_with_the_page_number_is_removed_even_if_it_never_repeats(): book = Book() heads = ["Introduction /3 /3", "4/Grimmsgate", "Grimmsgate/5", "6/The Wilderness", "/11", "- 12 -"] for page, head in enumerate(heads): if page: book.next_page() book.lines.append(TextLine(page, 0, head, BODY, True)) book._block = 1 book.title(f"Chapitre {page + 1}").para("Dégâts 2d6/tour, portée 9/18 m.").para("Suite du texte.") sections = split_by_structure(book.doc()).sections # L'en-tête part ; une ligne du texte qui contient une barre oblique reste. assert sections["Chapitre 1"] == "Dégâts 2d6/tour, portée 9/18 m.\n\nSuite du texte." assert all("Grimmsgate" not in text and "/3" not in text for text in sections.values()) assert sections["Chapitre 5"] == sections["Chapitre 6"] == sections["Chapitre 1"] def _row(book: Book, text: str, cells: int, size: float = BODY) -> None: book.lines.append(TextLine(book.page, 90 + len(book.lines), text, size, False, cells)) def test_rows_that_follow_each_other_make_a_table(): book = Book().title("Armes").para("Les armes de mêlée :") _row(book, "ITEM | DAMAGE | COST", 3) _row(book, "Dagger | 1d4+DEX piercing | 3 gp", 3) _row(book, "Sickle | 1d4+DEX slashing | 10 gp", 3) book.para("Fin du tableau.") book.next_page().title("Magie").para("La magie coûte du mana.") book.next_page().title("Repos").para("Une nuit de repos soigne tout.") assert split_by_structure(book.doc()).sections["Armes"] == ( "Les armes de mêlée :\n\n" "| ITEM | DAMAGE | COST |\n| --- | --- | --- |\n" "| Dagger | 1d4+DEX piercing | 3 gp |\n| Sickle | 1d4+DEX slashing | 10 gp |\n\n" "Fin du tableau.") def test_a_lone_row_and_rows_of_another_width_are_not_forced_into_one_table(): book = Book().title("Armes") _row(book, "SHIELDS | DEFENSE | COST", 3) _row(book, "Wooden Buckler | +2 | 5 gp", 3) _row(book, "Dragon Shield | +8", 2) book.next_page().title("Magie").para("La magie coûte du mana.") book.next_page().title("Repos").para("Une nuit de repos soigne tout.") assert split_by_structure(book.doc()).sections["Armes"] == ( "| SHIELDS | DEFENSE | COST |\n| --- | --- | --- |\n| Wooden Buckler | +2 | 5 gp |\n\n" "Dragon Shield — +8") def test_a_big_line_cut_by_a_wide_gap_is_still_a_title(): book = Book().title("Magie").para("La magie coûte du mana.") _row(book, "Flame Dart | 1 Action", 2, size=SUBTITLE) book.para("Portée : 10. Dégâts : 1d10.") book.next_page().title("Repos").para("Une nuit de repos soigne tout.") book.next_page().title("Glossaire").para("Avantage : un dé de plus.") assert "### Flame Dart 1 Action\n\nPortée : 10." in split_by_structure(book.doc()).sections["Magie"] def test_headers_flagged_by_the_extractor_are_removed_wherever_they_are_in_the_page(): """Après une remise en ordre des colonnes, un en-tête n'est plus forcément en tête de page.""" book = Book() for page in range(8): if page: book.next_page() book.title(f"Chapitre {page + 1}").para("Début du texte.") book.lines.append(TextLine(page, 50, "NIMBLE — RÈGLES", BODY, True)) book.para("Milieu du texte.").para("Fin du texte.").para("Dernière ligne.").para("Vraiment la dernière.") sections = split_by_structure(book.doc()).sections assert sections["Chapitre 3"] == ( "Début du texte.\n\nMilieu du texte.\n\nFin du texte.\n\nDernière ligne.\n\nVraiment la dernière.")