DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: add EPUB support for knowledge base (#843)
zhouraym0f2235380674
diff --git a/deeptutor/services/parsing/engines/text_only/engine.py b/deeptutor/services/parsing/engines/text_only/engine.pyindex ae7bc35df..dc66d092c 100644--- a/deeptutor/services/parsing/engines/text_only/engine.py+++ b/deeptutor/services/parsing/engines/text_only/engine.py@@ -18,7 +18,7 @@ from ...types import ParserErrorclass TextOnlyParser:- """Built-in PDF/Office/text-file extraction with no external engine."""+ """Built-in PDF/Office/EPUB/text-file extraction with no external engine."""name = "text_only"needs_local_models = Falsediff --git a/deeptutor/services/rag/file_routing.py b/deeptutor/services/rag/file_routing.pyindex f5c7655f8..4aa9cfa2f 100644--- a/deeptutor/services/rag/file_routing.py+++ b/deeptutor/services/rag/file_routing.py@@ -24,6 +24,7 @@ class DocumentType(Enum):DOCX = "docx"SPREADSHEET = "spreadsheet"PRESENTATION = "presentation"+ EPUB = "epub"IMAGE = "image"UNKNOWN = "unknown"@@ -42,14 +43,15 @@ class FileTypeRouter:"""File type router for the RAG pipeline.Classifies files before processing to route them to appropriate handlers:- - PDF / Office files -> parser-based text extraction+ - PDF / Office / EPUB files -> parser-based text extraction- Text files -> Direct read (fast, simple)- Unsupported -> Skip with warning"""PDF_EXTENSIONS = {".pdf"}OFFICE_EXTENSIONS = {".docx", ".xlsx", ".pptx"}- PARSER_EXTENSIONS = PDF_EXTENSIONS | OFFICE_EXTENSIONS+ EPUB_EXTENSIONS = {".epub"}+ PARSER_EXTENSIONS = PDF_EXTENSIONS | OFFICE_EXTENSIONS | EPUB_EXTENSIONSTEXT_EXTENSIONS = {# Plain text & docs@@ -191,6 +193,8 @@ class FileTypeRouter:return DocumentType.SPREADSHEETelif ext == ".pptx":return DocumentType.PRESENTATION+ elif ext in cls.EPUB_EXTENSIONS:+ return DocumentType.EPUBelif ext in cls.IMAGE_EXTENSIONS:return DocumentType.IMAGEelse:@@ -229,6 +233,7 @@ class FileTypeRouter:DocumentType.DOCX,DocumentType.SPREADSHEET,DocumentType.PRESENTATION,+ DocumentType.EPUB,):parser_files.append(path)elif doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN):@@ -297,6 +302,7 @@ class FileTypeRouter:DocumentType.DOCX,DocumentType.SPREADSHEET,DocumentType.PRESENTATION,+ DocumentType.EPUB,DocumentType.IMAGE,)diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.pyindex 17e362e9b..1de8973f2 100644--- a/deeptutor/utils/document_extractor.py+++ b/deeptutor/utils/document_extractor.py@@ -3,9 +3,11 @@Bytes-in, text-out. Used by the chat turn runtime to inline the text ofuser-dropped files into the ``effective_user_message`` sent to the LLM.-Two format families:+Three format families:* **Binary Office** (.pdf / .docx / .xlsx / .pptx) — parsed with pymupdf /python-docx / openpyxl / python-pptx.+ * **EPUB** (.epub) — ZIP of XHTML documents; text is pulled in the OPF+ spine reading order using only the standard library.* **Text-like** (plain text, Markdown, source code, JSON, XML, CSV, …) —the extension set is imported from ``FileTypeRouter.TEXT_EXTENSIONS`` sothe chat composer accepts every format the knowledge-base pipeline@@ -19,11 +21,14 @@ from __future__ import annotationsimport base64from collections.abc import Iterable+from html.parser import HTMLParserimport ioimport loggingfrom pathlib import Path, PurePosixPath+import posixpathimport refrom typing import Any+from urllib.parse import unquoteimport zipfilefrom defusedxml import ElementTree as DefusedElementTree@@ -89,6 +94,39 @@ def _current_limits() -> tuple[int, int, int, int]:_PDF_MAGIC = b"%PDF-"_OOXML_MAGIC = b"PK\x03\x04"+_EPUB_CONTENT_EXTENSIONS: frozenset[str] = frozenset({".xhtml", ".html", ".htm"})+_EPUB_MAX_MEMBERS = 4096+_EPUB_MAX_MEMBER_BYTES = 20 * 1024 * 1024+_EPUB_MAX_TOTAL_UNCOMPRESSED_BYTES = 200 * 1024 * 1024+_EPUB_MAX_COMPRESSION_RATIO = 200.0+_EPUB_BLOCK_TAGS: frozenset[str] = frozenset(+ {+ "p",+ "div",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "li",+ "blockquote",+ "tr",+ "table",+ "section",+ "article",+ "header",+ "footer",+ "aside",+ "figure",+ "figcaption",+ "dd",+ "dt",+ "dl",+ "hr",+ }+)+class DocumentExtractionError(Exception):"""Base class for extraction failures. ``str(exc)`` is user-friendly."""@@ -146,6 +184,12 @@ def _check_magic(ext: str, data: bytes, filename: str) -> None:f"{filename} does not look like a valid Office file (bad header)",filename=filename,)+ elif ext == ".epub":+ if not data.startswith(_OOXML_MAGIC):+ raise CorruptDocumentError(+ f"{filename} does not look like a valid EPUB (bad header)",+ filename=filename,+ )def extract_text_from_bytes(@@ -187,6 +231,8 @@ def extract_text_from_bytes(text = _extract_xlsx(data, filename)elif ext == ".pptx":text = _extract_pptx(data, filename)+ elif ext == ".epub":+ text = _extract_epub(data, filename)elif ext in TEXT_LIKE_EXTENSIONS:text = _extract_text_like(data, filename)else: # pragma: no cover - guarded above@@ -402,6 +448,208 @@ def _extract_text_like(data: bytes, filename: str) -> str:) from exc+def _epub_parse_member(zf: zipfile.ZipFile, member: str, filename: str) -> Any | None:+ """Parse one XML/XHTML member, returning ``None`` when unreadable.++ Real-world EPUBs occasionally ship sloppy XHTML (undeclared entities,+ stray tags); a single bad chapter must not sink the whole book, so parse+ failures are logged and skipped instead of raising.+ """+ try:+ return _parse_xml_member(zf, member, filename)+ except CorruptDocumentError as exc:+ logger.warning("EPUB %s: skipping unparseable member %s (%s)", filename, member, exc)+ return None+++class _EpubHTMLTextParser(HTMLParser):+ """Best-effort text renderer for EPUB chapters that are not valid XML."""++ def __init__(self) -> None:+ super().__init__(convert_charrefs=True)+ self.parts: list[str] = []+ self._ignored_depth = 0++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ del attrs+ tag = tag.lower()+ if tag in {"script", "style"}:+ self._ignored_depth += 1+ elif not self._ignored_depth and tag == "br":+ self.parts.append("\n")++ def handle_endtag(self, tag: str) -> None:+ tag = tag.lower()+ if tag in {"script", "style"} and self._ignored_depth:+ self._ignored_depth -= 1+ elif not self._ignored_depth and tag in _EPUB_BLOCK_TAGS:+ self.parts.append("\n\n")++ def handle_data(self, data: str) -> None:+ if not self._ignored_depth:+ self.parts.append(data)+++def _epub_render_text(element: Any, parts: list[str]) -> None:+ """Append the text of one XHTML element and its subtree to ``parts``.++ Element text is emitted before its children and each child's tail after+ it, preserving the document's word spacing. Block-level tags contribute a+ paragraph break; ``script``/``style`` subtrees are dropped entirely.+ """+ tag = _local_name(element.tag) if isinstance(element.tag, str) else ""+ if tag in {"script", "style"}:+ return+ if element.text:+ parts.append(element.text)+ if tag == "br":+ parts.append("\n")+ for child in element:+ _epub_render_text(child, parts)+ if child.tail:+ parts.append(child.tail)+ if tag in _EPUB_BLOCK_TAGS:+ parts.append("\n\n")+++def _epub_xhtml_text(root: Any) -> str:+ """Render one XHTML document as plain text with paragraph breaks.++ Keeps the source whitespace of text nodes (XHTML carries its own word+ spacing) and collapses each line afterwards, so ``<b>world</b>.`` stays+ ``world.`` instead of gaining a stray space.+ """+ parts: list[str] = []+ _epub_render_text(root, parts)+ return _normalize_epub_text(parts)+++def _normalize_epub_text(parts: Iterable[str]) -> str:+ raw = "".join(parts)+ lines = [re.sub(r"\s+", " ", line).strip() for line in raw.split("\n")]+ return "\n".join(line for line in lines if line)+++def _epub_chapter_text(zf: zipfile.ZipFile, member: str, filename: str) -> str:+ """Render a chapter as XHTML, falling back to tolerant HTML parsing."""+ try:+ root = _parse_xml_member(zf, member, filename)+ except CorruptDocumentError as exc:+ try:+ raw = zf.read(member)+ parser = _EpubHTMLTextParser()+ parser.feed(FileTypeRouter.decode_bytes(raw))+ parser.close()+ except Exception:+ logger.warning("EPUB %s: skipping unparseable member %s", filename, member)+ return ""+ text = _normalize_epub_text(parser.parts)+ if text:+ logger.info("EPUB %s: used tolerant HTML parser for %s (%s)", filename, member, exc)+ return text+ return _epub_xhtml_text(root) if root is not None else ""+++def _epub_html_members(names: list[str]) -> list[str]:+ """Archive members that look like XHTML content, in archive order."""+ return [name for name in names if _ext(name) in _EPUB_CONTENT_EXTENSIONS]+++def _epub_content_files(zf: zipfile.ZipFile, filename: str) -> list[str]:+ """Resolve the XHTML content documents of an EPUB in reading order.++ Follows the standard chain ``META-INF/container.xml`` -> OPF package+ document -> spine ``itemref`` order. Falls back to every HTML/XHTML+ member in archive order when package metadata is missing or unusable.+ """+ names = zf.namelist()+ name_set = set(names)++ container_root = _epub_parse_member(zf, "META-INF/container.xml", filename)+ if container_root is None:+ return _epub_html_members(names)++ opf_path = ""+ for node in container_root.iter():+ if _local_name(node.tag) == "rootfile":+ opf_path = node.get("full-path") or ""+ break+ if not opf_path or opf_path not in name_set:+ return _epub_html_members(names)++ opf_root = _epub_parse_member(zf, opf_path, filename)+ if opf_root is None:+ return _epub_html_members(names)++ manifest: dict[str, str] = {}+ spine_ids: list[str] = []+ for node in opf_root.iter():+ name = _local_name(node.tag)+ if name == "item":+ item_id = node.get("id")+ href = node.get("href")+ if item_id and href:+ manifest[item_id] = href+ elif name == "itemref":+ idref = node.get("idref")+ if idref:+ spine_ids.append(idref)++ opf_dir = posixpath.dirname(opf_path)+ ordered: list[str] = []+ seen: set[str] = set()+ for idref in spine_ids:+ href = manifest.get(idref)+ if not href:+ continue+ member = posixpath.normpath(posixpath.join(opf_dir, unquote(href.split("#", 1)[0])))+ if member in name_set and member not in seen:+ ordered.append(member)+ seen.add(member)+ return ordered or _epub_html_members(names)+++def _extract_epub(data: bytes, filename: str) -> str:+ """Extract the reading text of an EPUB with only the standard library."""+ with _open_ooxml(data, filename) as zf:+ _validate_epub_archive(zf, filename)+ chapters: list[str] = []+ for member in _epub_content_files(zf, filename):+ text = _epub_chapter_text(zf, member, filename)+ if text:+ chapters.append(text)+ return "\n\n".join(chapters)+++def _validate_epub_archive(zf: zipfile.ZipFile, filename: str) -> None:+ """Reject oversized or suspicious EPUB ZIPs before reading any member."""+ members = [info for info in zf.infolist() if not info.is_dir()]+ if len(members) > _EPUB_MAX_MEMBERS:+ raise DocumentTooLargeError(+ f"{filename}: EPUB has too many archive members ({len(members)})",+ filename=filename,+ )++ total = 0+ for info in members:+ if info.file_size > _EPUB_MAX_MEMBER_BYTES:+ raise DocumentTooLargeError(+ f"{filename}: EPUB member {info.filename} is too large",+ filename=filename,+ )+ total += info.file_size+ if total > _EPUB_MAX_TOTAL_UNCOMPRESSED_BYTES:+ raise DocumentTooLargeError(+ f"{filename}: EPUB uncompressed contents are too large",+ filename=filename,+ )+ if info.compress_size and info.file_size / info.compress_size > _EPUB_MAX_COMPRESSION_RATIO:+ raise DocumentTooLargeError(+ f"{filename}: EPUB member {info.filename} has a suspicious compression ratio",+ filename=filename,+ )++def _open_ooxml(data: bytes, filename: str) -> zipfile.ZipFile:try:return zipfile.ZipFile(io.BytesIO(data))diff --git a/deeptutor/utils/document_validator.py b/deeptutor/utils/document_validator.pyindex 25571dbf1..c7d01c34f 100644--- a/deeptutor/utils/document_validator.py+++ b/deeptutor/utils/document_validator.py@@ -33,6 +33,7 @@ class DocumentValidator:".xls",".pptx",".ppt",+ ".epub",}# MIME type mapping for additional validation@@ -52,6 +53,8 @@ class DocumentValidator:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation",+ "application/epub+zip",+ "application/epub",}@staticmethoddiff --git a/tests/services/rag/test_file_routing.py b/tests/services/rag/test_file_routing.pyindex 7d0dd7ac3..4d8cb53b7 100644--- a/tests/services/rag/test_file_routing.py+++ b/tests/services/rag/test_file_routing.py@@ -27,6 +27,8 @@ class TestExtensionClassification:("paper.docx", DocumentType.DOCX),("sheet.xlsx", DocumentType.SPREADSHEET),("deck.pptx", DocumentType.PRESENTATION),+ ("book.epub", DocumentType.EPUB),+ ("BOOK.EPUB", DocumentType.EPUB),("photo.png", DocumentType.IMAGE),],)@@ -56,15 +58,17 @@ class TestClassifyFiles:xlsx.write_bytes(b"PK\x03\x04")pptx = tmp_path / "a.pptx"pptx.write_bytes(b"PK\x03\x04")+ epub = tmp_path / "a.epub"+ epub.write_bytes(b"PK\x03\x04")txt = tmp_path / "a.txt"txt.write_text("hi")png = tmp_path / "a.png"png.write_bytes(b"\x89PNG\r\n")cls = FileTypeRouter.classify_files(- [str(pdf), str(docx), str(xlsx), str(pptx), str(txt), str(png)]+ [str(pdf), str(docx), str(xlsx), str(pptx), str(epub), str(txt), str(png)])- assert cls.parser_files == [str(pdf), str(docx), str(xlsx), str(pptx)]+ assert cls.parser_files == [str(pdf), str(docx), str(xlsx), str(pptx), str(epub)]assert cls.text_files == [str(txt)]assert cls.image_files == [str(png)]assert cls.unsupported == []@@ -86,6 +90,7 @@ class TestSupportedExtensionsAndGlobs:assert ".pptx" in extsassert ".md" in extsassert ".txt" in exts+ assert ".epub" in extsassert ".png" in extsdef test_glob_patterns_match_supported_extensions(self) -> None:@@ -129,6 +134,10 @@ class TestQuickHelpers:assert FileTypeRouter.needs_parser("sheet.xlsx") is Trueassert FileTypeRouter.needs_parser("deck.pptx") is True+ def test_needs_parser_for_epub(self) -> None:+ assert FileTypeRouter.needs_parser("book.epub") is True+ assert FileTypeRouter.needs_parser("BOOK.EPUB") is True+def test_needs_parser_false_for_text(self) -> None:assert FileTypeRouter.needs_parser("notes.md") is Falsediff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.pyindex f89edf63a..3562ed4cd 100644--- a/tests/utils/test_document_extractor.py+++ b/tests/utils/test_document_extractor.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport base64import io+import zipfilefrom docx import Document as DocxDocumentfrom openpyxl import Workbook@@ -66,6 +67,56 @@ def _make_pptx(slides_text: list[list[str]]) -> bytes:return buf.getvalue()+_CONTAINER_XML = (+ '<?xml version="1.0"?>'+ '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">'+ '<rootfiles><rootfile full-path="{opf}" media-type="application/oebps-package+xml"/>'+ "</rootfiles></container>"+)+++def _make_epub(+ chapters: dict[str, str],+ spine: list[str] | None = None,+ *,+ opf_dir: str = "OEBPS",+ with_container: bool = True,+ with_opf: bool = True,+) -> bytes:+ """Build a minimal EPUB in memory.++ ``chapters`` maps member names (relative to ``opf_dir``) to XHTML body+ markup. ``spine`` is an ordered subset of chapter keys controlling the+ reading order; it defaults to the dict order.+ """+ opf_path = f"{opf_dir}/content.opf"+ manifest = "".join(+ f'<item id="ch{i}" href="{name}" media-type="application/xhtml+xml"/>'+ for i, name in enumerate(chapters)+ )+ ids = {name: f"ch{i}" for i, name in enumerate(chapters)}+ spine_ids = spine if spine is not None else list(chapters)+ spine_xml = "".join(f'<itemref idref="{ids[name]}"/>' for name in spine_ids)+ opf = (+ '<?xml version="1.0"?>'+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0">'+ f"<manifest>{manifest}</manifest><spine>{spine_xml}</spine></package>"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("mimetype", "application/epub+zip")+ if with_container:+ zf.writestr("META-INF/container.xml", _CONTAINER_XML.format(opf=opf_path))+ if with_opf:+ zf.writestr(opf_path, opf)+ for name, body in chapters.items():+ zf.writestr(+ f"{opf_dir}/{name}",+ f'<html xmlns="http://www.w3.org/1999/xhtml"><body>{body}</body></html>',+ )+ return buf.getvalue()++# ---------------------------------------------------------------------------# is_document_extension# ---------------------------------------------------------------------------@@ -77,6 +128,7 @@ class TestIsDocumentExtension:assert is_document_extension("foo.DOCX")assert is_document_extension("report.xlsx")assert is_document_extension("deck.pptx")+ assert is_document_extension("book.epub")def test_text_and_code(self) -> None:# Any extension in FileTypeRouter.TEXT_EXTENSIONS should be supported.@@ -173,6 +225,111 @@ class TestExtractPptx:assert "第二行" in text+class TestExtractEpub:+ def test_follows_spine_reading_order(self) -> None:+ data = _make_epub(+ {+ "chap1.xhtml": "<h1>Chapter One</h1><p>Alpha text.</p>",+ "chap2.xhtml": "<h1>Chapter Two</h1><p>Beta text.</p>",+ },+ spine=["chap2.xhtml", "chap1.xhtml"],+ )++ text = extract_text_from_bytes("book.epub", data)++ assert text.index("Chapter Two") < text.index("Chapter One")+ assert "Alpha text." in text+ assert "Beta text." in text++ def test_inline_markup_keeps_word_boundaries(self) -> None:+ data = _make_epub({"c.xhtml": "<p>Hello <b>world</b>. <i>Nice</i> day.</p>"})++ text = extract_text_from_bytes("book.epub", data)++ assert "Hello world. Nice day." in text++ def test_scripts_and_styles_are_dropped(self) -> None:+ data = _make_epub(+ {+ "c.xhtml": (+ "<style>body{color:red}</style><script>var x=1;</script><p>Visible only.</p>"+ )+ }+ )++ text = extract_text_from_bytes("book.epub", data)++ assert "Visible only." in text+ assert "color:red" not in text+ assert "var x" not in text++ def test_falls_back_to_archive_order_without_container(self) -> None:+ data = _make_epub(+ {"a.xhtml": "<p>First member.</p>", "b.xhtml": "<p>Second member.</p>"},+ with_container=False,+ )++ text = extract_text_from_bytes("book.epub", data)++ assert "First member." in text+ assert "Second member." in text++ def test_falls_back_to_archive_order_without_opf(self) -> None:+ data = _make_epub({"only.xhtml": "<p>Solo chapter.</p>"}, with_opf=False)++ text = extract_text_from_bytes("book.epub", data)++ assert "Solo chapter." in text++ def test_malformed_xhtml_uses_tolerant_html_fallback(self) -> None:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("mimetype", "application/epub+zip")+ zf.writestr("META-INF/container.xml", _CONTAINER_XML.format(opf="OEBPS/content.opf"))+ zf.writestr(+ "OEBPS/content.opf",+ '<?xml version="1.0"?>'+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0">'+ '<manifest><item id="c0" href="bad.xhtml"/>'+ '<item id="c1" href="good.xhtml"/></manifest>'+ '<spine><itemref idref="c0"/><itemref idref="c1"/></spine></package>',+ )+ zf.writestr("OEBPS/bad.xhtml", "<html><body><p>Broken chapter</p></body></html>")+ zf.writestr("OEBPS/good.xhtml", "<html><body><p>Readable chapter.</p></body></html>")++ text = extract_text_from_bytes("book.epub", buf.getvalue())++ assert "Readable chapter." in text+ assert "Broken chapter" in text++ def test_rejects_suspicious_compression_ratio(self) -> None:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:+ zf.writestr("mimetype", "application/epub+zip")+ zf.writestr("chapter.xhtml", f"<p>{'A' * 1_000_000}</p>")++ with pytest.raises(DocumentTooLargeError, match="compression ratio"):+ extract_text_from_bytes("book.epub", buf.getvalue())++ def test_rejects_excessive_member_count(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(document_extractor_module, "_EPUB_MAX_MEMBERS", 2)+ data = _make_epub({"chapter.xhtml": "<p>text</p>"})++ with pytest.raises(DocumentTooLargeError, match="too many archive members"):+ extract_text_from_bytes("book.epub", data)++ def test_bad_header_raises_corrupt(self) -> None:+ with pytest.raises(CorruptDocumentError):+ extract_text_from_bytes("book.epub", b"not a zip at all")++ def test_zip_without_text_raises_empty(self) -> None:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("mimetype", "application/epub+zip")+ with pytest.raises(EmptyDocumentError):+ extract_text_from_bytes("book.epub", buf.getvalue())++class TestExtractTextLike:def test_plain_txt(self) -> None:text = extract_text_from_bytes("note.txt", "hello world\nline two".encode("utf-8"))diff --git a/tests/utils/test_document_validator.py b/tests/utils/test_document_validator.pyindex 7e8695cd5..88fbf5bc0 100644--- a/tests/utils/test_document_validator.py+++ b/tests/utils/test_document_validator.py@@ -1,5 +1,7 @@from __future__ import annotations+import mimetypes+from deeptutor.services.rag.file_routing import FileTypeRouterfrom deeptutor.utils.document_validator import DocumentValidator@@ -52,3 +54,23 @@ def test_validate_upload_safety_custom_policy_allows_images() -> None:)assert safe_name == "diagram.png"+++def test_validate_upload_safety_kb_policy_allows_epub() -> None:+ safe_name = DocumentValidator.validate_upload_safety(+ "Textbook.EPUB",+ 1024,+ allowed_extensions=FileTypeRouter.get_supported_extensions(),+ )++ assert safe_name == "Textbook.epub"+++def test_validate_upload_safety_default_policy_allows_epub() -> None:+ safe_name = DocumentValidator.validate_upload_safety("novel.epub", 1024)++ assert safe_name == "novel.epub"+ assert ".epub" in DocumentValidator.ALLOWED_EXTENSIONS+ assert "application/epub+zip" in DocumentValidator.ALLOWED_MIME_TYPES+ guessed, _ = mimetypes.guess_type("novel.epub")+ assert guessed is None or guessed in DocumentValidator.ALLOWED_MIME_TYPES