From da8ab37c0ba378d0e0ce515261c781e3b5bfb57c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 13:26:37 +0000 Subject: [PATCH] Make a document's text searchable, and read it as soon as it lands GAM already extracted a document's text into DocumentPage rows, but only when someone pressed "Extract text", and nothing searched those rows, so a phrase on page 74 could not be found and Video Creator had nothing to read. This closes the gap the plan recorded: - An upload queues extract_text for the formats it reads. Unconditional, like music analysis: it calls nothing and costs nothing. - Pages are indexed in a new FTS5 table, page_fts, written by extract_text and backfilled by its migration from pages already read. Their own table, since every reader of segment_fts takes a hit for a transcript segment and a second. - Pages are embedded (owner kind "page", cut to 6,000 chars so one long sheet cannot fail a batch), and a finished extraction chains the embed job. - Fusion carries a page_id beside segment_id, and a search hit names its page (page_id, page_number, page_label). The search view shows it where a timestamp goes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V1geD4DSV4uaESBMUTTuRu --- .../20261120_1200_add_page_search_index.py | 49 ++++ backend/app/enrichment/embed.py | 52 +++- backend/app/enrichment/extract_text.py | 17 +- backend/app/jobs/enrichment.py | 11 +- backend/app/models/embedding.py | 5 +- backend/app/routers/search.py | 10 + backend/app/search/fts.py | 95 +++++++- backend/app/search/hybrid.py | 18 +- backend/app/services/assets.py | 30 +++ backend/app/services/search.py | 58 ++++- backend/tests/test_document_search.py | 223 ++++++++++++++++++ backend/tests/test_extract_text.py | 43 +++- backend/tests/test_migrations.py | 34 ++- docs/plan-of-attack.md | 22 +- frontend/src/api/search.ts | 7 + frontend/src/views/SearchView.tsx | 8 +- 16 files changed, 636 insertions(+), 46 deletions(-) create mode 100644 backend/alembic/versions/20261120_1200_add_page_search_index.py create mode 100644 backend/tests/test_document_search.py diff --git a/backend/alembic/versions/20261120_1200_add_page_search_index.py b/backend/alembic/versions/20261120_1200_add_page_search_index.py new file mode 100644 index 0000000..94152ec --- /dev/null +++ b/backend/alembic/versions/20261120_1200_add_page_search_index.py @@ -0,0 +1,49 @@ +"""add the page search index + +A third FTS5 table, over what is written inside documents. `DocumentPage` rows have +existed since extract_text was built, and were in no index, so a phrase on page 74 of a +PDF could not be found by anything. + +Filled from the pages already extracted, in the same migration: an index that starts +empty would make every document read before this upgrade unsearchable until someone +thought to extract it again, and nothing would say so. + +The DDL is a literal copy of `app.search.fts.PAGE_FTS_DDL`, for the reason the first +search migration gives; test_migrations.py asserts the two agree. + +Revision ID: 9a3e5d7c1b24 +Revises: 5f2b8c1d9e73 +Create Date: 2026-11-20 12:00:00.000000+00:00 +""" +from typing import Sequence, Union + +from alembic import op + +revision: str = "9a3e5d7c1b24" +down_revision: Union[str, None] = "5f2b8c1d9e73" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.execute( + """ + CREATE VIRTUAL TABLE page_fts USING fts5( + page_id UNINDEXED, + asset_id UNINDEXED, + user_id UNINDEXED, + body, + tokenize='porter unicode61' + ) + """ + ) + op.execute( + """ + INSERT INTO page_fts (page_id, asset_id, user_id, body) + SELECT id, asset_id, user_id, text FROM documentpage WHERE trim(text) != '' + """ + ) + + +def downgrade() -> None: + op.execute("DROP TABLE IF EXISTS page_fts") diff --git a/backend/app/enrichment/embed.py b/backend/app/enrichment/embed.py index 17cd511..6b3f6eb 100644 --- a/backend/app/enrichment/embed.py +++ b/backend/app/enrichment/embed.py @@ -1,9 +1,10 @@ """The embed job: turn an asset's text into vectors so it can be found by meaning. -Two kinds of text, embedded separately because they answer different questions. Each -transcript segment becomes its own vector, which is what lets a hit carry a timestamp. -The asset's own name, description and summary become a single vector, so a photograph -with no speech in it is still findable by what it is of. +Three kinds of text, embedded separately because they answer different questions. Each +transcript segment becomes its own vector, which is what lets a hit carry a timestamp, +and each extracted document page its own, which is what lets a hit carry a page. The +asset's own name, description and summary become a single vector, so a photograph with +no speech in it is still findable by what it is of. """ from __future__ import annotations @@ -16,7 +17,8 @@ from app import music from app.embeddings import EmbeddingError, build_embedder from app.models.asset import Asset -from app.models.embedding import OWNER_ASSET, OWNER_SEGMENT +from app.models.document import DocumentPage +from app.models.embedding import OWNER_ASSET, OWNER_PAGE, OWNER_SEGMENT from app.models.transcript import TranscriptSegment from app.search import vectors @@ -24,6 +26,13 @@ Progress = Callable[..., None] +# How much of one page is embedded. A PDF page, a slide and a spreadsheet's sheet are one +# row each however long, and one input over a provider's cap (OpenAI's is 8,192 tokens) +# fails the whole batch, and so the job. Well under it even for text that tokenises +# densely. The vector then stands for the page's opening; the keyword index holds all of +# it, so an exact phrase further down is still found. +MAX_PAGE_EMBED_CHARS = 6000 + class EmbeddingUnavailable(Exception): """No embedder is configured for this user.""" @@ -54,6 +63,17 @@ def run(session: Session, asset: Asset, progress: Progress) -> int: progress("Embedding transcript", 40, f"{len(segments)} segments") written += _embed_segments(session, asset, segments, embedder) + pages = session.exec( + select(DocumentPage) + .where(DocumentPage.asset_id == asset.id) + .order_by(col(DocumentPage.idx)) + ).all() + pages = [p for p in pages if (p.text or "").strip()] + + if pages: + progress("Embedding document text", 60, f"{len(pages)} pages") + written += _embed_pages(session, asset, pages, embedder) + return written @@ -112,6 +132,28 @@ def _embed_segments(session: Session, asset: Asset, segments, embedder) -> int: ) +def _embed_pages(session: Session, asset: Asset, pages, embedder) -> int: + try: + computed = embedder.embed([p.text[:MAX_PAGE_EMBED_CHARS] for p in pages]) + except EmbeddingError: + raise + except Exception as exc: # noqa: BLE001 + raise EmbeddingError(f"Embedding failed: {type(exc).__name__}") from exc + + if len(computed) != len(pages): + # As for segments: a vector on the wrong page is worse than none. + raise EmbeddingError("The provider returned a different number of vectors than pages") + + return vectors.replace_for_asset( + session, + user_id=asset.user_id, + asset_id=asset.id, + owner_kind=OWNER_PAGE, + rows=list(zip((p.id for p in pages), computed)), + model=embedder.model, + ) + + def embeddable(asset: Asset) -> bool: """Whether there is anything worth embedding. diff --git a/backend/app/enrichment/extract_text.py b/backend/app/enrichment/extract_text.py index c02bfff..9f2fa0d 100644 --- a/backend/app/enrichment/extract_text.py +++ b/backend/app/enrichment/extract_text.py @@ -17,11 +17,12 @@ from pathlib import Path from typing import Callable, Iterator, Optional -from sqlmodel import Session, col, delete +from sqlmodel import Session, col, delete, select from app.ingest.filetypes import TYPE_DOCUMENT, extension_of from app.models.asset import Asset from app.models.document import DocumentPage +from app.search import fts from app.storage import build_storage logger = logging.getLogger(__name__) @@ -330,6 +331,20 @@ def _store(session: Session, asset: Asset, chunks: list[_Chunk]) -> int: ) session.commit() + + # Indexed here, the one writer of pages, so a document is findable by what it says + # the moment the job finishes. Never fails the job: text that was read and stored + # is still readable by everything that asks for it, and a re-run reindexes. + try: + rows = session.exec( + select(DocumentPage) + .where(DocumentPage.asset_id == asset.id) + .order_by(col(DocumentPage.idx)) + ).all() + fts.index_pages(session, asset.id, rows) + except Exception: # noqa: BLE001 - stored text beats indexed text + logger.warning("Could not index the pages of %s", asset.id, exc_info=True) + return len(chunks) diff --git a/backend/app/jobs/enrichment.py b/backend/app/jobs/enrichment.py index 981f2c3..7981267 100644 --- a/backend/app/jobs/enrichment.py +++ b/backend/app/jobs/enrichment.py @@ -404,12 +404,9 @@ def _run(job_id: str, q: JobQueue) -> None: error_message=None, ) - if job.kind == KIND_TRANSCRIBE: - # Not KIND_EXTRACT_TEXT: `embed` vectorises an asset's name, description - # and summary plus its transcript segments, and document pages are in - # none of those. Chaining it here would queue a job that does no new - # work and put a row in the activity feed saying so. It belongs here the - # day page bodies are embedded — see the search gap in plan-of-attack. + if job.kind in (KIND_TRANSCRIBE, KIND_EXTRACT_TEXT): + # A document's pages are embedded like a transcript's segments, so the + # text just read is findable by meaning as soon as it is by its words. _chain_embedding(session, asset) elif captioned is not None: _chain_embedding(session, captioned) @@ -497,7 +494,7 @@ def _run(job_id: str, q: JobQueue) -> None: def _chain_embedding(session: Session, asset: Asset) -> None: - """Embed an asset as soon as it has a transcript, without being asked. + """Embed an asset as soon as it has a transcript or a document's text, unasked. A transcript that is not embedded is invisible to half of search, and nothing else in the app would ever ask for the embed job — asking the user to press a second diff --git a/backend/app/models/embedding.py b/backend/app/models/embedding.py index c1c9217..36746f5 100644 --- a/backend/app/models/embedding.py +++ b/backend/app/models/embedding.py @@ -8,6 +8,9 @@ # a photo with no speech in it is still findable by meaning. OWNER_SEGMENT = "segment" OWNER_ASSET = "asset" +# A document's page, slide, sheet or part (`DocumentPage`): the written counterpart of a +# segment, so a hit on a document says where in it the meaning was found. +OWNER_PAGE = "page" class Embedding(SQLModel, table=True): @@ -30,7 +33,7 @@ class Embedding(SQLModel, table=True): id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True) user_id: str = Field(index=True) - owner_kind: str = Field(index=True) # segment | asset + owner_kind: str = Field(index=True) # segment | asset | page owner_id: str = Field(index=True) # Denormalised so a hit resolves to its asset without a join back through segments. asset_id: str = Field(index=True) diff --git a/backend/app/routers/search.py b/backend/app/routers/search.py index 3aa3343..a51407f 100644 --- a/backend/app/routers/search.py +++ b/backend/app/routers/search.py @@ -33,6 +33,13 @@ class SearchHit(BaseModel): # is, and for a moment whose transcript segment no longer exists. end_time: Optional[float] = None segment_id: Optional[str] = None + # Where in a document the words were found: the `DocumentPage` row, its real page + # number where the format has pages (a PDF's, a slide's, a sheet's position), and + # its label ("Page 3", "Slide 7", "Part 2"). Null for a hit that is not inside a + # document's text. `GET /api/assets/{id}/text` returns the same rows in full. + page_id: Optional[str] = None + page_number: Optional[int] = None + page_label: Optional[str] = None # Which retrievers found it — "keyword", "semantic", or both. sources: List[str] = Field(default_factory=list) other_matches: int = 0 @@ -85,6 +92,9 @@ def search( start_time=fused.start_time, end_time=fused.end_time, segment_id=fused.segment_id, + page_id=fused.page_id, + page_number=fused.page_number, + page_label=fused.page_label, sources=sorted(fused.sources), other_matches=fused.other_matches, ) diff --git a/backend/app/search/fts.py b/backend/app/search/fts.py index 7cc10fc..f500541 100644 --- a/backend/app/search/fts.py +++ b/backend/app/search/fts.py @@ -1,9 +1,10 @@ """Keyword search, on SQLite's FTS5. -Two indexes, because the two things being searched answer different questions. An -asset index matches what the *file* is called and how it was described; a segment index +Three indexes, because the things being searched answer different questions. An asset +index matches what the *file* is called and how it was described; a segment index matches what somebody *said* inside it, and carries the timestamp that makes the hit -useful. +useful; a page index matches what is *written* inside a document, and carries the page +that makes that hit useful the same way. The tables store their own copy of the text rather than using FTS5's external-content mode. External content saves that duplication, but it needs an integer rowid to point @@ -27,12 +28,14 @@ from sqlmodel import Session from app.models.asset import Asset +from app.models.document import DocumentPage from app.models.transcript import TranscriptSegment logger = logging.getLogger(__name__) ASSET_FTS = "asset_fts" SEGMENT_FTS = "segment_fts" +PAGE_FTS = "page_fts" # The virtual tables, as DDL. # @@ -77,6 +80,20 @@ ) """ +# A table of its own rather than pages in `segment_fts` with no start time. Everything +# that reads a segment hit treats its id as a `TranscriptSegment` and its start as the +# second it was said at, and a page riding in there would be cut to "0.0 s" of a PDF by +# the first caller that trusted that. Separate tables keep each hit's meaning in its type. +PAGE_FTS_DDL = """ +CREATE VIRTUAL TABLE page_fts USING fts5( + page_id UNINDEXED, + asset_id UNINDEXED, + user_id UNINDEXED, + body, + tokenize='porter unicode61' +) +""" + ASSET_FTS_COLUMNS = ( "asset_id", "user_id", @@ -88,10 +105,11 @@ "music_text", ) SEGMENT_FTS_COLUMNS = ("segment_id", "asset_id", "user_id", "body", "start_time") +PAGE_FTS_COLUMNS = ("page_id", "asset_id", "user_id", "body") # The virtual tables, plus the shadow tables SQLite creates behind each one # (_data, _idx, _content, _docsize, _config). -FTS_TABLE_PREFIXES = (ASSET_FTS, SEGMENT_FTS) +FTS_TABLE_PREFIXES = (ASSET_FTS, SEGMENT_FTS, PAGE_FTS) def is_fts_table(name: str) -> bool: @@ -122,6 +140,7 @@ def create_search_tables(connection) -> None: """ connection.execute(text(ASSET_FTS_DDL)) connection.execute(text(SEGMENT_FTS_DDL)) + connection.execute(text(PAGE_FTS_DDL)) @dataclass @@ -131,6 +150,7 @@ class FtsHit: snippet: str segment_id: Optional[str] = None start_time: Optional[float] = None + page_id: Optional[str] = None # ─── writing ───────────────────────────────────────────────────────────────── @@ -174,13 +194,11 @@ def index_asset( def remove_asset(session: Session, asset_id: str) -> None: - """Drop an asset and everything said inside it from the index.""" - session.execute( - text(f"DELETE FROM {ASSET_FTS} WHERE asset_id = :asset_id"), {"asset_id": asset_id} - ) - session.execute( - text(f"DELETE FROM {SEGMENT_FTS} WHERE asset_id = :asset_id"), {"asset_id": asset_id} - ) + """Drop an asset and everything said or written inside it from the index.""" + for table in (ASSET_FTS, SEGMENT_FTS, PAGE_FTS): + session.execute( + text(f"DELETE FROM {table} WHERE asset_id = :asset_id"), {"asset_id": asset_id} + ) session.commit() @@ -217,6 +235,35 @@ def index_segments(session: Session, asset_id: str, segments: Iterable[Transcrip return len(rows) +def index_pages(session: Session, asset_id: str, pages: Iterable[DocumentPage]) -> int: + """Replace this document's page index wholesale, as `index_segments` does a + transcript's: a re-extraction writes a new set of rows, never an edit of the old.""" + session.execute( + text(f"DELETE FROM {PAGE_FTS} WHERE asset_id = :asset_id"), {"asset_id": asset_id} + ) + + rows = [ + { + "page_id": page.id, + "asset_id": asset_id, + "user_id": page.user_id, + "body": page.text or "", + } + for page in pages + if (page.text or "").strip() + ] + if rows: + session.execute( + text( + f"INSERT INTO {PAGE_FTS} (page_id, asset_id, user_id, body)" + " VALUES (:page_id, :asset_id, :user_id, :body)" + ), + rows, + ) + session.commit() + return len(rows) + + # ─── querying ──────────────────────────────────────────────────────────────── # FTS5 treats a pile of characters as query syntax: unbalanced quotes, a bare `*`, or @@ -291,3 +338,29 @@ def search_segments(session: Session, user_id: str, query: str, limit: int = 50) ) for r in rows ] + + +def search_pages(session: Session, user_id: str, query: str, limit: int = 50) -> list[FtsHit]: + """Written-word hits inside documents, each carrying the page it is on. + + The page is to a document what the timestamp is to a recording: without it a hit on + a 200-page PDF says "somewhere in here", which is the question the search was asked. + """ + match = build_match_query(query) + if not match: + return [] + + rows = session.execute( + text( + f"SELECT page_id, asset_id, bm25({PAGE_FTS}) AS score," + f" snippet({PAGE_FTS}, 3, '«', '»', '…', 16) AS excerpt" + f" FROM {PAGE_FTS}" + f" WHERE {PAGE_FTS} MATCH :match AND user_id = :user_id" + " ORDER BY score LIMIT :limit" + ), + {"match": match, "user_id": user_id, "limit": limit}, + ).all() + + return [ + FtsHit(page_id=r[0], asset_id=r[1], score=r[2], snippet=r[3] or "") for r in rows + ] diff --git a/backend/app/search/hybrid.py b/backend/app/search/hybrid.py index f3e43ac..66490cd 100644 --- a/backend/app/search/hybrid.py +++ b/backend/app/search/hybrid.py @@ -33,19 +33,25 @@ @dataclass class Candidate: - """One retrievable thing: an asset, or a moment inside one.""" + """One retrievable thing: an asset, a moment inside one, or a page inside one.""" asset_id: str segment_id: Optional[str] = None start_time: Optional[float] = None snippet: str = "" + # A document page (`DocumentPage.id`). Never set alongside `segment_id`: a page has + # no time and a segment has no page, and one hit is one or the other. + page_id: Optional[str] = None # Which retrievers found it, for explaining a result rather than only ranking it. sources: set[str] = field(default_factory=set) score: float = 0.0 @property def key(self) -> tuple[str, Optional[str]]: - return (self.asset_id, self.segment_id) + # Both ids are uuids, so one slot tells them apart: the keyword and semantic + # retrievers finding the same page must merge into one candidate, as they do + # for a segment. + return (self.asset_id, self.segment_id or self.page_id) @dataclass @@ -66,6 +72,11 @@ class FusedAsset: # it to hand (the keyword index stores only the start), so it is looked up once for # the final page — see `services/search.py::_attach_end_times`. end_time: Optional[float] = None + # The matched page, for a hit inside a document; its number and label are looked up + # for the final page as end times are (`services/search.py::_attach_pages`). + page_id: Optional[str] = None + page_number: Optional[int] = None + page_label: Optional[str] = None def fuse(ranked_lists: dict[str, Sequence[Candidate]], *, k: int = RRF_K) -> list[Candidate]: @@ -85,6 +96,7 @@ def fuse(ranked_lists: dict[str, Sequence[Candidate]], *, k: int = RRF_K) -> lis segment_id=candidate.segment_id, start_time=candidate.start_time, snippet=candidate.snippet, + page_id=candidate.page_id, ) merged[candidate.key] = existing @@ -120,6 +132,7 @@ def collapse_to_assets(candidates: Sequence[Candidate]) -> list[FusedAsset]: start_time=candidate.start_time, segment_id=candidate.segment_id, sources=set(candidate.sources), + page_id=candidate.page_id, ) continue @@ -132,5 +145,6 @@ def collapse_to_assets(candidates: Sequence[Candidate]) -> list[FusedAsset]: existing.snippet = candidate.snippet existing.start_time = candidate.start_time existing.segment_id = candidate.segment_id + existing.page_id = candidate.page_id return sorted(best.values(), key=lambda a: (-a.score, a.asset_id)) diff --git a/backend/app/services/assets.py b/backend/app/services/assets.py index 0471765..960ec34 100644 --- a/backend/app/services/assets.py +++ b/backend/app/services/assets.py @@ -191,6 +191,7 @@ def _catalogue( _describe(session, storage, asset) _chain_transcription(session, asset) _chain_music_analysis(session, asset) + _chain_text_extraction(session, asset) return asset @@ -381,6 +382,35 @@ def _chain_music_analysis(session: Session, asset: Asset) -> None: logger.warning("Could not queue music analysis for asset %s", asset.id, exc_info=True) +def _chain_text_extraction(session: Session, asset: Asset) -> None: + """Read a document's text the moment it lands. + + Unconditional, like music analysis and unlike transcription: it calls no provider, + costs nothing and needs nothing configured. Without it a document's words were in + the library only after someone pressed "Extract text", so search could not find a + phrase in it and nothing outside GAM (Video Creator's assistant reading a document + it was asked to use) had any text to read. + + Only the formats `extract_text` reads. A legacy `.doc` or an `.odt` would queue a job + certain to fail, and a red row after every such upload trains people to ignore the + feed; its own refusal still says what to do when someone asks by hand. + + Imports lazily, for the cycle `_chain_transcription` describes. + """ + from app.enrichment.extract_text import extractable + from app.jobs import enrichment as enrichment_jobs + from app.models.job import KIND_EXTRACT_TEXT + + if not extractable(asset): + return + try: + if enrichment_jobs.active_job(session, asset.id, KIND_EXTRACT_TEXT) is not None: + return + enrichment_jobs.submit(session, asset, KIND_EXTRACT_TEXT) + except Exception: # noqa: BLE001 - an upload that succeeded must stay succeeded + logger.warning("Could not queue text extraction for asset %s", asset.id, exc_info=True) + + def _reindex(session: Session, asset: Asset) -> None: """Keep the keyword index in step with the row. diff --git a/backend/app/services/search.py b/backend/app/services/search.py index b8efef8..c05156a 100644 --- a/backend/app/services/search.py +++ b/backend/app/services/search.py @@ -10,7 +10,8 @@ from app.embeddings import EmbeddingError, build_embedder from app.models.asset import Asset -from app.models.embedding import OWNER_SEGMENT +from app.models.document import DocumentPage +from app.models.embedding import OWNER_PAGE, OWNER_SEGMENT from app.models.transcript import TranscriptSegment from app.search import fts, vectors from app.search.hybrid import Candidate, FusedAsset, collapse_to_assets, fuse @@ -22,6 +23,11 @@ # and it cannot promote what it was never handed. RETRIEVER_DEPTH = 50 +# How much of a page a semantic hit shows. The keyword retriever's snippet is FTS5's +# excerpt around the matched words; a vector match has no matched words, so it shows the +# page's opening, cut to about the length of that excerpt. +SEMANTIC_PAGE_SNIPPET_CHARS = 200 + SOURCE_KEYWORD = "keyword" SOURCE_SEMANTIC = "semantic" @@ -70,6 +76,7 @@ def search( page = fused[:limit] _attach_end_times(session, page) + _attach_pages(session, page) return SearchOutcome(assets=page, semantic_ran=semantic_ran, semantic_error=semantic_error) @@ -98,14 +105,36 @@ def _attach_end_times(session: Session, hits: list[FusedAsset]) -> None: hit.end_time = ends.get(hit.segment_id) +def _attach_pages(session: Session, hits: list[FusedAsset]) -> None: + """Give each document hit the page it is on, as the reader would name it. + + Looked up after `limit`, for the reason `_attach_end_times` gives. A page removed + since it was indexed (a re-extraction) leaves the hit with its snippet and no page, + rather than a number that now means a different page. + """ + page_ids = [h.page_id for h in hits if h.page_id] + if not page_ids: + return + rows = session.exec( + select(DocumentPage.id, DocumentPage.page_number, DocumentPage.label).where( + col(DocumentPage.id).in_(page_ids) + ) + ).all() + found = {row[0]: (row[1], row[2]) for row in rows} + for hit in hits: + if hit.page_id and hit.page_id in found: + hit.page_number, hit.page_label = found[hit.page_id] + + def _keyword_candidates(session: Session, user_id: str, query: str) -> list[Candidate]: - """Metadata hits and spoken hits, interleaved by their own rank. + """Metadata hits, spoken hits and written hits, each list in its own rank. - Two FTS queries rather than one because they are separate indexes; their results are - concatenated with segment hits first, since a hit that carries a timestamp is more - useful than one that only names a file. + Three FTS queries rather than one because they are separate indexes; their results + are concatenated with segment and page hits first, since a hit that says where in + the file it is is more useful than one that only names the file. """ segment_hits = fts.search_segments(session, user_id, query, limit=RETRIEVER_DEPTH) + page_hits = fts.search_pages(session, user_id, query, limit=RETRIEVER_DEPTH) asset_hits = fts.search_assets(session, user_id, query, limit=RETRIEVER_DEPTH) candidates = [ @@ -117,6 +146,10 @@ def _keyword_candidates(session: Session, user_id: str, query: str) -> list[Cand ) for hit in segment_hits ] + candidates.extend( + Candidate(asset_id=hit.asset_id, page_id=hit.page_id, snippet=hit.snippet) + for hit in page_hits + ) candidates.extend( Candidate(asset_id=hit.asset_id, snippet=hit.snippet) for hit in asset_hits ) @@ -150,6 +183,12 @@ def _semantic_candidates(session: Session, user_id: str, query: str) -> Optional ).all() segments = {row.id: row for row in rows} + page_ids = [h.owner_id for h in hits if h.owner_kind == OWNER_PAGE] + pages: dict[str, DocumentPage] = {} + if page_ids: + rows = session.exec(select(DocumentPage).where(col(DocumentPage.id).in_(page_ids))).all() + pages = {row.id: row for row in rows} + candidates: list[Candidate] = [] for hit in hits: if hit.owner_kind == OWNER_SEGMENT: @@ -165,6 +204,15 @@ def _semantic_candidates(session: Session, user_id: str, query: str) -> Optional snippet=segment.text, ) ) + elif hit.owner_kind == OWNER_PAGE: + found = pages.get(hit.owner_id) + if found is None: + # Re-extracted since it was embedded; the new pages' vectors replace it. + continue + text = " ".join((found.text or "").split()) + if len(text) > SEMANTIC_PAGE_SNIPPET_CHARS: + text = text[:SEMANTIC_PAGE_SNIPPET_CHARS].rsplit(" ", 1)[0] + "…" + candidates.append(Candidate(asset_id=hit.asset_id, page_id=found.id, snippet=text)) else: candidates.append(Candidate(asset_id=hit.asset_id)) diff --git a/backend/tests/test_document_search.py b/backend/tests/test_document_search.py new file mode 100644 index 0000000..43c76a9 --- /dev/null +++ b/backend/tests/test_document_search.py @@ -0,0 +1,223 @@ +"""A document is found by what is written in it, and the hit says on which page. + +Through the real pipeline: upload, extract, then search over HTTP. The pages are what +Video Creator's assistant (and anything else reading the library) is handed, so a hit +that names its page is what lets it go straight to the right part of the text. +""" + +import pytest +from sqlmodel import select + +from app.enrichment import embed, extract_text +from app.models.asset import Asset +from app.models.embedding import OWNER_PAGE, Embedding +from app.models.job import KIND_EMBED, EnrichmentJob +from app.search import vectors +from app.embeddings import PROVIDER_OLLAMA +from app.settings_store import EMBEDDING_PROVIDER, set_setting +from tests.test_search_api import StubEmbedder + +TEST_USER = "user-under-test" + +# Two paragraphs over the chunk size, so the file reads back as two parts and a hit on +# the second must say "Part 2". +FIRST = "Opening remarks about the harvest festival. " * 50 +SECOND = "The committee approved a new aerosol dispersion protocol for the lab. " * 45 +REPORT = (FIRST + "\n\n" + SECOND).encode() + + +def upload(client, body=REPORT, filename="committee_minutes.txt"): + return client.post( + "/api/assets", files=[("files", (filename, body, "text/plain"))] + ).json()["created"][0] + + +def extracted(client, session, **kwargs): + created = upload(client, **kwargs) + asset = session.get(Asset, created["id"]) + extract_text.run(session, asset, lambda *a, **k: None) + return asset + + +def search(client, q, **params): + response = client.get("/api/search", params={"q": q, **params}) + assert response.status_code == 200 + return response.json() + + +# ─── keyword ───────────────────────────────────────────────────────────────── + + +def test_a_phrase_inside_a_document_is_found(library, session): + asset = extracted(library, session) + + body = search(library, "dispersion protocol") + + assert [hit["asset"]["id"] for hit in body["data"]] == [asset.id] + + +def test_the_hit_says_which_part_of_the_document_it_is_in(library, session): + asset = extracted(library, session) + + hit = search(library, "dispersion protocol")["data"][0] + + assert hit["page_label"] == "Part 2" + # A text file has no pages a reader could turn to, so no number pretends otherwise. + assert hit["page_number"] is None + assert hit["page_id"] + assert "«dispersion»" in hit["snippet"] + # A page is not a moment: nothing for a video editor to cut to. + assert hit["start_time"] is None and hit["segment_id"] is None + pages = library.get(f"/api/assets/{asset.id}/text").json()["data"] + assert hit["page_id"] == pages[1]["id"] + + +def test_a_pdf_hit_carries_its_real_page_number(library, session): + from tests.test_extract_text import upload_document + + created = upload_document(library, ".pdf") + asset = session.get(Asset, created["id"]) + extract_text.run(session, asset, lambda *a, **k: None) + first_page = library.get(f"/api/assets/{asset.id}/text").json()["data"][0] + word = max(first_page["text"].split(), key=len).strip(".,:;()") + + hit = search(library, word)["data"][0] + + assert hit["asset"]["id"] == asset.id + assert hit["page_number"] == 1 + assert hit["page_label"] == "Page 1" + + +def test_documents_can_be_searched_by_type(library, session): + asset = extracted(library, session) + + assert [h["asset"]["id"] for h in search(library, "dispersion", asset_type="document")["data"]] == [asset.id] + assert search(library, "dispersion", asset_type="video")["data"] == [] + + +def test_a_re_extraction_replaces_what_is_found(library, session): + asset = extracted(library, session) + + # The file rewritten under the same row, then read again. + from app.storage import build_storage + + storage = build_storage() + with storage.materialise(asset.storage_key) as on_disk: + on_disk.write_bytes(b"Only a note about sourdough now.") + extract_text.run(session, asset, lambda *a, **k: None) + + assert search(library, "dispersion")["data"] == [] + assert [h["asset"]["id"] for h in search(library, "sourdough")["data"]] == [asset.id] + + +def test_deleting_the_document_takes_it_out_of_search(library, session): + asset = extracted(library, session) + + assert library.delete(f"/api/assets/{asset.id}").status_code in (200, 204) + + assert search(library, "dispersion")["data"] == [] + + +def test_someone_elses_document_is_not_found(library, session): + from app.models.document import DocumentPage + from app.search import fts + + asset = extracted(library, session) + asset.user_id = "somebody-else" + rows = session.exec(select(DocumentPage).where(DocumentPage.asset_id == asset.id)).all() + for row in rows: + row.user_id = "somebody-else" + session.commit() + fts.index_pages(session, asset.id, rows) + + assert search(library, "dispersion")["data"] == [] + + +# ─── meaning ───────────────────────────────────────────────────────────────── + + +@pytest.fixture(name="stub_embedder") +def stub_embedder_fixture(monkeypatch): + from app import embeddings + from app.services import search as search_service + + stub = StubEmbedder() + monkeypatch.setattr(embeddings, "build_embedder", lambda *_a, **_k: stub) + monkeypatch.setattr(search_service, "build_embedder", lambda *_a, **_k: stub) + monkeypatch.setattr(embed, "build_embedder", lambda *_a, **_k: stub) + vectors.invalidate() + return stub + + +def test_each_page_is_embedded(library, session, stub_embedder): + asset = extracted(library, session) + + embed.run(session, asset, lambda *a, **k: None) + + pages = session.exec( + select(Embedding).where(Embedding.asset_id == asset.id, Embedding.owner_kind == OWNER_PAGE) + ).all() + assert len(pages) == 2 + + +def test_a_long_page_is_cut_before_it_is_embedded(library, session, stub_embedder, monkeypatch): + """One input over a provider's cap fails the whole batch, so the job.""" + seen = [] + original = stub_embedder.embed + monkeypatch.setattr(stub_embedder, "embed", lambda texts: seen.extend(texts) or original(texts)) + from tests.test_extract_text import upload_document + + created = upload_document(library, ".pdf") + asset = session.get(Asset, created["id"]) + extract_text.run(session, asset, lambda *a, **k: None) + from app.models.document import DocumentPage + + page = session.exec(select(DocumentPage).where(DocumentPage.asset_id == asset.id)).first() + page.text = "word " * 5000 + session.commit() + + embed.run(session, asset, lambda *a, **k: None) + + assert max(len(text) for text in seen) <= embed.MAX_PAGE_EMBED_CHARS + + +def test_a_document_is_found_by_meaning_on_the_right_page(library, session, stub_embedder): + asset = extracted(library, session) + embed.run(session, asset, lambda *a, **k: None) + + # "weapons" and "armament" share no word with the text; the stub's geometry puts + # them on the same axis as "aerosol dispersion". + body = search(library, "armament") + + assert body["semantic"] is True + hit = body["data"][0] + assert hit["asset"]["id"] == asset.id + assert hit["page_label"] == "Part 2" + assert "semantic" in hit["sources"] + assert hit["snippet"] and len(hit["snippet"]) <= 201 + + +# ─── the chain ─────────────────────────────────────────────────────────────── + + +def test_a_finished_extraction_queues_its_own_embedding(library, session, monkeypatch): + """Pages nobody embeds are invisible to half of search.""" + from app.jobs import enrichment as enrichment_jobs + from tests.test_extract_text import queued_extraction + + created = upload(library) + set_setting(session, TEST_USER, EMBEDDING_PROVIDER, PROVIDER_OLLAMA) + job = queued_extraction(session, created["id"]) + + queue = enrichment_jobs.queue() + monkeypatch.setattr(queue, "engine", session.get_bind()) + enrichment_jobs._run_job(job.id) + + session.expire_all() + assert session.get(EnrichmentJob, job.id).status == "done" + embeds = session.exec( + select(EnrichmentJob).where( + EnrichmentJob.asset_id == created["id"], EnrichmentJob.kind == KIND_EMBED + ) + ).all() + assert len(embeds) == 1 diff --git a/backend/tests/test_extract_text.py b/backend/tests/test_extract_text.py index f15415a..d6696d4 100644 --- a/backend/tests/test_extract_text.py +++ b/backend/tests/test_extract_text.py @@ -73,6 +73,27 @@ def fake_post_json(url, *, headers=None, json_body, timeout, label, **kwargs): return state +def queued_extraction(session, asset_id): + """The extraction an upload queued on its own, or None.""" + return session.exec( + select(EnrichmentJob).where( + EnrichmentJob.asset_id == asset_id, + EnrichmentJob.kind == KIND_EXTRACT_TEXT, + col(EnrichmentJob.status).in_(("queued", "processing")), + ) + ).first() + + +def settle(session, asset_id): + """Finish the upload's own extraction job, as the worker would have by the time a + person presses the button, so the button is not refused as already running.""" + job = queued_extraction(session, asset_id) + if job is not None: + job.status = "done" + session.add(job) + session.commit() + + def pages_of(session, asset_id): return session.exec( select(DocumentPage) @@ -223,10 +244,27 @@ def test_deleting_the_asset_takes_its_pages_with_it(library, session): # --- the API ---------------------------------------------------------------------- +@pytest.mark.parametrize("extension", [".pdf", ".docx", ".pptx", ".xlsx", ".txt"]) +def test_an_upload_queues_its_own_extraction(library, session, extension): + """Nobody has to press anything for a document's words to reach search, or the + other apps reading the library: the upload asks, with no provider configured.""" + created = upload_document(library, extension) + + assert queued_extraction(session, created["id"]) is not None + + +def test_an_upload_nothing_can_read_queues_nothing(library, session): + """A job certain to fail would leave a red row after every such upload.""" + created = upload_document(library, ".txt", name="notes.rtf") + + assert queued_extraction(session, created["id"]) is None + + def test_the_endpoint_queues_a_job_without_a_provider(library, session): """The one enrichment action that must not require an LLM: it is the step that runs before one is any use.""" created = upload_document(library, ".pdf") + settle(session, created["id"]) response = library.post(f"/api/assets/{created['id']}/extract-text") @@ -256,6 +294,7 @@ def test_a_video_cannot_have_its_text_extracted(library, session): def test_two_runs_at_once_are_refused(library, session): created = upload_document(library, ".pdf") + settle(session, created["id"]) first = library.post(f"/api/assets/{created['id']}/extract-text") second = library.post(f"/api/assets/{created['id']}/extract-text") @@ -291,7 +330,7 @@ def test_the_text_endpoint_is_empty_before_extraction_runs(library, session): def test_the_worker_runs_it_end_to_end(library, session, monkeypatch): created = upload_document(library, ".pptx") - job = library.post(f"/api/assets/{created['id']}/extract-text").json()["data"] + job = {"id": queued_extraction(session, created["id"]).id} queue = enrichment_jobs.queue() monkeypatch.setattr(queue, "engine", session.get_bind()) @@ -308,7 +347,7 @@ def test_a_worker_failure_is_reported_in_the_users_words(library, session, monke """Not "crashed": TextExtractionError has to be in the dispatcher's exception ladder or the ladder's bare Exception branch swallows the sentence.""" created = upload_document(library, ".pdf") - job = library.post(f"/api/assets/{created['id']}/extract-text").json()["data"] + job = {"id": queued_extraction(session, created["id"]).id} def explode(*args, **kwargs): raise extract_text.TextExtractionError("The file could not be read.") diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index 9f6acea..a6f9cab 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -94,7 +94,7 @@ def test_the_migration_and_the_test_ddl_agree(alembic_config): """ import sqlite3 - from app.search.fts import ASSET_FTS_COLUMNS, SEGMENT_FTS_COLUMNS + from app.search.fts import ASSET_FTS_COLUMNS, PAGE_FTS_COLUMNS, SEGMENT_FTS_COLUMNS config, db_path = alembic_config command.upgrade(config, "head") @@ -103,6 +103,7 @@ def test_the_migration_and_the_test_ddl_agree(alembic_config): for table, expected in ( ("asset_fts", ASSET_FTS_COLUMNS), ("segment_fts", SEGMENT_FTS_COLUMNS), + ("page_fts", PAGE_FTS_COLUMNS), ): actual = tuple(row[1] for row in conn.execute(f"PRAGMA table_info({table})")) assert actual == expected, f"{table}: migration has {actual}, constants say {expected}" @@ -538,3 +539,34 @@ def test_asset_fts_rebuild_keeps_the_index_and_adds_music(alembic_config): with sqlite3.connect(db_path) as conn: hit = conn.execute("SELECT asset_id FROM asset_fts WHERE asset_fts MATCH 'Caravan'").fetchone() assert hit is not None and hit[0] == "a1" + + +def test_pages_extracted_before_the_page_index_are_searchable_after_it(alembic_config): + """An index that started empty would leave every document read before the upgrade + unsearchable until someone thought to extract it again, and nothing would say so.""" + config, db_path = alembic_config + command.upgrade(config, "5f2b8c1d9e73") + + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO documentpage (id, asset_id, user_id, idx, page_number, label, text)" + " VALUES ('p1', 'a1', 'u', 0, 74, 'Page 74', 'the aerosol dispersion protocol')" + ) + conn.execute( + "INSERT INTO documentpage (id, asset_id, user_id, idx, page_number, label, text)" + " VALUES ('p2', 'a1', 'u', 1, 75, 'Page 75', ' ')" + ) + conn.commit() + + from app import database + + database.engine.dispose() + command.upgrade(config, "head") + + with sqlite3.connect(db_path) as conn: + rows = conn.execute( + "SELECT page_id, asset_id, user_id FROM page_fts WHERE page_fts MATCH 'dispersion'" + ).fetchall() + assert rows == [("p1", "a1", "u")] + # A blank page is nothing to find, and is left out as index_pages leaves it out. + assert conn.execute("SELECT count(*) FROM page_fts").fetchone() == (1,) diff --git a/docs/plan-of-attack.md b/docs/plan-of-attack.md index a43eea1..3294f63 100644 --- a/docs/plan-of-attack.md +++ b/docs/plan-of-attack.md @@ -418,14 +418,20 @@ from a decision, which is the distinction PR bodies do not preserve. every PDF has a first-page thumbnail, so a document branch any lower would leave a PDF summarised from a picture of its cover. - Two parts of it remain, and neither is a decision: - - **Document text is not searchable.** The rows exist and are in neither `segment_fts` - nor the vector index, so a phrase on page 74 cannot be found. A document *is* - findable by the summary enrichment writes, because `apply_ai_metadata` reindexes — - which is easy to mistake for the body being indexed. Closing this means indexing page - bodies, embedding them, and teaching `search/hybrid.py` to resolve a hit id to either - a transcript segment or a page. `jobs/enrichment.py` carries the one-line - `_chain_embedding` change that goes with it, commented. + Text is read the moment a document lands: the upload queues `extract_text` for the + formats it reads (`services/assets._chain_text_extraction`), unconditionally, since it + calls nothing and costs nothing. Before that it ran only when someone pressed the + button, so most documents had no text for anything to read. + + - **~~Document text is not searchable.~~** Built. Pages are in their own FTS5 table, + `page_fts` (not in `segment_fts`, whose every reader takes a hit's id for a + transcript segment and its start for a second), written by `extract_text._store` and + backfilled by its migration from pages already read. They are embedded too (owner + kind `page`, cut to `MAX_PAGE_EMBED_CHARS` so one long sheet cannot fail a batch), + and a finished extraction chains the embed job. `search/hybrid.py` carries a + `page_id` beside `segment_id`, and a search hit names its page (`page_id`, + `page_number`, `page_label`) as a spoken hit names its second. Video Creator's + assistant finds a document this way and reads it with `GET /api/assets/{id}/text`. - **Legacy and OpenDocument formats refuse by name.** `.doc`, `.xls`, `.ppt`, `.rtf`, `.odt`, `.ods`, `.odp` are in `DOCUMENT_EXTENSIONS` and nothing reads them. The refusal says which format and what to do about it, rather than failing vaguely. diff --git a/frontend/src/api/search.ts b/frontend/src/api/search.ts index 4d90c5b..97cdbae 100644 --- a/frontend/src/api/search.ts +++ b/frontend/src/api/search.ts @@ -13,6 +13,13 @@ export interface SearchHit { /** Where that moment ends, for cutting it out as a clip. Null with `start_time`. */ end_time: number | null segment_id: string | null + /** + * Where in a document the words were found ("Page 74", "Slide 7", "Part 2"), and its + * real page number where the format has pages. Null for a hit outside a document's text. + */ + page_id?: string | null + page_number?: number | null + page_label?: string | null /** Which retrievers found it: 'keyword', 'semantic', or both. */ sources: string[] /** Other moments in the same asset that also matched. */ diff --git a/frontend/src/views/SearchView.tsx b/frontend/src/views/SearchView.tsx index 12abcd1..fea6709 100644 --- a/frontend/src/views/SearchView.tsx +++ b/frontend/src/views/SearchView.tsx @@ -235,7 +235,9 @@ function nextParams( function ResultRow({ hit, onOpen }: { hit: SearchHit; onOpen: () => void }) { const parts = splitHighlights(hit.snippet) - const timestamp = hit.start_time !== null ? formatDuration(hit.start_time) : '' + // A moment in a recording, or the page of a document: each says where to look. + const timestamp = + hit.start_time !== null ? formatDuration(hit.start_time) : (hit.page_label ?? '') return (
  • @@ -285,8 +287,8 @@ function ResultRow({ hit, onOpen }: { hit: SearchHit; onOpen: () => void }) { {hit.other_matches > 0 && (

    - and {hit.other_matches} more moment{hit.other_matches === 1 ? '' : 's'} in - this asset + and {hit.other_matches} more {hit.page_id ? 'place' : 'moment'} + {hit.other_matches === 1 ? '' : 's'} in this asset

    )}