Ingestion
Ingestion turns an upload or an import into searchable chunks with page numbers and a section tree. This page follows a file from the upload to the index. The code is in app/ingestion/.
The pipeline
flowchart LR U[Upload or import] --> J[index_document job] J --> P[Parse<br/>child process] P --> S[Structure<br/>section tree] S --> C[Chunk<br/>per section] C --> E[Embed<br/>with context header] E --> T[Swap index<br/>one transaction] T --> Y[Summaries<br/>background jobs]
Figure 1. From a file to the index. Every step runs in the job worker.
- Accept.
POST /api/library/uploadchecks the size limit and the storage quota, saves the file, and checks that its content matches its extension (a renamed program is not a PDF). It creates thedocumentsrow with statusprocessingand queues anindex_documentjob. - Parse. The worker parses the file in a child process that is killed after
PARSE_TIMEOUT_SECONDS, so a pathological PDF can't hang the worker. - Structure. It builds the section tree and gives every paragraph to the deepest section it belongs to.
- Chunk. It splits each section's text into chunks.
- Embed. It embeds every chunk, before writing anything.
- Swap. In one transaction it writes the new chunks under the next
index_version, deletes the old ones and marks the documentready. A failed re-index leaves the previous index in place. - Summaries. It queues section summaries at background priority.
The job reports its stage (parsing, structuring, embedding, saving) and progress, which the Library shows.
Parsing
| Type | How |
|---|---|
| pymupdf4llm turns each page into Markdown. It detects headings, drops running headers and footers, and runs OCR (RapidOCR) on pages without a text layer. If it fails, plain pypdf text per page is the fallback. | |
| DOCX | python-docx, with headings as sections |
| PPTX | One block per slide, with its speaker notes. The slide number is the page. |
| EPUB | Chapters in reading order, as Markdown with their headings |
| Markdown, HTML, TXT | Headings become sections. HTML is reduced to its article text with trafilatura. |
| Web page import | Fetched by the worker, reduced with trafilatura, or opened in the MCP browser when it needs JavaScript |
| YouTube | Captions with timestamps; local Whisper transcription when there are none and the extra is installed |
| arXiv, DOI | The PDF is downloaded once (the open-access copy for a DOI) and parsed as a PDF |
Cleaning removes private-use glyphs that math fonts use for tall brackets, and keeps equation numbers such as "(9.12)" with their equations.
Problems that don't stop indexing, such as pages without text, are kept as a note on the document.
Structure
The table of contents comes from the PDF's outline when it has one, and from the detected headings otherwise. It becomes the doc_nodes tree: number, title, level, page range. Every paragraph is assigned to the deepest section it belongs to, so a chunk never straddles two sections.
Each chunk carries a context path, for example "H&Z › 9 Epipolar Geometry and the Fundamental Matrix › 9.6 The essential matrix". The PDF's page labels are kept too, so printed page numbers ("p. 257") map to PDF pages.
Scopes
app/ingestion/scope.py resolves a scope string to page ranges with no model: 9.1-9.6, chapter 9 sections 1 to 6, pp. 239-262, p. 257, chapter 9 and section on the essential matrix (a fuzzy title match). Printed page numbers go through the page labels.
Chunking
A recursive splitter (langchain-text-splitters) cuts each section at headings first, then blank lines, lines and spaces. Chunks are 1,200 characters with 200 characters of overlap by default. A chunk keeps its page, section, position and, for videos, its start time.
Embedding
Each chunk is embedded with a context header in front of its text: the document title, the context path and the page, for example "H&Z › 9 Epipolar Geometry… › 9.6 The essential matrix · p. 275". The header helps a chunk that never names its topic, such as the middle of a proof.
Queries and passages are formatted differently: queries carry a task instruction, which instruction-tuned embedders need. app/ingestion/embeddings.py picks the prefixes per model family.
Vectors are stored as halfvec (16-bit) with an HNSW index. The text also gets a generated tsvector column for full-text search.
Figures and tables
After a PDF is indexed, an extract_figures job (app/ingestion/figures.py) renders its figures to PNG, in a child process with the parse time limit:
- Figures: a caption block ("Fig. 9.3. …", "Figure 2:") with drawings or images right above it. The area runs up to the previous caption or body paragraph and takes in short labels around the drawing ("(a)", "epipolar line"), but never the running header. A caption needs a graphic within 40 points, so a sentence that only starts with "Figure 9.3 shows" isn't one.
- Tables: a "Table" caption next to a table PyMuPDF finds on the page.
- Images: an uncaptioned picture covering at least 12 % of the page. A picture covering most of the page is a scanned page and is skipped.
Each is rendered at 2× into UPLOAD_DIR/figures/<document>/ and stored in figures with its page, label, number and caption; a document has at most 1,000. A 673-page textbook takes about 13 seconds and gives 255 figures. Failures skip a page, never the document. python -m scripts.extract_figures queues the job for items indexed before figures existed.
Section summaries
app/ingestion/summaries.py summarises the tree bottom up: a leaf section from its own chunks, a parent from its children's summaries. Each job handles a small batch and queues the next at background priority, so new uploads and chats never wait behind a long book. Summaries are embedded too. Concept maps are built from them.
Imports and safety
app/ingestion/importers.py fetches web pages, videos and papers in the worker, never in the request. Every request, including each redirect, passes an SSRF guard: http or https only, and the host must resolve to public addresses. Errors the user must fix (no transcript, no open-access PDF, a private address) are not retried. Network errors are.
Citation metadata
For captured pages, app/ingestion/citation_meta.py reads the page's own metadata: Highwire citation_* tags, Dublin Core and PRISM, JSON-LD, and Open Graph. Earlier sources win and nothing is guessed. The result fills the item's title, authors, year and bibliographic fields, which the study-guide references use.
Duplicates
app/ingestion/duplicates.py finds a new item that is probably one the student already has, in two passes, and the table duplicate_pairs keeps each pair and the decision.
- Header details, before saving (
POST /api/duplicates/check, called by the Library page and the extension): the same file hash, DOI, arXiv id or address scores 1.0; otherwise the title similarity (difflib ratio of normalised titles, at least 12 characters), unless the first authors or years (more than one apart) conflict, or the numbers in the titles differ ("lecture 1" and "lecture 2"). The student's choice comes back with the save asreplace_idorkeep_ids. - Content, after indexing (job
check_duplicates, queued when an index succeeds): header details again with what indexing learned, then up to 30 sampled passages find candidate items by nearest neighbour, and each candidate gets one score: the share of the shorter item's passages that have a passage with cosine at least 0.9 in the other. Measured on a saved IEEE page and the same paper's PDF: 33 of 37 passages matched; a different paper on the same topic: 0 of 60.
A pair at or over DUPLICATE_THRESHOLD is stored open with a few lines on how the items differ (how much of each one's text the other holds, which is fuller). POST /api/duplicates/{id} applies replace (the new item takes over the existing one's Space links, notes, study sets, tags and shared status; the existing item is deleted), keep (status kept, never raised again) or ignore (the new item is deleted). A replacement chosen before saving is stored as status replace and carried out by the job once the new item is ready.
Re-indexing
Reindex queues the same job. Notes on the document keep their place: their chunks move to the new index version. Summaries of sections that still exist are kept.