minor fix

This commit is contained in:
Bingxi Zhao (Frank)
2026-07-04 15:49:11 +08:00
parent bca6f6e983
commit 3d5b669cd3
11 changed files with 443 additions and 119 deletions

View File

@@ -2,13 +2,17 @@
<p align="center"><img src="assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: Agent-Native Personalized Tutoring
# DeepTutor: Lifelong Personalized Tutoring
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<a href="https://trendshift.io/repositories/17099" target="_blank"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-BCDCF7"></a>&nbsp;

View File

@@ -24,7 +24,11 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError
from deeptutor.core.i18n import t
from deeptutor.partners.config.paths import get_partner_media_dir
from deeptutor.partners.helpers import safe_filename
from deeptutor.services.partners import get_partner_manager, slugify_partner_id
from deeptutor.services.partners import (
get_partner_manager,
slugify_partner_id,
slugify_soul_id,
)
from deeptutor.services.partners.manager import (
LEGACY_GLOBAL_DELIVERY_KEYS,
PartnerConfig,
@@ -326,9 +330,13 @@ async def list_souls():
@router.post("/souls")
async def create_soul(payload: SoulCreateRequest):
mgr = get_partner_manager()
if mgr.get_soul(payload.id):
raise HTTPException(status_code=409, detail=t("api.soul_already_exists", name=payload.id))
return mgr.create_soul(payload.id, payload.name, payload.content)
# Slug the id server-side (authoritative): soul ids ride in ``/souls/<id>``
# URLs, so a raw CJK / path-unsafe id (e.g. ``我的灵魂`` or ``a/b``) would be
# unreachable or mis-routed. The client uses the returned ``id``.
soul_id = slugify_soul_id(payload.id or payload.name)
if mgr.get_soul(soul_id):
raise HTTPException(status_code=409, detail=t("api.soul_already_exists", name=soul_id))
return mgr.create_soul(soul_id, payload.name, payload.content)
@router.get("/souls/{soul_id}")

View File

@@ -7,6 +7,7 @@ from deeptutor.services.partners.manager import (
get_partner_manager,
mask_channel_secrets,
slugify_partner_id,
slugify_soul_id,
)
from deeptutor.services.partners.runtime import PartnerRunner
from deeptutor.services.partners.sessions import PartnerSessionStore
@@ -20,4 +21,5 @@ __all__ = [
"get_partner_manager",
"mask_channel_secrets",
"slugify_partner_id",
"slugify_soul_id",
]

View File

@@ -11,6 +11,7 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from datetime import datetime
import hashlib
import logging
from pathlib import Path
import re
@@ -91,15 +92,40 @@ def strip_legacy_global_delivery(channels: dict[str, Any]) -> dict[str, Any]:
return {k: v for k, v in channels.items() if k not in LEGACY_GLOBAL_DELIVERY_KEYS}
def slugify_partner_id(name: str) -> str:
# Keep Unicode letters/digits so non-Latin names (e.g. 中文) survive as a
# readable id; collapse every other run of characters to a single hyphen.
# ``isalnum`` is Unicode-aware and (unlike ``\w``) excludes underscore, so
# an id can never collide with the reserved ``_souls`` directory. ASCII is
# lower-cased; case-less scripts (CJK, …) pass through unchanged.
cleaned = "".join(c if c.isalnum() else "-" for c in name.strip().lower())
def _slugify_id(name: str, *, fallback: str) -> str:
# Ids ride in URLs (``/partners/<id>``, ``/souls/<id>``) and can become
# on-disk names, so they must be ASCII/URL-safe: a non-Latin id (e.g.
# ``中文``) yields a link the browser can't cleanly display or share, which
# left CJK-named entities unreachable. Keep ASCII letters/digits
# (lower-cased) and collapse every other run to a single hyphen —
# ``isascii`` drops CJK/other scripts and ``isalnum`` excludes underscore,
# so a partner id can't collide with the reserved ``_souls`` directory. When
# no ASCII survives (a pure-CJK name), fall back to a stable per-name handle
# so distinct non-Latin names still get distinct ids while the same name
# round-trips to the same id (keeping the create-time duplicate check
# meaningful). Only the id is slugged; the entity keeps its display name.
stripped = name.strip()
cleaned = "".join(c if c.isascii() and c.isalnum() else "-" for c in stripped.lower())
slug = _HYPHEN_RUN_RE.sub("-", cleaned).strip("-")
return slug or "partner"
if slug:
return slug
if not stripped:
return fallback
digest = hashlib.sha1(stripped.encode("utf-8")).hexdigest()[:8]
return f"{fallback}-{digest}"
def slugify_partner_id(name: str) -> str:
"""ASCII/URL-safe partner id derived from a display name (see
:func:`_slugify_id`); pure-CJK names get a stable ``partner-<hash>`` id."""
return _slugify_id(name, fallback="partner")
def slugify_soul_id(name: str) -> str:
"""ASCII/URL-safe soul-library id. Soul ids ride in ``/souls/<id>`` URLs
exactly like partner ids, so they get the same treatment (see
:func:`_slugify_id`); pure-CJK names get a stable ``soul-<hash>`` id."""
return _slugify_id(name, fallback="soul")
def _optional_str_list(value: Any) -> list[str] | None:

View File

@@ -34,7 +34,7 @@ class PartnerSessionStore:
self._write_lock = threading.Lock()
def _path(self, session_key: str) -> Path:
return self._dir / f"{safe_filename(session_key) or 'default'}.jsonl"
return self._dir / f"{self._stem(session_key)}.jsonl"
@staticmethod
def is_archived_key(session_key: str) -> bool:
@@ -68,7 +68,18 @@ class PartnerSessionStore:
)
def _stem(self, session_key: str) -> str:
return safe_filename(session_key) or "default"
# Single source of truth for key → on-disk stem. ``safe_filename``
# neutralizes path separators (so a key can't escape the sessions dir);
# we additionally strip leading/trailing dots and fall back to
# ``default`` so a degenerate key (empty, ``.`` / ``..``) can't produce a
# hidden or dots-only file. NOTE: safe_filename is intentionally lossy —
# ``:`` and ``/`` both fold to ``_`` — so keys differing only in unsafe
# characters share a file. Callers build keys from safe components (uuid
# hex, slugged ascii ids), so that collision is unreachable in practice;
# making the mapping injective would rename every existing session file
# (``web:<id>`` → ``web_<id>.jsonl``) and orphan history, so it is left
# as-is deliberately.
return safe_filename(session_key).strip(".") or "default"
def is_archived(self, session_key: str) -> bool:
"""Archived = soft flag in the index OR a legacy ``_archived_`` file."""
@@ -179,7 +190,7 @@ class PartnerSessionStore:
if not records:
return None
safe_key = safe_filename(session_key) or "default"
safe_key = self._stem(session_key)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
archive_key = f"{_ARCHIVE_PREFIX}{stamp}_{safe_key}"
archive_path = self._path(archive_key)

View File

@@ -1,8 +1,18 @@
"""Document loading for the LlamaIndex RAG pipeline."""
"""Document loading for the LlamaIndex RAG pipeline.
Parser-backed files (PDF / Office / e-book) are converted through the shared
document-parse bridge (``deeptutor/services/parsing``), so the engine the user
picked in Settings → Document Parsing (text-only, MinerU, Docling, markitdown,
PyMuPDF4LLM) owns extraction. This is the same seam LightRAG and GraphRAG use;
routing LlamaIndex through it too means the parse-engine choice is honored by
every local retrieval engine, and image-capable engines' extracted images flow
into the multimodal ``ImageNode`` path below.
"""
from __future__ import annotations
import base64
from dataclasses import dataclass
import logging
import mimetypes
from pathlib import Path
@@ -14,7 +24,6 @@ from llama_index.core.schema import ImageNode
from deeptutor.services.embedding import get_embedding_client
from deeptutor.services.llm.client import get_llm_client
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.utils.document_extractor import DocumentExtractionError, extract_text_from_path
from deeptutor.utils.document_validator import DocumentValidator
IMAGE_DESCRIPTION_SYSTEM_PROMPT = (
@@ -30,21 +39,37 @@ IMAGE_DESCRIPTION_PROMPT = (
)
@dataclass(frozen=True)
class _ImageSource:
"""An image to embed as an ``ImageNode``, plus the document it came from.
``path`` is the image file on disk (what gets embedded and served).
``origin`` is the document it belongs to: the image itself for a standalone
image file, or the source PDF/e-book for an image extracted during parsing —
so retrieval cites the source document rather than an opaque cache asset.
"""
path: Path
origin: Path
class LlamaIndexDocumentLoader:
"""Convert source files into LlamaIndex ``Document`` objects."""
"""Convert source files into LlamaIndex ``Document`` / ``ImageNode`` objects."""
def __init__(self, logger=None) -> None:
self.logger = logger or logging.getLogger(__name__)
async def load(self, file_paths: Iterable[str]) -> list[Any]:
documents: list[Any] = []
image_sources: list[_ImageSource] = []
classification = FileTypeRouter.classify_files(list(file_paths))
for file_path_str in classification.parser_files:
file_path = Path(file_path_str)
self.logger.info(f"Parsing document: {file_path.name}")
text = self._extract_parser_text(file_path)
text, extracted_images = self._parse_document(file_path)
self._append_if_nonempty(documents, file_path, text)
image_sources.extend(extracted_images)
for file_path_str in classification.text_files:
file_path = Path(file_path_str)
@@ -52,25 +77,74 @@ class LlamaIndexDocumentLoader:
text = await FileTypeRouter.read_text_file(str(file_path))
self._append_if_nonempty(documents, file_path, text)
if classification.image_files:
image_nodes = await self._load_image_nodes(classification.image_files)
documents.extend(image_nodes)
for file_path_str in classification.image_files:
path = Path(file_path_str)
image_sources.append(_ImageSource(path=path, origin=path))
if image_sources:
documents.extend(await self._load_image_nodes(image_sources))
for file_path_str in classification.unsupported:
self.logger.warning(f"Skipped unsupported file: {Path(file_path_str).name}")
return documents
def _extract_parser_text(self, file_path: Path) -> str:
try:
return extract_text_from_path(
file_path, max_bytes=DocumentValidator.MAX_FILE_SIZE, max_chars=None
)
except (DocumentExtractionError, OSError) as exc:
self.logger.error(f"Failed to extract {file_path.name}: {exc}")
return ""
def _parse_document(self, file_path: Path) -> tuple[str, list[_ImageSource]]:
"""Parse a document through the shared, engine-pluggable parse layer.
async def _load_image_nodes(self, file_paths: list[str]) -> list[ImageNode]:
Returns ``(text, extracted_images)``. A parse failure (engine
unavailable, unsupported format for the active engine, or models not
ready) is logged and the file is skipped — matching the sibling
LightRAG/GraphRAG pipelines — rather than aborting the whole batch.
"""
from deeptutor.services.parsing import ParserError, get_parse_service
try:
parsed = get_parse_service().parse(file_path)
except ParserError as exc:
self.logger.warning(
f"Skipped {file_path.name}: the active document-parsing engine could "
f"not handle it ({exc}). Change the engine in Settings → Document Parsing."
)
return "", []
text = parsed.markdown.strip() or self._text_from_blocks(parsed.blocks)
images = self._collect_asset_images(parsed.asset_dir, origin=file_path)
return text, images
@staticmethod
def _text_from_blocks(blocks: list[dict] | None) -> str:
"""Fall back to concatenating block text when an engine emits no markdown."""
if not blocks:
return ""
parts = [
str(block.get("text") or block.get("content") or "").strip()
for block in blocks
if isinstance(block, dict)
]
return "\n\n".join(part for part in parts if part)
def _collect_asset_images(self, asset_dir: Path | None, *, origin: Path) -> list[_ImageSource]:
"""Gather images the parse engine extracted into ``asset_dir``.
Engines that don't extract images (text-only, markitdown) leave
``asset_dir`` empty, so this returns nothing and the document is indexed
as text alone.
"""
if not asset_dir or not Path(asset_dir).is_dir():
return []
images = [
_ImageSource(path=child, origin=origin)
for child in sorted(Path(asset_dir).iterdir())
if child.is_file() and child.suffix.lower() in FileTypeRouter.IMAGE_EXTENSIONS
]
if images:
self.logger.info(
f"Extracted {len(images)} image(s) from {origin.name} for multimodal indexing"
)
return images
async def _load_image_nodes(self, sources: list[_ImageSource]) -> list[ImageNode]:
embedding_client = get_embedding_client()
llm_client = get_llm_client()
@@ -88,42 +162,41 @@ class LlamaIndexDocumentLoader:
)
if unsupported_reasons:
reason_text = "; ".join(unsupported_reasons)
for file_path_str in file_paths:
for source in sources:
self.logger.warning(
"Skipped image file because image indexing requires both "
"Skipped image because image indexing requires both "
f"multimodal embedding and multimodal LLM support; {reason_text}: "
f"{Path(file_path_str).name}"
f"{source.path.name}"
)
return []
paths = [Path(file_path_str) for file_path_str in file_paths]
embedded_paths: list[Path] = []
embedded: list[_ImageSource] = []
descriptions: list[str] = []
contents = []
for path in paths:
for source in sources:
try:
image_payload = self._load_image_payload(path)
image_payload = self._load_image_payload(source.path)
description = await self._describe_image(
path,
source.path,
image_payload["base64"],
image_payload["mimetype"],
)
if not description:
self.logger.warning(
"Skipped image file because the configured multimodal LLM "
f"returned no description: {path.name}"
"Skipped image because the configured multimodal LLM "
f"returned no description: {source.path.name}"
)
continue
contents.append({"image": image_payload["data_uri"]})
embedded_paths.append(path)
embedded.append(source)
descriptions.append(description)
except OSError as exc:
self.logger.error(f"Failed to read image {path.name}: {exc}")
self.logger.error(f"Failed to read image {source.path.name}: {exc}")
except Exception as exc:
self.logger.error(
"Failed to describe image %s with configured multimodal LLM "
"(binding=%s, model=%s): %s",
path.name,
source.path.name,
llm_client.config.binding,
llm_client.config.model,
exc,
@@ -144,23 +217,23 @@ class LlamaIndexDocumentLoader:
)
return []
nodes: list[ImageNode] = []
for path, description, embedding in zip(embedded_paths, descriptions, embeddings):
mimetype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
for source, description, embedding in zip(embedded, descriptions, embeddings):
mimetype = mimetypes.guess_type(source.path.name)[0] or "application/octet-stream"
nodes.append(
ImageNode(
text=f"[Image] {path.name}\n\n{description}",
image_path=str(path),
text=f"[Image] {source.origin.name}\n\n{description}",
image_path=str(source.path),
image_mimetype=mimetype,
metadata={
"file_name": path.name,
"file_path": str(path),
"file_name": source.origin.name,
"file_path": str(source.origin),
"content_type": "image",
"image_description": description,
},
embedding=embedding,
)
)
self.logger.info(f"Loaded image: {path.name} ({len(embedding)}D vector)")
self.logger.info(f"Loaded image: {source.path.name} ({len(embedding)}D vector)")
return nodes
async def _describe_image(self, file_path: Path, image_base64: str, mimetype: str) -> str:

View File

@@ -184,16 +184,24 @@ matrix-e2e = [
math-animator = ["manim>=0.19.0"]
# GraphRAG knowledge-base engine (microsoft/graphrag). Optional, heavy
# (LiteLLM + lancedb + graspologic) and constrained to python <3.14 — kept out
# of `all` so it stays a deliberate opt-in. The pipeline imports lazily and the
# adapter targets the 3.x API (see services/rag/pipelines/graphrag/engine.py).
graphrag = ["graphrag>=3.0.0,<4.0.0"]
# (LiteLLM + lancedb + graspologic) and kept out of `all` so it stays a
# deliberate opt-in. The pipeline imports lazily and the adapter targets the
# 3.x API (see services/rag/pipelines/graphrag/engine.py). Every graphrag 3.x
# release is capped at python <3.14; the `python_version` marker mirrors that
# so on 3.14+ the extra resolves to a no-op instead of an unsatisfiable hard
# dep — otherwise pip backtracks deeptutor to the last extra-free version
# (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.
rag-lightrag = ["raganything>=1.0.0"]
# 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.
rag-lightrag = ["raganything>=1.0.1,<2.0.0; python_version < '3.14'"]
# Dev/test tooling. Mirrors requirements/dev.txt.
dev = [

View File

@@ -222,6 +222,20 @@ class TestSoulLibraryEndpoints:
assert client.delete("/api/v1/partners/souls/custom-soul").status_code == 200
assert client.get("/api/v1/partners/souls/custom-soul").status_code == 404
def test_soul_cjk_id_is_ascii_safe(self, client):
# A pure-CJK soul name must not become a non-ASCII (unreachable) id: the
# server slugs it authoritatively and the returned id is URL-safe.
res = client.post(
"/api/v1/partners/souls",
json={"id": "我的灵魂", "name": "我的灵魂", "content": "# Soul"},
)
assert res.status_code == 200
soul_id = res.json()["id"]
assert soul_id.isascii() and soul_id.startswith("soul-")
# …and the soul is reachable / deletable by that returned id.
assert client.get(f"/api/v1/partners/souls/{soul_id}").status_code == 200
assert client.delete(f"/api/v1/partners/souls/{soul_id}").status_code == 200
def test_soul_sources_shape(self, client):
body = client.get("/api/v1/partners/soul-sources").json()
assert "library" in body and "personas" in body

View File

@@ -0,0 +1,100 @@
"""``slugify_partner_id`` must yield ASCII/URL-safe ids.
Partner ids ride in ``/partners/<id>`` links and become on-disk directory
names, so a non-Latin id (e.g. a raw CJK name) produced an unreachable link.
These tests pin the ASCII-safe behavior and the stable per-name fallback used
for names that have no ASCII characters at all.
"""
from __future__ import annotations
import string
from deeptutor.services.partners.manager import slugify_partner_id, slugify_soul_id
_ALLOWED = set(string.ascii_lowercase + string.digits + "-")
def _is_url_safe(slug: str) -> bool:
return bool(slug) and slug.isascii() and set(slug) <= _ALLOWED
class TestAsciiNames:
def test_lowercases_and_hyphenates(self):
assert slugify_partner_id("Ada Lovelace") == "ada-lovelace"
def test_collapses_runs_and_strips_edges(self):
assert slugify_partner_id(" Study Buddy!!! ") == "study-buddy"
assert slugify_partner_id("--Hi--") == "hi"
def test_underscore_is_not_kept(self):
# Underscore must not survive: it would let an id collide with the
# reserved ``_souls`` directory.
slug = slugify_partner_id("my_bot")
assert slug == "my-bot"
assert "_" not in slug
def test_result_is_url_safe(self):
for name in ("Ada", "R2-D2", "Café au lait", "数学老师Bot"):
assert _is_url_safe(slugify_partner_id(name))
class TestNonLatinNames:
def test_pure_cjk_falls_back_to_ascii_handle(self):
slug = slugify_partner_id("小助手")
assert _is_url_safe(slug)
assert slug.startswith("partner-")
def test_same_name_is_stable(self):
# Same name -> same id, so the create-time duplicate check still fires.
assert slugify_partner_id("小助手") == slugify_partner_id("小助手")
def test_distinct_cjk_names_get_distinct_ids(self):
# The whole point of the fallback: two different non-Latin names must
# not both collapse to the same "partner" id.
assert slugify_partner_id("小助手") != slugify_partner_id("数学老师")
def test_mixed_name_keeps_the_ascii_part(self):
assert slugify_partner_id("小助手Bot") == "bot"
class TestSoulSlug:
"""``slugify_soul_id`` shares the partner logic but falls back to ``soul``.
Soul ids ride in ``/souls/<id>`` URLs, so the same ASCII-safety guarantees
must hold.
"""
def test_ascii_name_slugged(self):
assert slugify_soul_id("Rigorous Tutor") == "rigorous-tutor"
def test_pure_cjk_falls_back_to_soul_handle(self):
slug = slugify_soul_id("我的灵魂")
assert _is_url_safe(slug)
assert slug.startswith("soul-")
def test_distinct_cjk_names_get_distinct_ids(self):
assert slugify_soul_id("我的灵魂") != slugify_soul_id("严谨助教")
def test_fallback_prefix_differs_from_partner(self):
# Same pure-CJK name → different prefixes, so a soul id and a partner id
# derived from the same name never collide by construction.
name = "我的灵魂"
assert slugify_soul_id(name).startswith("soul-")
assert slugify_partner_id(name).startswith("partner-")
def test_empty_becomes_soul(self):
assert slugify_soul_id(" ") == "soul"
class TestDegenerate:
def test_empty_and_whitespace_become_partner(self):
assert slugify_partner_id("") == "partner"
assert slugify_partner_id(" ") == "partner"
def test_punctuation_only_falls_back(self):
# No ASCII alphanumerics survive, but the name is non-empty -> stable
# per-name handle rather than a bare "partner".
slug = slugify_partner_id("!!!")
assert _is_url_safe(slug)
assert slug.startswith("partner-")

View File

@@ -1,82 +1,156 @@
"""Tests for LlamaIndex document loading."""
"""Tests for LlamaIndex document loading.
Parser-backed files (PDF / Office / e-book) are routed through the shared
parse layer, so these tests exercise the *routing* — that the loader turns a
``ParsedDocument`` into text ``Document``s and feeds engine-extracted images
into the multimodal ``ImageNode`` path. Real per-format text extraction is
covered by ``tests/utils/test_document_extractor.py`` and the parse-engine
tests under ``tests/services/parsing/``.
"""
from __future__ import annotations
import asyncio
import io
from pathlib import Path
import pytest
def _make_docx(paragraphs: list[str]) -> bytes:
DocxDocument = pytest.importorskip("docx").Document
doc = DocxDocument()
for paragraph in paragraphs:
doc.add_paragraph(paragraph)
buffer = io.BytesIO()
doc.save(buffer)
return buffer.getvalue()
def _install_stub_parse_service(monkeypatch, results: dict[str, "object"]) -> None:
"""Point ``get_parse_service`` at a stub keyed by source file name.
``results`` maps a file name to either a ``ParsedDocument`` to return or an
exception instance to raise (e.g. ``ParserError``).
"""
import deeptutor.services.parsing as parsing
class _StubService:
def parse(self, source_path, **_kwargs):
outcome = results[Path(source_path).name]
if isinstance(outcome, Exception):
raise outcome
return outcome
monkeypatch.setattr(parsing, "get_parse_service", lambda: _StubService())
def _make_xlsx(rows: list[list[object]]) -> bytes:
Workbook = pytest.importorskip("openpyxl").Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = "Data"
for row in rows:
sheet.append(row)
buffer = io.BytesIO()
workbook.save(buffer)
return buffer.getvalue()
def _make_pptx(texts: list[str]) -> bytes:
Presentation = pytest.importorskip("pptx").Presentation
Inches = pytest.importorskip("pptx.util").Inches
presentation = Presentation()
slide = presentation.slides.add_slide(presentation.slide_layouts[5])
for index, text in enumerate(texts):
text_box = slide.shapes.add_textbox(
Inches(1),
Inches(1 + index * 0.5),
Inches(6),
Inches(0.5),
)
text_box.text_frame.text = text
buffer = io.BytesIO()
presentation.save(buffer)
return buffer.getvalue()
def test_loader_extracts_chat_supported_office_files(tmp_path: Path) -> None:
def test_loader_routes_parser_files_through_active_parse_engine(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.parsing.types import ParsedDocument
from deeptutor.services.rag.pipelines.llamaindex.document_loader import (
LlamaIndexDocumentLoader,
)
docx_path = tmp_path / "notes.docx"
docx_path.write_bytes(_make_docx(["Docx paragraph"]))
xlsx_path = tmp_path / "book.xlsx"
xlsx_path.write_bytes(_make_xlsx([["cell-a", 42]]))
pptx_path = tmp_path / "slides.pptx"
pptx_path.write_bytes(_make_pptx(["Slide title", "Slide body"]))
docx_path.write_bytes(b"stub")
pdf_path = tmp_path / "paper.pdf"
pdf_path.write_bytes(b"stub")
documents = asyncio.run(
LlamaIndexDocumentLoader().load([str(docx_path), str(xlsx_path), str(pptx_path)])
_install_stub_parse_service(
monkeypatch,
{
"notes.docx": ParsedDocument(markdown="Docx body text"),
# No markdown, only structured blocks -> block-text fallback.
"paper.pdf": ParsedDocument(
markdown="",
blocks=[{"type": "text", "text": "Block one"}, {"content": "Block two"}],
),
},
)
assert {doc.metadata["file_name"] for doc in documents} == {
"notes.docx",
"book.xlsx",
"slides.pptx",
}
all_text = "\n".join(doc.text for doc in documents)
assert "Docx paragraph" in all_text
assert "cell-a" in all_text
assert "42" in all_text
assert "Slide title" in all_text
assert "Slide body" in all_text
documents = asyncio.run(LlamaIndexDocumentLoader().load([str(docx_path), str(pdf_path)]))
by_name = {doc.metadata["file_name"]: doc.text for doc in documents}
assert by_name["notes.docx"] == "Docx body text"
assert "Block one" in by_name["paper.pdf"]
assert "Block two" in by_name["paper.pdf"]
def test_loader_skips_document_when_active_engine_cannot_parse(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.parsing.types import ParserError
from deeptutor.services.rag.pipelines.llamaindex.document_loader import (
LlamaIndexDocumentLoader,
)
docx_path = tmp_path / "unsupported.docx"
docx_path.write_bytes(b"stub")
_install_stub_parse_service(
monkeypatch,
{"unsupported.docx": ParserError("the 'pymupdf4llm' engine doesn't support .docx files")},
)
with caplog.at_level("WARNING"):
documents = asyncio.run(LlamaIndexDocumentLoader().load([str(docx_path)]))
assert documents == []
assert "Skipped unsupported.docx" in caplog.text
assert "Settings" in caplog.text
def test_loader_indexes_images_extracted_from_parsed_document(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
pytest.importorskip("llama_index.core")
from llama_index.core.schema import ImageNode
from deeptutor.services.parsing.types import ParsedDocument
from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
pdf_path = tmp_path / "paper.pdf"
pdf_path.write_bytes(b"stub")
asset_dir = tmp_path / "assets"
asset_dir.mkdir()
(asset_dir / "figure-1.png").write_bytes(b"\x89PNG\r\n")
(asset_dir / "notes.txt").write_text("not an image", encoding="utf-8") # ignored
_install_stub_parse_service(
monkeypatch,
{"paper.pdf": ParsedDocument(markdown="Paper body", asset_dir=asset_dir)},
)
class _MultimodalEmbeddingClient:
config = type("Config", (), {"binding": "siliconflow", "model": "qwen3-vl"})()
def supports_multimodal_contents(self) -> bool:
return True
async def embed_contents(self, contents):
return [[0.4, 0.5, 0.6] for _ in contents]
class _VisionClient:
config = type("Config", (), {"binding": "openai", "model": "gpt-4o"})()
def supports_multimodal_images(self) -> bool:
return True
async def complete(self, prompt, **kwargs):
return "Figure showing a bar chart."
monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _MultimodalEmbeddingClient())
monkeypatch.setattr(loader_module, "get_llm_client", lambda: _VisionClient())
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(pdf_path)]))
text_docs = [doc for doc in documents if not isinstance(doc, ImageNode)]
image_nodes = [doc for doc in documents if isinstance(doc, ImageNode)]
assert len(text_docs) == 1
assert text_docs[0].text == "Paper body"
assert len(image_nodes) == 1
node = image_nodes[0]
assert node.embedding == [0.4, 0.5, 0.6]
assert node.metadata["content_type"] == "image"
# Provenance: the extracted image cites the source document, not the cache asset.
assert node.metadata["file_name"] == "paper.pdf"
assert node.image_path == str(asset_dir / "figure-1.png")
assert "Figure showing a bar chart." in node.text
def test_loader_skips_images_when_embedding_provider_is_text_only(

View File

@@ -28,12 +28,16 @@ import SoulEditor from "@/components/partners/SoulEditor";
type SourceTab = "library" | "persona" | "custom";
// Soul ids ride in /souls/<id> URLs, so keep them ASCII/URL-safe (a CJK id is
// unreachable) — the server re-slugs authoritatively and the create flow uses
// the returned id, but producing an ASCII slug here keeps the preview honest
// and avoids sending a non-ASCII id over the wire.
function slugifySoulId(name: string): string {
return (
name
.trim()
.toLowerCase()
.replace(/[^a-z0-9一-鿿]+/g, "-")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "") || `soul-${Date.now().toString(36)}`
);
}