Linking to specific page or section of an EPUB/PDF when user searches.

This commit is contained in:
Roland 2026-04-13 15:15:29 -06:00 • committed by lrnselfreliance
parent 673d851501
commit 8a75cf9057
13 changed files with 598 additions and 16 deletions

View file

@ -6,7 +6,7 @@ import pytest
from PIL import Image
from modules.docs import doc_modeler
from modules.docs.models import Doc
from modules.docs.models import Doc, DocSection
from wrolpi.dates import now
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
@ -52,6 +52,53 @@ async def test_doc_modeler_pdf(async_client, test_session, test_directory, examp
assert doc.size # Has a size.
@pytest.mark.asyncio
async def test_doc_modeler_persists_epub_sections(async_client, test_session, test_directory,
example_epub, refresh_files):
"""After modeling, per-spine-item DocSection rows exist for an EPUB."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
sections = test_session.query(DocSection).filter_by(doc_id=doc.id) \
.order_by(DocSection.ordinal).all()
assert sections, 'EPUB modeler should produce DocSection rows'
assert all(s.kind == 'epub_spine' for s in sections)
assert [s.ordinal for s in sections] == list(range(len(sections)))
@pytest.mark.asyncio
async def test_doc_modeler_persists_pdf_sections(async_client, test_session, test_directory,
example_pdf, refresh_files):
"""After modeling, per-page DocSection rows exist for a PDF."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
sections = test_session.query(DocSection).filter_by(doc_id=doc.id) \
.order_by(DocSection.ordinal).all()
assert sections, 'PDF modeler should produce DocSection rows'
assert all(s.kind == 'pdf_page' for s in sections)
# 1-based ordinals, test PDF has 3 pages.
assert [s.ordinal for s in sections] == [1, 2, 3]
@pytest.mark.asyncio
async def test_doc_modeler_replaces_sections(async_client, test_session, test_directory,
example_epub, refresh_files):
"""Re-modeling a Doc replaces its DocSection rows (no duplicates)."""
from modules.docs import _model_doc
await refresh_files()
doc: Doc = test_session.query(Doc).one()
initial_count = test_session.query(DocSection).filter_by(doc_id=doc.id).count()
assert initial_count > 0
# Re-run modeling on the same file_group and confirm we don't accumulate rows.
_model_doc(doc.file_group, test_session)
test_session.commit()
final_count = test_session.query(DocSection).filter_by(doc_id=doc.id).count()
assert final_count == initial_count
@pytest.mark.asyncio
async def test_doc_do_model_sets_model(test_session, example_pdf):
"""Doc.do_model sets file_group.model so the FileGroup is recognized as a doc."""

View file

@ -15,6 +15,77 @@ async def test_extract_epub(test_session, test_directory, example_epub):
assert metadata.cover_bytes # Has a cover image.
@pytest.mark.asyncio
async def test_extract_epub_sections(test_session, test_directory, example_epub):
"""extract_epub produces one DocSection per spine item with ascending ordinals."""
metadata = extract_epub(example_epub)
assert metadata.sections, 'EPUB should produce at least one section'
assert all(s.kind == 'epub_spine' for s in metadata.sections)
# Ordinals should be 0..N-1 and strictly ascending.
ordinals = [s.ordinal for s in metadata.sections]
assert ordinals == list(range(len(metadata.sections)))
# Every section has a label.
assert all(s.label for s in metadata.sections)
def test_resolve_spine_labels_carries_forward_across_split_chapters():
"""When a chapter spans multiple spine items (common in Calibre conversions),
sections after the TOC-anchored one inherit the chapter label instead of
falling back to a generic 'Section N'.
This models real-world books like 'Mountain States Medicinal Plants' where each
plant's chapter is split across ~5 spine items but the TOC only anchors the first.
"""
from modules.docs.extractors import _resolve_spine_labels
href_to_label = {
'text/mullein_0.xhtml': 'Mullein',
'text/yarrow_0.xhtml': 'Yarrow',
}
# (file_name, get_name) tuples in spine order.
hrefs = [
('front.xhtml', 'front.xhtml'),
('text/mullein_0.xhtml', 'text/mullein_0.xhtml'),
('text/mullein_1.xhtml', 'text/mullein_1.xhtml'),
('text/mullein_2.xhtml', 'text/mullein_2.xhtml'),
('text/yarrow_0.xhtml', 'text/yarrow_0.xhtml'),
('text/yarrow_1.xhtml', 'text/yarrow_1.xhtml'),
]
labels = _resolve_spine_labels(hrefs, href_to_label)
# Front matter has no TOC anchor yet — falls back.
assert labels[0] == 'Section 1'
# mullein_0 is the TOC-anchored entry for 'Mullein'; the next two inherit it.
assert labels[1:4] == ['Mullein', 'Mullein', 'Mullein']
# yarrow_0 flips the carry-forward to the next chapter.
assert labels[4:6] == ['Yarrow', 'Yarrow']
def test_build_epub_toc_label_map_strips_fragments_and_walks_nested():
"""_build_epub_toc_label_map handles fragments and nested (Section, [children])
tuples, taking the first label that wins for a given href."""
from modules.docs.extractors import _build_epub_toc_label_map
class FakeLink:
def __init__(self, href, title):
self.href = href
self.title = title
toc = (
FakeLink('chap1.xhtml', 'Chapter One'),
# A nested (Section, [children]) tuple — children should be walked.
(FakeLink('chap2.xhtml', 'Part Two'), [
FakeLink('chap2.xhtml#sub-a', 'Sub A'),
FakeLink('chap3.xhtml', 'Chapter Three'),
]),
FakeLink('chap1.xhtml', 'Chapter One Duplicate'), # first wins
)
result = _build_epub_toc_label_map(toc)
assert result['chap1.xhtml'] == 'Chapter One'
assert result['chap2.xhtml'] == 'Part Two' # fragment stripped; first wins
assert result['chap3.xhtml'] == 'Chapter Three'
@pytest.mark.asyncio
async def test_extract_pdf(test_session, test_directory, example_pdf):
"""Metadata can be extracted from a PDF file."""
@ -36,6 +107,17 @@ async def test_extract_pdf_metadata(test_session, test_directory, example_pdf):
assert metadata.text
@pytest.mark.asyncio
async def test_extract_pdf_sections(test_session, test_directory, example_pdf):
"""extract_pdf produces one DocSection per page with 1-based ordinals."""
metadata = extract_pdf(example_pdf)
assert metadata.sections, 'PDF should produce at least one section'
assert all(s.kind == 'pdf_page' for s in metadata.sections)
# Pages are 1-indexed; the test PDF has 3 pages.
assert [s.ordinal for s in metadata.sections] == [1, 2, 3]
assert all(s.label == f'Page {s.ordinal}' for s in metadata.sections)
@pytest.mark.asyncio
async def test_extract_docx(test_session, test_directory, example_docx):
"""DOCX extractor extracts text content."""

View file

@ -2,7 +2,9 @@ import pytest
from modules.docs.lib import is_valid_author, split_authors, get_or_create_author_collection, \
get_or_create_subject_collection, normalize_author, normalize_subject, split_subjects, is_valid_subject, \
search_authors_by_name, search_subjects_by_name
search_authors_by_name, search_subjects_by_name, _search_docs
from modules.docs.models import Doc, DocSection
from wrolpi.files.models import FileGroup
def test_is_valid_author():
@ -248,3 +250,83 @@ async def test_search_subjects_by_name(test_session):
# No match.
results = await search_subjects_by_name(test_session, 'nothing')
assert len(results) == 0
def _make_doc_with_sections(test_session, test_directory, filename, mimetype, sections):
"""Build a FileGroup + Doc + DocSection rows for search tests.
`sections` is a list of (ordinal, label, content) tuples. The section contents
are also concatenated into the FileGroup's d_text so the top-level tsvector
search can match the doc in the first place.
"""
path = test_directory / filename
path.write_bytes(b'') # Placeholder; _search_docs doesn't read the file.
fg = FileGroup.from_paths(test_session, path)
fg.mimetype = mimetype
fg.model = 'doc'
fg.title = filename
fg.a_text = filename
fg.d_text = ' '.join(c for _, _, c in sections)
test_session.flush()
doc = Doc(file_group_id=fg.id, size=1)
test_session.add(doc)
test_session.flush()
kind = 'pdf_page' if mimetype == 'application/pdf' else 'epub_spine'
for ordinal, label, content in sections:
test_session.add(DocSection(doc_id=doc.id, kind=kind, ordinal=ordinal,
label=label, content=content))
test_session.commit()
return fg, doc
@pytest.mark.asyncio
async def test_search_docs_attaches_section_hint_epub(test_session, test_directory):
"""_search_docs returns a section_hint pointing at the matching spine item."""
fg, _ = _make_doc_with_sections(test_session, test_directory,
'alpha.epub', 'application/epub+zip', [
(0, 'Introduction', 'preface about gardening'),
(1, 'Chapter 1', 'a tale of mullen and his dog'),
(2, 'Chapter 2', 'unrelated content about pottery'),
])
results, total = _search_docs(search_str='mullen', mimetype='application/epub')
assert total == 1
assert results[0]['id'] == fg.id
hint = results[0]['section_hint']
assert hint['kind'] == 'epub_spine'
assert hint['ordinal'] == 1
assert hint['label'] == 'Chapter 1'
assert 'mullen' in hint['snippet'].lower()
# The snippet uses our sentinel markers rather than raw HTML.
assert '[[WROLPI_HL]]' in hint['snippet']
@pytest.mark.asyncio
async def test_search_docs_attaches_section_hint_pdf(test_session, test_directory):
"""_search_docs returns a section_hint pointing at the matching PDF page."""
fg, _ = _make_doc_with_sections(test_session, test_directory,
'beta.pdf', 'application/pdf', [
(1, 'Page 1', 'cover page text'),
(2, 'Page 2', 'nothing to see here'),
(3, 'Page 3', 'here is where mullen shows up'),
])
results, total = _search_docs(search_str='mullen', mimetype='application/pdf')
assert total == 1
assert results[0]['id'] == fg.id
hint = results[0]['section_hint']
assert hint['kind'] == 'pdf_page'
assert hint['ordinal'] == 3
assert hint['label'] == 'Page 3'
@pytest.mark.asyncio
async def test_search_docs_no_hint_when_no_query(test_session, test_directory):
"""Without a search query, results have no section_hint."""
fg, _ = _make_doc_with_sections(test_session, test_directory,
'gamma.pdf', 'application/pdf', [
(1, 'Page 1', 'whatever'),
])
results, _ = _search_docs(mimetype='application/pdf')
assert results and results[0]['id'] == fg.id
assert 'section_hint' not in results[0]