Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions backend/alembic/versions/20261120_1200_add_page_search_index.py
Original file line number Diff line number Diff line change
@@ -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")
52 changes: 47 additions & 5 deletions backend/app/enrichment/embed.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -16,14 +17,22 @@
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

logger = logging.getLogger(__name__)

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."""
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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.

Expand Down
17 changes: 16 additions & 1 deletion backend/app/enrichment/extract_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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)


Expand Down
11 changes: 4 additions & 7 deletions backend/app/jobs/enrichment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion backend/app/models/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions backend/app/routers/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)
Expand Down
Loading
Loading