mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 20:11:38 +08:00
Merge pull request #1069 from NoxsMedia/codex/nox-3-lightrag-native
This commit is contained in:
@@ -170,6 +170,10 @@ jobs:
|
||||
pip install -r requirements/partners.txt
|
||||
pip install pytest pytest-asyncio
|
||||
|
||||
- name: Install optional LightRAG SDK
|
||||
if: matrix.python-version == '3.12'
|
||||
run: pip install "lightrag-hku==1.5.7rc2"
|
||||
|
||||
- name: Create minimal runtime config
|
||||
run: |
|
||||
mkdir -p data/user/settings
|
||||
|
||||
@@ -26,6 +26,8 @@ deeptutor/services/rag/eg_only_for_analysis/
|
||||
*.synctex.gz
|
||||
*.pdf
|
||||
!demo/*.pdf
|
||||
!tests/fixtures/lightrag_bridge/original.pdf
|
||||
!tests/fixtures/lightrag_bridge/mineru-v2-current/*_origin.pdf
|
||||
|
||||
# ============================================
|
||||
# Python Related
|
||||
|
||||
@@ -277,9 +277,11 @@ python -m pip install --upgrade pip
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Optional install extras</b> — dev / partners / matrix / math-animator</summary>
|
||||
<summary><b>Optional install extras</b> — RAG engines / dev / partners / matrix / math-animator</summary>
|
||||
|
||||
```bash
|
||||
pip install -e ".[rag-lightrag]" # Built-in LightRAG engine (exact supported SDK)
|
||||
pip install -e ".[graphrag]" # Microsoft GraphRAG engine
|
||||
pip install -e ".[dev]" # tests/lint tools
|
||||
pip install -e ".[partners]" # Partner IM channel SDKs
|
||||
pip install -e ".[matrix]" # Matrix channel without E2EE/libolm
|
||||
@@ -602,6 +604,8 @@ Knowledge bases are the document collections behind RAG — they ground Chat tur
|
||||
|
||||
Creating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). A KB can also track **GitHub repositories** (repo, branch, glob) or **documentation-site URLs** (bounded crawl depth and page count); on-demand sync hash-diffs added, changed, and removed content so followed documentation stays current without re-uploading. Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, or LiteParse — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. Docling can also run in **remote** mode against a Docling Serve server (no local install or models needed), configured via **Settings → Document Parsing** (`mode=remote`, a server base URL, and an optional API key) or the `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables. Tika is remote-only and points at an Apache Tika server (`TIKA_SERVER_URL`). The CLI mirrors the lifecycle with `list/info/create/add/search/set-default/delete`, source add/remove commands, `list-sources`, and `sync`.
|
||||
|
||||
The built-in LightRAG engine is installed with `pip install 'deeptutor[rag-lightrag]'`. That extra contains the supported LightRAG SDK but does not install MinerU. Choose MinerU independently in Document Parsing and either configure its cloud mode or install its local CLI when structured PDF parsing is wanted; text-only and the other parsing engines do not require MinerU.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
@@ -289,13 +289,11 @@ DEFAULT_GRAPHRAG_SETTINGS: dict[str, Any] = {
|
||||
"dynamic_community_selection": False,
|
||||
}
|
||||
|
||||
# LightRAG retrieval + indexing knobs (HKUDS/LightRAG via RAG-Anything). ``top_k``
|
||||
# LightRAG retrieval + indexing knobs (HKUDS/LightRAG native SDK). ``top_k``
|
||||
# is the number of entities/relations the query pulls; ``response_type`` mirrors
|
||||
# GraphRAG's. These ride into ``QueryParam`` via the engine's aquery() call;
|
||||
# wiring is defensive (an older RAG-Anything that rejects a kwarg degrades to a
|
||||
# mode-only query). ``max_concurrent_files`` maps to RAGAnythingConfig's batch
|
||||
# knob; ``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride into
|
||||
# LightRAG's own constructor via RAGAnything's ``lightrag_kwargs`` passthrough.
|
||||
# GraphRAG's. These ride into ``QueryParam`` and the pinned SDK constructor.
|
||||
# ``max_concurrent_files`` sizes the native parser worker pool after DeepTutor
|
||||
# has frozen each ParseService result; pre-parsing itself remains serial.
|
||||
DEFAULT_LIGHTRAG_SETTINGS: dict[str, Any] = {
|
||||
"version": 1,
|
||||
"top_k": 60,
|
||||
|
||||
@@ -127,7 +127,7 @@ def _absolutize_img_paths(blocks: list[dict], content_dir: Path) -> list[dict]:
|
||||
"""Anchor relative ``img_path`` entries at ``content_dir``.
|
||||
|
||||
Engines (MinerU especially) emit ``img_path`` values like ``images/x.png``
|
||||
relative to the content-list file. Consumers such as RAG-Anything resolve
|
||||
relative to the content-list file. Consumers such as LightRAG resolve
|
||||
them against their own working directory instead, so the images are never
|
||||
found (issue #624). The cached JSON stays relative — paths are rewritten
|
||||
only on load, keeping the cache dir relocatable.
|
||||
|
||||
@@ -9,7 +9,7 @@ today:
|
||||
* ``graphrag`` — local knowledge-graph retrieval (microsoft/graphrag);
|
||||
optional dependency, ``pip install 'deeptutor[graphrag]'``.
|
||||
* ``lightrag`` — graph + vector retrieval (HKUDS/LightRAG, multimodal
|
||||
via RAG-Anything); optional dependency,
|
||||
via the LightRAG native pipeline); optional dependency,
|
||||
``pip install 'deeptutor[rag-lightrag]'``.
|
||||
* ``lightrag-server`` — retrieval offloaded to an external, standalone
|
||||
LightRAG server the user runs. No local index: each
|
||||
|
||||
@@ -118,11 +118,50 @@ def _next_flat_version_dir(kb_dir: Path) -> Path:
|
||||
return kb_dir / f"{VERSION_PREFIX}{(max(existing) if existing else 0) + 1}"
|
||||
|
||||
|
||||
def _native_lightrag_output_ready(version_dir: Path, meta: dict[str, Any]) -> bool:
|
||||
workspace = str(meta.get("workspace") or "").strip()
|
||||
if workspace:
|
||||
workspace_path = Path(workspace)
|
||||
if workspace_path.is_absolute() or workspace_path.name != workspace:
|
||||
return False
|
||||
status_path = version_dir / workspace / "kv_store_doc_status.json"
|
||||
else:
|
||||
# Transitional/test layouts may still keep the status store flat.
|
||||
status_path = version_dir / "kv_store_doc_status.json"
|
||||
payload = _read_json(status_path)
|
||||
if not payload:
|
||||
return False
|
||||
return any(
|
||||
isinstance(row, dict)
|
||||
and (str(row.get("status") or "").lower() == "processed" or bool(row.get("chunks_list")))
|
||||
for row in payload.values()
|
||||
)
|
||||
|
||||
|
||||
def _entry_from_flat_version(version_dir: Path) -> dict[str, Any]:
|
||||
meta = _read_json(version_dir / META_FILENAME) or {}
|
||||
stored_meta = _read_json(version_dir / META_FILENAME)
|
||||
meta = dict(stored_meta or {})
|
||||
meta.setdefault("version", version_dir.name)
|
||||
meta.setdefault("signature", meta.get("signature") or version_dir.name)
|
||||
meta["ready"] = _is_storage_ready(version_dir)
|
||||
has_provider_output = _is_storage_ready(version_dir)
|
||||
# Legacy flat stores from other providers predate metadata, so their
|
||||
# established readiness rule remains output-based. A native LightRAG
|
||||
# candidate is identifiable before publication by its doc-status/ingress
|
||||
# files and must fail closed until schema-2 metadata is atomically written.
|
||||
is_unpublished_lightrag_candidate = stored_meta is None and (
|
||||
(version_dir / "kv_store_doc_status.json").exists()
|
||||
or (version_dir / "deeptutor_ingress").exists()
|
||||
)
|
||||
ready = has_provider_output and not is_unpublished_lightrag_candidate
|
||||
if stored_meta is not None and stored_meta.get("provider") == "lightrag":
|
||||
adapter_schema = stored_meta.get("lightrag_adapter_schema")
|
||||
if adapter_schema is not None:
|
||||
ready = bool(
|
||||
adapter_schema == 2
|
||||
and stored_meta.get("state") == "published"
|
||||
and _native_lightrag_output_ready(version_dir, stored_meta)
|
||||
)
|
||||
meta["ready"] = ready
|
||||
meta["storage_path"] = str(version_dir)
|
||||
meta["version_path"] = str(version_dir)
|
||||
meta["layout"] = "flat"
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
"""LightRAG / RAG-Anything knowledge-base engine.
|
||||
"""Native LightRAG knowledge-base engine.
|
||||
|
||||
A graph-based RAG provider built on HKUDS/LightRAG (multimodal via
|
||||
HKUDS/RAG-Anything). It consumes DeepTutor's shared parse layer for document
|
||||
parsing and exposes LightRAG's native query modes (naive/local/global/hybrid/mix)
|
||||
through the per-KB ``search_mode``.
|
||||
A graph-based RAG provider built directly on HKUDS/LightRAG. It consumes
|
||||
DeepTutor's shared parse layer for document parsing and exposes LightRAG's
|
||||
native query modes (naive/local/global/hybrid/mix) through the per-KB
|
||||
``search_mode``.
|
||||
|
||||
Modules:
|
||||
|
||||
* ``block_policy`` — versioned MinerU block classification before indexing.
|
||||
* ``config`` — availability + mode helpers + the LLM/vision/embedding adapters.
|
||||
* ``storage`` — per-KB version-dir layout + readiness marker.
|
||||
* ``engine`` — the ONLY module importing ``raganything``/``lightrag``.
|
||||
* ``engine`` — constructs the exact supported LightRAG SDK version.
|
||||
* ``pipeline`` — :class:`LightRagPipeline` implementing the ``RAGPipeline`` contract.
|
||||
"""
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Versioned MinerU block policy for LightRAG indexing.
|
||||
|
||||
MinerU's legacy ``content_list.json`` mixes semantic document content with
|
||||
page-layout helpers. DeepTutor retains the raw parser cache for audit and
|
||||
derives an independent, deep-copied list for indexing so RAG-Anything never
|
||||
needs to decide which parser blocks are semantic.
|
||||
page-layout helpers. DeepTutor retains the raw parser cache for audit and
|
||||
derives an independent, deep-copied list before the native LightRAG Sidecar
|
||||
bridge decides which parser blocks are semantic.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
"""Bridge DeepTutor's runtime config into LightRAG / RAG-Anything.
|
||||
|
||||
LightRAG (HKUDS/LightRAG) is a text knowledge-graph RAG engine; its multimodal
|
||||
story is RAG-Anything (HKUDS/RAG-Anything), built on top of LightRAG. The
|
||||
``lightrag`` provider uses RAG-Anything so multimodal content (the parse layer's
|
||||
``content_list``) becomes graph entities, while text-only documents fall back to
|
||||
a plain text insert.
|
||||
"""Bridge DeepTutor runtime configuration into the LightRAG 1.5 native SDK.
|
||||
|
||||
This module is the decoupling seam: it exposes availability + mode helpers and
|
||||
builds the three adapters LightRAG needs from DeepTutor's already-resolved LLM /
|
||||
embedding clients. It imports neither RAG-Anything nor LightRAG at module load —
|
||||
the adapter builders import ``lightrag.utils`` lazily (only the embedding wrapper
|
||||
needs it), and engine construction lives in ``engine.py``.
|
||||
builds the three adapters LightRAG needs from DeepTutor's already-resolved LLM,
|
||||
vision, and embedding clients. LightRAG imports remain lazy so every other RAG
|
||||
provider can import without the optional extra installed.
|
||||
|
||||
Decoupling notes:
|
||||
* ``llm_model_func`` / ``vision_model_func`` wrap DeepTutor's unified model
|
||||
@@ -45,7 +38,7 @@ DEFAULT_MODE = "hybrid"
|
||||
# Conservative cap for the embedding wrapper when the model doesn't advertise one.
|
||||
_DEFAULT_MAX_TOKEN_SIZE = 8192
|
||||
|
||||
# Keep retries at the LightRAG adapter boundary so RAG-Anything receives one
|
||||
# Keep retries at the LightRAG adapter boundary so the SDK receives one
|
||||
# predictable policy for both text and vision calls. Provider retries are disabled
|
||||
# on every attempt to prevent the two retry layers from multiplying.
|
||||
_ADAPTER_MAX_ATTEMPTS = 3
|
||||
@@ -59,7 +52,7 @@ _HTTP_STATUS_PATTERN = re.compile(
|
||||
|
||||
|
||||
class LightRagNotAvailableError(RuntimeError):
|
||||
"""Raised when the optional ``raganything`` dependency is not installed."""
|
||||
"""Raised when the optional ``lightrag-hku`` dependency is not installed."""
|
||||
|
||||
|
||||
class LightRagNotConfiguredError(RuntimeError):
|
||||
@@ -138,12 +131,12 @@ async def _run_adapter_with_retry(
|
||||
|
||||
|
||||
def is_lightrag_available() -> bool:
|
||||
"""True when RAG-Anything (which bundles LightRAG) can be imported.
|
||||
"""True when the native LightRAG SDK can be imported.
|
||||
|
||||
Opt-in extra: ``pip install 'deeptutor[rag-lightrag]'``. Until installed the
|
||||
provider is hidden / blocked in the UI.
|
||||
"""
|
||||
return importlib.util.find_spec("raganything") is not None
|
||||
return importlib.util.find_spec("lightrag") is not None
|
||||
|
||||
|
||||
def normalize_mode(mode: str | None) -> str:
|
||||
@@ -157,12 +150,7 @@ def normalize_mode(mode: str | None) -> str:
|
||||
|
||||
|
||||
def query_kwargs_from_settings() -> dict:
|
||||
"""Extra ``aquery`` kwargs (top_k, response_type) from runtime settings.
|
||||
|
||||
Returned as a dict so the engine can pass them through to LightRAG's
|
||||
``QueryParam`` and gracefully drop them if an older RAG-Anything rejects a
|
||||
kwarg. Empty on any read error.
|
||||
"""
|
||||
"""``QueryParam`` values from runtime settings."""
|
||||
try:
|
||||
from deeptutor.services.config import load_lightrag_settings
|
||||
|
||||
@@ -176,34 +164,18 @@ def query_kwargs_from_settings() -> dict:
|
||||
|
||||
|
||||
def indexing_kwargs_from_settings() -> dict:
|
||||
"""``RAGAnythingConfig`` batch-processing knobs from runtime settings.
|
||||
|
||||
Only ``max_concurrent_files`` is exposed for now (issue #640); the config
|
||||
object accepts several other batch/context knobs we deliberately leave on
|
||||
RAG-Anything's own defaults. Empty on any read error, so a bad settings
|
||||
file falls back to RAG-Anything's built-in default of 1.
|
||||
"""
|
||||
"""Native parser-pool knobs from runtime settings."""
|
||||
try:
|
||||
from deeptutor.services.config import load_lightrag_settings
|
||||
|
||||
settings = load_lightrag_settings()
|
||||
return {"max_concurrent_files": int(settings.get("max_concurrent_files", 1))}
|
||||
return {"max_parallel_parse_native": int(settings.get("max_concurrent_files", 1))}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def lightrag_kwargs_from_settings() -> dict:
|
||||
"""Extra kwargs forwarded to LightRAG's own constructor via RAG-Anything's
|
||||
``lightrag_kwargs`` passthrough.
|
||||
|
||||
``llm_model_max_async`` bounds how many concurrent LLM calls LightRAG's
|
||||
internal priority queue issues (covers both query and entity-extraction
|
||||
traffic, since both ride the same wrapped ``llm_model_func``).
|
||||
``entity_extract_max_gleaning`` controls how many extra extraction passes
|
||||
LightRAG runs per chunk to recover entities/relations the first pass
|
||||
missed. Empty on any read error, so a bad settings file falls back to
|
||||
LightRAG's own built-in defaults.
|
||||
"""
|
||||
def constructor_kwargs_from_settings() -> dict:
|
||||
"""Direct LightRAG constructor knobs from runtime settings."""
|
||||
try:
|
||||
from deeptutor.services.config import load_lightrag_settings
|
||||
|
||||
@@ -248,7 +220,7 @@ def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):
|
||||
|
||||
|
||||
def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
|
||||
"""Wrap DeepTutor's vision-capable callable for RAG-Anything's image step."""
|
||||
"""Map rc2 ``image_inputs`` to DeepTutor's vision callable."""
|
||||
from deeptutor.services.llm import get_llm_client
|
||||
|
||||
base = get_llm_client().get_vision_model_func()
|
||||
@@ -257,10 +229,19 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
|
||||
prompt="",
|
||||
system_prompt=None,
|
||||
history_messages=None,
|
||||
image_data=None,
|
||||
image_inputs=None,
|
||||
messages=None,
|
||||
**_ignored,
|
||||
):
|
||||
if not isinstance(image_inputs, list) or len(image_inputs) != 1:
|
||||
raise ValueError("LightRAG vision requests must contain exactly one image input")
|
||||
payload = image_inputs[0]
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("LightRAG vision image input must be an object")
|
||||
image_data = payload.get("base64")
|
||||
if not isinstance(image_data, str) or not image_data.strip():
|
||||
raise ValueError("LightRAG vision image input requires a non-empty base64 value")
|
||||
|
||||
async def request():
|
||||
return await base(
|
||||
prompt or "",
|
||||
@@ -269,12 +250,6 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
|
||||
image_data=image_data,
|
||||
messages=messages,
|
||||
max_retries=0,
|
||||
# Never strip the image and answer anyway. The provider's
|
||||
# stage-2 fallback exists to salvage a text answer from a model
|
||||
# that turns out not to take images, but here the *whole point*
|
||||
# of the call is the image: a description produced without it is
|
||||
# invented, and it would be indexed as fact. Fail the image
|
||||
# instead, and let the caller log and skip it.
|
||||
allow_image_fallback=False,
|
||||
)
|
||||
|
||||
@@ -283,6 +258,16 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
|
||||
return vision_model_func
|
||||
|
||||
|
||||
def vision_model_available() -> bool:
|
||||
"""Return whether the active DeepTutor model is explicitly vision-capable."""
|
||||
try:
|
||||
from deeptutor.services.llm import get_llm_client
|
||||
|
||||
return bool(get_llm_client().supports_multimodal_images())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):
|
||||
"""Wrap DeepTutor's embedding client in LightRAG's ``EmbeddingFunc``."""
|
||||
from lightrag.utils import EmbeddingFunc
|
||||
@@ -334,8 +319,9 @@ __all__ = [
|
||||
"normalize_mode",
|
||||
"query_kwargs_from_settings",
|
||||
"indexing_kwargs_from_settings",
|
||||
"lightrag_kwargs_from_settings",
|
||||
"constructor_kwargs_from_settings",
|
||||
"build_llm_model_func",
|
||||
"build_vision_model_func",
|
||||
"vision_model_available",
|
||||
"build_embedding_func",
|
||||
]
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
"""Thin adapter over the RAG-Anything / LightRAG Python API.
|
||||
|
||||
This is the ONLY module that imports ``raganything`` / ``lightrag``. Everything
|
||||
version-sensitive lives here, so an API shift between releases is a one-file
|
||||
fix. All imports are lazy so DeepTutor runs fine without the optional dependency
|
||||
installed.
|
||||
|
||||
A RAG-Anything instance is built from DeepTutor's LLM/vision/embedding adapters
|
||||
(see ``config.py``) over a per-KB ``working_dir``. Documents are inserted as a
|
||||
MinerU-style ``content_list`` (produced upstream by the parse layer), so the
|
||||
multimodal step never re-parses anything; retrieval delegates to LightRAG's
|
||||
native query modes.
|
||||
"""
|
||||
"""Exact-version adapter over the LightRAG 1.5 native Python SDK."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
import hashlib
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -26,335 +15,441 @@ from .config import (
|
||||
build_embedding_func,
|
||||
build_llm_model_func,
|
||||
build_vision_model_func,
|
||||
constructor_kwargs_from_settings,
|
||||
indexing_kwargs_from_settings,
|
||||
lightrag_kwargs_from_settings,
|
||||
normalize_mode,
|
||||
query_kwargs_from_settings,
|
||||
)
|
||||
from .ingress import IngressError, StagedDocument, pending_root
|
||||
from .worker import OwnerLoopBridge
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
LIGHTRAG_DISTRIBUTION = "lightrag-hku"
|
||||
LIGHTRAG_VERSION = "1.5.7rc2"
|
||||
PARSER_ENGINE = "deeptutor"
|
||||
|
||||
|
||||
def _accepts(target: Any, name: str) -> bool:
|
||||
"""Whether ``target``'s constructor takes a keyword called *name*.
|
||||
class LightRagContractError(RuntimeError):
|
||||
"""Raised when the pinned SDK returns a shape DeepTutor cannot trust."""
|
||||
|
||||
The settings knobs below ride on RAG-Anything parameters that arrived in
|
||||
different releases — ``lightrag_kwargs`` only exists from ~1.2.5, while the
|
||||
supported range starts at 1.0.1. Asking first keeps an older install
|
||||
working on RAG-Anything's own defaults instead of dying with a TypeError
|
||||
that takes the whole LightRAG engine down. Same defensive posture the query
|
||||
path already takes for ``QueryParam`` kwargs.
|
||||
"""
|
||||
import inspect
|
||||
|
||||
def installed_version() -> str:
|
||||
try:
|
||||
return name in inspect.signature(target).parameters
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return version(LIGHTRAG_DISTRIBUTION)
|
||||
except PackageNotFoundError as exc:
|
||||
raise LightRagContractError(
|
||||
"LightRAG is not installed. Install `deeptutor[rag-lightrag]`."
|
||||
) from exc
|
||||
|
||||
|
||||
def _drop_unsupported(target: Any, kwargs: dict[str, Any], *, what: str) -> dict[str, Any]:
|
||||
supported = {key: value for key, value in kwargs.items() if _accepts(target, key)}
|
||||
for key in kwargs.keys() - supported.keys():
|
||||
logger.warning(
|
||||
"Installed RAG-Anything does not accept %s=%r on %s; leaving it at "
|
||||
"the library default. Upgrade raganything to use this setting.",
|
||||
key,
|
||||
kwargs[key],
|
||||
what,
|
||||
def _require_exact_version() -> None:
|
||||
current = installed_version()
|
||||
if current != LIGHTRAG_VERSION:
|
||||
raise LightRagContractError(
|
||||
f"DeepTutor requires {LIGHTRAG_DISTRIBUTION}=={LIGHTRAG_VERSION}; found {current}"
|
||||
)
|
||||
return supported
|
||||
|
||||
|
||||
def _build_config(config_cls: Any, working_dir: Path) -> Any:
|
||||
knobs = _drop_unsupported(config_cls, indexing_kwargs_from_settings(), what="RAGAnythingConfig")
|
||||
return config_cls(working_dir=str(working_dir), **knobs)
|
||||
def _validate_component(value: str, *, label: str) -> str:
|
||||
path = Path(str(value or ""))
|
||||
if path.is_absolute() or ".." in path.parts or path.name != str(value):
|
||||
raise IngressError(f"{label} must be a canonical basename: {value!r}")
|
||||
if not path.name or path.name in {".", ".."}:
|
||||
raise IngressError(f"{label} is empty or invalid")
|
||||
return path.name
|
||||
|
||||
|
||||
def _construct(rag_cls: Any, **kwargs: Any) -> Any:
|
||||
extra = lightrag_kwargs_from_settings()
|
||||
if extra and _accepts(rag_cls, "lightrag_kwargs"):
|
||||
kwargs["lightrag_kwargs"] = extra
|
||||
elif extra:
|
||||
logger.warning(
|
||||
"Installed RAG-Anything has no lightrag_kwargs passthrough; %s stay "
|
||||
"at LightRAG's defaults. Upgrade raganything to use these settings.",
|
||||
", ".join(sorted(extra)),
|
||||
)
|
||||
return rag_cls(**kwargs)
|
||||
def _safe_candidate(root: Path, candidate: Path) -> Path | None:
|
||||
if candidate.is_symlink() or not candidate.is_file():
|
||||
return None
|
||||
resolved_root = root.resolve(strict=True)
|
||||
resolved = candidate.resolve(strict=True)
|
||||
try:
|
||||
resolved.relative_to(resolved_root)
|
||||
except ValueError as exc:
|
||||
raise IngressError(
|
||||
f"LightRAG source resolver escaped version ingress: {candidate}"
|
||||
) from exc
|
||||
return resolved
|
||||
|
||||
|
||||
def build_rag(working_dir: Path, *, io_bridge: OwnerLoopBridge | None = None) -> Any:
|
||||
"""Construct a RAG-Anything instance rooted at ``working_dir``.
|
||||
def _controlled_class():
|
||||
from lightrag import LightRAG
|
||||
|
||||
Pinned to RAG-Anything's config-based constructor; this is the single spot
|
||||
to touch if its API changes between releases.
|
||||
"""
|
||||
from raganything import RAGAnything, RAGAnythingConfig
|
||||
class DeepTutorLightRAG(LightRAG):
|
||||
def _resolve_source_file_for_parser(
|
||||
self,
|
||||
file_path: str,
|
||||
*,
|
||||
source_file: str | None = None,
|
||||
parser_engine: str | None = None,
|
||||
) -> str:
|
||||
if parser_engine not in (None, PARSER_ENGINE):
|
||||
raise IngressError(
|
||||
f"Unsupported parser engine for DeepTutor ingress: {parser_engine}"
|
||||
)
|
||||
name = _validate_component(file_path, label="file_path")
|
||||
if source_file is not None:
|
||||
source_name = _validate_component(source_file, label="source_file")
|
||||
if source_name != name:
|
||||
raise IngressError(
|
||||
f"LightRAG source hints disagree: {name!r} != {source_name!r}"
|
||||
)
|
||||
root = pending_root(Path(self.working_dir))
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
matches = [
|
||||
resolved
|
||||
for candidate in (root / name, root / "__parsed__" / name)
|
||||
if (resolved := _safe_candidate(root, candidate)) is not None
|
||||
]
|
||||
if len(matches) != 1:
|
||||
reason = "missing" if not matches else "ambiguous"
|
||||
raise IngressError(f"Version-local LightRAG source is {reason}: {name}")
|
||||
return str(matches[0])
|
||||
|
||||
config = _build_config(RAGAnythingConfig, working_dir)
|
||||
adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}
|
||||
funcs = {
|
||||
"llm_model_func": build_llm_model_func(**adapter_kwargs),
|
||||
"vision_model_func": build_vision_model_func(**adapter_kwargs),
|
||||
"embedding_func": build_embedding_func(**adapter_kwargs),
|
||||
return DeepTutorLightRAG
|
||||
|
||||
|
||||
_SUFFIXES = frozenset(
|
||||
{
|
||||
"txt",
|
||||
"md",
|
||||
"mdx",
|
||||
"pdf",
|
||||
"doc",
|
||||
"docx",
|
||||
"ppt",
|
||||
"pptx",
|
||||
"xls",
|
||||
"xlsx",
|
||||
"rtf",
|
||||
"odt",
|
||||
"tex",
|
||||
"epub",
|
||||
"html",
|
||||
"htm",
|
||||
"csv",
|
||||
"json",
|
||||
"xml",
|
||||
"yaml",
|
||||
"yml",
|
||||
"log",
|
||||
"conf",
|
||||
"ini",
|
||||
"properties",
|
||||
"sql",
|
||||
"sh",
|
||||
"c",
|
||||
"h",
|
||||
"cpp",
|
||||
"hpp",
|
||||
"py",
|
||||
"java",
|
||||
"js",
|
||||
"ts",
|
||||
"swift",
|
||||
"go",
|
||||
"rb",
|
||||
"php",
|
||||
"css",
|
||||
"scss",
|
||||
"less",
|
||||
"png",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"webp",
|
||||
"gif",
|
||||
"bmp",
|
||||
"tiff",
|
||||
}
|
||||
rag = _construct(RAGAnything, config=config, **funcs)
|
||||
# DeepTutor always feeds RAG-Anything a pre-parsed ``content_list`` (the
|
||||
# parse layer runs upstream via DeepTutor's own ParseService), so
|
||||
# RAG-Anything's bundled document parser is never invoked. Its LightRAG init
|
||||
# nevertheless runs a one-time installation check on its *default* parser
|
||||
# (``mineru``); when MinerU isn't installed that check hard-fails indexing
|
||||
# with "Parser 'mineru' is not properly installed" — even though the user
|
||||
# picked an entirely different parse engine (see issue #594). Marking the
|
||||
# check as already satisfied skips that spurious gate for a parser we don't
|
||||
# use, while leaving the real pre-parsed insert path untouched.
|
||||
rag._parser_installation_checked = True
|
||||
return rag
|
||||
)
|
||||
|
||||
|
||||
async def insert(rag: Any, content_list: list[dict], *, file_name: str, doc_id: str) -> None:
|
||||
"""Insert a pre-parsed ``content_list`` (multimodal-aware, no re-parsing)."""
|
||||
await rag.insert_content_list(
|
||||
content_list=content_list,
|
||||
file_path=file_name,
|
||||
doc_id=doc_id,
|
||||
def _register_parser() -> None:
|
||||
from lightrag.parser.registry import ParserSpec, register_parser
|
||||
|
||||
register_parser(
|
||||
ParserSpec(
|
||||
engine_name=PARSER_ENGINE,
|
||||
impl="deeptutor.services.rag.pipelines.lightrag.parser:DeepTutorParser",
|
||||
suffixes=_SUFFIXES,
|
||||
queue_group="native",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _managed_queue_funcs(lightrag: Any) -> Iterable[Callable[..., Any]]:
|
||||
"""Yield each current LightRAG queue wrapper exactly once."""
|
||||
role_funcs = getattr(lightrag, "role_llm_funcs", {})
|
||||
candidates: list[object] = []
|
||||
if isinstance(role_funcs, Mapping):
|
||||
candidates.extend(role_funcs.values())
|
||||
def workspace_for(working_dir: Path) -> str:
|
||||
identity = str(Path(working_dir).resolve()).encode("utf-8")
|
||||
return f"deeptutor_{hashlib.sha256(identity).hexdigest()[:16]}"
|
||||
|
||||
embedding = getattr(lightrag, "embedding_func", None)
|
||||
|
||||
def build_rag(
|
||||
working_dir: Path,
|
||||
*,
|
||||
io_bridge: OwnerLoopBridge | None = None,
|
||||
enable_vlm: bool = False,
|
||||
) -> Any:
|
||||
"""Construct one exact-version, version-isolated LightRAG instance."""
|
||||
_require_exact_version()
|
||||
_register_parser()
|
||||
from lightrag.llm_roles import RoleLLMConfig
|
||||
|
||||
adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}
|
||||
constructor = {
|
||||
"working_dir": str(Path(working_dir)),
|
||||
"workspace": workspace_for(working_dir),
|
||||
"llm_model_func": build_llm_model_func(**adapter_kwargs),
|
||||
"embedding_func": build_embedding_func(**adapter_kwargs),
|
||||
"auto_manage_storages_states": False,
|
||||
"vlm_process_enable": bool(enable_vlm),
|
||||
**indexing_kwargs_from_settings(),
|
||||
**constructor_kwargs_from_settings(),
|
||||
}
|
||||
if enable_vlm:
|
||||
constructor["role_llm_configs"] = {
|
||||
"vlm": RoleLLMConfig(func=build_vision_model_func(**adapter_kwargs))
|
||||
}
|
||||
return _controlled_class()(**constructor)
|
||||
|
||||
|
||||
async def initialize(rag: Any) -> None:
|
||||
result = rag.initialize_storages()
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
|
||||
|
||||
async def enqueue(rag: Any, staged: list[StagedDocument]) -> str:
|
||||
if not staged:
|
||||
raise ValueError("Cannot enqueue an empty LightRAG batch")
|
||||
return await rag.apipeline_enqueue_documents(
|
||||
[""] * len(staged),
|
||||
file_paths=[item.canonical_name for item in staged],
|
||||
docs_format="pending_parse",
|
||||
parse_engine=PARSER_ENGINE,
|
||||
process_options=[item.process_options for item in staged],
|
||||
chunk_options=[item.chunk_options for item in staged],
|
||||
)
|
||||
|
||||
|
||||
def _document_id(canonical_name: str) -> str:
|
||||
from lightrag.utils import compute_mdhash_id
|
||||
from lightrag.utils_pipeline import (
|
||||
has_known_document_source,
|
||||
normalize_document_file_path,
|
||||
)
|
||||
|
||||
source = normalize_document_file_path(canonical_name)
|
||||
if not has_known_document_source(source):
|
||||
raise LightRagContractError(
|
||||
f"LightRAG cannot derive a stable document ID for {canonical_name!r}"
|
||||
)
|
||||
return compute_mdhash_id(source, prefix="doc-")
|
||||
|
||||
|
||||
async def confirmed_unaccepted(rag: Any, staged: list[StagedDocument]) -> list[StagedDocument]:
|
||||
"""Return documents whose missing doc_status row was strictly confirmed."""
|
||||
ids_by_name = {item.canonical_name: _document_id(item.canonical_name) for item in staged}
|
||||
rows = await rag.doc_status.get_docs_by_ids(
|
||||
list(ids_by_name.values()),
|
||||
strict=True,
|
||||
)
|
||||
if not isinstance(rows, dict):
|
||||
raise LightRagContractError("doc_status.get_docs_by_ids must return an object")
|
||||
return [item for item in staged if ids_by_name[item.canonical_name] not in rows]
|
||||
|
||||
|
||||
def _managed_queue_funcs(rag: Any) -> Iterable[Callable[..., Any]]:
|
||||
role_funcs = getattr(rag, "role_llm_funcs", {})
|
||||
candidates: list[object] = list(role_funcs.values()) if isinstance(role_funcs, Mapping) else []
|
||||
embedding = getattr(rag, "embedding_func", None)
|
||||
candidates.append(getattr(embedding, "func", None))
|
||||
candidates.append(getattr(lightrag, "rerank_model_func", None))
|
||||
|
||||
candidates.append(getattr(rag, "rerank_model_func", None))
|
||||
seen: set[int] = set()
|
||||
for candidate in candidates:
|
||||
if not callable(candidate) or id(candidate) in seen:
|
||||
continue
|
||||
seen.add(id(candidate))
|
||||
yield candidate
|
||||
if callable(candidate) and id(candidate) not in seen:
|
||||
seen.add(id(candidate))
|
||||
yield candidate
|
||||
|
||||
|
||||
async def _shutdown_queues(lightrag: Any, *, cancel_pending: bool) -> None:
|
||||
"""Bound cleanup of LightRAG's role, embedding, and rerank queues."""
|
||||
async def _shutdown_queues(rag: Any, *, cancel_pending: bool) -> None:
|
||||
shutdowns: list[Awaitable[Any]] = []
|
||||
for func in _managed_queue_funcs(lightrag):
|
||||
for func in _managed_queue_funcs(rag):
|
||||
shutdown = getattr(func, "shutdown", None)
|
||||
if callable(shutdown):
|
||||
result = shutdown(graceful=not cancel_pending, timeout=5.0)
|
||||
if inspect.isawaitable(result):
|
||||
shutdowns.append(result)
|
||||
if not shutdowns:
|
||||
return
|
||||
|
||||
results = await asyncio.gather(*shutdowns, return_exceptions=True)
|
||||
failures = [result for result in results if isinstance(result, BaseException)]
|
||||
if failures:
|
||||
raise RuntimeError(
|
||||
f"Failed to shut down {len(failures)} LightRAG managed queue(s)"
|
||||
) from failures[0]
|
||||
if shutdowns:
|
||||
results = await asyncio.gather(*shutdowns, return_exceptions=True)
|
||||
failures = [item for item in results if isinstance(item, BaseException)]
|
||||
if failures:
|
||||
raise RuntimeError(
|
||||
f"Failed to shut down {len(failures)} LightRAG queue(s)"
|
||||
) from failures[0]
|
||||
|
||||
|
||||
async def finalize(rag: Any, *, cancel_pending: bool) -> None:
|
||||
"""Stop managed work before finalizing RAG-Anything storage resources."""
|
||||
lightrag = getattr(rag, "lightrag", None)
|
||||
if lightrag is not None:
|
||||
await _shutdown_queues(lightrag, cancel_pending=cancel_pending)
|
||||
|
||||
finalizer = getattr(rag, "finalize_storages", None)
|
||||
if not callable(finalizer):
|
||||
return
|
||||
result = finalizer()
|
||||
await _shutdown_queues(rag, cancel_pending=cancel_pending)
|
||||
result = rag.finalize_storages()
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
|
||||
|
||||
async def ensure_ready(rag: Any) -> None:
|
||||
"""Ensure RAG-Anything has an initialized LightRAG instance."""
|
||||
if getattr(rag, "lightrag", None) is not None:
|
||||
return
|
||||
|
||||
initializer = getattr(rag, "_ensure_lightrag_initialized", None)
|
||||
if initializer is None:
|
||||
return
|
||||
|
||||
result = await initializer()
|
||||
if isinstance(result, dict) and result.get("success") is False:
|
||||
raise RuntimeError(result.get("error") or "Failed to initialize LightRAG")
|
||||
def _string(value: Any, *, label: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise LightRagContractError(f"LightRAG query {label} must be a string")
|
||||
return value
|
||||
|
||||
|
||||
async def query(rag: Any, question: str, mode: str | None = None) -> str:
|
||||
"""Run a LightRAG query and return the synthesized answer string.
|
||||
def _records(data: dict[str, Any], key: str) -> list[dict[str, Any]]:
|
||||
value = data.get(key)
|
||||
if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):
|
||||
raise LightRagContractError(f"LightRAG query data.{key} must be an object array")
|
||||
return value
|
||||
|
||||
Extra knobs (top_k, response_type) from the lightrag.json slice ride into
|
||||
LightRAG's ``QueryParam`` via aquery's ``**kwargs``. Wiring is defensive: an
|
||||
older RAG-Anything that rejects one of these kwargs falls back to a
|
||||
mode-only query rather than failing the search.
|
||||
"""
|
||||
resolved = normalize_mode(mode) or DEFAULT_MODE
|
||||
extra = query_kwargs_from_settings()
|
||||
await ensure_ready(rag)
|
||||
try:
|
||||
result = await rag.aquery(question, mode=resolved, **extra)
|
||||
except TypeError:
|
||||
if extra:
|
||||
logger.debug("RAG-Anything rejected extra query kwargs; retrying mode-only.")
|
||||
result = await rag.aquery(question, mode=resolved)
|
||||
|
||||
def _query_sources(data: dict[str, Any], metadata: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
references = _records(data, "references")
|
||||
ref_paths = {
|
||||
str(item.get("reference_id")): str(item.get("file_path") or item.get("source") or "")
|
||||
for item in references
|
||||
if item.get("reference_id") is not None
|
||||
}
|
||||
sources: list[dict[str, Any]] = []
|
||||
|
||||
def add(kind: str, record: dict[str, Any], rank: int) -> None:
|
||||
ref = str(record.get("reference_id") or "")
|
||||
path = str(record.get("file_path") or ref_paths.get(ref, ""))
|
||||
if kind == "chunk":
|
||||
stable_id = str(record.get("chunk_id") or "")
|
||||
title = Path(path).name if path else "LightRAG chunk"
|
||||
content = _string(record.get("content", ""), label="chunk content")
|
||||
elif kind == "entity":
|
||||
stable_id = str(record.get("entity_name") or record.get("entity_id") or "")
|
||||
title = stable_id or "LightRAG entity"
|
||||
content = _string(record.get("description", ""), label="entity description")
|
||||
else:
|
||||
raise
|
||||
return result if isinstance(result, str) else str(result)
|
||||
src_id = str(record.get("src_id") or "")
|
||||
tgt_id = str(record.get("tgt_id") or "")
|
||||
stable_id = str(record.get("relation_id") or f"{src_id}->{tgt_id}")
|
||||
title = stable_id or "LightRAG relationship"
|
||||
content = _string(record.get("description", ""), label="relationship description")
|
||||
item = {
|
||||
"kind": kind,
|
||||
"title": title,
|
||||
"content": content,
|
||||
"source": path,
|
||||
"page": str(record.get("page") or ""),
|
||||
"reference_id": ref,
|
||||
"rank": rank,
|
||||
}
|
||||
if kind == "chunk":
|
||||
item["chunk_id"] = stable_id
|
||||
elif kind == "entity":
|
||||
item.update(
|
||||
{
|
||||
"entity_id": stable_id,
|
||||
"entity_name": str(record.get("entity_name") or ""),
|
||||
"entity_type": str(record.get("entity_type") or ""),
|
||||
"source_id": str(record.get("source_id") or ""),
|
||||
}
|
||||
)
|
||||
else:
|
||||
item.update(
|
||||
{
|
||||
"relation_id": stable_id,
|
||||
"src_id": str(record.get("src_id") or ""),
|
||||
"tgt_id": str(record.get("tgt_id") or ""),
|
||||
"keywords": record.get("keywords"),
|
||||
"weight": record.get("weight"),
|
||||
"source_id": str(record.get("source_id") or ""),
|
||||
}
|
||||
)
|
||||
sources.append(item)
|
||||
|
||||
for kind, key in (
|
||||
("chunk", "chunks"),
|
||||
("entity", "entities"),
|
||||
("relationship", "relationships"),
|
||||
):
|
||||
for record in _records(data, key):
|
||||
add(kind, record, len(sources) + 1)
|
||||
for reference in references:
|
||||
reference_id = str(reference.get("reference_id") or "")
|
||||
path = str(reference.get("file_path") or reference.get("source") or "")
|
||||
sources.append(
|
||||
{
|
||||
"kind": "reference",
|
||||
"title": Path(path).name if path else reference_id or "LightRAG reference",
|
||||
"content": "",
|
||||
"source": path,
|
||||
"page": str(reference.get("page") or ""),
|
||||
"reference_id": reference_id,
|
||||
"rank": len(sources) + 1,
|
||||
"reference": reference,
|
||||
}
|
||||
)
|
||||
sources.append(
|
||||
{
|
||||
"kind": "query_metadata",
|
||||
"title": "LightRAG query metadata",
|
||||
"content": "",
|
||||
"source": "",
|
||||
"page": "",
|
||||
"reference_id": "",
|
||||
"rank": len(sources) + 1,
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
async def query_with_sources(
|
||||
rag: Any, question: str, mode: str | None = None
|
||||
) -> tuple[str, list[dict[str, Any]]]:
|
||||
"""Return a LightRAG answer together with its structured provenance.
|
||||
from lightrag import QueryParam
|
||||
|
||||
``RAGAnything.aquery`` owns the answer path, including its optional VLM
|
||||
enhancement. LightRAG exposes the records used for retrieval separately via
|
||||
``aquery_data``. Keeping those calls separate preserves the existing answer
|
||||
behavior while allowing DeepTutor to surface citation metadata.
|
||||
"""
|
||||
answer = await query(rag, question, mode)
|
||||
return answer, await query_sources(rag, question, mode)
|
||||
|
||||
|
||||
async def query_sources(rag: Any, question: str, mode: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Fetch and normalize the structured records used by a LightRAG query.
|
||||
|
||||
``aquery_data`` was added by LightRAG after some supported RAG-Anything
|
||||
releases. Missing or failed provenance must not turn a successful answer
|
||||
into a failed user request, so older installations gracefully return no
|
||||
citations.
|
||||
"""
|
||||
await ensure_ready(rag)
|
||||
lightrag = getattr(rag, "lightrag", None)
|
||||
aquery_data = getattr(lightrag, "aquery_data", None)
|
||||
if not callable(aquery_data):
|
||||
logger.debug("Installed LightRAG has no structured query data API.")
|
||||
return []
|
||||
|
||||
resolved = normalize_mode(mode) or DEFAULT_MODE
|
||||
extra = query_kwargs_from_settings()
|
||||
try:
|
||||
from lightrag import QueryParam
|
||||
|
||||
try:
|
||||
result = await aquery_data(question, param=QueryParam(mode=resolved, **extra))
|
||||
except TypeError:
|
||||
if not extra:
|
||||
raise
|
||||
logger.debug("LightRAG rejected extra provenance query kwargs; retrying mode-only.")
|
||||
result = await aquery_data(question, param=QueryParam(mode=resolved))
|
||||
except Exception as exc:
|
||||
logger.warning("LightRAG provenance lookup failed; omitting citations: %s", exc)
|
||||
return []
|
||||
|
||||
return _query_data_to_sources(result)
|
||||
|
||||
|
||||
def _query_data_to_sources(result: Any) -> list[dict[str, Any]]:
|
||||
"""Map LightRAG's structured retrieval result to DeepTutor citations."""
|
||||
param = QueryParam(
|
||||
mode=normalize_mode(mode) or DEFAULT_MODE,
|
||||
stream=False,
|
||||
include_references=True,
|
||||
**query_kwargs_from_settings(),
|
||||
)
|
||||
result = await rag.aquery_llm(question, param=param)
|
||||
if not isinstance(result, dict):
|
||||
return []
|
||||
raise LightRagContractError("LightRAG query response must be an object")
|
||||
if result.get("status") != "success":
|
||||
message = result.get("message")
|
||||
raise LightRagContractError(
|
||||
str(message).strip()
|
||||
if isinstance(message, str) and message.strip()
|
||||
else "LightRAG retrieval failed"
|
||||
)
|
||||
response = result.get("llm_response")
|
||||
data = result.get("data")
|
||||
if not isinstance(data, dict):
|
||||
return []
|
||||
|
||||
reference_paths = {
|
||||
str(record.get("reference_id")): str(record.get("file_path"))
|
||||
for record in data.get("references", [])
|
||||
if isinstance(record, dict) and record.get("reference_id") and record.get("file_path")
|
||||
}
|
||||
sources: list[dict[str, Any]] = []
|
||||
|
||||
def source_path(record: dict[str, Any]) -> str:
|
||||
return str(
|
||||
record.get("file_path") or reference_paths.get(str(record.get("reference_id")), "")
|
||||
)
|
||||
|
||||
def source_title(path: str, fallback: str) -> str:
|
||||
return Path(path).name if path else fallback
|
||||
|
||||
for record in data.get("chunks", []):
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
path = source_path(record)
|
||||
content = str(record.get("content") or "")
|
||||
chunk_id = str(record.get("chunk_id") or "")
|
||||
if not (path or content or chunk_id):
|
||||
continue
|
||||
sources.append(
|
||||
{
|
||||
"title": source_title(path, "LightRAG chunk"),
|
||||
"content": content[:200],
|
||||
"source": path,
|
||||
"page": str(record.get("page") or ""),
|
||||
"chunk_id": chunk_id,
|
||||
"reference_id": str(record.get("reference_id") or ""),
|
||||
}
|
||||
)
|
||||
|
||||
for record in data.get("entities", []):
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
path = source_path(record)
|
||||
entity_id = str(record.get("entity_name") or record.get("entity_id") or "")
|
||||
description = str(record.get("description") or "")
|
||||
if not (path or entity_id or description):
|
||||
continue
|
||||
sources.append(
|
||||
{
|
||||
"title": entity_id or source_title(path, "LightRAG entity"),
|
||||
"content": description[:200],
|
||||
"source": path,
|
||||
"page": str(record.get("page") or ""),
|
||||
"entity_id": entity_id,
|
||||
"entity_type": str(record.get("entity_type") or ""),
|
||||
"source_id": str(record.get("source_id") or ""),
|
||||
"reference_id": str(record.get("reference_id") or ""),
|
||||
}
|
||||
)
|
||||
|
||||
for record in data.get("relationships", []):
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
path = source_path(record)
|
||||
source_id = str(record.get("src_id") or "")
|
||||
target_id = str(record.get("tgt_id") or "")
|
||||
relation_id = str(record.get("relation_id") or f"{source_id}->{target_id}")
|
||||
description = str(record.get("description") or "")
|
||||
if not (path or relation_id or description):
|
||||
continue
|
||||
sources.append(
|
||||
{
|
||||
"title": relation_id or source_title(path, "LightRAG relationship"),
|
||||
"content": description[:200],
|
||||
"source": path,
|
||||
"page": str(record.get("page") or ""),
|
||||
"relation_id": relation_id,
|
||||
"source_entity_id": source_id,
|
||||
"target_entity_id": target_id,
|
||||
"source_id": str(record.get("source_id") or ""),
|
||||
"reference_id": str(record.get("reference_id") or ""),
|
||||
}
|
||||
)
|
||||
|
||||
return sources
|
||||
metadata = result.get("metadata")
|
||||
if (
|
||||
not isinstance(response, dict)
|
||||
or not isinstance(data, dict)
|
||||
or not isinstance(metadata, dict)
|
||||
):
|
||||
raise LightRagContractError("LightRAG query response is missing structured fields")
|
||||
if response.get("is_streaming") is not False:
|
||||
raise LightRagContractError("LightRAG returned streaming output for a non-streaming query")
|
||||
content = _string(response.get("content"), label="llm_response.content")
|
||||
return content, _query_sources(data, metadata)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"LIGHTRAG_DISTRIBUTION",
|
||||
"LIGHTRAG_VERSION",
|
||||
"LightRagContractError",
|
||||
"PARSER_ENGINE",
|
||||
"build_rag",
|
||||
"ensure_ready",
|
||||
"confirmed_unaccepted",
|
||||
"enqueue",
|
||||
"finalize",
|
||||
"insert",
|
||||
"query",
|
||||
"initialize",
|
||||
"installed_version",
|
||||
"query_with_sources",
|
||||
"workspace_for",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Freeze DeepTutor parse results into version-local LightRAG ingress bundles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from deeptutor.services.file_io import atomic_write_json
|
||||
from deeptutor.services.parsing.types import ParsedDocument
|
||||
|
||||
from . import block_policy
|
||||
|
||||
PARSER_BRIDGE_SCHEMA = 1
|
||||
INGRESS_DIRNAME = "deeptutor_ingress"
|
||||
PENDING_DIRNAME = "pending"
|
||||
BUNDLES_DIRNAME = "bundles"
|
||||
MANIFEST_FILENAME = "manifest.json"
|
||||
|
||||
|
||||
class IngressError(RuntimeError):
|
||||
"""Raised when an ingress bundle crosses or violates its trust boundary."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StagedDocument:
|
||||
canonical_name: str
|
||||
source_path: Path
|
||||
bundle_dir: Path
|
||||
manifest_path: Path
|
||||
process_options: str
|
||||
chunk_options: dict[str, Any]
|
||||
audit_ledger: dict[str, Any] | None
|
||||
|
||||
|
||||
def ingress_root(working_dir: Path) -> Path:
|
||||
return Path(working_dir) / INGRESS_DIRNAME
|
||||
|
||||
|
||||
def pending_root(working_dir: Path) -> Path:
|
||||
return ingress_root(working_dir) / PENDING_DIRNAME
|
||||
|
||||
|
||||
def bundles_root(working_dir: Path) -> Path:
|
||||
return ingress_root(working_dir) / BUNDLES_DIRNAME
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _contained_regular_file(root: Path, path: Path, *, label: str) -> Path:
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
raise IngressError(f"Bundle root must be an ordinary directory: {root}")
|
||||
try:
|
||||
relative = path.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise IngressError(f"{label} escapes its bundle root: {path}") from exc
|
||||
current = root
|
||||
for part in relative.parts:
|
||||
current = current / part
|
||||
if current.is_symlink():
|
||||
raise IngressError(f"{label} must not traverse a symbolic link: {current}")
|
||||
if path.is_symlink():
|
||||
raise IngressError(f"{label} must not be a symbolic link: {path}")
|
||||
try:
|
||||
resolved_root = root.resolve(strict=True)
|
||||
resolved = path.resolve(strict=True)
|
||||
resolved.relative_to(resolved_root)
|
||||
except (FileNotFoundError, ValueError) as exc:
|
||||
raise IngressError(f"{label} escapes its bundle root: {path}") from exc
|
||||
stat = resolved.stat()
|
||||
if not resolved.is_file() or stat.st_nlink != 1:
|
||||
raise IngressError(f"{label} must be an ordinary, unlinked file: {path}")
|
||||
return resolved
|
||||
|
||||
|
||||
def _copy_regular(source: Path, target: Path, *, allowed_root: Path | None = None) -> str:
|
||||
if source.is_symlink() or not source.is_file():
|
||||
raise IngressError(f"Source is not an ordinary file: {source}")
|
||||
resolved_source = source.resolve(strict=True)
|
||||
if resolved_source.stat().st_nlink != 1:
|
||||
raise IngressError(f"Source must not be hard-linked: {source}")
|
||||
if allowed_root is not None:
|
||||
try:
|
||||
resolved_source.relative_to(allowed_root.resolve(strict=True))
|
||||
except ValueError as exc:
|
||||
raise IngressError(f"Source escapes allowed root: {source}") from exc
|
||||
source_digest = _sha256(resolved_source)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with resolved_source.open("rb") as src, target.open("xb") as dst:
|
||||
shutil.copyfileobj(src, dst, length=1024 * 1024)
|
||||
if target.is_symlink() or os.path.samefile(resolved_source, target):
|
||||
raise IngressError(f"Frozen copy must not share the source file: {target}")
|
||||
target_digest = _sha256(target)
|
||||
if target_digest != source_digest:
|
||||
raise IngressError(f"Digest drift while freezing {source.name}")
|
||||
if target.stat().st_nlink != 1:
|
||||
raise IngressError(f"Frozen copy has unexpected hard links: {target}")
|
||||
return target_digest
|
||||
|
||||
|
||||
def _write_new_bytes(path: Path, data: bytes) -> str:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("xb") as handle:
|
||||
handle.write(data)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _asset_files(asset_dir: Path | None) -> list[tuple[Path, Path]]:
|
||||
if asset_dir is None:
|
||||
return []
|
||||
root = Path(asset_dir)
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
raise IngressError(f"Parser asset directory is not an ordinary directory: {root}")
|
||||
files: list[tuple[Path, Path]] = []
|
||||
for path in sorted(root.rglob("*")):
|
||||
if path.is_symlink():
|
||||
raise IngressError(f"Parser asset is a symbolic link: {path}")
|
||||
if path.is_dir():
|
||||
continue
|
||||
if not path.is_file():
|
||||
raise IngressError(f"Parser asset is not an ordinary file: {path}")
|
||||
files.append((path, path.relative_to(root)))
|
||||
return files
|
||||
|
||||
|
||||
def _freeze_asset_paths(
|
||||
blocks: list[dict[str, Any]],
|
||||
asset_dir: Path | None,
|
||||
asset_files: list[tuple[Path, Path]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Rewrite parser-owned asset paths to bundle-relative copied paths."""
|
||||
frozen = deepcopy(blocks)
|
||||
if asset_dir is None:
|
||||
return frozen
|
||||
root = Path(asset_dir).resolve(strict=True)
|
||||
by_source = {source.resolve(strict=True): relative for source, relative in asset_files}
|
||||
by_relative = {relative: relative for _, relative in asset_files}
|
||||
for index, block in enumerate(frozen):
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
kind = str(block.get("type") or block.get("label") or "").lower()
|
||||
if kind not in {"image", "picture", "drawing", "chart"}:
|
||||
continue
|
||||
for key in ("img_path", "path"):
|
||||
raw = block.get(key)
|
||||
if not isinstance(raw, str) or not raw.strip():
|
||||
continue
|
||||
path = Path(raw)
|
||||
relative: Path | None = None
|
||||
if path.is_absolute():
|
||||
try:
|
||||
resolved = path.resolve(strict=True)
|
||||
except FileNotFoundError as exc:
|
||||
raise IngressError(f"Block {index} asset does not exist: {raw}") from exc
|
||||
relative = by_source.get(resolved)
|
||||
elif ".." not in path.parts:
|
||||
relative = by_relative.get(path)
|
||||
if relative is None:
|
||||
candidate = root / path
|
||||
try:
|
||||
relative = by_source.get(candidate.resolve(strict=True))
|
||||
except FileNotFoundError:
|
||||
relative = None
|
||||
if relative is None:
|
||||
raise IngressError(f"Block {index} asset is outside the frozen asset set: {raw}")
|
||||
block[key] = relative.as_posix()
|
||||
return frozen
|
||||
|
||||
|
||||
def freeze_document(working_dir: Path, source: Path, parsed: ParsedDocument) -> StagedDocument:
|
||||
"""Copy one parsed document into an immutable, digest-verified bundle."""
|
||||
source = Path(source)
|
||||
canonical_name = source.name
|
||||
if not canonical_name or canonical_name in {".", ".."}:
|
||||
raise IngressError(f"Document has no canonical basename: {source}")
|
||||
pending = pending_root(working_dir)
|
||||
bundles = bundles_root(working_dir)
|
||||
pending.mkdir(parents=True, exist_ok=True)
|
||||
bundles.mkdir(parents=True, exist_ok=True)
|
||||
staged_source = pending / canonical_name
|
||||
archived_source = pending / "__parsed__" / canonical_name
|
||||
final_bundle = bundles / f"{canonical_name}.bundle"
|
||||
if staged_source.exists() or archived_source.exists() or final_bundle.exists():
|
||||
raise IngressError(f"Canonical basename already exists in this version: {canonical_name}")
|
||||
|
||||
temp_bundle = bundles / f".{canonical_name}.{uuid.uuid4().hex}.tmp"
|
||||
temp_bundle.mkdir()
|
||||
try:
|
||||
asset_files = _asset_files(parsed.asset_dir)
|
||||
source_digest = _sha256(source.resolve(strict=True))
|
||||
staged_digest = _copy_regular(source, staged_source)
|
||||
if source_digest != staged_digest:
|
||||
raise IngressError(f"Source changed while staging {canonical_name}")
|
||||
|
||||
markdown = parsed.markdown.encode("utf-8")
|
||||
markdown_rel = Path("markdown.utf8")
|
||||
markdown_digest = _write_new_bytes(temp_bundle / markdown_rel, markdown)
|
||||
|
||||
decision = None
|
||||
blocks_rel: Path | None = None
|
||||
blocks_digest: str | None = None
|
||||
frozen_blocks: list[dict[str, Any]] | None = None
|
||||
if parsed.blocks:
|
||||
decision = block_policy.prepare_content_list(
|
||||
parsed.blocks,
|
||||
engine=parsed.engine,
|
||||
source_hash=parsed.source_hash,
|
||||
parser_signature=parsed.parser_signature,
|
||||
)
|
||||
frozen_blocks = _freeze_asset_paths(
|
||||
decision.content_list, parsed.asset_dir, asset_files
|
||||
)
|
||||
blocks_rel = Path("blocks.json")
|
||||
blocks_bytes = json.dumps(
|
||||
frozen_blocks, ensure_ascii=False, sort_keys=True, separators=(",", ":")
|
||||
).encode("utf-8")
|
||||
blocks_digest = _write_new_bytes(temp_bundle / blocks_rel, blocks_bytes)
|
||||
elif not parsed.markdown.strip():
|
||||
raise IngressError(f"Parsed document is empty: {canonical_name}")
|
||||
|
||||
asset_records: list[dict[str, Any]] = []
|
||||
for asset, relative in asset_files:
|
||||
target = temp_bundle / "assets" / relative
|
||||
digest = _copy_regular(asset, target, allowed_root=Path(parsed.asset_dir))
|
||||
asset_records.append(
|
||||
{"path": target.relative_to(temp_bundle).as_posix(), "sha256": digest}
|
||||
)
|
||||
|
||||
kinds = {
|
||||
str(block.get("type") or block.get("label") or "").lower()
|
||||
for block in (frozen_blocks or [])
|
||||
if isinstance(block, dict)
|
||||
}
|
||||
modalities = "".join(
|
||||
flag
|
||||
for flag, names in (
|
||||
("i", {"image", "picture", "drawing", "chart"}),
|
||||
("t", {"table"}),
|
||||
("e", {"equation", "formula"}),
|
||||
)
|
||||
if kinds & names
|
||||
)
|
||||
process_options = f"P{modalities}" if frozen_blocks else "F"
|
||||
chunk_options = (
|
||||
{"paragraph_semantic": {"chunk_token_size": 1200}}
|
||||
if frozen_blocks
|
||||
else {"fixed_token": {}}
|
||||
)
|
||||
manifest = {
|
||||
"parser_bridge_schema": PARSER_BRIDGE_SCHEMA,
|
||||
"canonical_filename": canonical_name,
|
||||
"parser": {
|
||||
"engine": parsed.engine,
|
||||
"source_hash": parsed.source_hash,
|
||||
"parser_signature": parsed.parser_signature,
|
||||
},
|
||||
"source": {
|
||||
"path": str(Path("..") / ".." / PENDING_DIRNAME / canonical_name),
|
||||
"sha256": staged_digest,
|
||||
},
|
||||
"markdown": {"path": markdown_rel.as_posix(), "sha256": markdown_digest},
|
||||
"blocks": (
|
||||
{"path": blocks_rel.as_posix(), "sha256": blocks_digest}
|
||||
if blocks_rel is not None
|
||||
else None
|
||||
),
|
||||
"assets": asset_records,
|
||||
"process_options": process_options,
|
||||
"chunk_options": chunk_options,
|
||||
"block_policy": decision.ledger if decision is not None else None,
|
||||
}
|
||||
atomic_write_json(temp_bundle / MANIFEST_FILENAME, manifest)
|
||||
os.replace(temp_bundle, final_bundle)
|
||||
return StagedDocument(
|
||||
canonical_name=canonical_name,
|
||||
source_path=staged_source,
|
||||
bundle_dir=final_bundle,
|
||||
manifest_path=final_bundle / MANIFEST_FILENAME,
|
||||
process_options=process_options,
|
||||
chunk_options=chunk_options,
|
||||
audit_ledger=decision.ledger if decision is not None else None,
|
||||
)
|
||||
except BaseException:
|
||||
shutil.rmtree(temp_bundle, ignore_errors=True)
|
||||
if staged_source.exists() and not staged_source.is_symlink():
|
||||
staged_source.unlink()
|
||||
raise
|
||||
|
||||
|
||||
def load_verified_bundle(working_dir: Path, canonical_name: str) -> tuple[dict[str, Any], Path]:
|
||||
"""Load and digest-verify one published bundle by canonical basename."""
|
||||
if Path(canonical_name).name != canonical_name or Path(canonical_name).is_absolute():
|
||||
raise IngressError(f"Invalid canonical basename: {canonical_name!r}")
|
||||
bundle = bundles_root(working_dir) / f"{canonical_name}.bundle"
|
||||
manifest_path = bundle / MANIFEST_FILENAME
|
||||
manifest = json.loads(
|
||||
_contained_regular_file(bundle, manifest_path, label="manifest").read_text(encoding="utf-8")
|
||||
)
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("parser_bridge_schema") != PARSER_BRIDGE_SCHEMA
|
||||
):
|
||||
raise IngressError(f"Unsupported parser bridge manifest: {manifest_path}")
|
||||
if manifest.get("canonical_filename") != canonical_name:
|
||||
raise IngressError(f"Bundle basename mismatch: {canonical_name}")
|
||||
|
||||
records: list[tuple[str, dict[str, Any]]] = []
|
||||
for key in ("markdown", "blocks"):
|
||||
record = manifest.get(key)
|
||||
if record is not None:
|
||||
if not isinstance(record, dict):
|
||||
raise IngressError(f"Malformed {key} record in {manifest_path}")
|
||||
records.append((key, record))
|
||||
assets = manifest.get("assets")
|
||||
if not isinstance(assets, list):
|
||||
raise IngressError(f"Malformed assets record in {manifest_path}")
|
||||
records.extend(("asset", record) for record in assets if isinstance(record, dict))
|
||||
if len(records) != 1 + int(manifest.get("blocks") is not None) + len(assets):
|
||||
raise IngressError(f"Malformed asset entry in {manifest_path}")
|
||||
for label, record in records:
|
||||
rel = Path(str(record.get("path") or ""))
|
||||
if rel.is_absolute() or ".." in rel.parts:
|
||||
raise IngressError(f"Unsafe {label} path in {manifest_path}")
|
||||
path = _contained_regular_file(bundle, bundle / rel, label=label)
|
||||
if _sha256(path) != record.get("sha256"):
|
||||
raise IngressError(f"Digest mismatch for {label}: {path}")
|
||||
return manifest, bundle
|
||||
|
||||
|
||||
def remove_unaccepted(staged: StagedDocument) -> None:
|
||||
"""Remove only a pre-enqueue source/bundle whose doc_status does not exist."""
|
||||
if staged.source_path.exists() and not staged.source_path.is_symlink():
|
||||
staged.source_path.unlink()
|
||||
shutil.rmtree(staged.bundle_dir, ignore_errors=True)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BUNDLES_DIRNAME",
|
||||
"INGRESS_DIRNAME",
|
||||
"IngressError",
|
||||
"PARSER_BRIDGE_SCHEMA",
|
||||
"PENDING_DIRNAME",
|
||||
"StagedDocument",
|
||||
"bundles_root",
|
||||
"freeze_document",
|
||||
"ingress_root",
|
||||
"load_verified_bundle",
|
||||
"pending_root",
|
||||
"remove_unaccepted",
|
||||
]
|
||||
@@ -0,0 +1,99 @@
|
||||
"""LightRAG parser that consumes frozen DeepTutor ingress bundles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
from lightrag.parser.base import BaseParser
|
||||
|
||||
from .ingress import IngressError, load_verified_bundle
|
||||
from .sidecar import build_ir
|
||||
|
||||
|
||||
class DeepTutorParser(BaseParser):
|
||||
"""Third-party parser registered as ``deeptutor`` in LightRAG rc2."""
|
||||
|
||||
engine_name = "deeptutor"
|
||||
|
||||
async def parse(self, ctx):
|
||||
from lightrag.constants import (
|
||||
FULL_DOCS_FORMAT_LIGHTRAG,
|
||||
FULL_DOCS_FORMAT_RAW,
|
||||
)
|
||||
from lightrag.parser.base import ParseResult
|
||||
from lightrag.sidecar.writer import write_sidecar
|
||||
from lightrag.utils import strip_control_characters
|
||||
from lightrag.utils_pipeline import make_lightrag_doc_content, sidecar_uri_for
|
||||
|
||||
resolved = ctx.resolve(self.engine_name)
|
||||
source = resolved.source_path
|
||||
if source.is_symlink() or not source.is_file():
|
||||
raise IngressError(f"Frozen ingress source is not an ordinary file: {source}")
|
||||
manifest, bundle = load_verified_bundle(Path(ctx.rag.working_dir), resolved.document_name)
|
||||
|
||||
digest = hashlib.sha256()
|
||||
with source.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
source_record = manifest.get("source")
|
||||
if not isinstance(source_record, dict) or digest.hexdigest() != source_record.get("sha256"):
|
||||
raise IngressError(f"Frozen source digest mismatch: {resolved.document_name}")
|
||||
|
||||
markdown_record = manifest["markdown"]
|
||||
markdown = strip_control_characters(
|
||||
(bundle / markdown_record["path"]).read_text(encoding="utf-8")
|
||||
)
|
||||
if manifest.get("blocks") is None:
|
||||
if not markdown.strip():
|
||||
raise IngressError(f"Frozen RAW document is empty: {resolved.document_name}")
|
||||
await ctx.rag._persist_parsed_full_docs(
|
||||
ctx.doc_id,
|
||||
{
|
||||
"content": markdown,
|
||||
"file_path": ctx.file_path,
|
||||
"parse_format": FULL_DOCS_FORMAT_RAW,
|
||||
"parse_engine": self.engine_name,
|
||||
"update_time": int(time.time()),
|
||||
},
|
||||
)
|
||||
await ctx.archive_source(str(source))
|
||||
return ParseResult(
|
||||
doc_id=ctx.doc_id,
|
||||
file_path=ctx.file_path,
|
||||
parse_format=FULL_DOCS_FORMAT_RAW,
|
||||
content=markdown,
|
||||
parse_engine=self.engine_name,
|
||||
)
|
||||
|
||||
ir = build_ir(manifest, bundle)
|
||||
parsed_data = write_sidecar(
|
||||
ir,
|
||||
parsed_dir=resolved.parsed_dir,
|
||||
doc_id=ctx.doc_id,
|
||||
engine=self.engine_name,
|
||||
)
|
||||
await ctx.rag._persist_parsed_full_docs(
|
||||
ctx.doc_id,
|
||||
{
|
||||
"content": make_lightrag_doc_content(parsed_data["content"]),
|
||||
"file_path": ctx.file_path,
|
||||
"parse_format": FULL_DOCS_FORMAT_LIGHTRAG,
|
||||
"sidecar_location": sidecar_uri_for(resolved.parsed_dir),
|
||||
"parse_engine": self.engine_name,
|
||||
"update_time": int(time.time()),
|
||||
},
|
||||
)
|
||||
await ctx.archive_source(str(source))
|
||||
return ParseResult(
|
||||
doc_id=ctx.doc_id,
|
||||
file_path=ctx.file_path,
|
||||
parse_format=FULL_DOCS_FORMAT_LIGHTRAG,
|
||||
content=parsed_data["content"],
|
||||
blocks_path=parsed_data["blocks_path"],
|
||||
parse_engine=self.engine_name,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["DeepTutorParser"]
|
||||
@@ -1,53 +1,95 @@
|
||||
"""LightRAG-backed RAG pipeline orchestration.
|
||||
|
||||
Implements the same contract as :class:`LlamaIndexPipeline` (see
|
||||
``..base.RAGPipeline``) but delegates indexing/retrieval to RAG-Anything /
|
||||
LightRAG. Each KB owns a self-contained LightRAG store under its ``version-N``
|
||||
directory (see ``storage``).
|
||||
|
||||
Documents are turned into a MinerU-style ``content_list`` by DeepTutor's shared
|
||||
parse layer (``deeptutor/services/parsing``) — the same bridge the question
|
||||
extractor uses — so multimodal parsing stays a decoupled, cached, engine-
|
||||
pluggable concern and this pipeline only ever feeds LightRAG ready content.
|
||||
|
||||
LightRAG is an optional dependency: every method fails with a clear, actionable
|
||||
message when it is not installed instead of an opaque ``ImportError``.
|
||||
"""
|
||||
"""DeepTutor orchestration for the LightRAG 1.5 native document pipeline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field, replace
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import traceback
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from deeptutor.runtime.home import get_runtime_data_root
|
||||
from deeptutor.services.rag.index_versioning import (
|
||||
list_kb_versions,
|
||||
resolve_storage_dir_for_read,
|
||||
resolve_storage_dir_for_rebuild,
|
||||
)
|
||||
from deeptutor.services.rag.kb_paths import resolve_kb_dir
|
||||
|
||||
from . import block_policy, engine, storage
|
||||
from . import block_policy, engine, ingress, storage
|
||||
from . import config as lr_config
|
||||
from .worker import OwnerLoopBridge, run_in_worker_loop
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
|
||||
|
||||
|
||||
class LightRagPipeline:
|
||||
"""Index/retrieve KB content via RAG-Anything / LightRAG."""
|
||||
@dataclass(frozen=True)
|
||||
class BatchOutcome:
|
||||
requested: int
|
||||
preflight_failed: dict[str, str] = field(default_factory=dict)
|
||||
accepted: int = 0
|
||||
processed: tuple[str, ...] = ()
|
||||
failed: dict[str, str] = field(default_factory=dict)
|
||||
nonterminal: dict[str, str] = field(default_factory=dict)
|
||||
missing: tuple[str, ...] = ()
|
||||
track_id: str = ""
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return (
|
||||
self.requested > 0
|
||||
and len(self.processed) == self.requested
|
||||
and not self.preflight_failed
|
||||
and not self.failed
|
||||
and not self.nonterminal
|
||||
and not self.missing
|
||||
)
|
||||
|
||||
|
||||
class LightRagBatchError(RuntimeError):
|
||||
def __init__(self, outcome: BatchOutcome) -> None:
|
||||
self.outcome = outcome
|
||||
failures = {**outcome.preflight_failed, **outcome.failed}
|
||||
detail = "; ".join(f"{name}: {error}" for name, error in sorted(failures.items()))
|
||||
message = (
|
||||
f"LightRAG batch incomplete: added {len(outcome.processed)}, "
|
||||
f"failed {len(failures)}, missing {len(outcome.missing)}, "
|
||||
f"nonterminal {len(outcome.nonterminal)}"
|
||||
)
|
||||
super().__init__(f"{message}: {detail}" if detail else message)
|
||||
|
||||
|
||||
class LightRagNeedsReindexError(RuntimeError):
|
||||
"""Raised when an append targets a pre-native LightRAG index."""
|
||||
|
||||
|
||||
def _status_text(row: Any) -> str:
|
||||
status = getattr(row, "status", None)
|
||||
value = getattr(status, "value", status)
|
||||
return str(value or "").strip().lower()
|
||||
|
||||
|
||||
def _row_name(row: Any) -> str:
|
||||
return Path(str(getattr(row, "file_path", "") or "")).name
|
||||
|
||||
|
||||
def _row_error(row: Any) -> str:
|
||||
for key in ("error_msg", "error"):
|
||||
value = getattr(row, key, None)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return _status_text(row) or "unknown LightRAG failure"
|
||||
|
||||
|
||||
class LightRagPipeline:
|
||||
def __init__(self, kb_base_dir: Optional[str] = None, **_: Any) -> None:
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR
|
||||
|
||||
# ----- helpers --------------------------------------------------------
|
||||
self._status_poll_seconds = 0.2
|
||||
self._status_no_progress_seconds = 600.0
|
||||
|
||||
def _ensure_available(self) -> None:
|
||||
if not lr_config.is_lightrag_available():
|
||||
@@ -68,265 +110,326 @@ class LightRagPipeline:
|
||||
default=lr_config.DEFAULT_MODE,
|
||||
)
|
||||
|
||||
def _cleanup_failed_version_dir(self, root_dir: Path) -> None:
|
||||
try:
|
||||
if root_dir.is_dir() and not (root_dir / storage.META_FILENAME).exists():
|
||||
shutil.rmtree(root_dir)
|
||||
except Exception as exc: # pragma: no cover - best-effort
|
||||
self.logger.warning("Could not clean up failed version dir %s: %s", root_dir, exc)
|
||||
|
||||
async def _ingest(
|
||||
self,
|
||||
rag: Any,
|
||||
file_paths: List[str],
|
||||
*,
|
||||
io_bridge: OwnerLoopBridge,
|
||||
progress_callback: Callable[[int, int], Any] | None = None,
|
||||
) -> int:
|
||||
"""Parse each file via the shared parse layer and insert it into LightRAG.
|
||||
|
||||
Returns the number of documents successfully inserted. Per-file failures
|
||||
are logged and skipped so one bad document doesn't abort the batch.
|
||||
"""
|
||||
from deeptutor.services.parsing import ParserError, get_parse_service
|
||||
def _stage_documents(
|
||||
self, working_dir: Path, file_paths: List[str]
|
||||
) -> tuple[list[ingress.StagedDocument], dict[str, str]]:
|
||||
from deeptutor.services.parsing import get_parse_service
|
||||
|
||||
parse_service = get_parse_service()
|
||||
inserted = 0
|
||||
total = len(file_paths)
|
||||
for file_path in file_paths:
|
||||
io_bridge.raise_if_cancelled()
|
||||
path = Path(file_path)
|
||||
staged: list[ingress.StagedDocument] = []
|
||||
failures: dict[str, str] = {}
|
||||
seen: set[str] = set()
|
||||
vision_available = lr_config.vision_model_available()
|
||||
for raw_path in file_paths:
|
||||
path = Path(raw_path)
|
||||
name = path.name
|
||||
if name in seen:
|
||||
failures[name] = "duplicate canonical basename in request"
|
||||
continue
|
||||
seen.add(name)
|
||||
try:
|
||||
doc = parse_service.parse(path)
|
||||
except ParserError as exc:
|
||||
self.logger.warning("LightRAG: parse failed for %s: %s", path.name, exc)
|
||||
continue
|
||||
parsed = parse_service.parse(path)
|
||||
item = ingress.freeze_document(working_dir, path, parsed)
|
||||
if "i" in item.process_options and not vision_available:
|
||||
item = replace(item, process_options=item.process_options.replace("i", ""))
|
||||
staged.append(item)
|
||||
except Exception as exc:
|
||||
failures[name or str(path)] = str(exc)
|
||||
return staged, failures
|
||||
|
||||
accepted_ledger: dict[str, Any] | None = None
|
||||
attempt_id: str | None = None
|
||||
if doc.blocks:
|
||||
document_id = doc.source_hash or path.stem
|
||||
decision = block_policy.prepare_content_list(
|
||||
doc.blocks,
|
||||
engine=doc.engine,
|
||||
source_hash=doc.source_hash,
|
||||
parser_signature=doc.parser_signature,
|
||||
)
|
||||
if decision.ledger is not None:
|
||||
outcome = "unknown_types" if decision.unknown_type_counts else "accepted"
|
||||
_, attempt_id = block_policy.write_attempt_ledger(
|
||||
Path(rag.working_dir).parent,
|
||||
document_id,
|
||||
decision.ledger,
|
||||
outcome=outcome,
|
||||
)
|
||||
counts = decision.ledger["counts"]
|
||||
self.logger.info(
|
||||
"MinerU block policy %s raw=%d filtered=%d eligible=%d unknown=%d",
|
||||
block_policy.POLICY_ID,
|
||||
counts["raw_total"],
|
||||
counts["filtered_total"],
|
||||
counts["eligible_total"],
|
||||
counts["unknown_total"],
|
||||
)
|
||||
if decision.unknown_type_counts:
|
||||
# Indexed, not dropped and not fatal — say so, because
|
||||
# this is the signal that the policy needs a new entry.
|
||||
self.logger.warning(
|
||||
"LightRAG: %s has MinerU block types with no policy "
|
||||
"entry (%s); indexing them unclassified",
|
||||
path.name,
|
||||
decision.unknown_summary(),
|
||||
)
|
||||
accepted_ledger = decision.ledger
|
||||
content_list = decision.content_list
|
||||
else:
|
||||
content_list = (
|
||||
[{"type": "text", "text": doc.markdown, "page_idx": 0}] if doc.markdown else []
|
||||
)
|
||||
if not content_list:
|
||||
self.logger.warning("LightRAG: empty document skipped: %s", path.name)
|
||||
continue
|
||||
|
||||
await engine.insert(
|
||||
rag,
|
||||
content_list,
|
||||
file_name=path.name,
|
||||
doc_id=doc.source_hash or path.stem,
|
||||
)
|
||||
async def _reconcile(
|
||||
self,
|
||||
rag: Any,
|
||||
staged: list[ingress.StagedDocument],
|
||||
preflight_failed: dict[str, str],
|
||||
track_id: str,
|
||||
io_bridge: OwnerLoopBridge,
|
||||
progress_callback: Callable[[int, int], Any] | None,
|
||||
) -> BatchOutcome:
|
||||
expected = {item.canonical_name: item for item in staged}
|
||||
last_snapshot: tuple[tuple[str, str], ...] | None = None
|
||||
last_progress = asyncio.get_running_loop().time()
|
||||
terminal_count = 0
|
||||
while True:
|
||||
io_bridge.raise_if_cancelled()
|
||||
doc_error = storage.document_error(Path(rag.working_dir), doc.source_hash or path.stem)
|
||||
if doc_error:
|
||||
raise RuntimeError(f"{path.name}: {doc_error}")
|
||||
if accepted_ledger is not None:
|
||||
block_policy.write_decision_ledger(
|
||||
Path(rag.working_dir),
|
||||
doc.source_hash or path.stem,
|
||||
accepted_ledger,
|
||||
attempt_id=attempt_id,
|
||||
rows = await rag.aget_docs_by_track_id(track_id)
|
||||
if not isinstance(rows, dict):
|
||||
raise engine.LightRagContractError("aget_docs_by_track_id must return an object")
|
||||
by_name: dict[str, tuple[str, Any]] = {}
|
||||
duplicates: set[str] = set()
|
||||
for doc_id, row in rows.items():
|
||||
name = _row_name(row)
|
||||
if name in by_name:
|
||||
duplicates.add(name)
|
||||
by_name[name] = (str(doc_id), row)
|
||||
if duplicates:
|
||||
raise engine.LightRagContractError(
|
||||
f"track_id returned duplicate canonical basenames: {sorted(duplicates)}"
|
||||
)
|
||||
inserted += 1
|
||||
self.logger.info("LightRAG: inserted %s", path.name)
|
||||
if progress_callback is not None:
|
||||
await io_bridge.call(progress_callback, inserted, total)
|
||||
return inserted
|
||||
|
||||
snapshot = tuple(
|
||||
sorted((name, _status_text(row)) for name, (_, row) in by_name.items())
|
||||
)
|
||||
if snapshot != last_snapshot:
|
||||
last_snapshot = snapshot
|
||||
last_progress = asyncio.get_running_loop().time()
|
||||
processed = tuple(
|
||||
sorted(
|
||||
name
|
||||
for name, (_, row) in by_name.items()
|
||||
if name in expected and _status_text(row) == "processed"
|
||||
)
|
||||
)
|
||||
failed = {
|
||||
name: _row_error(row)
|
||||
for name, (_, row) in by_name.items()
|
||||
if name in expected and _status_text(row) == "failed"
|
||||
}
|
||||
unknown = {
|
||||
name: _status_text(row)
|
||||
for name, (_, row) in by_name.items()
|
||||
if name in expected
|
||||
and _status_text(row)
|
||||
not in {
|
||||
"pending",
|
||||
"parsing",
|
||||
"analyzing",
|
||||
"processing",
|
||||
"preprocessed",
|
||||
"processed",
|
||||
"failed",
|
||||
}
|
||||
}
|
||||
active = {
|
||||
name: _status_text(row)
|
||||
for name, (_, row) in by_name.items()
|
||||
if name in expected
|
||||
and _status_text(row)
|
||||
in {"pending", "parsing", "analyzing", "processing", "preprocessed"}
|
||||
}
|
||||
missing = tuple(sorted(set(expected) - set(by_name)))
|
||||
current_terminal = len(processed) + len(failed)
|
||||
if progress_callback is not None and current_terminal != terminal_count:
|
||||
terminal_count = current_terminal
|
||||
await io_bridge.call(
|
||||
progress_callback, terminal_count, len(expected) + len(preflight_failed)
|
||||
)
|
||||
if not active and not missing:
|
||||
outcome = BatchOutcome(
|
||||
requested=len(expected) + len(preflight_failed),
|
||||
preflight_failed=preflight_failed,
|
||||
accepted=len(expected),
|
||||
processed=processed,
|
||||
failed=failed,
|
||||
nonterminal=unknown,
|
||||
missing=(),
|
||||
track_id=track_id,
|
||||
)
|
||||
for name in processed:
|
||||
item = expected[name]
|
||||
if item.audit_ledger is not None:
|
||||
doc_id = by_name[name][0]
|
||||
block_policy.write_decision_ledger(
|
||||
Path(rag.working_dir), doc_id, item.audit_ledger
|
||||
)
|
||||
return outcome
|
||||
if unknown:
|
||||
return BatchOutcome(
|
||||
requested=len(expected) + len(preflight_failed),
|
||||
preflight_failed=preflight_failed,
|
||||
accepted=len(expected),
|
||||
processed=processed,
|
||||
failed=failed,
|
||||
nonterminal=unknown,
|
||||
missing=missing,
|
||||
track_id=track_id,
|
||||
)
|
||||
if (
|
||||
asyncio.get_running_loop().time() - last_progress
|
||||
>= self._status_no_progress_seconds
|
||||
):
|
||||
return BatchOutcome(
|
||||
requested=len(expected) + len(preflight_failed),
|
||||
preflight_failed=preflight_failed,
|
||||
accepted=len(expected),
|
||||
processed=processed,
|
||||
failed=failed,
|
||||
nonterminal=active,
|
||||
missing=missing,
|
||||
track_id=track_id,
|
||||
)
|
||||
await asyncio.sleep(self._status_poll_seconds)
|
||||
|
||||
async def _run_indexing(
|
||||
self,
|
||||
working_dir: Path,
|
||||
file_paths: List[str],
|
||||
progress_callback: Callable[[int, int], Any] | None,
|
||||
) -> int:
|
||||
"""Run the complete local LightRAG indexing phase off the service loop.
|
||||
|
||||
The RAG instance is constructed and consumed in one worker thread, so
|
||||
its mutable stores and asyncio primitives never cross event loops.
|
||||
DeepTutor-owned network calls and progress callbacks cross back through
|
||||
``OwnerLoopBridge`` and remain responsive while local JSON storage is
|
||||
busy in the worker.
|
||||
"""
|
||||
|
||||
async def job(io_bridge: OwnerLoopBridge) -> int:
|
||||
) -> BatchOutcome:
|
||||
async def job(io_bridge: OwnerLoopBridge) -> BatchOutcome:
|
||||
io_bridge.raise_if_cancelled()
|
||||
rag = engine.build_rag(working_dir, io_bridge=io_bridge)
|
||||
failed = True
|
||||
try:
|
||||
result = await self._ingest(
|
||||
rag,
|
||||
file_paths,
|
||||
io_bridge=io_bridge,
|
||||
progress_callback=progress_callback,
|
||||
staged, preflight_failed = self._stage_documents(working_dir, file_paths)
|
||||
if not staged:
|
||||
raise LightRagBatchError(
|
||||
BatchOutcome(requested=len(file_paths), preflight_failed=preflight_failed)
|
||||
)
|
||||
try:
|
||||
rag = engine.build_rag(
|
||||
working_dir,
|
||||
io_bridge=io_bridge,
|
||||
enable_vlm=any("i" in item.process_options for item in staged),
|
||||
)
|
||||
except BaseException:
|
||||
for item in staged:
|
||||
ingress.remove_unaccepted(item)
|
||||
raise
|
||||
failed = True
|
||||
accepted = False
|
||||
enqueue_started = False
|
||||
cleanup: list[ingress.StagedDocument] = []
|
||||
try:
|
||||
await engine.initialize(rag)
|
||||
enqueue_started = True
|
||||
track_id = await engine.enqueue(rag, staged)
|
||||
if not isinstance(track_id, str) or not track_id.strip():
|
||||
raise engine.LightRagContractError(
|
||||
"LightRAG enqueue did not return a valid track_id"
|
||||
)
|
||||
accepted = True
|
||||
await rag.apipeline_process_enqueue_documents()
|
||||
outcome = await self._reconcile(
|
||||
rag,
|
||||
staged,
|
||||
preflight_failed,
|
||||
track_id,
|
||||
io_bridge,
|
||||
progress_callback,
|
||||
)
|
||||
if not outcome.complete:
|
||||
raise LightRagBatchError(outcome)
|
||||
failed = False
|
||||
return result
|
||||
return outcome
|
||||
except BaseException:
|
||||
if not enqueue_started:
|
||||
cleanup = staged
|
||||
elif not accepted:
|
||||
try:
|
||||
cleanup = await engine.confirmed_unaccepted(rag, staged)
|
||||
except BaseException:
|
||||
self.logger.exception(
|
||||
"Could not confirm which LightRAG documents were rejected; "
|
||||
"retaining all staged ingress"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
await engine.finalize(rag, cancel_pending=failed)
|
||||
except BaseException:
|
||||
if not failed:
|
||||
raise
|
||||
self.logger.exception(
|
||||
"LightRAG resource cleanup failed while indexing was aborting"
|
||||
)
|
||||
self.logger.exception("LightRAG cleanup failed while indexing was aborting")
|
||||
finally:
|
||||
for item in cleanup:
|
||||
ingress.remove_unaccepted(item)
|
||||
|
||||
return await run_in_worker_loop(job)
|
||||
|
||||
# ----- indexing -------------------------------------------------------
|
||||
def _remove_zero_accepted_candidate(self, root_dir: Path) -> None:
|
||||
if not root_dir.is_dir() or storage.has_any_doc_status(root_dir):
|
||||
return
|
||||
for ingress_dir in (ingress.pending_root(root_dir), ingress.bundles_root(root_dir)):
|
||||
if ingress_dir.is_dir() and any(path.is_file() for path in ingress_dir.rglob("*")):
|
||||
return
|
||||
shutil.rmtree(root_dir)
|
||||
|
||||
async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
|
||||
self._ensure_available()
|
||||
progress_callback = kwargs.get("progress_callback")
|
||||
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
|
||||
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
|
||||
self.logger.info(
|
||||
"Initializing KB '%s' with %d file(s) using LightRAG", kb_name, len(file_paths)
|
||||
)
|
||||
try:
|
||||
count = await self._run_indexing(
|
||||
storage.working_dir(root_dir), file_paths, progress_callback
|
||||
outcome = await self._run_indexing(
|
||||
root_dir, file_paths, kwargs.get("progress_callback")
|
||||
)
|
||||
if count == 0:
|
||||
self.logger.error("LightRAG: no extractable documents for '%s'", kb_name)
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
return False
|
||||
if not storage.has_output(root_dir):
|
||||
details = storage.failure_summary(root_dir)
|
||||
message = f"LightRAG did not produce a ready index for '{kb_name}'"
|
||||
if details:
|
||||
message = f"{message}: {details}"
|
||||
self.logger.error(message)
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
raise RuntimeError(message)
|
||||
raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")
|
||||
storage.write_meta(root_dir)
|
||||
self.logger.info("KB '%s' initialized with LightRAG (%d docs)", kb_name, count)
|
||||
return True
|
||||
return outcome.complete
|
||||
except asyncio.CancelledError:
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
raise
|
||||
except Exception as exc:
|
||||
self.logger.error("Failed to initialize LightRAG KB: %s", exc)
|
||||
self.logger.error(traceback.format_exc())
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
except LightRagBatchError as exc:
|
||||
if exc.outcome.accepted == 0:
|
||||
self._remove_zero_accepted_candidate(root_dir)
|
||||
raise
|
||||
except Exception:
|
||||
self._remove_zero_accepted_candidate(root_dir)
|
||||
raise
|
||||
|
||||
async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
|
||||
self._ensure_available()
|
||||
progress_callback = kwargs.get("progress_callback")
|
||||
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
|
||||
existing = resolve_storage_dir_for_read(kb_dir, None)
|
||||
if existing is not None and storage.has_output(existing):
|
||||
is_update = True
|
||||
if existing is not None and storage.meta_is_native_published(existing):
|
||||
root_dir = existing
|
||||
is_update = True
|
||||
elif existing is not None or list_kb_versions(kb_dir):
|
||||
raise LightRagNeedsReindexError(
|
||||
"This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt "
|
||||
"before appending."
|
||||
)
|
||||
else:
|
||||
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
|
||||
is_update = False
|
||||
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
|
||||
|
||||
self.logger.info(
|
||||
"Adding %d document(s) to LightRAG KB '%s' (update=%s)",
|
||||
len(file_paths),
|
||||
kb_name,
|
||||
is_update,
|
||||
)
|
||||
try:
|
||||
count = await self._run_indexing(
|
||||
storage.working_dir(root_dir), file_paths, progress_callback
|
||||
outcome = await self._run_indexing(
|
||||
root_dir, file_paths, kwargs.get("progress_callback")
|
||||
)
|
||||
if count == 0:
|
||||
self.logger.warning("LightRAG: no extractable documents to add for '%s'", kb_name)
|
||||
return False
|
||||
if not storage.has_output(root_dir):
|
||||
details = storage.failure_summary(root_dir)
|
||||
message = f"LightRAG did not produce a ready index for '{kb_name}'"
|
||||
if details:
|
||||
message = f"{message}: {details}"
|
||||
self.logger.error(message)
|
||||
if not is_update:
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
raise RuntimeError(message)
|
||||
raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")
|
||||
storage.write_meta(root_dir)
|
||||
self.logger.info("Added %d doc(s) to LightRAG KB '%s'", count, kb_name)
|
||||
return True
|
||||
except asyncio.CancelledError:
|
||||
if not is_update:
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
return outcome.complete
|
||||
except LightRagBatchError as exc:
|
||||
if not is_update and exc.outcome.accepted == 0:
|
||||
self._remove_zero_accepted_candidate(root_dir)
|
||||
raise
|
||||
except Exception as exc:
|
||||
self.logger.error("Failed to add documents to LightRAG KB: %s", exc)
|
||||
self.logger.error(traceback.format_exc())
|
||||
except Exception:
|
||||
if not is_update:
|
||||
self._cleanup_failed_version_dir(root_dir)
|
||||
self._remove_zero_accepted_candidate(root_dir)
|
||||
raise
|
||||
|
||||
# ----- retrieval ------------------------------------------------------
|
||||
|
||||
async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
|
||||
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
|
||||
root_dir = resolve_storage_dir_for_read(kb_dir, None)
|
||||
|
||||
if root_dir is None or not storage.has_output(root_dir):
|
||||
if root_dir is None or not storage.meta_is_native_published(root_dir):
|
||||
return {
|
||||
"query": query,
|
||||
"answer": (
|
||||
"This LightRAG knowledge base has no index yet. Add documents before querying."
|
||||
),
|
||||
"answer": "This LightRAG knowledge base must be rebuilt for the native pipeline.",
|
||||
"content": "",
|
||||
"sources": [],
|
||||
"provider": storage.PROVIDER,
|
||||
"needs_reindex": True,
|
||||
}
|
||||
|
||||
mode = self._resolve_mode(kb_name, kwargs)
|
||||
try:
|
||||
self._ensure_available()
|
||||
rag = engine.build_rag(storage.working_dir(root_dir))
|
||||
answer, sources = await engine.query_with_sources(rag, query, mode)
|
||||
|
||||
async def job(io_bridge: OwnerLoopBridge):
|
||||
rag = engine.build_rag(root_dir, io_bridge=io_bridge)
|
||||
failed = True
|
||||
try:
|
||||
await engine.initialize(rag)
|
||||
result = await engine.query_with_sources(rag, query, mode)
|
||||
failed = False
|
||||
return result
|
||||
finally:
|
||||
await engine.finalize(rag, cancel_pending=failed)
|
||||
|
||||
answer, sources = await run_in_worker_loop(job)
|
||||
except lr_config.LightRagNotAvailableError as exc:
|
||||
return self._error_result(query, exc, error_type="not_configured")
|
||||
except Exception as exc:
|
||||
self.logger.error("LightRAG search failed: %s", exc)
|
||||
self.logger.error(traceback.format_exc())
|
||||
return self._error_result(query, exc, error_type="retrieval_error")
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"answer": answer,
|
||||
@@ -346,15 +449,17 @@ class LightRagPipeline:
|
||||
"error_type": error_type,
|
||||
}
|
||||
|
||||
# ----- lifecycle ------------------------------------------------------
|
||||
|
||||
async def delete(self, kb_name: str, **kwargs) -> bool:
|
||||
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
|
||||
if kb_dir.exists():
|
||||
shutil.rmtree(kb_dir)
|
||||
self.logger.info("Deleted LightRAG KB '%s'", kb_name)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
__all__ = ["LightRagPipeline"]
|
||||
__all__ = [
|
||||
"BatchOutcome",
|
||||
"LightRagBatchError",
|
||||
"LightRagNeedsReindexError",
|
||||
"LightRagPipeline",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"""Map frozen DeepTutor MinerU blocks to LightRAG's public Sidecar IR."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
class SidecarMappingError(ValueError):
|
||||
"""Raised when a structured block cannot be represented without data loss."""
|
||||
|
||||
|
||||
def _text(item: dict[str, Any]) -> str:
|
||||
for key in ("text", "content", "body", "code_body"):
|
||||
value = item.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _strings(value: Any) -> list[str]:
|
||||
if isinstance(value, list):
|
||||
return [str(item).strip() for item in value if str(item).strip()]
|
||||
value = str(value or "").strip()
|
||||
return [value] if value else []
|
||||
|
||||
|
||||
def _position(item: dict[str, Any]):
|
||||
from lightrag.sidecar.ir import IRPosition
|
||||
|
||||
page = item.get("page_idx", item.get("page"))
|
||||
if isinstance(page, bool):
|
||||
page = None
|
||||
elif isinstance(page, int):
|
||||
page = str(page + 1) if page >= 0 else str(page)
|
||||
elif page is not None:
|
||||
page = str(page).strip() or None
|
||||
bbox = item.get("bbox")
|
||||
if isinstance(bbox, (list, tuple)) and len(bbox) >= 4:
|
||||
try:
|
||||
return IRPosition(type="bbox", anchor=page, range=[float(value) for value in bbox[:4]])
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return IRPosition(type="bbox", anchor=page) if page is not None else None
|
||||
|
||||
|
||||
def _heading(item: dict[str, Any], kind: str) -> tuple[str, int]:
|
||||
level = item.get("text_level", item.get("level", 0))
|
||||
try:
|
||||
level = int(level or 0)
|
||||
except (TypeError, ValueError):
|
||||
level = 0
|
||||
if kind in {"title", "section_header"}:
|
||||
return _text(item), max(level, 1)
|
||||
if kind == "text" and level > 0:
|
||||
return _text(item), level
|
||||
return "", 0
|
||||
|
||||
|
||||
def _rows(value: Any) -> list[list[str]] | None:
|
||||
if isinstance(value, str):
|
||||
stripped = value.strip()
|
||||
if stripped.startswith("["):
|
||||
try:
|
||||
value = json.loads(stripped)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
if not isinstance(value, list):
|
||||
return None
|
||||
rows: list[list[str]] = []
|
||||
for raw_row in value:
|
||||
if not isinstance(raw_row, list):
|
||||
continue
|
||||
rows.append(
|
||||
[
|
||||
str(cell.get("text", "")).strip() if isinstance(cell, dict) else str(cell).strip()
|
||||
for cell in raw_row
|
||||
]
|
||||
)
|
||||
return rows or None
|
||||
|
||||
|
||||
def _caption(item: dict[str, Any], *keys: str) -> str:
|
||||
direct = str(item.get("caption") or "").strip()
|
||||
if direct:
|
||||
return direct
|
||||
for key in keys:
|
||||
values = _strings(item.get(key))
|
||||
if values:
|
||||
return values[0]
|
||||
return ""
|
||||
|
||||
|
||||
def _resolve_asset(bundle: Path, manifest: dict[str, Any], raw: str) -> Path | None:
|
||||
if not raw:
|
||||
return None
|
||||
relative = Path(raw)
|
||||
if relative.is_absolute() or ".." in relative.parts:
|
||||
raise SidecarMappingError(f"Asset path escapes the frozen bundle: {raw}")
|
||||
candidates: list[Path] = []
|
||||
direct = bundle / "assets" / relative
|
||||
if direct.is_file():
|
||||
candidates.append(direct)
|
||||
basename = relative.name
|
||||
for record in manifest.get("assets", []):
|
||||
path = bundle / str(record.get("path") or "")
|
||||
if path.name == basename and path.is_file() and path not in candidates:
|
||||
candidates.append(path)
|
||||
if len(candidates) > 1:
|
||||
raise SidecarMappingError(f"Asset basename is ambiguous in the frozen bundle: {raw}")
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def build_ir(manifest: dict[str, Any], bundle: Path):
|
||||
"""Return an ``IRDoc`` using only LightRAG's public Sidecar types."""
|
||||
from lightrag.sidecar.ir import (
|
||||
AssetSpec,
|
||||
IRBlock,
|
||||
IRDoc,
|
||||
IRDrawing,
|
||||
IREquation,
|
||||
IRTable,
|
||||
)
|
||||
|
||||
blocks_record = manifest.get("blocks")
|
||||
if not isinstance(blocks_record, dict):
|
||||
raise SidecarMappingError("Sidecar mapping requires a blocks payload")
|
||||
raw_blocks = json.loads((bundle / blocks_record["path"]).read_text(encoding="utf-8"))
|
||||
if not isinstance(raw_blocks, list):
|
||||
raise SidecarMappingError("Frozen blocks payload is not an array")
|
||||
|
||||
output: list[Any] = []
|
||||
assets: list[Any] = []
|
||||
asset_refs: dict[Path, str] = {}
|
||||
heading_stack: list[str] = []
|
||||
current_lines: list[str] = []
|
||||
current_tables: list[Any] = []
|
||||
current_drawings: list[Any] = []
|
||||
current_equations: list[Any] = []
|
||||
current_positions: list[Any] = []
|
||||
current_heading = "Preface/Uncategorized"
|
||||
current_level = 0
|
||||
current_parents: list[str] = []
|
||||
sequence = 0
|
||||
document_title = ""
|
||||
|
||||
def next_key(prefix: str) -> str:
|
||||
nonlocal sequence
|
||||
sequence += 1
|
||||
return f"{prefix}{sequence}"
|
||||
|
||||
def flush() -> None:
|
||||
nonlocal \
|
||||
current_lines, \
|
||||
current_tables, \
|
||||
current_drawings, \
|
||||
current_equations, \
|
||||
current_positions
|
||||
content = "\n".join(line for line in current_lines if line).strip()
|
||||
if not content and not (current_tables or current_drawings or current_equations):
|
||||
current_lines = []
|
||||
current_positions = []
|
||||
return
|
||||
output.append(
|
||||
IRBlock(
|
||||
content_template=content,
|
||||
heading=current_heading,
|
||||
level=current_level,
|
||||
parent_headings=list(current_parents),
|
||||
positions=list(current_positions),
|
||||
tables=list(current_tables),
|
||||
drawings=list(current_drawings),
|
||||
equations=list(current_equations),
|
||||
)
|
||||
)
|
||||
current_lines = []
|
||||
current_tables = []
|
||||
current_drawings = []
|
||||
current_equations = []
|
||||
current_positions = []
|
||||
|
||||
for index, item in enumerate(raw_blocks):
|
||||
if not isinstance(item, dict):
|
||||
raise SidecarMappingError(f"Structured block {index} is not an object")
|
||||
kind = str(item.get("type") or item.get("label") or "").strip().lower()
|
||||
heading, level = _heading(item, kind)
|
||||
position = _position(item)
|
||||
if heading:
|
||||
flush()
|
||||
heading = re.sub(r"^#{1,6}\s+", "", heading).strip()
|
||||
heading_stack = heading_stack[: max(level - 1, 0)]
|
||||
current_parents = [value for value in heading_stack if value]
|
||||
heading_stack.append(heading)
|
||||
current_heading = heading
|
||||
current_level = level
|
||||
current_lines.append(f"{'#' * min(level, 6)} {heading}")
|
||||
if position is not None:
|
||||
current_positions.append(position)
|
||||
if not document_title and level == 1:
|
||||
document_title = heading
|
||||
continue
|
||||
|
||||
if kind in {"text", "aside_text", "page_footnote"}:
|
||||
value = _text(item)
|
||||
if value:
|
||||
current_lines.append(value)
|
||||
elif kind == "list":
|
||||
values = item.get("list_items")
|
||||
value = "\n".join(_strings(values)) if isinstance(values, list) else _text(item)
|
||||
if value:
|
||||
current_lines.append(value)
|
||||
elif kind == "code":
|
||||
value = str(item.get("code_body") or _text(item)).strip()
|
||||
if value:
|
||||
current_lines.extend(_strings(item.get("code_caption")))
|
||||
current_lines.append(value)
|
||||
current_lines.extend(_strings(item.get("code_footnote")))
|
||||
elif kind == "table":
|
||||
body = item.get("rows", item.get("table_body"))
|
||||
table_rows = _rows(body)
|
||||
table_html = (
|
||||
body.strip() if isinstance(body, str) and "<table" in body.lower() else None
|
||||
)
|
||||
if not table_rows and not table_html:
|
||||
raise SidecarMappingError(f"Structured table {index} has no usable body")
|
||||
key = next_key("tb")
|
||||
current_tables.append(
|
||||
IRTable(
|
||||
placeholder_key=key,
|
||||
rows=table_rows,
|
||||
html=table_html,
|
||||
num_rows=int(item.get("num_rows") or (len(table_rows) if table_rows else 0)),
|
||||
num_cols=int(
|
||||
item.get("num_cols") or (max(map(len, table_rows)) if table_rows else 0)
|
||||
),
|
||||
caption=_caption(item, "table_caption"),
|
||||
footnotes=_strings(item.get("table_footnote") or item.get("footnotes")),
|
||||
table_header=_rows(item.get("header")),
|
||||
self_ref=f"blocks.json#/{index}",
|
||||
)
|
||||
)
|
||||
current_lines.append(f"{{{{TBL:{key}}}}}")
|
||||
elif kind in {"image", "picture", "drawing", "chart"}:
|
||||
raw_path = str(item.get("img_path") or item.get("path") or "")
|
||||
asset_path = _resolve_asset(bundle, manifest, raw_path)
|
||||
if asset_path is None:
|
||||
raise SidecarMappingError(f"Structured {kind} {index} has no verified bundle asset")
|
||||
ref = ""
|
||||
ref = asset_refs.get(asset_path, "")
|
||||
if not ref:
|
||||
ref = f"asset-{len(asset_refs) + 1}"
|
||||
asset_refs[asset_path] = ref
|
||||
assets.append(AssetSpec(ref=ref, suggested_name=asset_path.name, source=asset_path))
|
||||
key = next_key("im")
|
||||
current_drawings.append(
|
||||
IRDrawing(
|
||||
placeholder_key=key,
|
||||
asset_ref=ref,
|
||||
fmt=Path(raw_path).suffix.lower().lstrip(".") or str(item.get("format") or ""),
|
||||
caption=_caption(item, "image_caption", "chart_caption", "captions"),
|
||||
footnotes=_strings(
|
||||
item.get("image_footnote")
|
||||
or item.get("chart_footnote")
|
||||
or item.get("footnotes")
|
||||
),
|
||||
src=str(item.get("src") or ""),
|
||||
self_ref=f"blocks.json#/{index}",
|
||||
)
|
||||
)
|
||||
current_lines.append(f"{{{{IMG:{key}}}}}")
|
||||
elif kind in {"equation", "formula"}:
|
||||
latex = _text(item)
|
||||
if not latex:
|
||||
raise SidecarMappingError(f"Structured equation {index} has no LaTeX")
|
||||
key = next_key("eq")
|
||||
inline = str(item.get("text_format") or "").lower() in {"inline", "inline_equation"}
|
||||
current_equations.append(
|
||||
IREquation(
|
||||
placeholder_key=key,
|
||||
latex=latex,
|
||||
is_block=not inline,
|
||||
caption=_caption(item, "equation_caption"),
|
||||
footnotes=_strings(item.get("equation_footnote") or item.get("footnotes")),
|
||||
self_ref=f"blocks.json#/{index}" if not inline else "",
|
||||
)
|
||||
)
|
||||
current_lines.append(f"{{{{{'EQI' if inline else 'EQ'}:{key}}}}}")
|
||||
else:
|
||||
value = _text(item)
|
||||
if not value:
|
||||
raise SidecarMappingError(
|
||||
f"Unknown structured block type {kind or '<missing>'!r} at {index} has no preservable text"
|
||||
)
|
||||
current_lines.append(value)
|
||||
if position is not None:
|
||||
current_positions.append(position)
|
||||
|
||||
flush()
|
||||
if not output:
|
||||
raise SidecarMappingError("Structured document produced no Sidecar blocks")
|
||||
name = str(manifest.get("canonical_filename") or "document")
|
||||
return IRDoc(
|
||||
document_name=name,
|
||||
document_format=Path(name).suffix.lower().lstrip("."),
|
||||
doc_title=document_title or Path(name).stem,
|
||||
split_option={
|
||||
"parser": str((manifest.get("parser") or {}).get("engine") or ""),
|
||||
"parser_signature": str((manifest.get("parser") or {}).get("parser_signature") or ""),
|
||||
},
|
||||
blocks=output,
|
||||
assets=assets,
|
||||
bbox_attributes={"origin": "LEFTTOP", "max": 1000},
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["SidecarMappingError", "build_ir"]
|
||||
@@ -31,6 +31,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
META_FILENAME = "meta.json"
|
||||
PROVIDER = "lightrag"
|
||||
ADAPTER_SCHEMA = 2
|
||||
PUBLISHED_STATE = "published"
|
||||
|
||||
# Glob patterns LightRAG writes once it has actually built chunk/vector data.
|
||||
# A graphml file alone is not enough: LightRAG creates an empty graph at startup
|
||||
@@ -46,11 +48,26 @@ def working_dir(root_dir: Path) -> Path:
|
||||
return Path(root_dir)
|
||||
|
||||
|
||||
def _store_root(root_dir: Path) -> Path:
|
||||
"""Resolve native workspace storage while retaining legacy flat reads."""
|
||||
root = Path(root_dir)
|
||||
if (root / _DOC_STATUS_FILENAME).exists() or any(root.glob("vdb_*.json")):
|
||||
return root
|
||||
meta = _read_meta(root)
|
||||
workspace = str((meta or {}).get("workspace") or "").strip()
|
||||
if not workspace:
|
||||
from .engine import workspace_for
|
||||
|
||||
workspace = workspace_for(root)
|
||||
candidate = root / workspace
|
||||
return candidate if candidate.is_dir() else root
|
||||
|
||||
|
||||
def has_output(root_dir: Path | None) -> bool:
|
||||
"""True when LightRAG has at least one successfully indexed document."""
|
||||
if root_dir is None:
|
||||
return False
|
||||
root = Path(root_dir)
|
||||
root = _store_root(Path(root_dir))
|
||||
if not root.is_dir():
|
||||
return False
|
||||
|
||||
@@ -93,7 +110,7 @@ def failure_summary(root_dir: Path | None, *, limit: int = 3) -> str:
|
||||
"""Return a short human-readable summary of failed LightRAG documents."""
|
||||
if root_dir is None:
|
||||
return ""
|
||||
payload = _read_doc_status(Path(root_dir))
|
||||
payload = _read_doc_status(_store_root(Path(root_dir)))
|
||||
if not payload:
|
||||
return ""
|
||||
|
||||
@@ -116,7 +133,7 @@ def document_error(root_dir: Path | None, doc_id: str) -> str:
|
||||
"""Return the stored LightRAG error for one document, if present."""
|
||||
if root_dir is None or not doc_id:
|
||||
return ""
|
||||
payload = _read_doc_status(Path(root_dir))
|
||||
payload = _read_doc_status(_store_root(Path(root_dir)))
|
||||
if not payload:
|
||||
return ""
|
||||
item = payload.get(doc_id)
|
||||
@@ -142,6 +159,58 @@ def _read_doc_status(root_dir: Path) -> dict[str, Any] | None:
|
||||
return None
|
||||
|
||||
|
||||
def has_any_doc_status(root_dir: Path | None) -> bool:
|
||||
if root_dir is None:
|
||||
return False
|
||||
payload = _read_doc_status(_store_root(Path(root_dir)))
|
||||
return bool(payload)
|
||||
|
||||
|
||||
def _read_meta(root_dir: Path) -> dict[str, Any] | None:
|
||||
path = Path(root_dir) / META_FILENAME
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
return payload if isinstance(payload, dict) else None
|
||||
|
||||
|
||||
def meta_is_native_published(root_dir: Path | None) -> bool:
|
||||
if root_dir is None:
|
||||
return False
|
||||
meta = _read_meta(Path(root_dir))
|
||||
return bool(
|
||||
meta
|
||||
and meta.get("provider") == PROVIDER
|
||||
and meta.get("signature") == PROVIDER
|
||||
and meta.get("lightrag_adapter_schema") == ADAPTER_SCHEMA
|
||||
and meta.get("parser_bridge_schema") == 1
|
||||
and meta.get("state") == PUBLISHED_STATE
|
||||
and has_output(Path(root_dir))
|
||||
)
|
||||
|
||||
|
||||
def _parser_inputs(root_dir: Path) -> list[dict[str, str]]:
|
||||
from .ingress import bundles_root, load_verified_bundle
|
||||
|
||||
records: set[tuple[str, str]] = set()
|
||||
for bundle in sorted(bundles_root(root_dir).glob("*.bundle")):
|
||||
canonical_name = bundle.name.removesuffix(".bundle")
|
||||
manifest, _ = load_verified_bundle(root_dir, canonical_name)
|
||||
parser = manifest.get("parser")
|
||||
if not isinstance(parser, dict):
|
||||
continue
|
||||
records.add(
|
||||
(
|
||||
str(parser.get("engine") or ""),
|
||||
str(parser.get("parser_signature") or ""),
|
||||
)
|
||||
)
|
||||
return [
|
||||
{"engine": engine, "parser_signature": signature} for engine, signature in sorted(records)
|
||||
]
|
||||
|
||||
|
||||
def write_meta(root_dir: Path) -> None:
|
||||
"""Write a flat-layout ``meta.json`` so the version lists as ready.
|
||||
|
||||
@@ -153,13 +222,24 @@ def write_meta(root_dir: Path) -> None:
|
||||
"""
|
||||
from deeptutor.services.rag.embedding_signature import embedding_meta_fields
|
||||
|
||||
from .engine import installed_version, workspace_for
|
||||
|
||||
target = Path(root_dir)
|
||||
previous = _read_meta(target) or {}
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||
payload = {
|
||||
"version": target.name,
|
||||
"signature": PROVIDER,
|
||||
"provider": PROVIDER,
|
||||
"state": PUBLISHED_STATE,
|
||||
"lightrag_adapter_schema": ADAPTER_SCHEMA,
|
||||
"lightrag_package_version": installed_version(),
|
||||
"parser_bridge_schema": 1,
|
||||
"parser_inputs": _parser_inputs(target),
|
||||
"workspace": workspace_for(target),
|
||||
"layout": "flat",
|
||||
"created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
|
||||
"created_at": str(previous.get("created_at") or now),
|
||||
"updated_at": now,
|
||||
**embedding_meta_fields(),
|
||||
}
|
||||
atomic_write_json(target / META_FILENAME, payload)
|
||||
@@ -170,7 +250,9 @@ __all__ = [
|
||||
"PROVIDER",
|
||||
"document_error",
|
||||
"failure_summary",
|
||||
"has_any_doc_status",
|
||||
"working_dir",
|
||||
"has_output",
|
||||
"meta_is_native_published",
|
||||
"write_meta",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Event-loop isolation helpers for local LightRAG indexing.
|
||||
|
||||
RAG-Anything's local storage backends perform synchronous graph merging and
|
||||
LightRAG's local storage backends perform synchronous graph merging and
|
||||
JSON serialization from inside async methods. Running those methods on the
|
||||
service event loop therefore stalls unrelated API and LLM work. This module
|
||||
provides one narrow boundary: run the indexing coroutine on a worker thread's
|
||||
|
||||
@@ -147,10 +147,19 @@ def _graphrag_preflight() -> dict:
|
||||
|
||||
|
||||
def _lightrag_preflight() -> dict:
|
||||
package_detail = "pip install 'deeptutor[rag-lightrag]'"
|
||||
try:
|
||||
from .pipelines.lightrag.config import is_lightrag_available
|
||||
from .pipelines.lightrag.engine import LIGHTRAG_VERSION, installed_version
|
||||
|
||||
installed = is_lightrag_available()
|
||||
current_version = installed_version() if is_lightrag_available() else ""
|
||||
installed = current_version == LIGHTRAG_VERSION
|
||||
if current_version:
|
||||
package_detail = (
|
||||
f"Installed {current_version}."
|
||||
if installed
|
||||
else f"Found {current_version}; required {LIGHTRAG_VERSION}."
|
||||
)
|
||||
except Exception:
|
||||
installed = False
|
||||
emb_model, emb_dim = _active_embedding()
|
||||
@@ -167,9 +176,9 @@ def _lightrag_preflight() -> dict:
|
||||
[
|
||||
_check(
|
||||
"package",
|
||||
"RAG-Anything package installed",
|
||||
"LightRAG package installed",
|
||||
installed,
|
||||
"Installed." if installed else "pip install 'deeptutor[rag-lightrag]'",
|
||||
package_detail,
|
||||
),
|
||||
_check(
|
||||
"chat",
|
||||
@@ -189,7 +198,7 @@ def _lightrag_preflight() -> dict:
|
||||
vision_ok,
|
||||
"Active chat model supports vision."
|
||||
if vision_ok
|
||||
else "Active chat model has no vision — multimodal documents fall back to text.",
|
||||
else "Active chat model has no vision — image analysis is disabled.",
|
||||
optional=True,
|
||||
),
|
||||
]
|
||||
|
||||
@@ -55,7 +55,7 @@ dependencies = [
|
||||
"openpyxl>=3.1.0",
|
||||
"python-pptx>=1.0.0",
|
||||
"pypdf>=4.0.0",
|
||||
"pdfplumber>=0.11.0,<0.11.8",
|
||||
"pdfplumber>=0.11.0",
|
||||
"reportlab>=4.0.0",
|
||||
"defusedxml>=0.7.1",
|
||||
]
|
||||
|
||||
+9
-17
@@ -12,8 +12,8 @@ description = "An agent-native intelligent learning companion with multi-agent c
|
||||
# Capped below 3.14 on purpose (issue #664): on 3.14 pip can't find wheels for
|
||||
# some compiled base deps (e.g. faiss-cpu) and silently backtracks into a
|
||||
# doomed source build that dies with "subprocess-exited-with-error". The heavy
|
||||
# RAG extras (graphrag, rag-lightrag) already carry a `python_version < '3.14'`
|
||||
# marker for the same reason; capping here makes pip refuse 3.14 with a
|
||||
# GraphRAG also carries a `python_version < '3.14'` marker; capping the project
|
||||
# itself makes every install, including LightRAG, refuse 3.14 with a
|
||||
# readable "Requires a different Python" message instead of a build failure.
|
||||
requires-python = ">=3.11,<3.14"
|
||||
readme = "README.md"
|
||||
@@ -61,7 +61,7 @@ dependencies = [
|
||||
"openpyxl>=3.1.0",
|
||||
"python-pptx>=1.0.0",
|
||||
"pypdf>=4.0.0",
|
||||
"pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
|
||||
"pdfplumber>=0.11.0",
|
||||
"reportlab>=4.0.0",
|
||||
"defusedxml>=0.7.1",
|
||||
"fastapi>=0.100.0",
|
||||
@@ -109,7 +109,7 @@ cli = [
|
||||
"openpyxl>=3.1.0",
|
||||
"python-pptx>=1.0.0",
|
||||
"pypdf>=4.0.0",
|
||||
"pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
|
||||
"pdfplumber>=0.11.0",
|
||||
"reportlab>=4.0.0",
|
||||
"defusedxml>=0.7.1",
|
||||
]
|
||||
@@ -228,19 +228,11 @@ math-animator = ["manim>=0.19.0"]
|
||||
# (1.4.5) and silently downgrades. Floor is 3.0.1 (3.0.0/3.0.3 were yanked).
|
||||
graphrag = ["graphrag>=3.0.1,<4.0.0; python_version < '3.14'"]
|
||||
|
||||
# LightRAG knowledge-base engine (HKUDS/LightRAG) with multimodal parsing via
|
||||
# RAG-Anything (HKUDS/RAG-Anything). Optional, heavy (pulls MinerU transitively —
|
||||
# see the pdfplumber pin above). The pipeline imports lazily and the adapter is
|
||||
# isolated in services/rag/pipelines/lightrag/engine.py. raganything pulls
|
||||
# `mineru[core]`, which is capped at python <3.14, so this carries the same
|
||||
# `python_version` marker as graphrag to avoid a silent backtrack/downgrade on
|
||||
# 3.14+. Floor is 1.0.1 (no 1.0.0 was ever published) with a <2.0.0 ceiling so
|
||||
# a future API-breaking 2.x isn't pulled in silently.
|
||||
# 1.2.5 is the first release carrying the ``lightrag_kwargs`` passthrough the
|
||||
# LightRAG concurrency/extraction settings ride on. Older installs still run —
|
||||
# engine.py drops knobs the installed version cannot take — but a fresh install
|
||||
# should get the capable one.
|
||||
rag-lightrag = ["raganything>=1.2.5,<2.0.0; python_version < '3.14'"]
|
||||
# Built-in LightRAG provider. The exact release is intentional: the adapter
|
||||
# isolates a private rc2 source-resolver seam and locks it with smoke tests.
|
||||
# MinerU remains an independently selected DeepTutor parser and is not a
|
||||
# transitive dependency of this extra.
|
||||
rag-lightrag = ["lightrag-hku==1.5.7rc2"]
|
||||
|
||||
# Dev/test tooling. Mirrors requirements/dev.txt.
|
||||
dev = [
|
||||
|
||||
@@ -52,7 +52,7 @@ python-docx>=1.1.0
|
||||
openpyxl>=3.1.0
|
||||
python-pptx>=1.0.0
|
||||
pypdf>=4.0.0
|
||||
pdfplumber>=0.11.0,<0.11.8 # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
|
||||
pdfplumber>=0.11.0
|
||||
reportlab>=4.0.0
|
||||
defusedxml>=0.7.1
|
||||
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# LightRAG parser-bridge fixtures
|
||||
|
||||
`original.pdf` is generated by `generate_original_pdf.py` and is original
|
||||
DeepTutor test material licensed under the repository's Apache-2.0 license. It
|
||||
contains only synthetic text, an equation, a small table, and a drawn rectangle;
|
||||
it has no third-party document content.
|
||||
|
||||
Generated file SHA-256: `e2abd3404f3a03d90c36feec19786689892434e730841cbdbd2a1a28875f3a80`.
|
||||
|
||||
Golden parser outputs in this directory must record the exact source commit or
|
||||
authenticated MinerU API capture date, response schema/version, capture command,
|
||||
and SHA-256. Secrets and transient service metadata must never be committed.
|
||||
|
||||
The current MinerU v4 capture is produced interactively with:
|
||||
|
||||
```bash
|
||||
.venv/bin/python tests/fixtures/lightrag_bridge/capture_current_mineru.py
|
||||
```
|
||||
|
||||
The script prompts privately with `getpass`; it does not accept the token in a
|
||||
command argument, environment variable, output file, or log.
|
||||
|
||||
`mineru-legacy-official-example/content_list.json` is extracted byte-for-byte
|
||||
from the official MinerU documentation at commit
|
||||
`61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99` by
|
||||
`extract_legacy_example.py`. Its provenance explicitly identifies it as an
|
||||
official schema example, not a live parser run. The authenticated current
|
||||
capture remains the real-output fixture for `original.pdf`.
|
||||
|
||||
## Frozen mapping contract
|
||||
|
||||
| MinerU field | LightRAG public Sidecar field | Failure boundary |
|
||||
| --- | --- | --- |
|
||||
| `title`, `section_header`, or positive `text_level` | `IRBlock.heading`, `level`, `parent_headings` | Empty headings remain ordinary content and cannot create a hierarchy node. |
|
||||
| `text`, `content`, `body`, `code_body` | `IRBlock.content_template` | An unknown block with none of these non-empty fields fails the document. |
|
||||
| `rows` or `table_body` | `IRTable.rows` or `html` | A table with neither a row matrix nor HTML fails before analysis. |
|
||||
| `table_caption`, `header`, `table_footnote` | `caption`, `table_header`, `footnotes` | Malformed optional values normalize to empty fields; table body remains mandatory. |
|
||||
| `img_path` or `path` | verified `AssetSpec` plus `IRDrawing.asset_ref` | Absolute/traversal/missing/ambiguous/unfrozen assets fail the document. |
|
||||
| `image_caption`/`chart_caption`, image/chart footnote, format | `IRDrawing.caption`, `footnotes`, `fmt` | No prompt-only or missing-asset fallback is allowed. |
|
||||
| equation text/body plus `text_format` | `IREquation.latex`, `is_block` | Empty equation content fails the document. |
|
||||
| `page_idx` or `page`, and `bbox` | `IRPosition.anchor`, `range` | Integer `page_idx` is converted from zero-based to one-based; invalid bbox is omitted. |
|
||||
|
||||
Both raw parser fixtures and expected Sidecar assertions are immutable test
|
||||
inputs. Production code may import only LightRAG's public Sidecar IR and writer;
|
||||
the upstream MinerU builder is comparison evidence, not a runtime dependency.
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Capture a current authenticated MinerU v4 result without storing its token."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import getpass
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from deeptutor.services.parsing.engines.mineru.cloud import parse_cloud
|
||||
from deeptutor.services.parsing.engines.mineru.config import MinerUConfig
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SOURCE = HERE / "original.pdf"
|
||||
TARGET = HERE / "mineru-v2-current"
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if TARGET.exists():
|
||||
raise SystemExit(f"Refusing to overwrite existing capture: {TARGET}")
|
||||
token = getpass.getpass("MinerU API token (not stored): ").strip()
|
||||
if not token:
|
||||
raise SystemExit("No token entered")
|
||||
config = MinerUConfig(
|
||||
mode="cloud",
|
||||
api_token=token,
|
||||
model_version="pipeline",
|
||||
enable_formula=True,
|
||||
enable_table=True,
|
||||
)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="deeptutor-mineru-capture-") as raw:
|
||||
parsed = parse_cloud(SOURCE, Path(raw), config)
|
||||
candidates = sorted(parsed.rglob("*_content_list.json"))
|
||||
if len(candidates) != 1:
|
||||
raise RuntimeError(f"Expected one content_list artifact, found {len(candidates)}")
|
||||
content_root = candidates[0].parent
|
||||
shutil.copytree(content_root, TARGET)
|
||||
finally:
|
||||
token = ""
|
||||
|
||||
files = {
|
||||
path.relative_to(TARGET).as_posix(): _sha256(path)
|
||||
for path in sorted(TARGET.rglob("*"))
|
||||
if path.is_file()
|
||||
}
|
||||
provenance = {
|
||||
"capture_schema": 1,
|
||||
"captured_at_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"service": "https://mineru.net/api/v4",
|
||||
"model_version": "pipeline",
|
||||
"authenticated": True,
|
||||
"source": {"path": "../original.pdf", "sha256": _sha256(SOURCE)},
|
||||
"artifacts": files,
|
||||
}
|
||||
(TARGET / "deeptutor-fixture-provenance.json").write_text(
|
||||
json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
||||
)
|
||||
print(f"Captured {len(files)} artifact(s) in {TARGET}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Extract MinerU's official legacy content-list example byte-for-byte."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
COMMIT = "61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99"
|
||||
SOURCE_PATH = "docs/en/reference/output_files.md"
|
||||
DEFAULT_REPOSITORY = Path("/home/ubuntu/sources/github.com/opendatalab/MinerU")
|
||||
HERE = Path(__file__).resolve().parent
|
||||
TARGET = HERE / "mineru-legacy-official-example"
|
||||
|
||||
|
||||
def main(repository: Path = DEFAULT_REPOSITORY) -> None:
|
||||
if TARGET.exists():
|
||||
raise SystemExit(f"Refusing to overwrite existing fixture: {TARGET}")
|
||||
markdown = subprocess.check_output(
|
||||
["git", "-C", str(repository), "show", f"{COMMIT}:{SOURCE_PATH}"], text=True
|
||||
)
|
||||
heading = "#### Content List (content_list.json)"
|
||||
section = markdown.split(heading, 1)[1]
|
||||
sample = section.split("##### Sample Data", 1)[1]
|
||||
payload = sample.split("```json", 1)[1].split("```", 1)[0].strip().encode("utf-8") + b"\n"
|
||||
json.loads(payload)
|
||||
TARGET.mkdir()
|
||||
output = TARGET / "content_list.json"
|
||||
output.write_bytes(payload)
|
||||
provenance = {
|
||||
"fixture_schema": 1,
|
||||
"kind": "official-legacy-schema-example",
|
||||
"repository": "https://github.com/opendatalab/MinerU.git",
|
||||
"commit": COMMIT,
|
||||
"source_path": SOURCE_PATH,
|
||||
"source_section": heading,
|
||||
"content_sha256": hashlib.sha256(payload).hexdigest(),
|
||||
"note": "Exact official documentation example; not a live parser capture.",
|
||||
}
|
||||
(TARGET / "deeptutor-fixture-provenance.json").write_text(
|
||||
json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Generate the redistributable MinerU bridge fixture PDF."""
|
||||
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
TARGET = Path(__file__).with_name("original.pdf")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
page = canvas.Canvas(str(TARGET), pagesize=letter, invariant=True)
|
||||
page.setTitle("DeepTutor LightRAG Bridge Fixture")
|
||||
page.setAuthor("DeepTutor contributors")
|
||||
page.setFont("Helvetica-Bold", 18)
|
||||
page.drawString(72, 720, "DeepTutor LightRAG Bridge Fixture")
|
||||
page.setFont("Helvetica", 11)
|
||||
page.drawString(72, 690, "A short paragraph preserves text and heading hierarchy.")
|
||||
page.setFont("Times-Italic", 18)
|
||||
page.drawCentredString(306, 650, "E = m c^2")
|
||||
|
||||
page.setFont("Helvetica-Bold", 11)
|
||||
page.drawString(72, 610, "Table 1. Retrieval engine paths")
|
||||
columns = (72, 222, 372)
|
||||
rows = (590, 566, 542)
|
||||
for x in columns:
|
||||
page.line(x, rows[-1], x, rows[0])
|
||||
for y in rows:
|
||||
page.line(columns[0], y, columns[-1], y)
|
||||
page.setFont("Helvetica", 10)
|
||||
page.drawString(82, 574, "Engine")
|
||||
page.drawString(232, 574, "Path")
|
||||
page.drawString(82, 550, "LightRAG")
|
||||
page.drawString(232, 550, "Native")
|
||||
|
||||
image = Image.new("RGB", (360, 160), "white")
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.line((35, 130, 330, 130), fill="black", width=3)
|
||||
draw.line((35, 20, 35, 130), fill="black", width=3)
|
||||
draw.line((50, 110, 140, 75, 230, 90, 315, 35), fill="#1f77b4", width=6)
|
||||
draw.text((85, 135), "Deterministic fixture chart", fill="black")
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
buffer.seek(0)
|
||||
page.drawImage(ImageReader(buffer), 72, 340, width=360, height=160, mask="auto")
|
||||
page.setFont("Helvetica", 10)
|
||||
page.drawString(72, 322, "Figure 1. Synthetic trend chart.")
|
||||
page.showPage()
|
||||
page.save()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
[
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The response of flow duration curves to afforestation ",
|
||||
"text_level": 1,
|
||||
"bbox": [
|
||||
62,
|
||||
480,
|
||||
946,
|
||||
904
|
||||
],
|
||||
"page_idx": 0
|
||||
},
|
||||
{
|
||||
"type": "image",
|
||||
"img_path": "images/a8ecda1c69b27e4f79fce1589175a9d721cbdc1cf78b4cc06a015f3746f6b9d8.jpg",
|
||||
"img_caption": [
|
||||
"Fig. 1. Annual flow duration curves of daily flows from Pine Creek, Australia, 1989–2000. "
|
||||
],
|
||||
"img_footnote": [],
|
||||
"bbox": [
|
||||
62,
|
||||
480,
|
||||
946,
|
||||
904
|
||||
],
|
||||
"page_idx": 1
|
||||
},
|
||||
{
|
||||
"type": "equation",
|
||||
"img_path": "images/181ea56ef185060d04bf4e274685f3e072e922e7b839f093d482c29bf89b71e8.jpg",
|
||||
"text": "$$\nQ _ { \\% } = f ( P ) + g ( T )\n$$",
|
||||
"text_format": "latex",
|
||||
"bbox": [
|
||||
62,
|
||||
480,
|
||||
946,
|
||||
904
|
||||
],
|
||||
"page_idx": 2
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"img_path": "images/e3cb413394a475e555807ffdad913435940ec637873d673ee1b039e3bc3496d0.jpg",
|
||||
"table_caption": [
|
||||
"Table 2 Significance of the rainfall and time terms "
|
||||
],
|
||||
"table_footnote": [
|
||||
"indicates that the rainfall term was significant at the $5 \\%$ level, $T$ indicates that the time term was significant at the $5 \\%$ level, \\* represents significance at the $10 \\%$ level, and na denotes too few data points for meaningful analysis. "
|
||||
],
|
||||
"table_body": "<html><body><table><tr><td rowspan=\"2\">Site</td><td colspan=\"10\">Percentile</td></tr><tr><td>10</td><td>20</td><td>30</td><td>40</td><td>50</td><td>60</td><td>70</td><td>80</td><td>90</td><td>100</td></tr><tr><td>Traralgon Ck</td><td>P</td><td>P,*</td><td>P</td><td>P</td><td>P,</td><td>P,</td><td>P,</td><td>P,</td><td>P</td><td>P</td></tr><tr><td>Redhill</td><td>P,T</td><td>P,T</td><td>,*</td><td>**</td><td>P.T</td><td>P,*</td><td>P*</td><td>P*</td><td>*</td><td>,*</td></tr><tr><td>Pine Ck</td><td></td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td><td>T</td><td>na</td><td>na</td></tr><tr><td>Stewarts Ck 5</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P.T</td><td>P.T</td><td>P,T</td><td>na</td><td>na</td><td>na</td></tr><tr><td>Glendhu 2</td><td>P</td><td>P,T</td><td>P,*</td><td>P,T</td><td>P.T</td><td>P,ns</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td></tr><tr><td>Cathedral Peak 2</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Cathedral Peak 3</td><td>P.T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Lambrechtsbos A</td><td>P,T</td><td>P</td><td>P</td><td>P,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>T</td></tr><tr><td>Lambrechtsbos B</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td></tr><tr><td>Biesievlei</td><td>P,T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>*,T</td><td>T</td><td>T</td><td>P,T</td><td>P,T</td></tr></table></body></html>",
|
||||
"bbox": [
|
||||
62,
|
||||
480,
|
||||
946,
|
||||
904
|
||||
],
|
||||
"page_idx": 5
|
||||
}
|
||||
]
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"commit": "61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99",
|
||||
"content_sha256": "e3a09b50a8a902a584452ca7085533fa6fe294bffe400c0dcabfdbe0339b92b7",
|
||||
"fixture_schema": 1,
|
||||
"kind": "official-legacy-schema-example",
|
||||
"note": "Exact official documentation example; not a live parser capture.",
|
||||
"repository": "https://github.com/opendatalab/MinerU.git",
|
||||
"source_path": "docs/en/reference/output_files.md",
|
||||
"source_section": "#### Content List (content_list.json)"
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
[
|
||||
{
|
||||
"type": "text",
|
||||
"text": "DeepTutor LightRAG Bridge Fixture",
|
||||
"text_level": 2,
|
||||
"bbox": [
|
||||
114,
|
||||
70,
|
||||
619,
|
||||
97
|
||||
],
|
||||
"page_idx": 0
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"text": "A short paragraph preserves text and heading hierarchy.",
|
||||
"bbox": [
|
||||
111,
|
||||
114,
|
||||
568,
|
||||
133
|
||||
],
|
||||
"page_idx": 0
|
||||
},
|
||||
{
|
||||
"type": "equation",
|
||||
"img_path": "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg",
|
||||
"text": "$$\nE = m c ^ { \\wedge } 2\n$$",
|
||||
"text_format": "latex",
|
||||
"bbox": [
|
||||
434,
|
||||
160,
|
||||
562,
|
||||
181
|
||||
],
|
||||
"page_idx": 0
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"img_path": "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg",
|
||||
"table_caption": [
|
||||
"Table 1. Retrieval engine paths"
|
||||
],
|
||||
"table_footnote": [],
|
||||
"table_body": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
|
||||
"bbox": [
|
||||
114,
|
||||
251,
|
||||
607,
|
||||
314
|
||||
],
|
||||
"page_idx": 0
|
||||
},
|
||||
{
|
||||
"type": "chart",
|
||||
"img_path": "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg",
|
||||
"content": "",
|
||||
"chart_caption": [
|
||||
"Figure 1. Synthetic trend chart."
|
||||
],
|
||||
"chart_footnote": [],
|
||||
"bbox": [
|
||||
166,
|
||||
386,
|
||||
658,
|
||||
556
|
||||
],
|
||||
"page_idx": 0
|
||||
}
|
||||
]
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
[
|
||||
[
|
||||
{
|
||||
"type": "title",
|
||||
"content": {
|
||||
"title_content": [
|
||||
{
|
||||
"type": "text",
|
||||
"content": "DeepTutor LightRAG Bridge Fixture"
|
||||
}
|
||||
],
|
||||
"level": 2
|
||||
},
|
||||
"bbox": [
|
||||
114,
|
||||
70,
|
||||
619,
|
||||
97
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "paragraph",
|
||||
"content": {
|
||||
"paragraph_content": [
|
||||
{
|
||||
"type": "text",
|
||||
"content": "A short paragraph preserves text and heading hierarchy."
|
||||
}
|
||||
]
|
||||
},
|
||||
"bbox": [
|
||||
111,
|
||||
114,
|
||||
568,
|
||||
133
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "equation_interline",
|
||||
"content": {
|
||||
"math_content": "E = m c ^ { \\wedge } 2",
|
||||
"math_type": "latex",
|
||||
"image_source": {
|
||||
"path": "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"
|
||||
}
|
||||
},
|
||||
"bbox": [
|
||||
434,
|
||||
160,
|
||||
562,
|
||||
181
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"content": {
|
||||
"image_source": {
|
||||
"path": "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"
|
||||
},
|
||||
"table_caption": [
|
||||
{
|
||||
"type": "text",
|
||||
"content": "Table 1. Retrieval engine paths"
|
||||
}
|
||||
],
|
||||
"table_footnote": [],
|
||||
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
|
||||
"table_type": "simple_table",
|
||||
"table_nest_level": 1
|
||||
},
|
||||
"bbox": [
|
||||
114,
|
||||
251,
|
||||
607,
|
||||
314
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "chart",
|
||||
"content": {
|
||||
"image_source": {
|
||||
"path": "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"
|
||||
},
|
||||
"content": "",
|
||||
"chart_caption": [
|
||||
{
|
||||
"type": "text",
|
||||
"content": "Figure 1. Synthetic trend chart."
|
||||
}
|
||||
],
|
||||
"chart_footnote": []
|
||||
},
|
||||
"bbox": [
|
||||
166,
|
||||
386,
|
||||
658,
|
||||
556
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
Vendored
+141
@@ -0,0 +1,141 @@
|
||||
[
|
||||
{
|
||||
"layout_dets": [
|
||||
{
|
||||
"cls_id": 17,
|
||||
"label": "paragraph_title",
|
||||
"score": 0.5515,
|
||||
"bbox": [
|
||||
195,
|
||||
156,
|
||||
1055,
|
||||
215
|
||||
],
|
||||
"index": 1
|
||||
},
|
||||
{
|
||||
"cls_id": 22,
|
||||
"label": "text",
|
||||
"score": 0.9291,
|
||||
"bbox": [
|
||||
191,
|
||||
255,
|
||||
968,
|
||||
295
|
||||
],
|
||||
"index": 2
|
||||
},
|
||||
{
|
||||
"cls_id": 5,
|
||||
"label": "display_formula",
|
||||
"score": 0.9417,
|
||||
"bbox": [
|
||||
740,
|
||||
353,
|
||||
958,
|
||||
401
|
||||
],
|
||||
"index": 3,
|
||||
"latex": "E = m c ^ { \\wedge } 2"
|
||||
},
|
||||
{
|
||||
"cls_id": 7,
|
||||
"label": "figure_title",
|
||||
"score": 0.9427,
|
||||
"bbox": [
|
||||
193,
|
||||
477,
|
||||
653,
|
||||
517
|
||||
],
|
||||
"index": 4
|
||||
},
|
||||
{
|
||||
"cls_id": 21,
|
||||
"label": "table",
|
||||
"score": 0.9627,
|
||||
"bbox": [
|
||||
197,
|
||||
554,
|
||||
1034,
|
||||
694
|
||||
],
|
||||
"index": 5,
|
||||
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>"
|
||||
},
|
||||
{
|
||||
"cls_id": 3,
|
||||
"label": "chart",
|
||||
"score": 0.9352,
|
||||
"bbox": [
|
||||
284,
|
||||
851,
|
||||
1122,
|
||||
1226
|
||||
],
|
||||
"index": 6
|
||||
},
|
||||
{
|
||||
"cls_id": 7,
|
||||
"label": "figure_title",
|
||||
"score": 0.9393,
|
||||
"bbox": [
|
||||
193,
|
||||
1278,
|
||||
583,
|
||||
1317
|
||||
],
|
||||
"index": 7
|
||||
},
|
||||
{
|
||||
"label": "ocr_text",
|
||||
"bbox": [
|
||||
200,
|
||||
159,
|
||||
1051,
|
||||
212
|
||||
],
|
||||
"score": 1.0,
|
||||
"text": ""
|
||||
},
|
||||
{
|
||||
"label": "ocr_text",
|
||||
"bbox": [
|
||||
200,
|
||||
260,
|
||||
962,
|
||||
289
|
||||
],
|
||||
"score": 1.0,
|
||||
"text": ""
|
||||
},
|
||||
{
|
||||
"label": "ocr_text",
|
||||
"bbox": [
|
||||
199,
|
||||
478,
|
||||
648,
|
||||
513
|
||||
],
|
||||
"score": 1.0,
|
||||
"text": ""
|
||||
},
|
||||
{
|
||||
"label": "ocr_text",
|
||||
"bbox": [
|
||||
199,
|
||||
1283,
|
||||
578,
|
||||
1313
|
||||
],
|
||||
"score": 1.0,
|
||||
"text": ""
|
||||
}
|
||||
],
|
||||
"page_info": {
|
||||
"page_no": 0,
|
||||
"width": 1700,
|
||||
"height": 2200
|
||||
}
|
||||
}
|
||||
]
|
||||
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
%PDF-1.7
|
||||
%¡³Å×
|
||||
1 0 obj
|
||||
<</Pages 2 0 R /Type/Catalog>>
|
||||
endobj
|
||||
2 0 obj
|
||||
<</Count 1/Kids[ 4 0 R ]/Type/Pages>>
|
||||
endobj
|
||||
3 0 obj
|
||||
<</CreationDate(D:20260828225606)/Creator(PDFium)/Producer(PDFium)>>
|
||||
endobj
|
||||
4 0 obj
|
||||
<</Contents 5 0 R /MediaBox[ 0 0 612 792]/Parent 2 0 R /Resources<</Font 6 0 R /ProcSet[/PDF/Text/ImageB/ImageC/ImageI]/XObject<</FormXob.1fe5b52c6a9de28e0822ad9f49443d36 10 0 R >>>>/Rotate 0/Trans<<>>/Type/Page>>
|
||||
endobj
|
||||
5 0 obj
|
||||
<</Filter[/ASCII85Decode/FlateDecode]/Length 492>>stream
|
||||
GasIc9i'e''YNU1b]2SQifBQ#^k&M-05.a$5&`i/PLnHc9o<^9q"JPOr;oul7*3Vc1?3ZK0bj.erNfZ.'90%1"67`90UYStHedkea#R7iE6`KH`7[oFR`E$j?K'M#BW^/YkAfr/)]imHA)^eM&8(>n]Qq)=IY#3q-q?eY4,TQ#<EA-Gq%aq(q1,mCVX\88Z1bOJ^SMA@]a'q5L*]d1[XiS^NN_\=rmaelRtRgt01uU/)GKU=K,(D!r`+^QG\f8dBJX!.=H3UnhU0n*6#GXcMEujMSEREG[uob!0GQ>9&s!XdHk5u%!>c!Ppr)'<S:d*\_m)8>8!-n"GX%UjO*E!Z)7e@>BMkDaF+4\e'M%$;)#$-CM=(/Q?^booG0E/t\F$9_CF3"8&E>j,&Mbq]FuAU`lD^99CdFilLf_`XCZ6WT-0M-H0B?5-;%&(lQi6eAH;]cE88"=#->moDmc-eV/-T)uG`$iM=l[EamNMH<>SP\d~>
|
||||
endstream
|
||||
endobj
|
||||
6 0 obj
|
||||
<</F1 7 0 R /F2 8 0 R /F3 9 0 R >>
|
||||
endobj
|
||||
7 0 obj
|
||||
<</BaseFont/Helvetica/Encoding/WinAnsiEncoding/Name/F1/Subtype/Type1/Type/Font>>
|
||||
endobj
|
||||
8 0 obj
|
||||
<</BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding/Name/F2/Subtype/Type1/Type/Font>>
|
||||
endobj
|
||||
9 0 obj
|
||||
<</BaseFont/Times-Italic/Encoding/WinAnsiEncoding/Name/F3/Subtype/Type1/Type/Font>>
|
||||
endobj
|
||||
10 0 obj
|
||||
<</BitsPerComponent 8/ColorSpace/DeviceRGB/Filter[/ASCII85Decode/FlateDecode]/Height 160/Length 2327/Subtype/Image/Type/XObject/Width 360>>stream
|
||||
Gb"0VgP\dS"2OFsarrd0SFYs)>R3(>.+8SoEf.r'jHLAYJ6.VK7>c,AU*ph8$Z95-`hAXG%8BQ+jDZD*`8hWprUm=bh0s#*g!?affmBp?kL5W\=_lSl^\+\cGCFn1H9++gzzzzz.f&CKotD"\208qV9/hC2F9@=l2h8D[",KT/J@K\'LeB[W\9%h/9/hC2F9@=l2h8D["8_6=s1)>%>GsF8J6iW&./[$4H`8IMJDM`8L2I!VFX]cie"I]l96\e1%A6[S@cT*]\cFsf(r^S!.^R>IV&N6^@[*].:mPZ^"hF`2'VdG>J7=f^4eWf+;2h*q%HnLcQumtN;iG&0%J!1LH:Kp8-cP9Wh&qIeUQ9ML>d;N:(V2n]-q8^6%J%:iUOVM4RAUo#:,g6JbD[pu%5LL0W_,4k*mpoEh&o?)UGd4HbRfc&d1%ir0ksB@83=eh4l%6o/2QQ[2b5C:W$C+@FY#?6:,b][`CL'd+>#-#P!_0!5/g&2h&tZE,Csrh`);Q4dLD@21m1Nk8/fH<52@>Y'I+?7UY!/urQ?r@7<Bb,mrgR5Wp-5s4kGl>Lu.s;4MWf%NITID>aPfsaFd)6h5Htb`@sS%Sk5sH7]BSR,)<KOcXY90h'gkKH*&?Wj^aaHV]22s-[SihT%0!7CcFGAkAJdbP3/tol+M/\b%EYr2An;UP2tLD]o]:4UhIbZUEmsl'Dbd*\rkX5eT9t)8P1'[4d>>Oe:%0m<FSUaZ0+f[XEGi+\Yu1h--=]dcEiIP,MNTb?DqF,4RN'f7Q9D&kGh\ucTET'h@4CAh^JbLV6h1Jh5V(s.SF&+]XN$W(_fV92nZLhj8%k@o"-%]C#NDbIO)?@()W-88aD+95k65!)i=Z1;>4tL"f+m6]:g(';RPtJ>X7#nZ5[fbfhd<==C=D6<3I6]!EiE^DC>^"><d9u/g)P<V&P9m\^Hg^a9CX'n%'YYOCti0@=\H$<i6ne^1X+QidOX"%%pt=;:R`2P,9&1(KCmb\__J(HM7Le?etas4[A;r"q[,=!-.6-&=787ETmZ=QYleCklq]cD?+\@"q[,=!-.6-&=787ETmZ=QYleCr<:\<]r-=OeGJ2j:=X^VpJno!+66;4k</eF!!#tk>?fjuK*OVhqGco&J\2g\FQe;[$Pk@"3.Lr*F6ChkGM%HK#PrJ+f%/E9-Vqb<)dTiApBK*D9fm[nkei/d]0!*T2d^=\aH<`fn+RcOqC50iNfK-cQBk11/lb*:Q?mf';56VRbB\CdmKr4MoUpMf?g1(A*]5i6Ie`D@_hJVY(GBZ@C:\opIe`cRIJX3Y*4TP$P1!X`)7FA7&q8h1gKV.)SMFd!WDf_3Ocq.g5'#^TQOAM,4aZlZ2`K'O2='hpbJegh*BVj!cnK+XSEne1(G8nDqsN:P[;4BKePZ,$gUD*rD[^E?E*2npQS2^?_nn-0Y$;8PgUD)cJ,Xi[GtRNQ])T(2.sp*h&8'4X)%@`?MSc-X0k3]CGb`_'hZ.1SnPoA\oB3W'j0igZG44;$nCLaF?Ho')]D/V9]7p_3Ep_SgBRB7,_;TpKGJJ_0@HtORq/X?*$!f.t4rHeQX1c2pd\KIRHcM'_oD/"@[^NW()`Ms>s3qO.DVDJ^_M&A+j6YI*4*Ks=*C@.'k09A,T*GlJ/6fQaliCD#$hn"OFChWp^*O]7e#-!:+b[&V\T?s4qtGg7(-`T#%5OgUQ2^XQlbEF3_;D+bSbh[(YJO^ZG7>KLm.]u+d2>7aU+_7O6shL9ZXMJ+Nut.a&L0aZn(kX%o9qOPDVVbLj]eI=M%_99q!fSFKM*$Z(:<]HLCYI:oCp4^(Yp)C$m.Yqg*ka+g!Q(uDWq^!mS9B<]kc6&E4.BsmF2S#VtcOkFmIWLjib]*+91`_\+&#=g>BVm]D/T;]=Mf[fI0GGZ?sK'_hWiJ_Cs^aY5\CspBj89D!^&o5:co.4F,B2V8KAFF2,oTZD/psh9mGt?+Mk7,:msE]?3;QaG.P^*Br<*RlBfuc("%MXc&M,=0Gp^/G6o&#d^MsY.3<OmeH:H]XbR5HrfOrkSQC)CuM+B_cEsIIIZ=9Y]8gLRGGK!GB_I(fqGCEl1*fSiG=#Cr$ag*=AcH6[YBbT-Vf?@&RE,am-)Su[r_nN7un/Ss6SFF6%]B,%^U*VO:?pD%boXg)#]?\p$:4<eq?WHdaHS#hB!]G@`=4i.p&%meR.,<Ii^XmB^XZd%1NceNup#[['9<#oB5(5_pqhj>#k?b:jS9nM\b-^HT,d-gpo5bo]#Iq!D]7N4Ua5rTI@LGZD/psh9mJ5h7GV9H2[U4Tm4uEV"g=o%0-A.zzz!$og=!LY8KdJ~>
|
||||
endstream
|
||||
endobj
|
||||
xref
|
||||
0 11
|
||||
0000000000 65535 f
|
||||
0000000017 00000 n
|
||||
0000000066 00000 n
|
||||
0000000122 00000 n
|
||||
0000000209 00000 n
|
||||
0000000441 00000 n
|
||||
0000001021 00000 n
|
||||
0000001074 00000 n
|
||||
0000001173 00000 n
|
||||
0000001277 00000 n
|
||||
0000001379 00000 n
|
||||
trailer
|
||||
<<
|
||||
/Root 1 0 R
|
||||
/Info 3 0 R
|
||||
/Size 11/ID[<E919D9A2E5EDF6C6F2B6DA9CF2041B12><E919D9A2E5EDF6C6F2B6DA9CF2041B12>]>>
|
||||
startxref
|
||||
3884
|
||||
%%EOF
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"artifacts": {
|
||||
"a5d0461c-c073-4d71-944c-e79759a67637_content_list.json": "e8e5bb9c00a6da26d9a7b93abd6938acf3145503ae734cd05831c56bd7e5e842",
|
||||
"a5d0461c-c073-4d71-944c-e79759a67637_content_list_v2.json": "920ef83a39170889d001b75973293fc65b8a7c8ac0b309c807b7d2cdcf199284",
|
||||
"a5d0461c-c073-4d71-944c-e79759a67637_model.json": "9574219a0d6f52303d4d46e15c01d19b02bd49b2674f542eebd729ad29af9e59",
|
||||
"a5d0461c-c073-4d71-944c-e79759a67637_origin.pdf": "bf173e5d24d268a8a5a25766d190d2b01a124394c5e0e33094c08c6a9d8bbbc4",
|
||||
"full.md": "e2861269e39a18874137029375666f79ea75af68d3ccbe490d112d1141368344",
|
||||
"images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg": "a4542ec348a798c6a6dba4b89a4ab91d1b23c45b4c50bfaeb8303a4874e1e10d",
|
||||
"images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg": "18c517e03a9b15f5e7748ab4187dd8cd349018f7582784425a03bb538c146691",
|
||||
"images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg": "53eaf9d9acb37f7f885dd51d17f183590da9068d3fd26d9701b885cf4f8fc970",
|
||||
"layout.json": "549cb6fcd708664adb081afa494781a54bea250e1d86acc7776049f2e2c35d63"
|
||||
},
|
||||
"authenticated": true,
|
||||
"capture_schema": 1,
|
||||
"captured_at_utc": "2026-08-28T14:56:16.031586+00:00",
|
||||
"model_version": "pipeline",
|
||||
"service": "https://mineru.net/api/v4",
|
||||
"source": {
|
||||
"path": "../original.pdf",
|
||||
"sha256": "e2abd3404f3a03d90c36feec19786689892434e730841cbdbd2a1a28875f3a80"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
## DeepTutor LightRAG Bridge Fixture
|
||||
|
||||
A short paragraph preserves text and heading hierarchy.
|
||||
|
||||
$$
|
||||
E = m c ^ { \wedge } 2
|
||||
$$
|
||||
|
||||
Table 1. Retrieval engine paths
|
||||
<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>
|
||||
|
||||

|
||||
Figure 1. Synthetic trend chart.
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 2.9 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,552 @@
|
||||
{
|
||||
"pdf_info": [
|
||||
{
|
||||
"preproc_blocks": [
|
||||
{
|
||||
"score": 0.5515,
|
||||
"bbox": [
|
||||
70,
|
||||
56,
|
||||
379,
|
||||
77
|
||||
],
|
||||
"index": 1,
|
||||
"type": "title",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
57,
|
||||
378,
|
||||
76
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
57,
|
||||
378,
|
||||
76
|
||||
],
|
||||
"type": "text",
|
||||
"content": "DeepTutor LightRAG Bridge Fixture",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"level": 2
|
||||
},
|
||||
{
|
||||
"score": 0.9291,
|
||||
"bbox": [
|
||||
68,
|
||||
91,
|
||||
348,
|
||||
106
|
||||
],
|
||||
"index": 2,
|
||||
"type": "text",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
93,
|
||||
346,
|
||||
104
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
93,
|
||||
346,
|
||||
104
|
||||
],
|
||||
"type": "text",
|
||||
"content": "A short paragraph preserves text and heading hierarchy.",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"score": 0.9417,
|
||||
"bbox": [
|
||||
266,
|
||||
127,
|
||||
344,
|
||||
144
|
||||
],
|
||||
"index": 3,
|
||||
"type": "interline_equation",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
266,
|
||||
127,
|
||||
344,
|
||||
144
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
266,
|
||||
127,
|
||||
344,
|
||||
144
|
||||
],
|
||||
"type": "interline_equation",
|
||||
"content": "E = m c ^ { \\wedge } 2",
|
||||
"image_path": "4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"score": 0.9427,
|
||||
"bbox": [
|
||||
69,
|
||||
171,
|
||||
235,
|
||||
186
|
||||
],
|
||||
"index": 4,
|
||||
"type": "table_caption",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
172,
|
||||
233,
|
||||
184
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
172,
|
||||
233,
|
||||
184
|
||||
],
|
||||
"type": "text",
|
||||
"content": "Table 1. Retrieval engine paths",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"score": 0.9627,
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"index": 5,
|
||||
"type": "table_body",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"type": "table",
|
||||
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
|
||||
"image_path": "c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"index": 5,
|
||||
"score": 0.9627
|
||||
},
|
||||
{
|
||||
"type": "chart",
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"score": 0.9352,
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"index": 6,
|
||||
"type": "chart_body",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"type": "chart",
|
||||
"image_path": "f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"score": 0.9393,
|
||||
"bbox": [
|
||||
69,
|
||||
460,
|
||||
209,
|
||||
474
|
||||
],
|
||||
"index": 7,
|
||||
"type": "chart_caption",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
461,
|
||||
208,
|
||||
472
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
461,
|
||||
208,
|
||||
472
|
||||
],
|
||||
"type": "text",
|
||||
"content": "Figure 1. Synthetic trend chart.",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"index": 6,
|
||||
"score": 0.9352
|
||||
}
|
||||
],
|
||||
"page_idx": 0,
|
||||
"page_size": [
|
||||
612,
|
||||
792
|
||||
],
|
||||
"discarded_blocks": [],
|
||||
"para_blocks": [
|
||||
{
|
||||
"score": 0.5515,
|
||||
"bbox": [
|
||||
70,
|
||||
56,
|
||||
379,
|
||||
77
|
||||
],
|
||||
"index": 1,
|
||||
"type": "title",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
57,
|
||||
378,
|
||||
76
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
57,
|
||||
378,
|
||||
76
|
||||
],
|
||||
"type": "text",
|
||||
"content": "DeepTutor LightRAG Bridge Fixture",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"level": 2
|
||||
},
|
||||
{
|
||||
"score": 0.9291,
|
||||
"bbox": [
|
||||
68,
|
||||
91,
|
||||
348,
|
||||
106
|
||||
],
|
||||
"index": 2,
|
||||
"type": "text",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
93,
|
||||
346,
|
||||
104
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
72,
|
||||
93,
|
||||
346,
|
||||
104
|
||||
],
|
||||
"type": "text",
|
||||
"content": "A short paragraph preserves text and heading hierarchy.",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"bbox_fs": [
|
||||
72,
|
||||
93,
|
||||
346,
|
||||
104
|
||||
]
|
||||
},
|
||||
{
|
||||
"score": 0.9417,
|
||||
"bbox": [
|
||||
266,
|
||||
127,
|
||||
344,
|
||||
144
|
||||
],
|
||||
"index": 3,
|
||||
"type": "interline_equation",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
266,
|
||||
127,
|
||||
344,
|
||||
144
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
266,
|
||||
127,
|
||||
344,
|
||||
144
|
||||
],
|
||||
"type": "interline_equation",
|
||||
"content": "E = m c ^ { \\wedge } 2",
|
||||
"image_path": "4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"score": 0.9427,
|
||||
"bbox": [
|
||||
69,
|
||||
171,
|
||||
235,
|
||||
186
|
||||
],
|
||||
"index": 4,
|
||||
"type": "table_caption",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
172,
|
||||
233,
|
||||
184
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
172,
|
||||
233,
|
||||
184
|
||||
],
|
||||
"type": "text",
|
||||
"content": "Table 1. Retrieval engine paths",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"score": 0.9627,
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"index": 5,
|
||||
"type": "table_body",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
70,
|
||||
199,
|
||||
372,
|
||||
249
|
||||
],
|
||||
"type": "table",
|
||||
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
|
||||
"image_path": "c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"index": 5,
|
||||
"score": 0.9627
|
||||
},
|
||||
{
|
||||
"type": "chart",
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"score": 0.9352,
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"index": 6,
|
||||
"type": "chart_body",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
102,
|
||||
306,
|
||||
403,
|
||||
441
|
||||
],
|
||||
"type": "chart",
|
||||
"image_path": "f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"score": 0.9393,
|
||||
"bbox": [
|
||||
69,
|
||||
460,
|
||||
209,
|
||||
474
|
||||
],
|
||||
"index": 7,
|
||||
"type": "chart_caption",
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
461,
|
||||
208,
|
||||
472
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
71,
|
||||
461,
|
||||
208,
|
||||
472
|
||||
],
|
||||
"type": "text",
|
||||
"content": "Figure 1. Synthetic trend chart.",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"index": 6,
|
||||
"score": 0.9352
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"_backend": "pipeline",
|
||||
"_version_name": "3.4.4"
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
%PDF-1.3
|
||||
%“Œ‹ž ReportLab Generated PDF document (opensource)
|
||||
1 0 obj
|
||||
<<
|
||||
/F1 2 0 R /F2 3 0 R /F3 4 0 R
|
||||
>>
|
||||
endobj
|
||||
2 0 obj
|
||||
<<
|
||||
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
|
||||
>>
|
||||
endobj
|
||||
3 0 obj
|
||||
<<
|
||||
/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
|
||||
>>
|
||||
endobj
|
||||
4 0 obj
|
||||
<<
|
||||
/BaseFont /Times-Italic /Encoding /WinAnsiEncoding /Name /F3 /Subtype /Type1 /Type /Font
|
||||
>>
|
||||
endobj
|
||||
5 0 obj
|
||||
<<
|
||||
/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 160 /Length 2327 /Subtype /Image
|
||||
/Type /XObject /Width 360
|
||||
>>
|
||||
stream
|
||||
Gb"0VgP\dS"2OFsarrd0SFYs)>R3(>.+8SoEf.r'jHLAYJ6.VK7>c,AU*ph8$Z95-`hAXG%8BQ+jDZD*`8hWprUm=bh0s#*g!?affmBp?kL5W\=_lSl^\+\cGCFn1H9++gzzzzz.f&CKotD"\208qV9/hC2F9@=l2h8D[",KT/J@K\'LeB[W\9%h/9/hC2F9@=l2h8D["8_6=s1)>%>GsF8J6iW&./[$4H`8IMJDM`8L2I!VFX]cie"I]l96\e1%A6[S@cT*]\cFsf(r^S!.^R>IV&N6^@[*].:mPZ^"hF`2'VdG>J7=f^4eWf+;2h*q%HnLcQumtN;iG&0%J!1LH:Kp8-cP9Wh&qIeUQ9ML>d;N:(V2n]-q8^6%J%:iUOVM4RAUo#:,g6JbD[pu%5LL0W_,4k*mpoEh&o?)UGd4HbRfc&d1%ir0ksB@83=eh4l%6o/2QQ[2b5C:W$C+@FY#?6:,b][`CL'd+>#-#P!_0!5/g&2h&tZE,Csrh`);Q4dLD@21m1Nk8/fH<52@>Y'I+?7UY!/urQ?r@7<Bb,mrgR5Wp-5s4kGl>Lu.s;4MWf%NITID>aPfsaFd)6h5Htb`@sS%Sk5sH7]BSR,)<KOcXY90h'gkKH*&?Wj^aaHV]22s-[SihT%0!7CcFGAkAJdbP3/tol+M/\b%EYr2An;UP2tLD]o]:4UhIbZUEmsl'Dbd*\rkX5eT9t)8P1'[4d>>Oe:%0m<FSUaZ0+f[XEGi+\Yu1h--=]dcEiIP,MNTb?DqF,4RN'f7Q9D&kGh\ucTET'h@4CAh^JbLV6h1Jh5V(s.SF&+]XN$W(_fV92nZLhj8%k@o"-%]C#NDbIO)?@()W-88aD+95k65!)i=Z1;>4tL"f+m6]:g(';RPtJ>X7#nZ5[fbfhd<==C=D6<3I6]!EiE^DC>^"><d9u/g)P<V&P9m\^Hg^a9CX'n%'YYOCti0@=\H$<i6ne^1X+QidOX"%%pt=;:R`2P,9&1(KCmb\__J(HM7Le?etas4[A;r"q[,=!-.6-&=787ETmZ=QYleCklq]cD?+\@"q[,=!-.6-&=787ETmZ=QYleCr<:\<]r-=OeGJ2j:=X^VpJno!+66;4k</eF!!#tk>?fjuK*OVhqGco&J\2g\FQe;[$Pk@"3.Lr*F6ChkGM%HK#PrJ+f%/E9-Vqb<)dTiApBK*D9fm[nkei/d]0!*T2d^=\aH<`fn+RcOqC50iNfK-cQBk11/lb*:Q?mf';56VRbB\CdmKr4MoUpMf?g1(A*]5i6Ie`D@_hJVY(GBZ@C:\opIe`cRIJX3Y*4TP$P1!X`)7FA7&q8h1gKV.)SMFd!WDf_3Ocq.g5'#^TQOAM,4aZlZ2`K'O2='hpbJegh*BVj!cnK+XSEne1(G8nDqsN:P[;4BKePZ,$gUD*rD[^E?E*2npQS2^?_nn-0Y$;8PgUD)cJ,Xi[GtRNQ])T(2.sp*h&8'4X)%@`?MSc-X0k3]CGb`_'hZ.1SnPoA\oB3W'j0igZG44;$nCLaF?Ho')]D/V9]7p_3Ep_SgBRB7,_;TpKGJJ_0@HtORq/X?*$!f.t4rHeQX1c2pd\KIRHcM'_oD/"@[^NW()`Ms>s3qO.DVDJ^_M&A+j6YI*4*Ks=*C@.'k09A,T*GlJ/6fQaliCD#$hn"OFChWp^*O]7e#-!:+b[&V\T?s4qtGg7(-`T#%5OgUQ2^XQlbEF3_;D+bSbh[(YJO^ZG7>KLm.]u+d2>7aU+_7O6shL9ZXMJ+Nut.a&L0aZn(kX%o9qOPDVVbLj]eI=M%_99q!fSFKM*$Z(:<]HLCYI:oCp4^(Yp)C$m.Yqg*ka+g!Q(uDWq^!mS9B<]kc6&E4.BsmF2S#VtcOkFmIWLjib]*+91`_\+&#=g>BVm]D/T;]=Mf[fI0GGZ?sK'_hWiJ_Cs^aY5\CspBj89D!^&o5:co.4F,B2V8KAFF2,oTZD/psh9mGt?+Mk7,:msE]?3;QaG.P^*Br<*RlBfuc("%MXc&M,=0Gp^/G6o&#d^MsY.3<OmeH:H]XbR5HrfOrkSQC)CuM+B_cEsIIIZ=9Y]8gLRGGK!GB_I(fqGCEl1*fSiG=#Cr$ag*=AcH6[YBbT-Vf?@&RE,am-)Su[r_nN7un/Ss6SFF6%]B,%^U*VO:?pD%boXg)#]?\p$:4<eq?WHdaHS#hB!]G@`=4i.p&%meR.,<Ii^XmB^XZd%1NceNup#[['9<#oB5(5_pqhj>#k?b:jS9nM\b-^HT,d-gpo5bo]#Iq!D]7N4Ua5rTI@LGZD/psh9mJ5h7GV9H2[U4Tm4uEV"g=o%0-A.zzz!$og=!LY8KdJ~>endstream
|
||||
endobj
|
||||
6 0 obj
|
||||
<<
|
||||
/Contents 10 0 R /MediaBox [ 0 0 612 792 ] /Parent 9 0 R /Resources <<
|
||||
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject <<
|
||||
/FormXob.1fe5b52c6a9de28e0822ad9f49443d36 5 0 R
|
||||
>>
|
||||
>> /Rotate 0 /Trans <<
|
||||
|
||||
>>
|
||||
/Type /Page
|
||||
>>
|
||||
endobj
|
||||
7 0 obj
|
||||
<<
|
||||
/PageMode /UseNone /Pages 9 0 R /Type /Catalog
|
||||
>>
|
||||
endobj
|
||||
8 0 obj
|
||||
<<
|
||||
/Author (DeepTutor contributors) /CreationDate (D:20000101000000+00'00') /Creator (anonymous) /Keywords () /ModDate (D:20000101000000+00'00') /Producer (ReportLab PDF Library - \(opensource\))
|
||||
/Subject (unspecified) /Title (DeepTutor LightRAG Bridge Fixture) /Trapped /False
|
||||
>>
|
||||
endobj
|
||||
9 0 obj
|
||||
<<
|
||||
/Count 1 /Kids [ 6 0 R ] /Type /Pages
|
||||
>>
|
||||
endobj
|
||||
10 0 obj
|
||||
<<
|
||||
/Filter [ /ASCII85Decode /FlateDecode ] /Length 492
|
||||
>>
|
||||
stream
|
||||
GasIc9i'e''YNU1b]2SQifBQ#^k&M-05.a$5&`i/PLnHc9o<^9q"JPOr;oul7*3Vc1?3ZK0bj.erNfZ.'90%1"67`90UYStHedkea#R7iE6`KH`7[oFR`E$j?K'M#BW^/YkAfr/)]imHA)^eM&8(>n]Qq)=IY#3q-q?eY4,TQ#<EA-Gq%aq(q1,mCVX\88Z1bOJ^SMA@]a'q5L*]d1[XiS^NN_\=rmaelRtRgt01uU/)GKU=K,(D!r`+^QG\f8dBJX!.=H3UnhU0n*6#GXcMEujMSEREG[uob!0GQ>9&s!XdHk5u%!>c!Ppr)'<S:d*\_m)8>8!-n"GX%UjO*E!Z)7e@>BMkDaF+4\e'M%$;)#$-CM=(/Q?^booG0E/t\F$9_CF3"8&E>j,&Mbq]FuAU`lD^99CdFilLf_`XCZ6WT-0M-H0B?5-;%&(lQi6eAH;]cE88"=#->moDmc-eV/-T)uG`$iM=l[EamNMH<>SP\d~>endstream
|
||||
endobj
|
||||
xref
|
||||
0 11
|
||||
0000000000 65535 f
|
||||
0000000061 00000 n
|
||||
0000000112 00000 n
|
||||
0000000219 00000 n
|
||||
0000000331 00000 n
|
||||
0000000441 00000 n
|
||||
0000002959 00000 n
|
||||
0000003216 00000 n
|
||||
0000003284 00000 n
|
||||
0000003583 00000 n
|
||||
0000003642 00000 n
|
||||
trailer
|
||||
<<
|
||||
/ID
|
||||
[<1032306cdd7e2f90b2233ccd4ed2d1e2><1032306cdd7e2f90b2233ccd4ed2d1e2>]
|
||||
% ReportLab generated PDF document -- digest (opensource)
|
||||
|
||||
/Info 8 0 R
|
||||
/Root 7 0 R
|
||||
/Size 11
|
||||
>>
|
||||
startxref
|
||||
4225
|
||||
%%EOF
|
||||
@@ -0,0 +1,337 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.parsing import cache as parsing_cache
|
||||
from deeptutor.services.parsing.types import ParsedDocument
|
||||
from deeptutor.services.rag.pipelines.lightrag import ingress, sidecar
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lightrag_bridge"
|
||||
REQUIRES_LIGHTRAG = pytest.mark.skipif(
|
||||
importlib.util.find_spec("lightrag") is None,
|
||||
reason="requires the optional rag-lightrag extra",
|
||||
)
|
||||
|
||||
|
||||
def _structured(asset_dir: Path | None = None) -> ParsedDocument:
|
||||
return ParsedDocument(
|
||||
markdown="# Fixture\n\nBody",
|
||||
blocks=[
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Fixture",
|
||||
"text_level": 1,
|
||||
"page_idx": 0,
|
||||
"bbox": [1, 2, 3, 4],
|
||||
},
|
||||
{"type": "text", "text": "Body", "page_idx": 0},
|
||||
{"type": "list", "list_items": ["one", "two"], "page_idx": 0},
|
||||
{
|
||||
"type": "code",
|
||||
"code_body": "print('ok')",
|
||||
"code_caption": ["Fixture code"],
|
||||
"code_footnote": ["Code note"],
|
||||
"page_idx": 0,
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"table_body": "<table><tr><td>A</td></tr></table>",
|
||||
"table_caption": ["Table caption"],
|
||||
"page_idx": 1,
|
||||
},
|
||||
{
|
||||
"type": "image",
|
||||
"img_path": "images/chart.png",
|
||||
"image_caption": ["Chart caption"],
|
||||
"page_idx": 1,
|
||||
},
|
||||
{"type": "equation", "text": "x^2", "page_idx": 1},
|
||||
],
|
||||
asset_dir=asset_dir,
|
||||
source_hash="source-sha",
|
||||
parser_signature="mineru-signature",
|
||||
engine="mineru",
|
||||
)
|
||||
|
||||
|
||||
def test_freeze_is_an_independent_digest_verified_bundle(tmp_path: Path) -> None:
|
||||
source = tmp_path / "paper.pdf"
|
||||
source.write_bytes(b"original pdf")
|
||||
assets = tmp_path / "parser-assets"
|
||||
(assets / "images").mkdir(parents=True)
|
||||
original_asset = assets / "images" / "chart.png"
|
||||
original_asset.write_bytes(b"image")
|
||||
working = tmp_path / "version-1"
|
||||
|
||||
staged = ingress.freeze_document(working, source, _structured(assets))
|
||||
manifest, bundle = ingress.load_verified_bundle(working, "paper.pdf")
|
||||
|
||||
assert staged.source_path.read_bytes() == b"original pdf"
|
||||
assert os.stat(staged.source_path).st_ino != os.stat(source).st_ino
|
||||
frozen_asset = bundle / manifest["assets"][0]["path"]
|
||||
assert frozen_asset.read_bytes() == b"image"
|
||||
assert os.stat(frozen_asset).st_ino != os.stat(original_asset).st_ino
|
||||
assert manifest["process_options"] == "Pite"
|
||||
assert manifest["chunk_options"] == {"paragraph_semantic": {"chunk_token_size": 1200}}
|
||||
|
||||
source.write_bytes(b"mutated pdf")
|
||||
original_asset.write_bytes(b"mutated image")
|
||||
assert staged.source_path.read_bytes() == b"original pdf"
|
||||
assert frozen_asset.read_bytes() == b"image"
|
||||
ingress.load_verified_bundle(working, "paper.pdf")
|
||||
|
||||
|
||||
def test_absolute_cached_image_path_is_rewritten_to_frozen_asset(tmp_path: Path) -> None:
|
||||
source = tmp_path / "paper.pdf"
|
||||
source.write_bytes(b"pdf")
|
||||
assets = tmp_path / "images"
|
||||
assets.mkdir()
|
||||
image = assets / "figure.png"
|
||||
image.write_bytes(b"image")
|
||||
parsed = ParsedDocument(
|
||||
markdown="figure",
|
||||
blocks=[{"type": "image", "img_path": str(image)}],
|
||||
asset_dir=assets,
|
||||
engine="mineru",
|
||||
)
|
||||
|
||||
staged = ingress.freeze_document(tmp_path / "version-1", source, parsed)
|
||||
manifest, bundle = ingress.load_verified_bundle(tmp_path / "version-1", staged.canonical_name)
|
||||
frozen_blocks = json.loads((bundle / manifest["blocks"]["path"]).read_text())
|
||||
|
||||
assert frozen_blocks[0]["img_path"] == "figure.png"
|
||||
assert parsed.blocks[0]["img_path"] == str(image)
|
||||
assert (bundle / "assets" / "figure.png").read_bytes() == b"image"
|
||||
|
||||
|
||||
def test_bundle_tamper_and_unsafe_names_fail_closed(tmp_path: Path) -> None:
|
||||
source = tmp_path / "notes.md"
|
||||
source.write_text("notes", encoding="utf-8")
|
||||
working = tmp_path / "version-1"
|
||||
staged = ingress.freeze_document(
|
||||
working,
|
||||
source,
|
||||
ParsedDocument(markdown="notes", engine="text_only", source_hash="h", parser_signature="s"),
|
||||
)
|
||||
assert staged.process_options == "F"
|
||||
(staged.bundle_dir / "markdown.utf8").write_text("tampered", encoding="utf-8")
|
||||
with pytest.raises(ingress.IngressError, match="Digest mismatch"):
|
||||
ingress.load_verified_bundle(working, "notes.md")
|
||||
with pytest.raises(ingress.IngressError, match="Invalid canonical basename"):
|
||||
ingress.load_verified_bundle(working, "../notes.md")
|
||||
|
||||
|
||||
def test_bundle_payload_rejects_a_symlinked_parent(tmp_path: Path) -> None:
|
||||
source = tmp_path / "notes.md"
|
||||
source.write_text("notes", encoding="utf-8")
|
||||
working = tmp_path / "version-1"
|
||||
staged = ingress.freeze_document(
|
||||
working,
|
||||
source,
|
||||
ParsedDocument(markdown="notes", engine="text_only"),
|
||||
)
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
(outside / "payload").write_text("notes", encoding="utf-8")
|
||||
markdown = staged.bundle_dir / "markdown.utf8"
|
||||
markdown.unlink()
|
||||
nested = staged.bundle_dir / "nested"
|
||||
nested.symlink_to(outside, target_is_directory=True)
|
||||
manifest = json.loads(staged.manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["markdown"]["path"] = "nested/payload"
|
||||
staged.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with pytest.raises(ingress.IngressError, match="symbolic link"):
|
||||
ingress.load_verified_bundle(working, "notes.md")
|
||||
|
||||
|
||||
def test_source_and_assets_reject_links(tmp_path: Path) -> None:
|
||||
source = tmp_path / "source.pdf"
|
||||
source.write_bytes(b"pdf")
|
||||
hardlink = tmp_path / "hardlink.pdf"
|
||||
os.link(source, hardlink)
|
||||
with pytest.raises(ingress.IngressError, match="hard-linked"):
|
||||
ingress.freeze_document(tmp_path / "version-hardlink", source, _structured())
|
||||
|
||||
ordinary = tmp_path / "ordinary.pdf"
|
||||
ordinary.write_bytes(b"pdf")
|
||||
assets = tmp_path / "assets"
|
||||
assets.mkdir()
|
||||
(assets / "outside.png").write_bytes(b"image")
|
||||
(assets / "link.png").symlink_to(assets / "outside.png")
|
||||
with pytest.raises(ingress.IngressError, match="symbolic link"):
|
||||
ingress.freeze_document(tmp_path / "version-symlink", ordinary, _structured(assets))
|
||||
|
||||
|
||||
def test_same_canonical_basename_is_rejected_before_enqueue(tmp_path: Path) -> None:
|
||||
first = tmp_path / "a" / "same.md"
|
||||
second = tmp_path / "b" / "same.md"
|
||||
first.parent.mkdir()
|
||||
second.parent.mkdir()
|
||||
first.write_text("first", encoding="utf-8")
|
||||
second.write_text("second", encoding="utf-8")
|
||||
parsed = ParsedDocument(markdown="content", engine="text_only")
|
||||
working = tmp_path / "version-1"
|
||||
ingress.freeze_document(working, first, parsed)
|
||||
with pytest.raises(ingress.IngressError, match="basename already exists"):
|
||||
ingress.freeze_document(working, second, parsed)
|
||||
|
||||
|
||||
@REQUIRES_LIGHTRAG
|
||||
def test_sidecar_maps_structured_fields_and_positions(tmp_path: Path) -> None:
|
||||
source = tmp_path / "paper.pdf"
|
||||
source.write_bytes(b"pdf")
|
||||
assets = tmp_path / "parser-assets"
|
||||
(assets / "images").mkdir(parents=True)
|
||||
(assets / "images" / "chart.png").write_bytes(b"image")
|
||||
working = tmp_path / "version-1"
|
||||
staged = ingress.freeze_document(working, source, _structured(assets))
|
||||
manifest, bundle = ingress.load_verified_bundle(working, staged.canonical_name)
|
||||
|
||||
document = sidecar.build_ir(manifest, bundle)
|
||||
|
||||
assert document.document_name == "paper.pdf"
|
||||
assert document.doc_title == "Fixture"
|
||||
assert document.split_option == {"parser": "mineru", "parser_signature": "mineru-signature"}
|
||||
assert len(document.assets) == 1
|
||||
assert document.assets[0].source.read_bytes() == b"image"
|
||||
block = document.blocks[0]
|
||||
assert block.heading == "Fixture"
|
||||
assert block.level == 1
|
||||
assert "one\ntwo" in block.content_template
|
||||
assert "print('ok')" in block.content_template
|
||||
assert "Fixture code" in block.content_template
|
||||
assert "Code note" in block.content_template
|
||||
assert block.tables[0].html.startswith("<table>")
|
||||
assert block.drawings[0].caption == "Chart caption"
|
||||
assert block.equations[0].latex == "x^2"
|
||||
assert block.positions[0].anchor == "1"
|
||||
assert block.positions[0].range == [1.0, 2.0, 3.0, 4.0]
|
||||
|
||||
|
||||
@REQUIRES_LIGHTRAG
|
||||
def test_sidecar_unknown_content_is_preserved_or_rejected(tmp_path: Path) -> None:
|
||||
bundle = tmp_path / "bundle"
|
||||
bundle.mkdir()
|
||||
blocks = bundle / "blocks.json"
|
||||
manifest = {
|
||||
"canonical_filename": "doc.pdf",
|
||||
"parser": {"engine": "mineru", "parser_signature": "s"},
|
||||
"blocks": {"path": "blocks.json"},
|
||||
"assets": [],
|
||||
}
|
||||
blocks.write_text(json.dumps([{"type": "new_semantic", "text": "keep me"}]), encoding="utf-8")
|
||||
assert "keep me" in sidecar.build_ir(manifest, bundle).blocks[0].content_template
|
||||
blocks.write_text(json.dumps([{"type": "new_semantic"}]), encoding="utf-8")
|
||||
with pytest.raises(sidecar.SidecarMappingError, match="no preservable text"):
|
||||
sidecar.build_ir(manifest, bundle)
|
||||
|
||||
|
||||
@REQUIRES_LIGHTRAG
|
||||
def test_sidecar_asset_traversal_is_rejected(tmp_path: Path) -> None:
|
||||
bundle = tmp_path / "bundle"
|
||||
bundle.mkdir()
|
||||
blocks = bundle / "blocks.json"
|
||||
blocks.write_text(
|
||||
json.dumps([{"type": "image", "img_path": "../outside.png"}]), encoding="utf-8"
|
||||
)
|
||||
manifest = {
|
||||
"canonical_filename": "doc.pdf",
|
||||
"parser": {},
|
||||
"blocks": {"path": "blocks.json"},
|
||||
"assets": [],
|
||||
}
|
||||
with pytest.raises(sidecar.SidecarMappingError, match="escapes"):
|
||||
sidecar.build_ir(manifest, bundle)
|
||||
|
||||
|
||||
@REQUIRES_LIGHTRAG
|
||||
def test_official_legacy_mineru_golden_maps_without_private_builder(tmp_path: Path) -> None:
|
||||
golden = FIXTURES / "mineru-legacy-official-example" / "content_list.json"
|
||||
provenance = json.loads(
|
||||
(golden.parent / "deeptutor-fixture-provenance.json").read_text(encoding="utf-8")
|
||||
)
|
||||
blocks = json.loads(golden.read_text(encoding="utf-8"))
|
||||
# The official example's image bytes are not distributed with its docs;
|
||||
# the authenticated current capture covers AssetSpec. The exact legacy
|
||||
# table/equation/text records remain untouched here.
|
||||
bridge_blocks = [block for block in blocks if block.get("type") != "image"]
|
||||
source = tmp_path / "legacy.pdf"
|
||||
source.write_bytes(b"legacy fixture source")
|
||||
working = tmp_path / "version-1"
|
||||
|
||||
staged = ingress.freeze_document(
|
||||
working,
|
||||
source,
|
||||
ParsedDocument(
|
||||
markdown="# Legacy fixture",
|
||||
blocks=bridge_blocks,
|
||||
engine="mineru",
|
||||
source_hash=provenance["content_sha256"],
|
||||
parser_signature=provenance["commit"],
|
||||
),
|
||||
)
|
||||
manifest, bundle = ingress.load_verified_bundle(working, staged.canonical_name)
|
||||
document = sidecar.build_ir(manifest, bundle)
|
||||
|
||||
assert provenance["kind"] == "official-legacy-schema-example"
|
||||
assert document.doc_title == "The response of flow duration curves to afforestation"
|
||||
block = document.blocks[0]
|
||||
assert block.tables[0].caption.startswith("Table 2")
|
||||
assert "Q _ { \\% }" in block.equations[0].latex
|
||||
assert {position.anchor for position in block.positions} == {"1", "3", "6"}
|
||||
|
||||
|
||||
@REQUIRES_LIGHTRAG
|
||||
def test_authenticated_current_mineru_golden_maps_from_public_artifacts(tmp_path: Path) -> None:
|
||||
capture = FIXTURES / "mineru-v2-current"
|
||||
provenance = json.loads(
|
||||
(capture / "deeptutor-fixture-provenance.json").read_text(encoding="utf-8")
|
||||
)
|
||||
source = (capture / provenance["source"]["path"]).resolve()
|
||||
|
||||
assert provenance["capture_schema"] == 1
|
||||
assert provenance["authenticated"] is True
|
||||
assert provenance["service"] == "https://mineru.net/api/v4"
|
||||
assert hashlib.sha256(source.read_bytes()).hexdigest() == provenance["source"]["sha256"]
|
||||
for relative, expected_digest in provenance["artifacts"].items():
|
||||
artifact = capture / relative
|
||||
assert artifact.is_file()
|
||||
assert hashlib.sha256(artifact.read_bytes()).hexdigest() == expected_digest
|
||||
|
||||
markdown, blocks, asset_dir = parsing_cache.load_ir(capture)
|
||||
assert blocks is not None
|
||||
assert asset_dir is not None
|
||||
assert {block["type"] for block in blocks} == {"text", "equation", "table", "chart"}
|
||||
|
||||
staged = ingress.freeze_document(
|
||||
tmp_path / "version-1",
|
||||
source,
|
||||
ParsedDocument(
|
||||
markdown=markdown,
|
||||
blocks=blocks,
|
||||
asset_dir=asset_dir,
|
||||
engine="mineru",
|
||||
source_hash=provenance["source"]["sha256"],
|
||||
parser_signature=provenance["model_version"],
|
||||
),
|
||||
)
|
||||
manifest, bundle = ingress.load_verified_bundle(tmp_path / "version-1", staged.canonical_name)
|
||||
document = sidecar.build_ir(manifest, bundle)
|
||||
|
||||
assert document.doc_title == "original"
|
||||
assert document.blocks[0].heading == "DeepTutor LightRAG Bridge Fixture"
|
||||
assert document.blocks[0].tables[0].caption == "Table 1. Retrieval engine paths"
|
||||
assert "E = m c" in document.blocks[0].equations[0].latex
|
||||
assert document.blocks[0].drawings[0].caption == "Figure 1. Synthetic trend chart."
|
||||
assert len(document.assets) == 1
|
||||
assert (
|
||||
document.assets[0].source.read_bytes()
|
||||
== (asset_dir / Path(blocks[-1]["img_path"]).name).read_bytes()
|
||||
)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Offline integration smoke tests against the real pinned LightRAG SDK."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
EmbeddingFunc = pytest.importorskip("lightrag.utils").EmbeddingFunc
|
||||
|
||||
from deeptutor.services.parsing.types import ParsedDocument
|
||||
from deeptutor.services.rag.index_versioning import list_kb_versions
|
||||
from deeptutor.services.rag.pipelines.lightrag import engine, ingress, storage
|
||||
|
||||
|
||||
async def _fake_llm(_prompt, **_kwargs) -> str:
|
||||
# This superset satisfies rc2's table/equation analysis schemas. Entity
|
||||
# extraction may validly produce zero records; the document still reaches
|
||||
# PROCESSED with real parser, chunk, storage and embedding code.
|
||||
return '{"name":"fixture","description":"fixture analysis","equation":"x^2","type":"Other"}'
|
||||
|
||||
|
||||
async def _fake_embedding(texts: list[str]) -> np.ndarray:
|
||||
return np.ones((len(texts), 32), dtype=float)
|
||||
|
||||
|
||||
def _configure_real_sdk(monkeypatch, llm=_fake_llm) -> None:
|
||||
monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: llm)
|
||||
monkeypatch.setattr(
|
||||
engine,
|
||||
"build_embedding_func",
|
||||
lambda **_kwargs: EmbeddingFunc(
|
||||
embedding_dim=32,
|
||||
max_token_size=4096,
|
||||
func=_fake_embedding,
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 1}
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
engine, "constructor_kwargs_from_settings", lambda: {"entity_extract_max_gleaning": 0}
|
||||
)
|
||||
|
||||
|
||||
async def _process(working_dir: Path, staged: ingress.StagedDocument) -> dict:
|
||||
rag = engine.build_rag(working_dir, enable_vlm=False)
|
||||
await engine.initialize(rag)
|
||||
failed = True
|
||||
try:
|
||||
track_id = await engine.enqueue(rag, [staged])
|
||||
await rag.apipeline_process_enqueue_documents()
|
||||
rows = await rag.aget_docs_by_track_id(track_id)
|
||||
failed = False
|
||||
return rows
|
||||
finally:
|
||||
await engine.finalize(rag, cancel_pending=failed)
|
||||
|
||||
|
||||
def test_real_rc2_raw_bridge_reaches_processed(monkeypatch, tmp_path: Path) -> None:
|
||||
_configure_real_sdk(monkeypatch)
|
||||
working = tmp_path / "version-1"
|
||||
working.mkdir()
|
||||
source = tmp_path / "notes.md"
|
||||
source.write_text("DeepTutor native LightRAG fixture.", encoding="utf-8")
|
||||
staged = ingress.freeze_document(
|
||||
working,
|
||||
source,
|
||||
ParsedDocument(
|
||||
markdown="# Native fixture\n\nDeepTutor uses LightRAG.",
|
||||
engine="text_only",
|
||||
source_hash="fixture-source",
|
||||
parser_signature="fixture-parser",
|
||||
),
|
||||
)
|
||||
|
||||
rows = asyncio.run(_process(working, staged))
|
||||
|
||||
assert len(rows) == 1
|
||||
row = next(iter(rows.values()))
|
||||
assert getattr(row.status, "value", row.status) == "processed"
|
||||
assert row.file_path == "notes.md"
|
||||
assert storage.has_output(working) is True
|
||||
monkeypatch.setattr(
|
||||
"deeptutor.services.rag.embedding_signature.embedding_meta_fields",
|
||||
lambda: {"embedding": "fixture"},
|
||||
)
|
||||
storage.write_meta(working)
|
||||
assert storage.meta_is_native_published(working) is True
|
||||
assert list_kb_versions(tmp_path)[0]["ready"] is True
|
||||
meta = storage._read_meta(working)
|
||||
assert meta["parser_inputs"] == [{"engine": "text_only", "parser_signature": "fixture-parser"}]
|
||||
|
||||
|
||||
def test_real_rc2_sidecar_bridge_reaches_processed(monkeypatch, tmp_path: Path) -> None:
|
||||
_configure_real_sdk(monkeypatch)
|
||||
working = tmp_path / "version-1"
|
||||
working.mkdir()
|
||||
source = tmp_path / "paper.pdf"
|
||||
source.write_bytes(b"%PDF-1.4 fixture")
|
||||
assets = tmp_path / "assets"
|
||||
assets.mkdir()
|
||||
(assets / "figure.png").write_bytes(b"fixture image")
|
||||
staged = ingress.freeze_document(
|
||||
working,
|
||||
source,
|
||||
ParsedDocument(
|
||||
markdown="# Structured fixture",
|
||||
blocks=[
|
||||
{"type": "text", "text": "Structured fixture", "text_level": 1, "page_idx": 0},
|
||||
{"type": "text", "text": "DeepTutor structured body.", "page_idx": 0},
|
||||
{
|
||||
"type": "table",
|
||||
"table_body": "<table><tr><td>value</td></tr></table>",
|
||||
"page_idx": 0,
|
||||
},
|
||||
{"type": "image", "img_path": "figure.png", "page_idx": 0},
|
||||
{"type": "equation", "text": "x^2", "page_idx": 0},
|
||||
],
|
||||
asset_dir=assets,
|
||||
engine="mineru",
|
||||
source_hash="fixture-source",
|
||||
parser_signature="fixture-parser",
|
||||
),
|
||||
)
|
||||
# The image asset still passes through the real Sidecar writer; disabling
|
||||
# i only avoids requiring a vision call in this deterministic offline test.
|
||||
staged = replace(staged, process_options=staged.process_options.replace("i", ""))
|
||||
|
||||
rows = asyncio.run(_process(working, staged))
|
||||
|
||||
assert len(rows) == 1
|
||||
row = next(iter(rows.values()))
|
||||
assert getattr(row.status, "value", row.status) == "processed"
|
||||
assert row.file_path == "paper.pdf"
|
||||
assert storage.has_output(working) is True
|
||||
assert list((ingress.pending_root(working) / "__parsed__").glob("paper.pdf"))
|
||||
|
||||
|
||||
def test_real_rc2_append_uses_only_new_doc_and_links_existing_entity(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
async def entity_llm(prompt, **_kwargs) -> str:
|
||||
if "Second document" in prompt:
|
||||
return (
|
||||
"(entity<|#|>SECOND<|#|>CONCEPT<|#|>Second entity)\n"
|
||||
"(relation<|#|>SHARED<|#|>SECOND<|#|>links<|#|>Shared links to Second)"
|
||||
"<|COMPLETE|>"
|
||||
)
|
||||
return "(entity<|#|>SHARED<|#|>CONCEPT<|#|>Shared entity)<|COMPLETE|>"
|
||||
|
||||
_configure_real_sdk(monkeypatch, entity_llm)
|
||||
working = tmp_path / "version-1"
|
||||
working.mkdir()
|
||||
first_source = tmp_path / "first.md"
|
||||
second_source = tmp_path / "second.md"
|
||||
first_source.write_text("First document names Shared.", encoding="utf-8")
|
||||
second_source.write_text("Second document links Shared to Second.", encoding="utf-8")
|
||||
first = ingress.freeze_document(
|
||||
working,
|
||||
first_source,
|
||||
ParsedDocument(markdown="First document names Shared.", engine="text_only"),
|
||||
)
|
||||
|
||||
async def run() -> None:
|
||||
rag = engine.build_rag(working)
|
||||
await engine.initialize(rag)
|
||||
failed = True
|
||||
try:
|
||||
first_track = await engine.enqueue(rag, [first])
|
||||
await rag.apipeline_process_enqueue_documents()
|
||||
first_rows = await rag.aget_docs_by_track_id(first_track)
|
||||
assert [row.file_path for row in first_rows.values()] == ["first.md"]
|
||||
|
||||
second = ingress.freeze_document(
|
||||
working,
|
||||
second_source,
|
||||
ParsedDocument(
|
||||
markdown="Second document links Shared to Second.", engine="text_only"
|
||||
),
|
||||
)
|
||||
second_track = await engine.enqueue(rag, [second])
|
||||
await rag.apipeline_process_enqueue_documents()
|
||||
second_rows = await rag.aget_docs_by_track_id(second_track)
|
||||
assert [row.file_path for row in second_rows.values()] == ["second.md"]
|
||||
assert await rag.chunk_entity_relation_graph.get_node("SHARED") is not None
|
||||
assert await rag.chunk_entity_relation_graph.get_node("SECOND") is not None
|
||||
assert await rag.chunk_entity_relation_graph.get_edge("SHARED", "SECOND") is not None
|
||||
failed = False
|
||||
finally:
|
||||
await engine.finalize(rag, cancel_pending=failed)
|
||||
|
||||
asyncio.run(run())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,145 +1,66 @@
|
||||
"""The LightRAG settings knobs must not break older RAG-Anything installs.
|
||||
|
||||
``max_concurrent_files`` rides on ``RAGAnythingConfig`` and
|
||||
``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride on RAG-Anything's
|
||||
``lightrag_kwargs`` passthrough — a parameter that only exists from ~1.2.5,
|
||||
while the supported range starts at 1.0.1. Passing it blind raised TypeError
|
||||
and took the whole engine down, so the wiring asks the installed class first.
|
||||
|
||||
raganything is an optional extra and is absent from CI, so these tests exercise
|
||||
``build_rag`` against stand-in classes with each constructor shape.
|
||||
"""
|
||||
"""Settings are wired directly to the pinned native LightRAG constructor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.rag.pipelines.lightrag import engine as engine_module
|
||||
from deeptutor.services.rag.pipelines.lightrag import engine
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
importlib.util.find_spec("lightrag") is None,
|
||||
reason="requires the optional rag-lightrag extra",
|
||||
)
|
||||
|
||||
|
||||
class _ModernConfig:
|
||||
"""RAG-Anything >= 1.2.5: config takes the batch knob."""
|
||||
|
||||
def __init__(self, working_dir: str, max_concurrent_files: int = 1) -> None:
|
||||
self.working_dir = working_dir
|
||||
self.max_concurrent_files = max_concurrent_files
|
||||
class _NativeLightRag:
|
||||
def __init__(self, **kwargs) -> None:
|
||||
self.kwargs = kwargs
|
||||
|
||||
|
||||
class _LegacyConfig:
|
||||
"""RAG-Anything 1.0.x: no batch knob at all."""
|
||||
|
||||
def __init__(self, working_dir: str) -> None:
|
||||
self.working_dir = working_dir
|
||||
def _stub_build(monkeypatch) -> None:
|
||||
monkeypatch.setattr(engine, "_require_exact_version", lambda: None)
|
||||
monkeypatch.setattr(engine, "_register_parser", lambda: None)
|
||||
monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)
|
||||
monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")
|
||||
monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")
|
||||
|
||||
|
||||
class _ModernRag:
|
||||
"""RAG-Anything >= 1.2.5: exposes the lightrag_kwargs passthrough."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Any,
|
||||
llm_model_func: Any,
|
||||
vision_model_func: Any,
|
||||
embedding_func: Any,
|
||||
lightrag_kwargs: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.lightrag_kwargs = lightrag_kwargs
|
||||
self.set_content_source_func = None
|
||||
|
||||
|
||||
class _LegacyRag:
|
||||
"""RAG-Anything 1.0.x: no passthrough."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Any,
|
||||
llm_model_func: Any,
|
||||
vision_model_func: Any,
|
||||
embedding_func: Any,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.lightrag_kwargs = None
|
||||
self.set_content_source_func = None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_raganything(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Install a stand-in ``raganything`` module with the given class shapes."""
|
||||
|
||||
def install(rag_cls: type, config_cls: type) -> None:
|
||||
module = types.ModuleType("raganything")
|
||||
module.RAGAnything = rag_cls # type: ignore[attr-defined]
|
||||
module.RAGAnythingConfig = config_cls # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "raganything", module)
|
||||
|
||||
return install
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _stub_adapters(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
for name in ("build_llm_model_func", "build_vision_model_func", "build_embedding_func"):
|
||||
monkeypatch.setattr(engine_module, name, lambda **_kwargs: lambda *a, **k: None)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _settings(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path: Path) -> None:
|
||||
_stub_build(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
engine_module, "indexing_kwargs_from_settings", lambda: {"max_concurrent_files": 4}
|
||||
engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 4}
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
engine_module,
|
||||
"lightrag_kwargs_from_settings",
|
||||
engine,
|
||||
"constructor_kwargs_from_settings",
|
||||
lambda: {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2},
|
||||
)
|
||||
|
||||
rag = engine.build_rag(tmp_path)
|
||||
|
||||
def test_modern_raganything_receives_every_knob(fake_raganything, tmp_path: Path) -> None:
|
||||
fake_raganything(_ModernRag, _ModernConfig)
|
||||
|
||||
rag = engine_module.build_rag(tmp_path)
|
||||
|
||||
assert rag.config.max_concurrent_files == 4
|
||||
assert rag.lightrag_kwargs == {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2}
|
||||
assert rag.kwargs["working_dir"] == str(tmp_path)
|
||||
assert rag.kwargs["workspace"] == engine.workspace_for(tmp_path)
|
||||
assert rag.kwargs["llm_model_func"] == "llm"
|
||||
assert rag.kwargs["embedding_func"] == "embedding"
|
||||
assert rag.kwargs["auto_manage_storages_states"] is False
|
||||
assert rag.kwargs["max_parallel_parse_native"] == 4
|
||||
assert rag.kwargs["llm_model_max_async"] == 8
|
||||
assert rag.kwargs["entity_extract_max_gleaning"] == 2
|
||||
assert rag.kwargs["vlm_process_enable"] is False
|
||||
assert "role_llm_configs" not in rag.kwargs
|
||||
|
||||
|
||||
def test_legacy_raganything_still_builds(
|
||||
fake_raganything, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""The knobs are dropped with a warning rather than raising TypeError."""
|
||||
fake_raganything(_LegacyRag, _LegacyConfig)
|
||||
def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -> None:
|
||||
_stub_build(monkeypatch)
|
||||
monkeypatch.setattr(engine, "build_vision_model_func", lambda **_kwargs: "vision")
|
||||
monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
|
||||
monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
rag = engine_module.build_rag(tmp_path)
|
||||
rag = engine.build_rag(tmp_path, enable_vlm=True)
|
||||
|
||||
assert rag.lightrag_kwargs is None
|
||||
assert not hasattr(rag.config, "max_concurrent_files")
|
||||
assert "max_concurrent_files" in caplog.text
|
||||
assert "lightrag_kwargs" in caplog.text
|
||||
|
||||
|
||||
def test_mixed_versions_drop_only_the_unsupported_knob(fake_raganything, tmp_path: Path) -> None:
|
||||
fake_raganything(_LegacyRag, _ModernConfig)
|
||||
|
||||
rag = engine_module.build_rag(tmp_path)
|
||||
|
||||
assert rag.config.max_concurrent_files == 4
|
||||
assert rag.lightrag_kwargs is None
|
||||
|
||||
|
||||
def test_no_configured_knobs_passes_nothing_extra(
|
||||
fake_raganything, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(engine_module, "indexing_kwargs_from_settings", dict)
|
||||
monkeypatch.setattr(engine_module, "lightrag_kwargs_from_settings", dict)
|
||||
fake_raganything(_ModernRag, _ModernConfig)
|
||||
|
||||
rag = engine_module.build_rag(tmp_path)
|
||||
|
||||
assert rag.config.max_concurrent_files == 1 # the library default
|
||||
assert rag.lightrag_kwargs is None
|
||||
role = rag.kwargs["role_llm_configs"]["vlm"]
|
||||
assert role.func == "vision"
|
||||
assert rag.kwargs["vlm_process_enable"] is True
|
||||
|
||||
@@ -82,13 +82,24 @@ def test_pageindex_sdk_range_matches_every_install_surface() -> None:
|
||||
).splitlines().count(expected) == 1
|
||||
|
||||
|
||||
def test_lightrag_extra_is_the_exact_native_sdk_without_parser_transitives() -> None:
|
||||
with (REPOSITORY_ROOT / "pyproject.toml").open("rb") as file:
|
||||
extras = tomllib.load(file)["project"]["optional-dependencies"]
|
||||
|
||||
requirements = extras["rag-lightrag"]
|
||||
assert requirements == ["lightrag-hku==1.5.7rc2"]
|
||||
names = [requirement.lower().split("=", 1)[0].split("<", 1)[0] for requirement in requirements]
|
||||
assert "raganything" not in names
|
||||
assert "mineru" not in names
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"expected",
|
||||
[
|
||||
"loguru>=0.7.3,<1.0.0",
|
||||
"json-repair>=0.57.0,<1.0.0",
|
||||
"pyte>=0.8.1",
|
||||
"pdfplumber>=0.11.0,<0.11.8",
|
||||
"pdfplumber>=0.11.0",
|
||||
"reportlab>=4.0.0",
|
||||
],
|
||||
)
|
||||
|
||||
@@ -77,7 +77,7 @@ export interface LightRagConfig {
|
||||
version: number;
|
||||
top_k: number;
|
||||
response_type: string;
|
||||
/** Files RAG-Anything processes in parallel while indexing. */
|
||||
/** Frozen documents LightRAG parses in parallel while indexing. */
|
||||
max_concurrent_files: number;
|
||||
/** Concurrent LLM calls LightRAG's internal queue issues. */
|
||||
llm_model_max_async: number;
|
||||
|
||||
@@ -2709,7 +2709,7 @@
|
||||
"API key configured": "API key configured",
|
||||
"GraphRAG package installed": "GraphRAG package installed",
|
||||
"Active chat model": "Active chat model",
|
||||
"RAG-Anything package installed": "RAG-Anything package installed",
|
||||
"LightRAG package installed": "LightRAG package installed",
|
||||
"Vision model for multimodal": "Vision model for multimodal",
|
||||
"Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.": "Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.",
|
||||
"Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.": "Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.",
|
||||
|
||||
@@ -2709,7 +2709,7 @@
|
||||
"API key configured": "已配置 API 密钥",
|
||||
"GraphRAG package installed": "已安装 GraphRAG 依赖包",
|
||||
"Active chat model": "已启用对话模型",
|
||||
"RAG-Anything package installed": "已安装 RAG-Anything 依赖包",
|
||||
"LightRAG package installed": "已安装 LightRAG 依赖包",
|
||||
"Vision model for multimodal": "用于多模态的视觉模型",
|
||||
"Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.": "本地向量引擎,开箱即用。检索使用你当前启用的嵌入模型;可选安装 BM25 包以启用混合检索。",
|
||||
"Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.": "托管引擎:文档上传到 PageIndex 服务器,聊天 agent 通过 PageIndex MCP 工具阅读文档。需配置 API 密钥;支持 PDF、Office、文本和 Markdown 格式。",
|
||||
|
||||
Reference in New Issue
Block a user