Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix scanned PDF uploads with local OCR fallback (#10620)

Lee Jacksonab6960778477
diff --git a/studio/PDF_OCR.md b/studio/PDF_OCR.md
new file mode 100644
index 00000000000..c8d2fbc598f
--- /dev/null
+++ b/studio/PDF_OCR.md
@@ -0,0 +1,47 @@
+# Scanned PDF uploads
+
+Studio can extract text from scanned PDFs in Chat, project sources, and Data Recipes.
+Existing selectable text is preserved. OCR runs on image-only pages, including scans
+with a selectable header or footer. Small logos do not require OCR when selectable
+text is present. Large images with little selectable body text are treated as
+possible scans, so illustrated pages can also require OCR. Chat has a separate
+figure-captioning setting.
+
+Chat first uses the loaded local vision GGUF model when available, then tries local
+Tesseract OCR for scanned pages that were not transcribed. Data Recipes uses local
+Tesseract OCR without requiring a loaded chat model.
+Recipe PDF extraction runs in separate worker processes so OCR does not block
+other requests.
+
+## Local OCR setup
+
+PyMuPDF includes the OCR integration. Install Tesseract language data on the machine
+running the Studio backend, and set TESSDATA_PREFIX to the folder containing the
+.traineddata files before starting Studio. No data is downloaded automatically.
+
+For example, install your operating system's Tesseract package and English language
+data, then point TESSDATA_PREFIX to its tessdata directory. You can also obtain
+language files from the [official Tesseract repository](https://github.com/tesseract-ocr/tessdata_fast).
+See [PyMuPDF's OCR setup](https://pymupdf.readthedocs.io/en/latest/installation.html#enabling-integrated-ocr-support)
+for platform-specific details.
+
+Set RAG_OCR_LANGUAGE to the installed language codes; the default is eng.
+For example, eng+deu requires both eng.traineddata and deu.traineddata.
+
+## Limits and failed uploads
+
+RAG_OCR_SCANNED=0 disables scanned-page OCR by default. Chat's **OCR scanned pages**
+setting overrides this for chat/project uploads. Data Recipes follows the backend
+default.
+
+RAG_OCR_MAX_PAGES defaults to 20 scanned pages per PDF. Raise it before starting
+Studio when longer scans are expected. Local OCR uses RAG_OCR_DPI (default 150).
+
+If scanned pages remain unreadable, the upload fails with their page numbers rather
+than silently accepting an incomplete document. Configure the OCR language data,
+enable OCR, increase the page budget when necessary, or upload a searchable PDF,
+then attach the file again. Empty documents also fail instead of appearing indexed
+with zero searchable chunks.
+
+OCR is fallible, especially for handwriting, low-resolution scans, and complex
+tables. Check extracted results against the original document.
diff --git a/studio/backend/core/rag/captioner.py b/studio/backend/core/rag/captioner.py
index af850b008fd..5a3c597c2ea 100644
--- a/studio/backend/core/rag/captioner.py
+++ b/studio/backend/core/rag/captioner.py
@@ -179,6 +179,7 @@ def caption_images(
*,
endpoint: tuple[str, str] | None = None,
on_progress: Callable[[int, int], None] | None = None,
+ on_caption: Callable[[object], None] | None = None,
) -> dict[int, list[str]]:
"""Caption ``ParsedImage`` objects, keyed by 1-based page number; ``{}`` when there
are no images or no vision model. The caller (`ingestion._run`) owns the on/off
@@ -199,6 +200,8 @@ def caption_images(
if caption:
page = getattr(img, "page_number", None) or 0
out.setdefault(int(page), []).append(_collapse_runaway(caption))
+ if on_caption is not None:
+ on_caption(img)
if on_progress is not None:
on_progress(index, len(selected))
return out
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.py
index ecc91c40027..e023242a492 100644
--- a/studio/backend/core/rag/config.py
+++ b/studio/backend/core/rag/config.py
@@ -66,7 +66,8 @@ FIGURE_TILE_OVERLAP = float(os.environ.get("RAG_FIGURE_TILE_OVERLAP", "0.12"))
FIGURE_FULLPAGE = os.environ.get("RAG_FIGURE_FULLPAGE", "1") == "1"
CAPTION_MAX_PAGES = int(os.environ.get("RAG_CAPTION_MAX_PAGES", "4"))
-# Needs a vision model, else the page stays empty; MIN_CHARS is the text length below which a page counts as scanned.
+# OCR uses the loaded vision model, falling back to local Tesseract language data.
+# MIN_CHARS is the text length below which a page is considered for transcription.
OCR_SCANNED = os.environ.get("RAG_OCR_SCANNED", "1") == "1"
OCR_MIN_CHARS = int(os.environ.get("RAG_OCR_MIN_CHARS", "16"))
OCR_MAX_PAGES = int(os.environ.get("RAG_OCR_MAX_PAGES", "20"))
diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.py
index 26fe5fc86df..6b1ce5a1960 100644
--- a/studio/backend/core/rag/ingestion.py
+++ b/studio/backend/core/rag/ingestion.py
@@ -18,7 +18,7 @@ from collections.abc import Callable
from storage import rag_db
-from . import captioner, chunking, config, embeddings, job_leases, parsers, store
+from . import captioner, chunking, config, embeddings, job_leases, parsers, pdf_ocr, store
logger = logging.getLogger(__name__)
@@ -167,8 +167,8 @@ def _ocr_scanned_pages(
ocr: bool | None = None,
) -> tuple[list, set[int]]:
"""Replace text on near-empty (scanned/image-only) PDF pages with vision-model OCR
- so image PDFs become searchable. ``ocr`` overrides ``config.OCR_SCANNED`` per upload
- (``None`` = config default); no-op without scanned pages or a vision model. OCR'd
+ so image PDFs become searchable. Local Tesseract is the fallback. The per-upload
+ ``ocr`` flag overrides ``config.OCR_SCANNED``; no-op without scanned pages. OCR'd
pages have no text layer, so no preview highlight regions, but stay searchable.
Returns ``(pages, ocred)``: new ``Page`` objects for OCR'd pages (originals
otherwise) and the set of page numbers actually transcribed."""
@@ -177,10 +177,14 @@ def _ocr_scanned_pages(
scanned = [
p.page_number
for p in pages
- if p.page_number is not None and len((p.text or "").strip()) < config.OCR_MIN_CHARS
+ if p.page_number is not None
+ and (p.needs_ocr or len((p.text or "").strip()) < config.OCR_MIN_CHARS)
]
- if not scanned or captioner.vision_endpoint() is None:
+ if not scanned:
return pages, set()
+ required = {p.page_number for p in pages if p.needs_ocr}
+ # Optional short/blank pages must not displace actual scans from the budget.
+ scanned.sort(key = lambda number: number not in required)
if len(scanned) > config.OCR_MAX_PAGES:
logger.warning(
"OCR: %d scanned pages exceed OCR_MAX_PAGES=%d; pages past the cap stay "
@@ -190,11 +194,22 @@ def _ocr_scanned_pages(
)
scanned = scanned[: config.OCR_MAX_PAGES]
_progress(conn, job_id, "ocr", 0.25)
- page_pngs = parsers.render_pdf_pages(stored_path, scanned, dpi = config.OCR_DPI)
- texts = captioner.ocr_pages(
- page_pngs,
- on_progress = lambda done, total: _progress(conn, job_id, "ocr", 0.25 + 0.15 * done / total),
- )
+ texts = {}
+ if captioner.vision_endpoint() is not None:
+ page_pngs = parsers.render_pdf_pages(stored_path, scanned, dpi = config.OCR_DPI)
+ texts = captioner.ocr_pages(
+ page_pngs,
+ on_progress = lambda done, total: _progress(
+ conn, job_id, "ocr", 0.25 + 0.15 * done / total
+ ),
+ )
+ # Keep the existing vision pass, but allow scanned PDFs with text-only models too.
+ local_pages = [
+ p.page_number
+ for p in pages
+ if p.needs_ocr and p.page_number in scanned and p.page_number not in texts
+ ]
+ texts.update(pdf_ocr.ocr_pages(stored_path, local_pages))
if not texts:
return pages, set()
@@ -286,6 +301,7 @@ def _run(
_progress(conn, job_id, "parsing", 0.1)
pages = parsers.parse(stored_path)
is_pdf = stored_path.lower().endswith(".pdf")
+ scanned_pages = {p.page_number for p in pages if p.needs_ocr}
ocred: set[int] = set()
if is_pdf:
pages, ocred = _ocr_scanned_pages(pages, stored_path, conn, job_id, ocr = ocr)
@@ -320,15 +336,38 @@ def _run(
logger.warning("figure tiling failed for job %s", job_id, exc_info = True)
tiles = []
if tiles:
+ complete_captions: set[int] = set()
+ captioned_tiles: dict[int, set[int]] = {}
+
+ def record_caption(image):
+ number = image.page_number
+ if image.full_page:
+ complete_captions.add(number)
+ elif image.tile_index is not None and image.tile_count:
+ indices = captioned_tiles.setdefault(number, set())
+ indices.add(image.tile_index)
+ if len(indices) == image.tile_count:
+ complete_captions.add(number)
+
captions = captioner.merge_page_captions(
captioner.caption_images(
tiles,
+ on_caption = record_caption,
on_progress = lambda done, total: _progress(
conn, job_id, "captioning", 0.4 + 0.2 * done / total
),
)
)
pages = captioner.splice_captions(pages, captions)
+ ocred.update(complete_captions)
+
+ if scanned_pages - ocred:
+ if _abort_if_document_deleted(conn, job_id, document_id):
+ return
+ if not job_leases.renew_owned(conn, job_leases.INGESTION, job_id):
+ conn.rollback()
+ raise job_leases.JobLeaseLost("Ingestion job lease was reclaimed")
+ raise pdf_ocr.unreadable_pages_error(scanned_pages - ocred)
_progress(conn, job_id, "chunking", 0.6)
count = embeddings.token_counter(model_name)
@@ -339,18 +378,14 @@ def _run(
count = count,
)
if not chunks:
- # An empty parse still completes the document and retires the one it replaces, so it needs the same
- # guard as the chunk write.
if _abort_if_document_deleted(conn, job_id, document_id):
return
- # inside the write transaction the guard opened, as _progress does
if not job_leases.renew_owned(conn, job_leases.INGESTION, job_id):
+ conn.rollback()
raise job_leases.JobLeaseLost("Ingestion job lease was reclaimed")
- store.set_document_status(conn, document_id, "completed", num_chunks = 0)
- _replace_old_document(conn, replaces, stored_path, document_id)
- _set_job(conn, job_id, status = "completed", stage = "done", progress = 1.0)
- _emit(job_id, {"type": "complete", "num_chunks": 0})
- return
+ raise ValueError(
+ "No extractable text found in file. Upload a document containing readable text."
+ )
_progress(conn, job_id, "embedding", 0.65)
# An ST encode failure swaps the process to llama-server, so the embedder that produced these
diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.py
index 8b426b3c027..a9b77af27f0 100644
--- a/studio/backend/core/rag/parsers.py
+++ b/studio/backend/core/rag/parsers.py
@@ -29,6 +29,7 @@ class Page:
text: str
page_number: int | None = None
char_count: int = 0
+ needs_ocr: bool = False
@dataclass(frozen = True)
@@ -38,6 +39,9 @@ class ParsedImage:
image_bytes: bytes
page_number: int | None
xref: int
+ full_page: bool = False
+ tile_index: int | None = None
+ tile_count: int = 0
def _page(text: str, page_number: int | None) -> Page:
@@ -162,7 +166,27 @@ def _pdf(
text = candidate
else:
text = plain
- pages.append(_page(text, page_number + 1))
+ # Markdown may contain image placeholders even when there is no text layer.
+ # Record scanned pages from the PDF itself; blank separator pages need no OCR.
+ images_on_page = page.get_image_info()
+ needs_ocr = bool(images_on_page) and not plain.strip()
+ for info in images_on_page:
+ image_rect = fitz.Rect(info["bbox"]) & page.rect
+ if image_rect.get_area() < page.rect.get_area() * 0.5:
+ continue
+ # A selectable header/footer does not make the scanned body readable.
+ body = fitz.Rect(
+ image_rect.x0,
+ image_rect.y0 + image_rect.height * 0.1,
+ image_rect.x1,
+ image_rect.y1 - image_rect.height * 0.1,
+ )
+ if len(page.get_text("text", clip = body).strip()) < config.OCR_MIN_CHARS:
+ needs_ocr = True
+ break
+ if needs_ocr:
+ text = plain
+ pages.append(Page(text, page_number + 1, len(text), needs_ocr = needs_ocr))
if want_images:
for img in page.get_images(full = True):
xref = img[0]
@@ -326,10 +350,20 @@ def render_pdf_figure_tiles(
)
& rect
)
- for clip in clips:
+ for index, clip in enumerate(clips):
try:
pix = page.get_pixmap(dpi = dpi, clip = clip)
- out.append(ParsedImage(image_bytes = pix.tobytes("png"), page_number = num, xref = 0))
+ is_full_page = fullpage and index == 0
+ out.append(
+ ParsedImage(
+ image_bytes = pix.tobytes("png"),
+ page_number = num,
+ xref = 0,
+ full_page = is_full_page,
+ tile_index = None if is_full_page else index - int(fullpage),
+ tile_count = rows * cols,
+ )
+ )
except Exception:
continue
if len(out) >= max_tiles:
diff --git a/studio/backend/core/rag/pdf_ocr.py b/studio/backend/core/rag/pdf_ocr.py
new file mode 100644
index 00000000000..9aece9288b4
--- /dev/null
+++ b/studio/backend/core/rag/pdf_ocr.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Local scanned-PDF OCR shared by document ingestion and Data Recipes."""
+
+from __future__ import annotations
+
+import logging
+import os
+
+from . import config
+
+logger = logging.getLogger(__name__)
+
+
+class PDFOCRError(ValueError):
+ """An incomplete PDF extraction that should be shown to the uploader."""
+
+
+def unreadable_pages_error(page_numbers) -> PDFOCRError:
+ numbers = sorted(page_numbers)
+ label = ", ".join(map(str, numbers[:20]))
+ if len(numbers) > 20:
+ label += f" (and {len(numbers) - 20} more)"
+ return PDFOCRError(
+ f"Could not read scanned PDF pages: {label}. "
+ "Enable OCR and configure Tesseract language data (TESSDATA_PREFIX), "
+ "or upload a PDF with a searchable text layer. "
+ f"OCR is limited to {config.OCR_MAX_PAGES} scanned pages per upload."
+ )
+
+
+def ocr_pages(path: str, page_numbers) -> dict[int, str]:
+ """Transcribe only requested pages using PyMuPDF's integrated Tesseract.
+
+ No downloads or model loading. Tesseract language data must already be installed.
+ The caller owns the page budget and decides how to report unresolved pages.
+ """
+ if not page_numbers:
+ return {}
+ import pymupdf
+
+ out: dict[int, str] = {}
+ with pymupdf.open(path) as doc:
+ for number in page_numbers:
+ try:
+ page = doc[number - 1]
+ textpage = page.get_textpage_ocr(
+ language = os.environ.get("RAG_OCR_LANGUAGE", "eng"),
+ dpi = config.OCR_DPI,
+ full = True,
+ tessdata = os.environ.get("TESSDATA_PREFIX") or None,
+ )
+ text = page.get_text("text", textpage = textpage).strip()
+ except Exception:
+ # A missing engine/language pack affects every page. Do not repeatedly
+ # try an unavailable OCR engine for an entire scanned document.
+ logger.warning("Local PDF OCR failed on page %s", number, exc_info = True)
+ break
+ if text:
+ out[number] = text
+ return out
+
+
+def extract_text(path: str, ocr: bool, max_pages: int) -> str:
+ """Extract a complete PDF in one process, preserving selectable text."""
+ from . import parsers
+
+ pages = parsers.parse(path)
+ scanned = [page.page_number for page in pages if page.needs_ocr]
+ texts = ocr_pages(path, scanned[:max_pages]) if ocr else {}
+ if set(scanned) - texts.keys():
+ raise unreadable_pages_error(set(scanned) - texts.keys())
+ parts = []
+ for page in pages:
+ original = page.text.strip()
+ text = texts.get(page.page_number, "")
+ parts.append(
+ text
+ if not original or original in text
+ else "\n\n".join(filter(None, [original, text]))
+ )
+ return "\n\n".join(parts)
diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.py
index 4bf54127213..f7feadb5985 100644
--- a/studio/backend/routes/data_recipe/seed.py
+++ b/studio/backend/routes/data_recipe/seed.py
@@ -16,6 +16,7 @@ from pathlib import Path
from typing import Any
from uuid import uuid4
+from anyio import CapacityLimiter, to_process
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File as FastAPIFile, Form
from auth.authentication import allow_ambient_hf_token
@@ -420,10 +421,8 @@ def _extract_text_from_file(file_path: Path, ext: str) -> str:
if ext in {".txt", ".md"}:
raw = file_path.read_text(encoding = "utf-8", errors = "ignore")
elif ext == ".pdf":
- import pymupdf4llm
- raw = pymupdf4llm.to_markdown(
- str(file_path), write_images = False, show_progress = False, use_ocr = False
- )
+ from core.rag import config, pdf_ocr
+ raw = pdf_ocr.extract_text(str(file_path), config.OCR_SCANNED, config.OCR_MAX_PAGES)
elif ext == ".docx":
import mammoth
with open(str(file_path), "rb") as f:
@@ -438,6 +437,27 @@ def _extract_text_from_file(file_path: Path, ext: str) -> str:
return chunking.normalize_unstructured_text(raw)
+_pdf_extraction_limiter = CapacityLimiter(2)
+
+
+async def _extract_text_from_file_async(file_path: Path, ext: str) -> str:
+ if ext != ".pdf":
+ return _extract_text_from_file(file_path, ext)
+ from core.rag import config, pdf_ocr
+
+ # MuPDF is not thread-safe; each worker owns its document and OCR state.
+ raw = await to_process.run_sync(
+ pdf_ocr.extract_text,
+ str(file_path),
+ config.OCR_SCANNED,
+ config.OCR_MAX_PAGES,
+ cancellable = True,
+ limiter = _pdf_extraction_limiter,
+ )
+ chunking = _chunking()
+ return chunking.normalize_unstructured_text(raw) if chunking is not None else raw
+
+
def _get_block_total_size(block_dir: Path) -> int:
"""Sum raw upload sizes for the whole block from server-owned files."""
if not block_dir.exists():
@@ -563,7 +583,7 @@ async def upload_unstructured_file(
extracted_path = block_dir / f"{file_id}.extracted.txt"
try:
- extracted_text = _extract_text_from_file(raw_path, ext)
+ extracted_text = await _extract_text_from_file_async(raw_path, ext)
if not extracted_text or not extracted_text.strip():
raw_path.unlink(missing_ok = True)
return UnstructuredFileUploadResponse(
@@ -606,6 +626,8 @@ async def upload_unstructured_file(
error = "Text extraction failed.",
)
except Exception as e:
+ from core.rag.pdf_ocr import PDFOCRError
+
raw_path.unlink(missing_ok = True)
extracted_path.unlink(missing_ok = True)
logger.error(
@@ -618,9 +640,15 @@ async def upload_unstructured_file(
filename = original_filename,
size_bytes = size_bytes,
status = "error",
- error = "Text extraction failed.",
+ error = str(e) if isinstance(e, PDFOCRError) else "Text extraction failed.",
)
+ except BaseException:
+ # Cancellation kills the OCR worker before its input can be removed.
+ raw_path.unlink(missing_ok = True)
+ extracted_path.unlink(missing_ok = True)
+ raise
+
try:
meta_path = block_dir / f"{file_id}.meta.json"
meta_path.write_text(
diff --git a/studio/backend/tests/test_data_recipe_seed.py b/studio/backend/tests/test_data_recipe_seed.py
index f603c47419a..6c514e95f0c 100644
--- a/studio/backend/tests/test_data_recipe_seed.py
+++ b/studio/backend/tests/test_data_recipe_seed.py
@@ -30,7 +30,12 @@ class _FakeUpload:
return self._content
-def _load_seed_route(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
+def _load_seed_route(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ *,
+ inline_extraction = True,
+):
pytest.importorskip("fastapi")
pytest.importorskip("multipart")
pytest.importorskip("structlog")
@@ -43,6 +48,12 @@ def _load_seed_route(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
seed_route = importlib.util.module_from_spec(spec)
spec.loader.exec_module(seed_route)
seed_route.UNSTRUCTURED_UPLOAD_ROOT = tmp_path / "unstructured-uploads"
+ if inline_extraction:
+ # Unit cases inject extractor failures in this process. Process isolation has separate tests.
+ async def extract(file_path, ext):
+ return seed_route._extract_text_from_file(file_path, ext)
+
+ monkeypatch.setattr(seed_route, "_extract_text_from_file_async", extract)
return seed_route
diff --git a/studio/backend/tests/test_pdf_local_ocr.py b/studio/backend/tests/test_pdf_local_ocr.py
new file mode 100644
index 00000000000..f2b85e6d59f
--- /dev/null
+++ b/studio/backend/tests/test_pdf_local_ocr.py
@@ -0,0 +1,221 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Image-only PDFs must yield searchable text or an actionable upload error."""
+
+import pytest
+import pymupdf
+
+from core.rag import captioner, config, ingestion, parsers, pdf_ocr, store, tool
+from .test_data_recipe_seed import _load_seed_route, _run_upload, _block_files
+from .test_rag_ocr_fallback import _ingest
+
+
+def scanned_pdf(
+ path,
+ *,
+ mixed = False,
+ header = False,
+ scans = 1,
+):
+ with pymupdf.open() as original:
+ page = original.new_page()
+ page.insert_text((72, 100), "Invoice zebra-42 total 123 dollars", fontsize = 20)
+ png = page.get_pixmap(dpi = 120).tobytes("png")
+ with pymupdf.open() as doc:
+ if mixed:
+ page = doc.new_page()
+ page.insert_text((72, 100), "Digital content quokka-17 is preserved.")
+ for _ in range(scans):
+ page = doc.new_page()
+ if header:
+ page.insert_text((40, 30), "A digitally added header above the scanned body")
+ page.insert_image(pymupdf.Rect(0, 60, 595, 842), stream = png)
+ doc.save(str(path))
+
+
+def local_ocr(monkeypatch):
+ """Only native recognition is stubbed: exercise page selection and extraction."""
+ calls = []
+
+ def recognize(page, **kwargs):
+ calls.append(page.number + 1)
+ assert kwargs["full"] is True
+ page.insert_text((72, 130), "Invoice zebra-42 total 123 dollars")
+ return page.get_textpage()
+
+ monkeypatch.setattr(pymupdf.Page, "get_textpage_ocr", recognize)
+ monkeypatch.setattr(captioner, "vision_endpoint", lambda: None)
+ monkeypatch.setattr(config, "OCR_SCANNED", True)
+ monkeypatch.setattr(config, "OCR_MAX_PAGES", 20)
+ monkeypatch.setattr(config, "CAPTION_IMAGES", False)
+ return calls
+
+
[email protected]("mixed", [False, True])
+def test_recipe_scanned_pdf_extracts_local_ocr(monkeypatch, tmp_path, local_ocr, mixed):
+ route = _load_seed_route(monkeypatch, tmp_path)
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf, mixed = mixed)
+ result = _run_upload(route, pdf.name, pdf.read_bytes())
+ assert result.status == "ok", result.error
+ extracted = next(route.UNSTRUCTURED_UPLOAD_ROOT.rglob("*.extracted.txt")).read_text()
+ assert "zebra-42" in extracted
+ assert local_ocr == [2 if mixed else 1]
+ if mixed:
+ assert extracted.index("quokka-17") < extracted.index("zebra-42")
+
+
[email protected]("mixed", [False, True])
+def test_chat_scanned_pdf_searchable_without_vision(
+ rag_conn, stub_embeddings, tmp_path, local_ocr, mixed
+):
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf, mixed = mixed)
+ doc = _ingest(rag_conn, "t1", pdf.name, pdf)
+ assert doc["status"] == "completed", doc["error"]
+ text, sources = tool.whole_document_context(scope_thread_id = "t1", max_tokens = 6000)
+ assert "zebra-42" in text
+ assert local_ocr == [2 if mixed else 1]
+ if mixed:
+ assert "quokka-17" in text
+
+
+def test_scan_with_digital_header_still_gets_ocr(tmp_path, local_ocr, monkeypatch):
+ pdf = tmp_path / "header.pdf"
+ scanned_pdf(pdf, header = True)
+ pages = parsers.parse(str(pdf))
+ assert pages[0].needs_ocr
+ route = _load_seed_route(monkeypatch, tmp_path)
+ text = route._extract_text_from_file(pdf, ".pdf")
+ assert text.count("digitally added header") == 1
+ assert "zebra-42" in text
+
+
[email protected]("mixed", [False, True])
+def test_recipe_missing_ocr_rejects_incomplete_pdf(monkeypatch, tmp_path, mixed):
+ route = _load_seed_route(monkeypatch, tmp_path)
+ monkeypatch.setattr(pdf_ocr, "ocr_pages", lambda *a: {})
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf, mixed = mixed)
+ result = _run_upload(route, pdf.name, pdf.read_bytes())
+ assert result.status == "error"
+ assert f"scanned PDF pages: {2 if mixed else 1}" in result.error
+ assert "TESSDATA_PREFIX" in result.error
+ assert _block_files(route) == []
+
+
[email protected]("vision_failure", [False, True])
+def test_chat_unreadable_pdf_emits_error(
+ rag_conn, stub_embeddings, monkeypatch, tmp_path, vision_failure
+):
+ monkeypatch.setattr(config, "OCR_SCANNED", True)
+ monkeypatch.setattr(config, "CAPTION_IMAGES", False)
+ monkeypatch.setattr(
+ captioner, "vision_endpoint", lambda: ("http://unused", "local") if vision_failure else None
+ )
+ monkeypatch.setattr(captioner, "_ocr_one", lambda *a: None)
+ monkeypatch.setattr(pdf_ocr, "ocr_pages", lambda *a: {})
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf, mixed = True)
+ doc_id, job_id = ingestion.start_ingestion(
+ store.thread_scope("t1"), None, "t1", pdf.name, str(pdf)
+ )
+ events = list(ingestion.job_events(job_id))
+ doc = store.get_document(rag_conn, doc_id)
+ assert doc["status"] == "failed"
+ assert "scanned PDF pages: 2" in doc["error"]
+ assert not doc["num_chunks"]
+ assert any(e["type"] == "error" for e in events)
+ assert not any(e["type"] == "complete" for e in events)
+
+
+def test_chat_vision_failure_falls_back_locally(
+ rag_conn, stub_embeddings, monkeypatch, tmp_path, local_ocr
+):
+ monkeypatch.setattr(captioner, "vision_endpoint", lambda: ("http://unused", "local"))
+ monkeypatch.setattr(captioner, "_ocr_one", lambda *a: None)
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf)
+ doc = _ingest(rag_conn, "t1", pdf.name, pdf)
+ assert doc["status"] == "completed"
+ assert local_ocr == [1]
+
+
[email protected]("recipe", [False, True])
+def test_ocr_page_cap_does_not_silently_drop_pages(
+ rag_conn, stub_embeddings, monkeypatch, tmp_path, local_ocr, recipe
+):
+ monkeypatch.setattr(config, "OCR_MAX_PAGES", 1)
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf, scans = 2)
+ if recipe:
+ route = _load_seed_route(monkeypatch, tmp_path)
+ result = _run_upload(route, pdf.name, pdf.read_bytes())
+ assert result.status == "error"
+ error = result.error
+ else:
+ doc = _ingest(rag_conn, "t1", pdf.name, pdf)
+ assert doc["status"] == "failed"
+ error = doc["error"]
+ assert "scanned PDF pages: 2" in error
+ assert local_ocr == [1]
+
+
+def test_blank_separator_needs_no_ocr(tmp_path):
+ pdf = tmp_path / "blank.pdf"
+ with pymupdf.open() as doc:
+ doc.new_page()
+ doc.save(str(pdf))
+ assert not parsers.parse(str(pdf))[0].needs_ocr
+
+
+def test_local_ocr_engine_failure_returns_no_text(monkeypatch, tmp_path):
+ def unavailable(*args, **kwargs):
+ raise RuntimeError("Missing language data")
+
+ monkeypatch.setattr(pymupdf.Page, "get_textpage_ocr", unavailable)
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf)
+ assert pdf_ocr.ocr_pages(str(pdf), [1]) == {}
+
+
+def test_recipe_respects_disabled_ocr(monkeypatch, tmp_path, local_ocr):
+ monkeypatch.setattr(config, "OCR_SCANNED", False)
+ route = _load_seed_route(monkeypatch, tmp_path)
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf)
+ result = _run_upload(route, pdf.name, pdf.read_bytes())
+ assert result.status == "error"
+ assert "scanned PDF pages: 1" in result.error
+ assert local_ocr == []
+
+
+def test_failed_scan_replacement_preserves_searchable_original(
+ rag_conn, stub_embeddings, monkeypatch, tmp_path
+):
+ old_path = tmp_path / "old.txt"
+ old_path.write_text("Existing searchable content quokka-17")
+ old = _ingest(rag_conn, "t1", old_path.name, old_path)
+ assert old["status"] == "completed"
+ monkeypatch.setattr(config, "OCR_SCANNED", False)
+ monkeypatch.setattr(config, "CAPTION_IMAGES", False)
+ pdf = tmp_path / "scan.pdf"
+ scanned_pdf(pdf)
+ scope = store.thread_scope("t1")
+ doc_id = store.create_document(
+ rag_conn,
+ scope = scope,
+ filename = pdf.name,
+ sha256 = "new",
+ thread_id = "t1",
+ status = "pending",
+ stored_path = str(pdf),
+ )
+ job_id = ingestion._new_job(rag_conn, doc_id, scope)
+ ingestion._run(job_id, doc_id, scope, str(pdf), None, replaces = (old["id"], str(old_path)))
+ assert store.get_document(rag_conn, doc_id)["status"] == "failed"
+ assert store.get_document(rag_conn, old["id"])["status"] == "completed"
+ text, _ = tool.whole_document_context(scope_thread_id = "t1", max_tokens = 6000)
+ assert "quokka-17" in text
diff --git a/studio/backend/tests/test_pdf_ocr_regressions.py b/studio/backend/tests/test_pdf_ocr_regressions.py
new file mode 100644
index 00000000000..6d3b23cfe61
--- /dev/null
+++ b/studio/backend/tests/test_pdf_ocr_regressions.py
@@ -0,0 +1,214 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+from pathlib import Path
+import time
+import sys
+
+import pymupdf
+import pytest
+
+from core.rag import captioner, chunking, config, ingestion, job_leases, parsers, pdf_ocr, store
+from storage import rag_db
+from .test_data_recipe_seed import _FakeUpload, _block_files, _load_seed_route
+from .test_pdf_local_ocr import local_ocr, scanned_pdf
+from .test_rag_ocr_fallback import _ingest
+
+
+def test_short_digital_title_with_logo_needs_no_ocr(tmp_path):
+ path = tmp_path / "logo.pdf"
+ with pymupdf.open() as doc:
+ page = doc.new_page()
+ page.insert_text((40, 35), "Report")
+ pix = pymupdf.Pixmap(pymupdf.csRGB, pymupdf.IRect(0, 0, 20, 20))
+ pix.clear_with(150)
+ page.insert_image(pymupdf.Rect(40, 70, 60, 90), pixmap = pix)
+ doc.save(path)
+ page = parsers.parse(str(path))[0]
+ assert not page.needs_ocr
+ assert "Report" in page.text
+
+
+def test_selectable_overlay_header_does_not_hide_scan(tmp_path):
+ path = tmp_path / "overlay.pdf"
+ scanned_pdf(path)
+ with pymupdf.open(path) as doc:
+ doc[0].insert_text((40, 75), "A selectable header inside the image rectangle")
+ doc.saveIncr()
+ assert parsers.parse(str(path))[0].needs_ocr
+
+
+def test_blank_page_does_not_displace_scan_from_budget(
+ rag_conn, stub_embeddings, tmp_path, monkeypatch, local_ocr
+):
+ path = tmp_path / "blank-first.pdf"
+ scanned_pdf(path)
+ with pymupdf.open(path) as doc:
+ doc.new_page(pno = 0)
+ doc.saveIncr()
+ monkeypatch.setattr(config, "OCR_MAX_PAGES", 1)
+ result = _ingest(rag_conn, "blank-first", path.name, path)
+ assert result["status"] == "completed", result["error"]
+ assert local_ocr == [2]
+
+
+ "fullpage, cap, failed_image, expected",
+ [
+ (False, 1, None, "failed"),
+ (False, 4, None, "completed"),
+ (False, 4, 2, "failed"),
+ (True, 1, None, "completed"),
+ (True, 2, 1, "failed"),
+ ],
+)
+def test_only_complete_caption_coverage_resolves_a_scan(
+ rag_conn, stub_embeddings, tmp_path, monkeypatch, fullpage, cap, failed_image, expected
+):
+ path = tmp_path / "captions.pdf"
+ scanned_pdf(path)
+ monkeypatch.setattr(config, "OCR_SCANNED", False)
+ monkeypatch.setattr(config, "CAPTION_IMAGES", True)
+ monkeypatch.setattr(config, "FIGURE_FULLPAGE", fullpage)
+ monkeypatch.setattr(config, "FIGURE_TILE_ROWS", 2)
+ monkeypatch.setattr(config, "FIGURE_TILE_COLS", 2)
+ monkeypatch.setattr(config, "CAPTION_MAX_IMAGES", cap)
+ monkeypatch.setattr(captioner, "vision_endpoint", lambda: ("http://unused", "vision"))
+ calls = []
+
+ def caption(*args):
+ calls.append(1)
+ return None if len(calls) == failed_image else "A transcribed page region"
+
+ monkeypatch.setattr(captioner, "_caption_one", caption)
+ result = _ingest(rag_conn, "captions", path.name, path)
+ assert result["status"] == expected, result["error"]
+ if expected == "failed":
+ assert "scanned PDF pages: 1" in result["error"]
+ assert result["num_chunks"] == 0
+
+
[email protected]("phase", ["ocr", "chunking"])
+def test_empty_result_cannot_fail_job_after_lease_reclaim(
+ rag_conn, stub_embeddings, tmp_path, monkeypatch, phase
+):
+ path = tmp_path / "reclaimed.pdf"
+ scanned_pdf(path)
+ monkeypatch.setattr(config, "CAPTION_IMAGES", False)
+ monkeypatch.setattr(config, "OCR_SCANNED", True)
+ monkeypatch.setattr(captioner, "vision_endpoint", lambda: None)
+
+ def reclaim():
+ conn = rag_db.get_connection()
+ try:
+ conn.execute(
+ "UPDATE rag_job_leases SET owner_id=? WHERE job_id=?", ("successor", job_id)
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ def empty_ocr(*args):
+ reclaim()
+ return {}
+
+ def empty_chunks(*args, **kwargs):
+ reclaim()
+ return []
+
+ if phase == "ocr":
+ monkeypatch.setattr(pdf_ocr, "ocr_pages", empty_ocr)
+ else:
+ monkeypatch.setattr(pdf_ocr, "ocr_pages", lambda *a: {1: "Readable page text"})
+ monkeypatch.setattr(chunking, "chunk_pages", empty_chunks)
+ scope = store.thread_scope("reclaim")
+ doc_id = store.create_document(
+ rag_conn,
+ scope = scope,
+ thread_id = "reclaim",
+ filename = path.name,
+ sha256 = phase,
+ stored_path = str(path),
+ )
+ job_id = ingestion._new_job(rag_conn, doc_id, scope)
+ events = []
+ monkeypatch.setattr(ingestion, "_emit", lambda job, event: events.append(event))
+ ingestion._run(job_id, doc_id, scope, str(path), None)
+ assert store.get_document(rag_conn, doc_id)["status"] == "pending"
+ assert ingestion.get_job_status(job_id)["status"] == "running"
+ assert (
+ rag_conn.execute(
+ "SELECT owner_id FROM rag_job_leases WHERE job_id=?", (job_id,)
+ ).fetchone()[0]
+ == "successor"
+ )
+ assert any(event and event["type"] == "progress" for event in events)
+ assert not any(event and event["type"] in {"error", "complete"} for event in events)
+
+
[email protected]("module_launcher", [False, True])
+def test_recipe_pdf_process_keeps_event_loop_responsive(monkeypatch, tmp_path, module_launcher):
+ if module_launcher:
+ monkeypatch.setattr(
+ sys.modules["__main__"],
+ "__file__",
+ str(Path(__file__).resolve().parents[3] / "unsloth_cli/__main__.py"),
+ raising = False,
+ )
+ route = _load_seed_route(monkeypatch, tmp_path, inline_extraction = False)
+ path = tmp_path / "digital.pdf"
+ with pymupdf.open() as doc:
+ for _ in range(10):
+ doc.new_page().insert_text((50, 100), "Worker process extracts readable text")
+ doc.save(path)
+
+ async def run():
+ upload = asyncio.create_task(
+ route.upload_unstructured_file(_FakeUpload(path.name, path.read_bytes()), "block")
+ )
+ ticks = 0
+ while not upload.done():
+ await asyncio.sleep(0.01)
+ if not upload.done():
+ ticks += 1
+ return await upload, ticks
+
+ result, ticks = asyncio.run(run())
+ assert result.status == "ok", result.error
+ assert ticks > 0
+ assert (
+ "Worker process extracts"
+ in next(route.UNSTRUCTURED_UPLOAD_ROOT.rglob("*.extracted.txt")).read_text()
+ )
+
+
+def _slow_extraction(path, *args):
+ Path(path).with_suffix(".started").write_text("worker started")
+ time.sleep(60)
+ return "late output"
+
+
+def test_cancelled_pdf_upload_kills_worker_before_cleanup(monkeypatch, tmp_path):
+ route = _load_seed_route(monkeypatch, tmp_path, inline_extraction = False)
+ monkeypatch.setattr(pdf_ocr, "extract_text", _slow_extraction)
+
+ async def run():
+ upload = asyncio.create_task(
+ route.upload_unstructured_file(_FakeUpload("slow.pdf", b"%PDF-1.7"), "block")
+ )
+ for _ in range(500):
+ if list(route.UNSTRUCTURED_UPLOAD_ROOT.rglob("*.started")):
+ break
+ if upload.done():
+ pytest.fail(f"worker did not start: {upload.result()}")
+ await asyncio.sleep(0.01)
+ else:
+ upload.cancel()
+ pytest.fail("worker did not signal start")
+ upload.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await upload
+
+ asyncio.run(run())
+ assert all(name.endswith(".started") for name in _block_files(route))
diff --git a/studio/backend/tests/test_rag_ingestion.py b/studio/backend/tests/test_rag_ingestion.py
index e9815185619..4c7bde2d9a3 100644
--- a/studio/backend/tests/test_rag_ingestion.py
+++ b/studio/backend/tests/test_rag_ingestion.py
@@ -554,15 +554,15 @@ def test_ingestion_rejects_unsupported_ext(rag_home, stub_embeddings, tmp_path):
ingestion.start_ingestion(store.kb_scope("K1"), "K1", None, "doc.xyz", path)
-def test_ingestion_empty_doc_completes_with_zero_chunks(rag_home, stub_embeddings, tmp_path):
+def test_ingestion_empty_doc_reports_failure(rag_home, stub_embeddings, tmp_path):
path = _write(tmp_path, "empty.txt", " \n ")
scope = store.kb_scope("K1")
doc_id, job_id = ingestion.start_ingestion(scope, "K1", None, "empty.txt", path)
events = _drain(job_id)
- assert events[-1]["type"] == "complete"
- assert events[-1]["num_chunks"] == 0
+ assert events[-1]["type"] == "error"
+ assert "No extractable text" in events[-1]["error"]
status = _wait_completed(job_id)
- assert status["status"] == "completed"
+ assert status["status"] == "failed"
@pytest.mark.skipif(
diff --git a/studio/backend/tests/test_rag_ocr_fallback.py b/studio/backend/tests/test_rag_ocr_fallback.py
index ac70257dc01..7de8a17c474 100644
--- a/studio/backend/tests/test_rag_ocr_fallback.py
+++ b/studio/backend/tests/test_rag_ocr_fallback.py
@@ -228,7 +228,9 @@ def test_ocr_override_false_skips_ocr_when_config_on(
pdf = tmp_path / "scan.pdf"
_image_only_pdf(pdf, pages = 1)
doc = _ingest_with_ocr(rag_conn, "t1", pdf, ocr = False)
- assert doc["num_chunks"] == 0 # scanned page left empty
+ assert doc["num_chunks"] == 0
+ assert doc["status"] == "failed"
+ assert "scanned PDF pages: 1" in doc["error"]
def test_ocr_override_true_runs_ocr_when_config_off(
@@ -246,14 +248,16 @@ def test_ocr_override_true_runs_ocr_when_config_off(
assert "quokka" in text
-def test_ocr_disabled_leaves_scanned_pdf_empty(rag_conn, stub_embeddings, monkeypatch, tmp_path):
+def test_ocr_disabled_reports_unreadable_scanned_pdf(
+ rag_conn, stub_embeddings, monkeypatch, tmp_path
+):
monkeypatch.setattr(captioner.config, "OCR_SCANNED", False)
pdf = tmp_path / "scan.pdf"
_image_only_pdf(pdf, pages = 1)
doc = _ingest(rag_conn, "t1", "scan.pdf", pdf)
- # With OCR off, a text-less scanned page yields no chunks (prior behavior).
- assert doc["status"] == "completed"
+ assert doc["status"] == "failed"
+ assert "scanned PDF pages: 1" in doc["error"]
assert doc["num_chunks"] == 0
assert tool.whole_document_context(scope_thread_id = "t1", max_tokens = 6000) is None
diff --git a/studio/frontend/src/features/rag/components/retrieval-settings-section.tsx b/studio/frontend/src/features/rag/components/retrieval-settings-section.tsx
index 9cd7199af40..a485c0636b2 100644
--- a/studio/frontend/src/features/rag/components/retrieval-settings-section.tsx
+++ b/studio/frontend/src/features/rag/components/retrieval-settings-section.tsx
@@ -215,10 +215,10 @@ export function RetrievalSettingsSection() {
<span className="flex items-center gap-1.5 text-ui-13 font-medium leading-[1.25] tracking-nav text-nav-fg">
OCR scanned pages
<InfoHint>
- Read text off scanned or image-only PDF pages with the loaded
- model's vision, at upload time, so picture-only documents become
- searchable. Needs a vision model; pages with a text layer are
- unaffected.
+ Read scanned or image-only PDF pages at upload time using the
+ loaded vision model or local Tesseract OCR. Local OCR requires
+ installed language data. Selectable headers alone may not cover a
+ scanned page's body.
</InfoHint>
</span>
<span className="text-ui-12 leading-[1.3] text-muted-foreground">
@@ -238,9 +238,9 @@ export function RetrievalSettingsSection() {
<span className="flex items-center gap-1.5 text-ui-13 font-medium leading-[1.25] tracking-nav text-nav-fg">
Describe figures &amp; charts
<InfoHint>
- Caption PDF figures, charts, tables and diagrams at upload with the
- loaded model's vision, so their content becomes searchable. Needs a
- vision model; adds vision calls for detected figures.
+ Caption PDF figures, charts, tables and diagrams at upload with
+ the loaded model's vision, so their content becomes searchable.
+ Needs a vision model; adds vision calls for detected figures.
</InfoHint>
</span>
<span className="text-ui-12 leading-[1.3] text-muted-foreground">
diff --git a/unsloth_cli/__main__.py b/unsloth_cli/__main__.py
index c89bd6c6dc9..f508b3008c3 100644
--- a/unsloth_cli/__main__.py
+++ b/unsloth_cli/__main__.py
@@ -41,11 +41,12 @@ Output is identical to the console script, which takes three things:
import sys
-# Before the import, so a direct `python .../__main__.py` run takes the console-script gate in __init__.
-sys.argv[0] = "unsloth"
+if __name__ == "__main__":
+ # Worker processes import this file as __mp_main__; they must not launch the CLI.
+ sys.argv[0] = "unsloth"
-import unsloth_cli # noqa: E402
+ import unsloth_cli
-unsloth_cli._prepare_entry_point()
-# A returned value must become the exit status, like the console script's `sys.exit(app())`.
-sys.exit(unsloth_cli.app(prog_name = "unsloth"))
+ unsloth_cli._prepare_entry_point()
+ # A returned value must become the exit status, like the console script's sys.exit(app()).
+ sys.exit(unsloth_cli.app(prog_name = "unsloth"))