Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(parsing): add LiteParse as a document parsing engine (#771)

绝世这天下9228d10abc11
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 64c528bf3..7940f4cd8 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -95,6 +95,7 @@ DOCUMENT_PARSING_ENGINE_MINERU = "mineru"
DOCUMENT_PARSING_ENGINE_DOCLING = "docling"
DOCUMENT_PARSING_ENGINE_MARKITDOWN = "markitdown"
DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM = "pymupdf4llm"
+DOCUMENT_PARSING_ENGINE_LITEPARSE = "liteparse"
_DOCUMENT_PARSING_ENGINES = frozenset(
{
DOCUMENT_PARSING_ENGINE_TEXT_ONLY,
@@ -102,10 +103,14 @@ _DOCUMENT_PARSING_ENGINES = frozenset(
DOCUMENT_PARSING_ENGINE_DOCLING,
DOCUMENT_PARSING_ENGINE_MARKITDOWN,
DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,
+ DOCUMENT_PARSING_ENGINE_LITEPARSE,
}
)
# Image formats PyMuPDF4LLM can write extracted page images as.
_PYMUPDF4LLM_IMAGE_FORMATS = frozenset({"png", "jpg", "jpeg", "webp"})
+# How LiteParse presents images in its Markdown. Independent of whether the
+# image bytes are extracted (that is the engine's ``extract_images`` knob).
+LITEPARSE_IMAGE_MODES = frozenset({"off", "placeholder", "embed"})
# Fresh installs default to the built-in text extractor so parsing works out of
# the box without optional parser packages or model weights.
# Migrated v1 installs keep MinerU (see ``_normalize_document_parsing``).
@@ -162,6 +167,17 @@ _DEFAULT_PYMUPDF4LLM_ENGINE: dict[str, Any] = {
"image_dpi": 150,
}
+# LiteParse engine slice. Rust-backed, no model downloads. Like PyMuPDF4LLM it
+# can extract embedded images into the parse's images/ dir. Output format and
+# image directory are fixed by the workdir contract, so neither is a knob here
+# (see engines/liteparse/engine.py). ``max_pages`` 0 means the whole document.
+_DEFAULT_LITEPARSE_ENGINE: dict[str, Any] = {
+ "image_mode": "placeholder",
+ "extract_links": True,
+ "extract_images": False,
+ "max_pages": 0,
+}
+
# Built-in text-only engine slice. It deliberately has no knobs: it reuses
# DeepTutor's legacy text extractors for PDF / Office / text-like files.
_DEFAULT_TEXT_ONLY_ENGINE: dict[str, Any] = {}
@@ -179,6 +195,7 @@ DEFAULT_DOCUMENT_PARSING_SETTINGS: dict[str, Any] = {
DOCUMENT_PARSING_ENGINE_DOCLING: _DEFAULT_DOCLING_ENGINE,
DOCUMENT_PARSING_ENGINE_MARKITDOWN: _DEFAULT_MARKITDOWN_ENGINE,
DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: _DEFAULT_PYMUPDF4LLM_ENGINE,
+ DOCUMENT_PARSING_ENGINE_LITEPARSE: _DEFAULT_LITEPARSE_ENGINE,
},
}
@@ -801,6 +818,9 @@ class RuntimeSettingsService:
DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: self._normalize_pymupdf4llm_engine(
engines_in.get(DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM) or {}
),
+ DOCUMENT_PARSING_ENGINE_LITEPARSE: self._normalize_liteparse_engine(
+ engines_in.get(DOCUMENT_PARSING_ENGINE_LITEPARSE) or {}
+ ),
}
engine = _string(settings.get("engine")).lower().replace("-", "_").replace(" ", "_")
@@ -856,6 +876,17 @@ class RuntimeSettingsService:
),
}
+ def _normalize_liteparse_engine(self, settings: dict[str, Any]) -> dict[str, Any]:
+ image_mode = _string(settings.get("image_mode")).lower() or "placeholder"
+ if image_mode not in LITEPARSE_IMAGE_MODES:
+ image_mode = "placeholder"
+ return {
+ "image_mode": image_mode,
+ "extract_links": _coerce_bool(settings.get("extract_links"), True),
+ "extract_images": _coerce_bool(settings.get("extract_images"), False),
+ "max_pages": _coerce_clamped_int(settings.get("max_pages"), 0, 0, 100_000),
+ }
+
def _normalize_pymupdf4llm_engine(self, settings: dict[str, Any]) -> dict[str, Any]:
image_format = _string(settings.get("image_format")).lower() or "png"
if image_format not in _PYMUPDF4LLM_IMAGE_FORMATS:
@@ -1077,10 +1108,12 @@ __all__ = [
"DEFAULT_PAGEINDEX_SETTINGS",
"DEFAULT_SYSTEM_SETTINGS",
"DOCUMENT_PARSING_ENGINE_DOCLING",
+ "DOCUMENT_PARSING_ENGINE_LITEPARSE",
"DOCUMENT_PARSING_ENGINE_MARKITDOWN",
"DOCUMENT_PARSING_ENGINE_MINERU",
"DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM",
"DOCUMENT_PARSING_ENGINE_TEXT_ONLY",
+ "LITEPARSE_IMAGE_MODES",
"MINERU_MODE_CLOUD",
"MINERU_MODE_LOCAL",
"ChatAttachmentLimits",
diff --git a/deeptutor/services/parsing/engines/_install.py b/deeptutor/services/parsing/engines/_install.py
index 12dc365ea..2d25d7c56 100644
--- a/deeptutor/services/parsing/engines/_install.py
+++ b/deeptutor/services/parsing/engines/_install.py
@@ -42,6 +42,7 @@ ENGINE_PIP_SPECS: dict[str, list[str]] = {
"pymupdf4llm": ["pymupdf4llm>=0.0.17,<1.0"],
"markitdown": ["markitdown[pdf,docx,pptx,xlsx]>=0.0.1a2"],
"docling": ["docling>=2.0.0"],
+ "liteparse": ["liteparse>=2.11.1,<3.0"],
}
# Engine id -> console-script argv that downloads its model weights. The script
diff --git a/deeptutor/services/parsing/engines/factory.py b/deeptutor/services/parsing/engines/factory.py
index 8f7bc6ffa..e5d27aa3b 100644
--- a/deeptutor/services/parsing/engines/factory.py
+++ b/deeptutor/services/parsing/engines/factory.py
@@ -12,6 +12,7 @@ from typing import Any, Callable, Dict, List
from deeptutor.services.config.runtime_settings import (
DOCUMENT_PARSING_ENGINE_DOCLING,
+ DOCUMENT_PARSING_ENGINE_LITEPARSE,
DOCUMENT_PARSING_ENGINE_MARKITDOWN,
DOCUMENT_PARSING_ENGINE_MINERU,
DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,
@@ -46,6 +47,12 @@ def _markitdown_class():
return MarkItDownParser
+def _liteparse_class():
+ from .liteparse.engine import LiteParseParser
+
+ return LiteParseParser
+
+
def _pymupdf4llm_class():
from .pymupdf4llm.engine import PyMuPDF4LLMParser
@@ -59,6 +66,7 @@ _ENGINE_LOADERS: Dict[str, Callable[[], Any]] = {
DOCUMENT_PARSING_ENGINE_DOCLING: _docling_class,
DOCUMENT_PARSING_ENGINE_MARKITDOWN: _markitdown_class,
DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: _pymupdf4llm_class,
+ DOCUMENT_PARSING_ENGINE_LITEPARSE: _liteparse_class,
}
KNOWN_ENGINES = frozenset(_ENGINE_LOADERS)
@@ -106,6 +114,15 @@ _ENGINE_META: Dict[str, Dict[str, Any]] = {
),
"needs_local_models": False,
},
+ DOCUMENT_PARSING_ENGINE_LITEPARSE: {
+ "name": "LiteParse",
+ "description": (
+ "Fast, lightweight PDF parser with spatial text extraction. "
+ "Markdown output, optional image extraction. No model downloads. "
+ "Developed by LlamaIndex."
+ ),
+ "needs_local_models": False,
+ },
}
diff --git a/deeptutor/services/parsing/engines/liteparse/__init__.py b/deeptutor/services/parsing/engines/liteparse/__init__.py
new file mode 100644
index 000000000..bf124b6b0
--- /dev/null
+++ b/deeptutor/services/parsing/engines/liteparse/__init__.py
@@ -0,0 +1,7 @@
+"""liteparse document-parsing engine adapter."""
+
+from __future__ import annotations
+
+from .engine import LiteParseParser
+
+__all__ = ["LiteParseParser"]
diff --git a/deeptutor/services/parsing/engines/liteparse/config.py b/deeptutor/services/parsing/engines/liteparse/config.py
new file mode 100644
index 000000000..620e8351c
--- /dev/null
+++ b/deeptutor/services/parsing/engines/liteparse/config.py
@@ -0,0 +1,60 @@
+"""liteparse engine config (read-side adapter over the v2 settings slice)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from deeptutor.services.config.runtime_settings import (
+ DOCUMENT_PARSING_ENGINE_LITEPARSE,
+ LITEPARSE_IMAGE_MODES,
+ load_document_parsing_settings,
+)
+
+
+@dataclass(frozen=True)
+class LiteParseConfig:
+ """User-facing knobs for the liteparse engine.
+
+ ``output_format`` and the image output directory are deliberately absent:
+ the parse contract is "one Markdown file plus an ``images/`` dir in the
+ workdir" (see the engine docstring), so neither is the user's to choose.
+ """
+
+ # How images appear in the Markdown: "off" | "placeholder" | "embed".
+ image_mode: str = "placeholder"
+ # Render hyperlink annotations as [text](url) instead of bare anchor text.
+ extract_links: bool = True
+ # Write embedded images into the parse's ``images/`` dir.
+ extract_images: bool = False
+ # Stop after this many pages (0 = whole document).
+ max_pages: int = 0
+
+
+def _image_mode(value: object) -> str:
+ mode = str(value or "").strip().lower()
+ return mode if mode in LITEPARSE_IMAGE_MODES else "placeholder"
+
+
+def _max_pages(value: object) -> int:
+ try:
+ pages = int(value or 0)
+ except (TypeError, ValueError):
+ return 0
+ return pages if pages > 0 else 0
+
+
+def resolve_liteparse_config() -> LiteParseConfig:
+ slice_ = (
+ load_document_parsing_settings()
+ .get("engines", {})
+ .get(DOCUMENT_PARSING_ENGINE_LITEPARSE, {})
+ )
+ return LiteParseConfig(
+ image_mode=_image_mode(slice_.get("image_mode")),
+ extract_links=bool(slice_.get("extract_links", True)),
+ extract_images=bool(slice_.get("extract_images", False)),
+ max_pages=_max_pages(slice_.get("max_pages")),
+ )
+
+
+__all__ = ["LiteParseConfig", "resolve_liteparse_config"]
diff --git a/deeptutor/services/parsing/engines/liteparse/engine.py b/deeptutor/services/parsing/engines/liteparse/engine.py
new file mode 100644
index 000000000..fd367f130
--- /dev/null
+++ b/deeptutor/services/parsing/engines/liteparse/engine.py
@@ -0,0 +1,145 @@
+"""LiteParse engine adapter implementing the ``Parser`` protocol.
+
+LiteParse (run-llama/liteparse) is a Rust-backed PDF/Office/image parser: no
+model weights, no CUDA, in-process. Like the PyMuPDF4LLM engine it can extract
+embedded images, so it follows the same workdir contract — one
+``<stem>.md`` plus an ``images/`` dir with portable ``images/<name>`` links
+(the MinerU/Docling asset convention the cache loader expects).
+
+Two of LiteParse's own defaults are overridden here rather than exposed:
+``output_format`` is pinned to Markdown (the workdir contract is a ``.md``
+file, so JSON or plain text would produce a mislabelled document), and
+``image_output_dir`` is pinned to the workdir's ``images/`` (anywhere else is
+invisible to the cache loader).
+"""
+
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+import re
+from typing import Any, Callable, Optional
+
+from ...base import ReadinessReport
+from ...signature import ParserSignature
+from ...types import ParserError
+from .._versions import package_version
+from .config import LiteParseConfig, resolve_liteparse_config
+
+# Document and image types LiteParse decodes natively. Office formats and bare
+# images are converted internally before parsing.
+_SUPPORTED = frozenset(
+ {".pdf", ".docx", ".pptx", ".xlsx", ".png", ".jpg", ".jpeg", ".gif", ".webp"}
+)
+
+# LiteParse references extracted images by bare file name — ``![](img_p1_1.png)``
+# — so links are rewritten to ``images/<name>`` to match the asset convention.
+_IMAGE_LINK_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
+
+
+class LiteParseParser:
+ """PDF/Office/image → Markdown via liteparse (no models, optional images)."""
+
+ name = "liteparse"
+ needs_local_models = False
+
+ @classmethod
+ def is_available(cls) -> bool:
+ return importlib.util.find_spec("liteparse") is not None
+
+ def resolve_config(self) -> LiteParseConfig:
+ return resolve_liteparse_config()
+
+ def supported_formats(self) -> frozenset[str]:
+ return _SUPPORTED
+
+ def signature(self, config: LiteParseConfig) -> ParserSignature:
+ return ParserSignature.build(
+ "liteparse",
+ package_version("liteparse"),
+ {
+ "image_mode": config.image_mode,
+ "extract_links": config.extract_links,
+ "extract_images": config.extract_images,
+ "max_pages": config.max_pages,
+ },
+ )
+
+ def is_ready(self, config: LiteParseConfig) -> ReadinessReport:
+ if not self.is_available():
+ return ReadinessReport(
+ ready=False,
+ reason="not_configured",
+ message="liteparse isn't installed (pip install deeptutor[parse-liteparse]).",
+ )
+ return ReadinessReport(ready=True)
+
+ def parse(
+ self,
+ source_path: Path,
+ workdir: Path,
+ *,
+ config: LiteParseConfig,
+ on_output: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ from liteparse import LiteParse
+
+ source_path = Path(source_path)
+ workdir = Path(workdir)
+ if on_output:
+ on_output(f"Converting {source_path.name} via LiteParse…")
+
+ images_dir = workdir / "images"
+ kwargs: dict[str, Any] = {
+ "output_format": "markdown",
+ "image_mode": config.image_mode,
+ "extract_links": config.extract_links,
+ "quiet": True,
+ # A systemic OCR failure aborts the whole parse by default. Prefer
+ # the natively recovered text over losing the document outright —
+ # the ingestion pipeline treats a ParserError as "no content".
+ "ocr_failure_fatal": False,
+ }
+ if config.extract_images:
+ images_dir.mkdir(parents=True, exist_ok=True)
+ kwargs["extract_images"] = True
+ kwargs["image_output_dir"] = str(images_dir)
+ if config.max_pages > 0:
+ kwargs["max_pages"] = config.max_pages
+
+ try:
+ result = LiteParse(**kwargs).parse(str(source_path))
+ except Exception as exc: # noqa: BLE001 - surface as a parser error
+ raise ParserError(f"LiteParse failed to convert {source_path.name}: {exc}") from exc
+
+ markdown = str(getattr(result, "text", "") or "")
+ if config.extract_images:
+ markdown = self._portable_image_links(markdown, getattr(result, "images", None))
+ # Drop the images dir if nothing was actually extracted, so the
+ # cache loader doesn't report an empty asset_dir.
+ if images_dir.is_dir() and not any(images_dir.iterdir()):
+ images_dir.rmdir()
+
+ (workdir / f"{source_path.stem}.md").write_text(markdown, encoding="utf-8")
+
+ @staticmethod
+ def _portable_image_links(markdown: str, images: Any) -> str:
+ """Prefix links naming an extracted image with the ``images/`` dir.
+
+ Only names LiteParse reports as extracted are rewritten, so a link the
+ document itself carried to an unrelated URL is left alone.
+ """
+ names = {
+ name for image in (images or []) if (name := str(getattr(image, "name", "") or ""))
+ }
+ if not names:
+ return markdown
+
+ def _repl(match: re.Match[str]) -> str:
+ alt, target = match.group(1), match.group(2)
+ return f"![{alt}](images/{target})" if target in names else match.group(0)
+
+ return _IMAGE_LINK_RE.sub(_repl, markdown)
+
+
+__all__ = ["LiteParseParser"]
diff --git a/pyproject.toml b/pyproject.toml
index f689fea7e..845ba35d5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -167,10 +167,15 @@ parse-docling = ["docling>=2.0.0"]
# pulls a heavy dep, downloads a model, and can't extract images — defeating the
# "lightweight, runs on a Pi, extracts images" point of this engine.
parse-pymupdf4llm = ["pymupdf4llm>=0.0.17,<1.0"]
+# LiteParse ships its parser as a compiled Rust extension, so a major bump
+# can change both the Python API and the Markdown it emits (which the parse
+# cache keys on). Pin the major like parse-pymupdf4llm does.
+parse-liteparse = ["liteparse>=2.11.1,<3.0"]
parse = [
"deeptutor[parse-markitdown]",
"deeptutor[parse-docling]",
"deeptutor[parse-pymupdf4llm]",
+ "deeptutor[parse-liteparse]",
]
# Legacy alias kept for one release: `pip install deeptutor[tutorbot]`.
diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.py
index 414056e50..fdb8f109b 100644
--- a/tests/services/parsing/test_engines.py
+++ b/tests/services/parsing/test_engines.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from pathlib import Path
import zipfile
import pytest
@@ -15,6 +16,7 @@ def test_known_engines() -> None:
"docling",
"markitdown",
"pymupdf4llm",
+ "liteparse",
}
@@ -26,6 +28,7 @@ def test_list_engines_reports_metadata_and_availability() -> None:
"docling",
"markitdown",
"pymupdf4llm",
+ "liteparse",
}
assert engines["text_only"]["available"] is True
assert engines["text_only"]["needs_local_models"] is False
@@ -35,6 +38,7 @@ def test_list_engines_reports_metadata_and_availability() -> None:
assert engines["mineru"]["needs_local_models"] is True
assert engines["markitdown"]["needs_local_models"] is False
assert engines["pymupdf4llm"]["needs_local_models"] is False
+ assert engines["liteparse"]["needs_local_models"] is False
def test_get_parser_unknown_raises() -> None:
@@ -198,6 +202,146 @@ def test_pymupdf4llm_no_images_leaves_no_asset_dir(tmp_path) -> None:
assert not (workdir / "images").exists()
+def test_liteparse_signature_tracks_knobs() -> None:
+ parser = factory.get_parser("liteparse")
+ from deeptutor.services.parsing.engines.liteparse.config import LiteParseConfig
+
+ base = parser.signature(LiteParseConfig()).hash()
+ with_images = parser.signature(LiteParseConfig(extract_images=True)).hash()
+ capped = parser.signature(LiteParseConfig(max_pages=5)).hash()
+ assert base != with_images
+ assert base != capped
+
+
+def test_liteparse_readiness_reflects_install() -> None:
+ parser = factory.get_parser("liteparse")
+ # Name lookup is case-insensitive (the metadata label is mixed-case).
+ assert type(factory.get_parser("LiteParse")) is type(parser)
+ report = parser.is_ready(parser.resolve_config())
+ if parser.is_available():
+ assert report.ready is True
+ else:
+ assert report.reason == "not_configured"
+ assert "liteparse" in report.message
+
+
+def test_liteparse_config_rejects_unknown_image_mode_and_coerces_strings() -> None:
+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService
+
+ normalized = RuntimeSettingsService._normalize_liteparse_engine(
+ None, # type: ignore[arg-type] - pure function of its argument
+ {
+ "image_mode": "IMAGINARY",
+ # Settings round-trip through JSON/env can deliver strings; a bare
+ # bool() would read "false" as True.
+ "extract_links": "false",
+ "extract_images": "true",
+ "max_pages": "-3",
+ },
+ )
+ assert normalized == {
+ "image_mode": "placeholder",
+ "extract_links": False,
+ "extract_images": True,
+ "max_pages": 0,
+ }
+
+
+def _install_fake_liteparse(monkeypatch, *, image_names: tuple[str, ...] = ()) -> dict:
+ """Stand in for the compiled ``liteparse`` package, recording its kwargs."""
+ import sys
+ import types
+
+ seen: dict = {}
+
+ class _FakeImage:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+ class _FakeResult:
+ def __init__(self, text: str, images: list) -> None:
+ self.text = text
+ self.images = images
+
+ class _FakeLiteParse:
+ def __init__(self, **kwargs) -> None:
+ seen["kwargs"] = kwargs
+
+ def parse(self, path: str):
+ seen["path"] = path
+ body = " ".join(f"![]({name})" for name in image_names)
+ out_dir = seen["kwargs"].get("image_output_dir")
+ if out_dir:
+ for name in image_names:
+ (Path(out_dir) / name).write_bytes(b"\x89PNG")
+ return _FakeResult(f"# Doc\n\n{body}\n", [_FakeImage(n) for n in image_names])
+
+ module = types.ModuleType("liteparse")
+ module.LiteParse = _FakeLiteParse # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "liteparse", module)
+ return seen
+
+
+def test_liteparse_pins_markdown_output_and_images_dir(tmp_path, monkeypatch) -> None:
+ """The workdir contract, not the library's defaults, decides these two."""
+ from deeptutor.services.parsing.engines.liteparse.config import LiteParseConfig
+
+ seen = _install_fake_liteparse(monkeypatch, image_names=("img_p1_1.png",))
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ source = tmp_path / "paper.pdf"
+ source.write_bytes(b"%PDF-1.4")
+
+ factory.get_parser("liteparse").parse(
+ source, workdir, config=LiteParseConfig(extract_images=True, max_pages=7)
+ )
+
+ # LiteParse defaults output_format to "json"; a .md holding JSON would be
+ # a mislabelled document, so the engine pins Markdown.
+ assert seen["kwargs"]["output_format"] == "markdown"
+ assert seen["kwargs"]["image_output_dir"] == str(workdir / "images")
+ assert seen["kwargs"]["max_pages"] == 7
+ # A systemic OCR failure must degrade, not lose the whole document.
+ assert seen["kwargs"]["ocr_failure_fatal"] is False
+
+ markdown = (workdir / "paper.md").read_text(encoding="utf-8")
+ # Bare ``![](img_p1_1.png)`` is invalid once the file lands in images/.
+ assert "![](images/img_p1_1.png)" in markdown
+ assert (workdir / "images" / "img_p1_1.png").exists()
+
+
+def test_liteparse_without_images_leaves_no_asset_dir(tmp_path, monkeypatch) -> None:
+ from deeptutor.services.parsing.engines.liteparse.config import LiteParseConfig
+
+ seen = _install_fake_liteparse(monkeypatch)
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ source = tmp_path / "paper.pdf"
+ source.write_bytes(b"%PDF-1.4")
+
+ factory.get_parser("liteparse").parse(
+ source, workdir, config=LiteParseConfig(extract_images=False)
+ )
+
+ assert "extract_images" not in seen["kwargs"]
+ assert "image_output_dir" not in seen["kwargs"]
+ # An empty asset dir would make the cache loader report assets that
+ # aren't there.
+ assert not (workdir / "images").exists()
+
+
+def test_liteparse_leaves_foreign_image_links_alone(tmp_path, monkeypatch) -> None:
+ """Only names LiteParse reports as extracted get the images/ prefix."""
+ from deeptutor.services.parsing.engines.liteparse.engine import LiteParseParser
+
+ rewritten = LiteParseParser._portable_image_links(
+ "![a](img_p1_1.png) ![b](https://example.com/logo.png)",
+ [type("I", (), {"name": "img_p1_1.png"})()],
+ )
+ assert "![a](images/img_p1_1.png)" in rewritten
+ assert "![b](https://example.com/logo.png)" in rewritten
+
+
def test_install_manager_spec_allowlist() -> None:
from deeptutor.services.parsing.engines._install import (
ENGINE_PIP_SPECS,
@@ -205,8 +349,9 @@ def test_install_manager_spec_allowlist() -> None:
)
# Only optional pip-backed engines are installable; built-in / external are not.
- assert installable_engines() == {"pymupdf4llm", "markitdown", "docling"}
+ assert installable_engines() == {"pymupdf4llm", "markitdown", "docling", "liteparse"}
assert ENGINE_PIP_SPECS["pymupdf4llm"] == ["pymupdf4llm>=0.0.17,<1.0"]
+ assert ENGINE_PIP_SPECS["liteparse"] == ["liteparse>=2.11.1,<3.0"]
assert "text_only" not in ENGINE_PIP_SPECS
assert "mineru" not in ENGINE_PIP_SPECS
@@ -221,6 +366,7 @@ def test_model_download_allowlist() -> None:
assert model_downloadable_engines() == {"docling"}
assert ENGINE_MODEL_DOWNLOADERS["docling"][0] == "docling-tools"
assert "pymupdf4llm" not in ENGINE_MODEL_DOWNLOADERS
+ assert "liteparse" not in ENGINE_MODEL_DOWNLOADERS
def test_resolve_model_downloader_unknown_engine() -> None:
diff --git a/web/app/(utility)/settings/document-parsing/page.tsx b/web/app/(utility)/settings/document-parsing/page.tsx
index 335e45fa2..61aa408ce 100644
--- a/web/app/(utility)/settings/document-parsing/page.tsx
+++ b/web/app/(utility)/settings/document-parsing/page.tsx
@@ -38,6 +38,7 @@ const PIP_HINT: Record<string, string> = {
docling: "pip install deeptutor[parse-docling]",
markitdown: "pip install deeptutor[parse-markitdown]",
pymupdf4llm: "pip install deeptutor[parse-pymupdf4llm]",
+ liteparse: "pip install deeptutor[parse-liteparse]",
};
export default function DocumentParsingSettingsPage() {
@@ -235,6 +236,21 @@ export default function DocumentParsingSettingsPage() {
}
/>
)}
+
+ {data.engine === "liteparse" && (
+ <LiteParsePanel
+ slice={data.engines.liteparse || {}}
+ available={
+ data.available_engines.find((e) => e.id === "liteparse")
+ ?.available ?? false
+ }
+ busy={busy}
+ onInstalled={load}
+ onSave={(patch) =>
+ putDocumentParsing({ engines: { liteparse: patch } })
+ }
+ />
+ )}
</>
)}
</div>
@@ -536,6 +552,105 @@ function PyMuPDF4LLMPanel({
);
}
+function LiteParsePanel({
+ slice,
+ available,
+ busy,
+ onInstalled,
+ onSave,
+}: {
+ slice: Record<string, unknown>;
+ available: boolean;
+ busy: boolean;
+ onInstalled: () => void;
+ onSave: (patch: Record<string, unknown>) => void;
+}) {
+ const { t } = useTranslation();
+ const imageMode =
+ typeof slice.image_mode === "string" ? slice.image_mode : "placeholder";
+ const extractLinks = slice.extract_links !== false;
+ const extractImages = Boolean(slice.extract_images);
+ const maxPages = typeof slice.max_pages === "number" ? slice.max_pages : 0;
+
+ if (!available) {
+ return (
+ <NotInstalledSection
+ engineId="liteparse"
+ title={t("LiteParse")}
+ onInstalled={onInstalled}
+ />
+ );
+ }
+
+ return (
+ <SettingSection
+ title={t("LiteParse")}
+ description={t(
+ "Fast Rust-backed PDF/Office/image parser from LlamaIndex. Markdown output, no model downloads.",
+ )}
+ >
+ <SettingRow
+ title={t("Image mode")}
+ description={t("How images are represented in the output.")}
+ control={
+ <select
+ className={nativeSelectClass + " w-32"}
+ value={imageMode}
+ disabled={busy}
+ onChange={(e) => onSave({ image_mode: e.target.value })}
+ >
+ {["placeholder", "off", "embed"].map((m) => (
+ <option key={m} className={selectOptionClass} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ }
+ />
+ <SettingRow
+ title={t("Extract links")}
+ description={t("Render [text](url) links in markdown output.")}
+ control={
+ <Toggle
+ checked={extractLinks}
+ disabled={busy}
+ onChange={(v) => onSave({ extract_links: v })}
+ />
+ }
+ />
+ <SettingRow
+ title={t("Extract images")}
+ description={t("Save embedded images alongside the parsed Markdown.")}
+ control={
+ <Toggle
+ checked={extractImages}
+ disabled={busy}
+ onChange={(v) => onSave({ extract_images: v })}
+ />
+ }
+ />
+ <SettingRow
+ title={t("Max pages")}
+ description={t("0 = unlimited. Limit pages parsed per document.")}
+ control={
+ <input
+ type="number"
+ min={0}
+ step={1}
+ value={maxPages}
+ disabled={busy}
+ onChange={(e) => {
+ const v = Number(e.target.value);
+ if (Number.isFinite(v) && v >= 0) onSave({ max_pages: v });
+ }}
+ className="w-24 rounded-lg border border-[var(--border)] bg-transparent px-2 py-1 text-[12px] text-[var(--foreground)]"
+ />
+ }
+ />
+ </SettingSection>
+ );
+}
+
type JobKind = "install" | "models";
type JobStatus = {