Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): read a file the same way whichever door it arrives through
Ruben Lütkeb1825ae8aa77
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 9a82aa3f6a..3f04277b79 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3195,9 +3195,13 @@"format_jsonl": "Datensatzabschnitte","format_json": "Datendateien","format_pdf": "PDF-Dokumente",+ "format_document": "Dokumente und Präsentationen","format_html": "Webseiten","format_markdown": "Notizen",- "format_text": "Textdateien"+ "format_text": "Textdateien",+ "format_image": "Bilder",+ "format_audio": "Aufnahmen",+ "format_video": "Videos"},"picker": {"builtin_group": "Auf diesem Gerät",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex e257a7c529..3be119c7d2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3181,9 +3181,13 @@"format_jsonl": "record chunks","format_json": "data files","format_pdf": "PDF documents",+ "format_document": "documents and slide decks","format_html": "web pages","format_markdown": "notes",- "format_text": "text files"+ "format_text": "text files",+ "format_image": "pictures",+ "format_audio": "recordings",+ "format_video": "videos"},"picker": {"builtin_group": "On this machine",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 9b2484f31d..86e90cb477 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3180,9 +3180,13 @@"format_jsonl": "bloques de registros","format_json": "archivos de datos","format_pdf": "documentos PDF",+ "format_document": "documentos y presentaciones","format_html": "páginas web","format_markdown": "notas",- "format_text": "archivos de texto"+ "format_text": "archivos de texto",+ "format_image": "imágenes",+ "format_audio": "grabaciones",+ "format_video": "vídeos"},"picker": {"builtin_group": "En este equipo",diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.tsindex 7110f96b6a..fce8b605fb 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts@@ -1010,9 +1010,13 @@ export const ULTRAWIKI_EXPORT_FORMATS = ["jsonl","json","pdf",+ "document","html","markdown","text",+ "image",+ "audio",+ "video",] as const;export type UltraWikiExportFormat = (typeof ULTRAWIKI_EXPORT_FORMATS)[number];diff --git a/jarvis/ultrawiki/connectors/export_import.py b/jarvis/ultrawiki/connectors/export_import.pyindex 0a0b7499c0..ae1c4bcf0e 100644--- a/jarvis/ultrawiki/connectors/export_import.py+++ b/jarvis/ultrawiki/connectors/export_import.py@@ -88,7 +88,9 @@ log = logging.getLogger(__name__)__all__ = ["ARCHIVE_FORMAT",+ "CONTAINER_FORMATS","EXPORT_FORMATS",+ "TAR_FORMAT","ExportImportConnector","ScanReport","chat_name_from_filename",@@ -116,15 +118,47 @@ EXPORT_FORMATS: tuple[str, ...] = ("jsonl","json","pdf",+ "document","html","markdown","text",+ "image",+ "audio",+ "video",)-#: The one container format. Not in :data:`EXPORT_FORMATS` — it yields no-#: items of its own, only the entries inside it.+#: The container formats. Not in :data:`EXPORT_FORMATS` — they yield no items+#: of their own, only the entries inside them.ARCHIVE_FORMAT = "zip"+#: Google Takeout offers `.zip` AND `.tgz`, and the second used to be refused+#: outright — so the user who clicked the default download was left holding a+#: file this importer would not open.+TAR_FORMAT = "tar"++CONTAINER_FORMATS: tuple[str, ...] = (ARCHIVE_FORMAT, TAR_FORMAT)++#: Suffixes whose bytes are a ZIP but whose CONTENT is one document. The one+#: place the extension outranks the magic, and it has to: telling a `.docx`+#: from a plain archive means reading the archive's member list, which the+#: sniffer (which sees only the first few KB) cannot do. Getting this wrong is+#: not cosmetic — a Word file would be walked as an archive and imported as a+#: pile of its own internal XML parts.+_DOCUMENT_EXTENSIONS: dict[str, str] = {+ ".docx": "document", ".docm": "document",+ ".xlsx": "document", ".xlsm": "document",+ ".pptx": "document", ".pptm": "document",+ ".odt": "document", ".ods": "document", ".odp": "document", ".odg": "document",+ ".epub": "document",+ ".rtf": "document",+ ".doc": "document", ".xls": "document", ".ppt": "document",+}++#: Formats handed to the shared extractor rather than parsed here.+_SHARED_EXTRACTOR_KINDS: frozenset[str] = frozenset(+ {"docx", "xlsx", "pptx", "odf", "epub", "rtf", "legacy_office"}+)+_EXTENSION_FORMATS: dict[str, str] = {".mbox": "mbox",".mbx": "mbox",@@ -170,6 +204,21 @@ MAX_BUFFERED_ZIP_BYTES = 256 * 1024 * 1024#: archive. On disk it is opened by path and this cap never applies.MAX_BUFFERED_PDF_BYTES = 128 * 1024 * 1024+#: An Office/OpenDocument/EPUB file is a ZIP the extractor must seek inside,+#: so it is read whole. Generous — a slide deck with images is routinely+#: 50 MB around a few pages of text — but never unbounded.+MAX_BUFFERED_DOCUMENT_BYTES = 128 * 1024 * 1024++#: Bytes read from a media file. EXIF sits in front of the image data, so the+#: header is all that is needed — which is what keeps a folder of 4K video+#: from being pulled through memory to learn a capture date.+MEDIA_HEADER_BYTES = 512 * 1024++#: One tar entry buffered in memory. A compressed tar has no central+#: directory, so entries can only be read in order and cannot be re-opened;+#: buffering is the only way to hand a parser a re-readable stream.+MAX_BUFFERED_TAR_ENTRY_BYTES = 64 * 1024 * 1024+#: Formats parsed from one whole in-memory string (calendar, contacts, JSON,#: HTML). Bigger than this is refused with an honest line rather than an#: out-of-memory kill; the streaming formats have no such limit.@@ -206,11 +255,22 @@ SKIP_DIR_NAMES: frozenset[str] = frozenset({"__MACOSX", "node_modules"})# Detection# ---------------------------------------------------------------------------+#: ``PK`` is handled ahead of this table (an office document is a ZIP), and a+#: gzip stream resolves through its NAME because compression records nothing+#: about what was compressed._MAGIC_PREFIXES: tuple[tuple[bytes, str], ...] = ((b"%PDF-", "pdf"),- (b"PK\x03\x04", ARCHIVE_FORMAT),(b"BEGIN:VCALENDAR", "ics"),(b"BEGIN:VCARD", "vcard"),+ (b"\x1f\x8b", "gzip_or_tar"),+)++#: Media formats this importer now carries through to the enrichment stage.+_MEDIA_FORMATS: frozenset[str] = frozenset({"image", "audio", "video"})++#: Double suffixes that mark a compressed stream as a tar archive.+_TARBALL_SUFFIXES: tuple[str, ...] = (+ ".tgz", ".tar.gz", ".taz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar.zst")#: An mbox opens with a ``From <envelope> <date>`` separator line, followed@@ -292,19 +352,60 @@ def detect_format(name: str, head: bytes) -> str:if stripped.startswith(_UTF8_BOM):stripped = stripped[len(_UTF8_BOM) :]stripped = stripped.lstrip(b"\r\n \t")+ suffix = Path(name).suffix.lower()++ # A ZIP is the one case where the name has to win: every modern Office and+ # OpenDocument file IS a ZIP, and walking one as an archive would import a+ # Word document as a heap of its own internal XML.+ if stripped.startswith(b"PK\x03\x04"):+ return _DOCUMENT_EXTENSIONS.get(suffix, ARCHIVE_FORMAT)+for prefix, fmt in _MAGIC_PREFIXES:if stripped[: len(prefix)].upper() == prefix.upper():+ if fmt == "gzip_or_tar":+ return TAR_FORMAT if _looks_like_tarball(name) else ""return fmtif _MBOX_MAGIC.match(stripped):return "mbox"- ext_format = _EXTENSION_FORMATS.get(Path(name).suffix.lower(), "")+ ext_format = _EXTENSION_FORMATS.get(suffix, "")if ext_format in ("", "text", "markdown") and _looks_like_whatsapp(head):return "whatsapp"- if not ext_format and head and _is_probably_text(head):+ if ext_format:+ return ext_format++ # Everything the shared extractor knows and this module never learned:+ # photos, voice notes, video, Office documents saved without a helpful+ # name, tar archives. One detector, so a format is supported once.+ shared = _shared_kind(name, head)+ if shared in _MEDIA_FORMATS:+ return shared+ if shared in _SHARED_EXTRACTOR_KINDS:+ return "document"+ if shared == "tar":+ return TAR_FORMAT++ if head and _is_probably_text(head):# A Takeout mail file has no suffix at all; anything that reads as# text is still worth importing as text rather than being dropped.return "text"- return ext_format+ return ""+++def _shared_kind(name: str, head: bytes) -> str:+ """What :mod:`jarvis.ultrawiki.extract` makes of these leading bytes."""+ try:+ from jarvis.ultrawiki.extract import detect_kind # noqa: PLC0415 — lazy (AP-26)++ return detect_kind(head, filename=name)+ except Exception: # noqa: BLE001 — a sniff never fails an import+ log.debug("export import: shared detection failed for %s", name, exc_info=True)+ return ""+++def _looks_like_tarball(name: str) -> bool:+ """Whether a compressed stream's NAME says it wraps a tar archive."""+ lowered = Path(name).name.lower()+ return any(lowered.endswith(suffix) for suffix in _TARBALL_SUFFIXES)def _is_probably_text(head: bytes) -> bool:@@ -468,6 +569,14 @@ class _Entry:#: Set only for on-disk files — a seekable original that ``pypdf`` and the#: whole-read parsers can use without buffering.disk_path: Path | None = None+ #: Which container this came out of, if any (``zip`` / ``tar`` / ``""``).+ archive_kind: str = ""+ #: On-disk path of that container, empty when it is itself nested. Only a+ #: ZIP on disk can be reopened entry by entry later, which is what the+ #: enrichment stage needs to describe a photo inside an export.+ archive_path: str = ""+ #: The entry's name inside that container.+ archive_entry: str = ""def _sorted_disk_files(root: Path) -> list[tuple[str, Path]]:@@ -546,6 +655,19 @@ def _entries_for_disk_file(budget=budget,depth=depth + 1,label=key,+ archive_path=str(path.resolve()),+ )+ return+ if fmt == TAR_FORMAT:+ report.archives["files"] += 1+ yield from _entries_for_tar(+ lambda: path.open("rb"),+ origin=key,+ prefix="",+ report=report,+ budget=budget,+ depth=depth + 1,+ label=key,)returnif not fmt:@@ -588,6 +710,7 @@ def _entries_for_zip(budget: _Budget,depth: int,label: str,+ archive_path: str = "",) -> Iterator[_Entry]:"""Walk one archive's entries as streams — nothing is written to disk."""if depth > MAX_ZIP_DEPTH:@@ -639,14 +762,15 @@ def _entries_for_zip(report.refuse(key, str(exc))continuefmt = detect_format(parts[-1], head)- if fmt == ARCHIVE_FORMAT:+ if fmt in CONTAINER_FORMATS:buffered = _buffer_zip_entry(archive, info, key, report, MAX_BUFFERED_ZIP_BYTES, "archive")if buffered is None:continuereport.archives["files"] += 1- yield from _entries_for_zip(+ walk = _entries_for_zip if fmt == ARCHIVE_FORMAT else _entries_for_tar+ yield from walk(lambda data=buffered: io.BytesIO(data),origin=origin,prefix=f"{full_inner}!",@@ -669,7 +793,156 @@ def _entries_for_zip(fmt=fmt,timestamp_utc=_zip_entry_timestamp(info),open_binary=opener,+ archive_kind=ARCHIVE_FORMAT,+ archive_path=archive_path,+ archive_entry=inner,+ )+++def _entries_for_tar(+ open_archive: Callable[[], IO[bytes]],+ *,+ origin: str,+ prefix: str,+ report: ScanReport,+ budget: _Budget,+ depth: int,+ label: str,+) -> Iterator[_Entry]:+ """Walk a tar (plain or compressed) as a forward-only stream.++ The honest differences from the ZIP walk, all forced by the format:++ * **Order is the archive's, not sorted.** A compressed tar has no central+ directory, so the entries can only be read in the order they were+ written. Resume therefore restarts at the archive, which is safe because+ every re-read upserts as ``unchanged`` on ``(source_id, external_id)``.+ * **Each entry is buffered** under :data:`MAX_BUFFERED_TAR_ENTRY_BYTES`.+ A stream member cannot be re-opened, and the parsers need to read a+ member more than once (sniff, then parse).+ * **A member is never written to disk**, and paths are flattened, so a+ hostile ``../`` entry cannot escape anywhere — there is nowhere to+ escape TO.+ """+ import tarfile # noqa: PLC0415 — lazy (AP-26): only a tar import pays for it++ if depth > MAX_ZIP_DEPTH:+ report.note(+ f"'{label}' contains archives nested deeper than {MAX_ZIP_DEPTH} "+ "levels; those were left unread."+ )+ return+ report.archives["max_depth"] = max(report.archives["max_depth"], depth)+ try:+ # "r|*" is the STREAM mode: no seeking, so it works on a compressed+ # archive and on a member of another archive alike.+ archive = tarfile.open(fileobj=open_archive(), mode="r|*")+ except (OSError, tarfile.TarError, RuntimeError, EOFError) as exc:+ report.refuse(label, f"{type(exc).__name__}: {exc}")+ return+ with archive:+ try:+ yield from _tar_members(+ archive,+ origin=origin,+ prefix=prefix,+ report=report,+ budget=budget,+ depth=depth,+ label=label,)+ except (OSError, tarfile.TarError, RuntimeError, EOFError) as exc:+ # A truncated download is the normal way this ends. Everything+ # read up to here is kept.+ report.refuse(label, f"{type(exc).__name__}: {exc}")+++def _tar_members(+ archive: Any,+ *,+ origin: str,+ prefix: str,+ report: ScanReport,+ budget: _Budget,+ depth: int,+ label: str,+) -> Iterator[_Entry]:+ for member in archive:+ if not member.isfile():+ continue+ inner = str(member.name).replace("\\", "/")+ parts = [part for part in inner.split("/") if part and part != "."]+ if not parts or any(+ part.startswith(".") or part in SKIP_DIR_NAMES or part == ".."+ for part in parts+ ):+ continue+ if not budget.take(int(member.size)):+ report.archives["budget_exhausted"] = True+ report.note(+ "The archive expands to more than "+ f"{ZIP_UNCOMPRESSED_BUDGET // (1024**3)} GB; reading stopped "+ "there so the import cannot be used to fill this machine's "+ "disk or memory."+ )+ return+ report.archives["entries"] += 1+ full_inner = f"{prefix}{inner}"+ key = f"{origin}!{full_inner}"+ if int(member.size) > MAX_BUFFERED_TAR_ENTRY_BYTES:+ report.refuse(+ key,+ "an entry inside a tar archive has to be held in memory to be "+ f"read, and this one is larger than "+ f"{MAX_BUFFERED_TAR_ENTRY_BYTES // (1024 * 1024)} MB; unpack "+ "the archive and import the folder instead",+ )+ continue+ try:+ handle = archive.extractfile(member)+ payload = b"" if handle is None else handle.read()+ except Exception as exc: # noqa: BLE001 — one bad member, not the archive+ report.refuse(key, f"{type(exc).__name__}: {exc}")+ continue+ fmt = detect_format(parts[-1], payload[:SNIFF_BYTES])+ if fmt in CONTAINER_FORMATS:+ report.archives["files"] += 1+ walk = _entries_for_zip if fmt == ARCHIVE_FORMAT else _entries_for_tar+ yield from walk(+ lambda data=payload: io.BytesIO(data),+ origin=origin,+ prefix=f"{full_inner}!",+ report=report,+ budget=budget,+ depth=depth + 1,+ label=key,+ )+ continue+ if not fmt:+ report.count_unknown(parts[-1], int(member.size))+ continue+ report.count_file(fmt, int(member.size))+ yield _Entry(+ origin=origin,+ key=key,+ name=parts[-1],+ permalink=f"file:///{quote(label)}#{quote(full_inner)}",+ size=int(member.size),+ fmt=fmt,+ timestamp_utc=_tar_member_timestamp(member),+ open_binary=lambda data=payload: io.BytesIO(data),+ archive_kind=TAR_FORMAT,+ archive_entry=inner,+ )+++def _tar_member_timestamp(member: Any) -> str:+ try:+ return datetime.fromtimestamp(int(member.mtime), tz=UTC).strftime(+ "%Y-%m-%dT%H:%M:%SZ"+ )+ except (TypeError, ValueError, OSError, OverflowError):+ return ""def _zip_base_uri(open_archive: Callable[[], IO[bytes]], label: str) -> str:@@ -1610,6 +1883,177 @@ def _whatsapp_item()+# --- Documents and media, through the shared extractor ----------------------+++def _parse_document(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:+ """One Office / OpenDocument / EPUB file, read by the shared service.++ Not parsed here on purpose: those formats are supported once, in+ :mod:`jarvis.ultrawiki.extract`, so a folder walk and a dropped export+ read the same file identically. A file that yields no text is still+ stored, carrying the honest reason — a later run with the missing extra+ installed can then reclaim it instead of it never having existed.+ """+ from jarvis.ultrawiki.extract import extract_text # noqa: PLC0415 — lazy (AP-26)++ source = _entry_bytes(entry, report, MAX_BUFFERED_DOCUMENT_BYTES, "document")+ if source is None:+ return+ result = extract_text(source, filename=entry.name)+ if result.ok:+ yield _item(+ entry,+ natural_id="",+ body=result.text,+ title=_document_title(entry, result.text),+ metadata={"document_kind": result.kind, **result.meta},+ )+ return+ yield _item(+ entry,+ natural_id="",+ body=_file_facts(entry, {}),+ title=Path(entry.name).stem,+ metadata={+ "document_kind": result.kind,+ "content_missing": True,+ "content_missing_reason": result.reason,+ },+ )+++def _parse_media(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:+ """A photo, recording or video: stored now, understood later.++ The body holds only what the FILE states — name, folder, capture date,+ camera, coordinates. That is enough to find it by time or place+ immediately, and it claims nothing about what the picture shows.+ """+ from jarvis.ultrawiki.extract import extract_text # noqa: PLC0415 — lazy (AP-26)++ # Only the header is needed (EXIF sits in front of the image data), which+ # is what keeps a folder of 4K video from being read into memory.+ source = _entry_bytes(entry, report, MEDIA_HEADER_BYTES, "media header", partial=True)+ if source is None:+ return+ result = extract_text(source, filename=entry.name)+ facts = dict(result.meta)+ metadata: dict[str, Any] = {+ "media_kind": entry.fmt,+ "enrich_pending": True,+ **facts,+ }+ reference = _media_reference(entry)+ if reference is not None:+ metadata.update(reference.as_metadata())+ else:+ # Honest rather than silent: a tar entry cannot be reopened without+ # decompressing the whole stream again, so nothing will describe it.+ metadata["enrich_pending"] = False+ metadata["enrich_blocked_reason"] = (+ "this file came out of a tar archive, which cannot be reopened "+ "entry by entry; import the same export as a .zip, or unpack it "+ "first, to have it described"+ )+ captured = str(facts.get("captured_at") or "")+ yield _item(+ entry,+ natural_id="",+ body=_file_facts(entry, facts),+ title=Path(entry.name).stem,+ timestamp_utc=captured or entry.timestamp_utc,+ metadata=metadata,+ )+++def _media_reference(entry: _Entry) -> Any:+ """A reopenable reference for this entry, or ``None`` when there is none."""+ from jarvis.ultrawiki.media import MediaRef # noqa: PLC0415 — lazy (AP-26)++ if entry.disk_path is not None:+ return MediaRef(kind="file", path=str(entry.disk_path.resolve()))+ if entry.archive_kind == ARCHIVE_FORMAT and entry.archive_path:+ return MediaRef(+ kind="zip-entry", path=entry.archive_path, entry=entry.archive_entry+ )+ return None+++def _document_title(entry: _Entry, text: str) -> str:+ heading = _H1_RE.search(text[:4000])+ if heading:+ return heading.group(1).strip()[:200]+ return Path(entry.name).stem+++def _file_facts(entry: _Entry, facts: dict[str, Any]) -> str:+ """What is known about a file before anything has read its content.++ Every line comes from the file itself. Never a guess — an item that+ speculates about content it has not read is worse than no item at all.+ """+ lines = [f"File: {entry.name}"]+ folder = Path(entry.key.replace("!", "/")).parent.name+ if folder:+ lines.append(f"Folder: {folder}")+ for label, key in (("Taken", "captured_at"), ("Camera", "camera")):+ value = facts.get(key)+ if value:+ lines.append(f"{label}: {value}")+ latitude, longitude = facts.get("latitude"), facts.get("longitude")+ if latitude is not None and longitude is not None:+ lines.append(f"Location: {latitude}, {longitude}")+ return "\n".join(lines)+++def _entry_bytes(+ entry: _Entry,+ report: ScanReport,+ limit: int,+ what: str,+ *,+ partial: bool = False,+) -> Any:+ """The entry's bytes, or its path when it has one. ``None`` when refused.++ A path is preferred wherever it exists: the extractors that can stream+ (PDF above all) then never hold the file in memory. ``partial`` reads only+ the leading ``limit`` bytes instead of refusing an oversized file, which is+ what a media header needs.+ """+ if entry.disk_path is not None:+ if partial:+ try:+ with entry.disk_path.open("rb") as stream:+ return stream.read(limit)+ except OSError as exc:+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")+ return None+ if entry.size > limit:+ report.refuse(+ entry.key,+ f"the {what} is larger than {limit // (1024 * 1024)} MB",+ )+ return None+ return entry.disk_path+ try:+ with entry.open_binary() as stream:+ data = stream.read(limit if partial else limit + 1)+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")+ return None+ if not partial and len(data) > limit:+ report.refuse(+ entry.key,+ f"the {what} inside the archive is larger than "+ f"{limit // (1024 * 1024)} MB, which is more than this import will "+ "hold in memory at once",+ )+ return None+ return data++_PARSERS: dict[str, Callable[[_Entry, ScanReport], Iterator[RawItem]]] = {"mbox": _parse_mbox,"eml": _parse_eml,@@ -1621,9 +2065,13 @@ _PARSERS: dict[str, Callable[[_Entry, ScanReport], Iterator[RawItem]]] = {"jsonl": _parse_jsonl,"json": _parse_json,"pdf": _parse_pdf,+ "document": _parse_document,"html": _parse_html,"markdown": _parse_text,"text": _parse_text,+ "image": _parse_media,+ "audio": _parse_media,+ "video": _parse_media,}diff --git a/jarvis/ultrawiki/connectors/local_folder.py b/jarvis/ultrawiki/connectors/local_folder.pyindex 041d3621e7..94090e3280 100644--- a/jarvis/ultrawiki/connectors/local_folder.py+++ b/jarvis/ultrawiki/connectors/local_folder.py@@ -41,11 +41,14 @@ from collections.abc import AsyncIterator, Sequencefrom datetime import UTC, datetimefrom pathlib import Path-from jarvis.ultrawiki.document_text import (+from jarvis.ultrawiki.extract import (DOCUMENT_EXTENSIONS,- extract_document_text,- is_document,+ MEDIA_EXTENSIONS,+ MEDIA_KINDS,+ detect_kind,+ extract_text,)+from jarvis.ultrawiki.media import MediaReffrom jarvis.ultrawiki.types import (AuthKind,ConnectorCapabilities,@@ -198,6 +201,17 @@ _CODE_EXTENSIONS = (".gradle",)+#: Formats whose SIZE says nothing about how much text they hold. A 30 MB PDF+#: is mostly layout and images around a few pages of prose, so judging it by+#: the plain-text ceiling would drop every real document.+_LARGE_DOCUMENT_KINDS: frozenset[str] = frozenset(+ {"pdf", "docx", "xlsx", "pptx", "odf", "epub", "rtf"}+)++#: Absolute ceiling for anything read as a whole document, media excluded.+#: Far above the text limit, far below what could exhaust a small VPS.+MAX_DOCUMENT_BYTES = 64 * 1024 * 1024+#: Files stat'ed + read per worker-thread hop. Filesystem I/O must never run#: on the event loop (it also serves voice and chat), but one hop per file#: would pay the handoff thousands of times over a real vault — a small batch@@ -264,7 +278,8 @@ class LocalFolderConnector:*_DATA_EXTENSIONS,*_MARKUP_EXTENSIONS,*_CODE_EXTENSIONS,- *DOCUMENT_EXTENSIONS,+ *sorted(DOCUMENT_EXTENSIONS),+ *sorted(MEDIA_EXTENSIONS),)#: Directory names skipped in addition to hidden (dot-prefixed) ones.SKIP_DIR_NAMES: frozenset[str] = NOISE_DIR_NAMES@@ -461,31 +476,6 @@ class LocalFolderConnector:items.append(item)return items- def _body_for(self, path: Path, size: int) -> str | None:- """The file's text, or ``None`` when there is none worth an item.-- Two different reads behind one call: an opaque document goes through- an extractor (and carries its own, far larger size ceiling — a PDF is- mostly layout, and judging it by the plain-text limit would drop every- real one), everything else is read as UTF-8 with replacement.- """- if is_document(path):- return extract_document_text(path)- if size > self.MAX_FILE_BYTES:- log.info(- "%s: skipping %s (%d bytes exceeds the %d-byte limit)",- self.id,- path,- size,- self.MAX_FILE_BYTES,- )- return None- try:- return path.read_text(encoding="utf-8", errors="replace")- except OSError as exc:- log.debug("%s: read failed for %s: %s", self.id, path, exc)- return None-def _mtime_ns(self, path: Path) -> int | None:try:return path.stat().st_mtime_ns@@ -494,21 +484,142 @@ class LocalFolderConnector:return Nonedef _item_for(self, root: Path, path: Path) -> RawItem | None:+ """One file as an item, whatever kind of file it turns out to be.++ Everything goes through the one shared extractor. Three outcomes:++ * **text came out** — the ordinary case.+ * **it is a photo, recording or video** — stored with what the file+ says about ITSELF (name, folder, capture date, camera, place) so it+ is findable immediately, and marked for the enrichment stage to+ describe later. Deliberately not skipped: a photo library is the+ largest and most personal thing most people own.+ * **text could exist but did not come out** — a scan with no OCR+ layer, a format needing an uninstalled extra. Stored with the honest+ reason, so a later run can reclaim it rather than the file silently+ never having existed.+ """try:stat = path.stat()except OSError as exc:log.debug("%s: stat failed for %s: %s", self.id, path, exc)return None- body = self._body_for(path, stat.st_size)- if body is None:++ kind = self._detect(path)+ if kind in MEDIA_KINDS:+ return self._media_item(root, path, stat, kind)++ # The size ceiling is a TEXT ceiling and is checked only here: a photo+ # or video is never read whole (only its header is), so judging it by+ # the plain-text limit would drop every real one.+ if kind not in _LARGE_DOCUMENT_KINDS and stat.st_size > self.MAX_FILE_BYTES:+ log.info(+ "%s: skipping %s (%d bytes exceeds the %d-byte limit)",+ self.id,+ path,+ stat.st_size,+ self.MAX_FILE_BYTES,+ )+ return None+ if stat.st_size > MAX_DOCUMENT_BYTES:+ log.info(+ "%s: skipping %s (%d bytes exceeds the %d-byte document limit)",+ self.id,+ path,+ stat.st_size,+ MAX_DOCUMENT_BYTES,+ )return None++ result = extract_text(path, filename=path.name)+ if result.ok:+ return self._build_item(root, path, stat, result.text, {})+ if result.content_missing:+ return self._build_item(+ root,+ path,+ stat,+ self._placeholder_body(path, {}),+ {"content_missing": True, "content_missing_reason": result.reason},+ )+ return None++ def _detect(self, path: Path) -> str:+ """The file's real kind, read from its first bytes. ``""`` on any error."""+ try:+ return detect_kind(path, filename=path.name)+ except Exception: # noqa: BLE001 — an unreadable file is skipped, not raised+ log.debug("%s: could not identify %s", self.id, path, exc_info=True)+ return ""++ def _media_item(+ self, root: Path, path: Path, stat: os.stat_result, kind: str+ ) -> RawItem | None:+ result = extract_text(path, filename=path.name)+ facts = dict(result.meta)+ metadata: dict[str, object] = {+ "media_kind": kind,+ "enrich_pending": True,+ **facts,+ **MediaRef(kind="file", path=str(path.resolve())).as_metadata(),+ }+ # The camera's own date beats the filesystem's: a file's mtime is the+ # day it was COPIED, so an album restored from a backup would otherwise+ # collapse onto one meaningless afternoon.+ captured = str(facts.get("captured_at") or "")+ return self._build_item(+ root,+ path,+ stat,+ self._placeholder_body(path, facts),+ metadata,+ timestamp_utc=captured or iso_utc_from_timestamp(stat.st_mtime),+ )++ def _placeholder_body(self, path: Path, facts: dict[str, object]) -> str:+ """What is known about a file before anything has read its content.++ Every line is a fact the file itself carries — never a guess. That is+ what makes it safe to index: a search for a month, a camera or a folder+ finds the picture, and nothing claims to know what is in it.+ """+ lines = [f"File: {path.name}"]+ parent = path.parent.name+ if parent:+ lines.append(f"Folder: {parent}")+ for label, key in (+ ("Taken", "captured_at"),+ ("Camera", "camera"),+ ):+ value = facts.get(key)+ if value:+ lines.append(f"{label}: {value}")+ latitude, longitude = facts.get("latitude"), facts.get("longitude")+ if latitude is not None and longitude is not None:+ lines.append(f"Location: {latitude}, {longitude}")+ return "\n".join(lines)++ def _build_item(+ self,+ root: Path,+ path: Path,+ stat: os.stat_result,+ body: str,+ extra: dict[str, object],+ *,+ timestamp_utc: str = "",+ ) -> RawItem:return RawItem(external_id=self._external_id_for(root, path),body=body,permalink=path.resolve().as_uri(),- timestamp_utc=iso_utc_from_timestamp(stat.st_mtime),+ timestamp_utc=timestamp_utc or iso_utc_from_timestamp(stat.st_mtime),title=self._title_for(path, body),- metadata={"mtime_ns": stat.st_mtime_ns, "size_bytes": stat.st_size},+ metadata={+ "mtime_ns": stat.st_mtime_ns,+ "size_bytes": stat.st_size,+ **extra,+ },)diff --git a/jarvis/ultrawiki/document_text.py b/jarvis/ultrawiki/document_text.pyindex 57f923e0b9..5810042af8 100644--- a/jarvis/ultrawiki/document_text.py+++ b/jarvis/ultrawiki/document_text.py@@ -70,7 +70,19 @@ def extract_document_text(path: Path) -> str | None:``None`` covers every honest miss: oversized, encrypted, corrupt, a scanwithout a text layer, or an extractor that is not installed. Blocking.++ **Delegates to** :func:`jarvis.ultrawiki.extract.extract_text`. This+ function is kept for callers that predate the shared service and for the+ ``None``-means-nothing contract they were written against; the parsing+ below is gone rather than left as a second copy to drift. Reaching for the+ shared service directly is preferred in new code — it reports WHY a file+ yielded nothing, which this signature cannot express.++ The import is local: ``extract`` imports this module's hardened XML parser,+ so a module-level import here would be circular."""+ from jarvis.ultrawiki.extract import extract_text # noqa: PLC0415 — see above+try:size = path.stat().st_sizeexcept OSError as exc:@@ -84,12 +96,11 @@ def extract_document_text(path: Path) -> str | None:MAX_DOCUMENT_BYTES,)return None- suffix = path.suffix.lower()- if suffix == ".pdf":- return _clean(_pdf_text(path))- if suffix in (".docx", ".pptx"):- return _clean(_ooxml_text(path))- return None+ result = extract_text(path, filename=path.name)+ if not result.ok:+ log.info("document yielded no text: %s (%s)", path, result.reason)+ return None+ return _clean(result.text)def _clean(text: str | None) -> str | None:diff --git a/jarvis/ultrawiki/extract.py b/jarvis/ultrawiki/extract.pyindex e1994901a1..bc1a0cc6c8 100644--- a/jarvis/ultrawiki/extract.py+++ b/jarvis/ultrawiki/extract.py@@ -56,7 +56,9 @@ from jarvis.ultrawiki.document_text import safe_xml_parserlog = logging.getLogger(__name__)__all__ = [+ "DOCUMENT_EXTENSIONS","ExtractResult",+ "MEDIA_EXTENSIONS","MEDIA_KINDS","TEXT_EXTENSIONS","detect_kind",@@ -104,6 +106,26 @@ _ZIP_MARKERS: tuple[tuple[str, str], ...] = (("META-INF/container.xml", "epub"),)+#: Second-pass identification: a member PREFIX rather than an exact manifest+#: part, for archives that lost their manifest but kept their content.+_ZIP_LAYOUT_MARKERS: tuple[tuple[str, str], ...] = (+ ("ppt/slides/", "pptx"),+ ("word/", "docx"),+ ("xl/worksheets/", "xlsx"),+ ("xl/", "xlsx"),+ ("OEBPS/", "epub"),+ ("EPUB/", "epub"),+)++#: Last resort: the name, for a ZIP that identified as nothing at all.+_ZIP_SUFFIX_KINDS: dict[str, str] = {+ ".docx": "docx", ".docm": "docx",+ ".xlsx": "xlsx", ".xlsm": "xlsx",+ ".pptx": "pptx", ".pptm": "pptx",+ ".odt": "odf", ".ods": "odf", ".odp": "odf", ".odg": "odf",+ ".epub": "epub",+}+#: Kinds that hold meaning no text extractor can reach, but a model can.#: The enrichment stage reads exactly these; everything else it ignores.MEDIA_KINDS: frozenset[str] = frozenset({"image", "audio", "video"})@@ -210,6 +232,22 @@ _MEDIA_EXTENSIONS: dict[str, str] = {# from a developer's own knowledge base.}+#: Public view of the mapping above, for the walkers that decide which files to+#: even look at. A folder walk needs the list BEFORE it opens anything.+MEDIA_EXTENSIONS: frozenset[str] = frozenset(_MEDIA_EXTENSIONS)++#: Suffixes this service can turn into text but a plain UTF-8 read cannot.+#: Same purpose: a walker's allowlist has to name them or they are never seen.+DOCUMENT_EXTENSIONS: frozenset[str] = frozenset(+ {+ ".pdf", ".docx", ".xlsx", ".pptx", ".epub", ".rtf",+ ".odt", ".ods", ".odp", ".odg", ".odf",+ # Pre-2007 Office: not readable, but naming them means the user gets+ # the "re-save it in the modern format" line instead of silence.+ ".doc", ".xls", ".ppt",+ }+)+#: Files whose NAME says binary regardless of what decodes. Media extensions#: are deliberately NOT here any more — they resolve to their media kind#: above, which is what makes a photo library importable at all.@@ -325,8 +363,16 @@ def is_probably_text(head: bytes) -> bool:return lenient.count("\ufffd") <= max(2, len(lenient) * 0.02)-def _zip_kind(data: bytes | Path) -> str:- """Which office format a ZIP actually is, or plain ``archive``."""+def _zip_kind(data: bytes | Path, filename: str = "") -> str:+ """Which office format a ZIP actually is, or plain ``archive``.++ Three passes, weakest evidence last. The manifest part is conclusive, but+ an archive can be missing it and still hold every slide: a file repaired by+ a converter, truncated by a sync client, or produced by a tool that writes+ only what it needs. Falling straight to "archive" there discards a deck+ whose text is sitting right in front of us, so the layout of the members —+ and finally the name — get their turn.+ """try:source: Any = data if isinstance(data, Path) else io.BytesIO(data)with zipfile.ZipFile(source) as archive:@@ -336,7 +382,11 @@ def _zip_kind(data: bytes | Path) -> str:for marker, kind in _ZIP_MARKERS:if marker in names:return kind- return "archive"+ for prefix, kind in _ZIP_LAYOUT_MARKERS:+ if any(name.startswith(prefix) for name in names):+ return kind+ suffix = Path(filename).suffix.lower() if filename else ""+ return _ZIP_SUFFIX_KINDS.get(suffix, "archive")def _container_kind(head: bytes) -> str:@@ -417,7 +467,7 @@ def detect_kind(data: bytes | Path, filename: str = "", mime: str = "") -> str:return "tar"return kindif head.startswith(b"PK\x03\x04"):- return _zip_kind(data)+ return _zip_kind(data, filename)if _is_tar(data):return "tar"@@ -455,9 +505,21 @@ def _clean(text: str) -> str:return text.strip()[:_MAX_TEXT_CHARS]+#: UTF-16 is only ever tried when the file SAYS it is UTF-16. Without a byte+#: order mark the codec accepts almost any even-length input and silently+#: produces CJK-looking noise: `b"caf\xe9 notes"` — an ordinary Windows-encoded+#: note — decoded to `"慣ﺩ潮整"` and was stored that way, unfindable and+#: unreadable, with nothing anywhere reporting a problem. A BOM is the only+#: honest evidence for this encoding.+_UTF16_BOMS: tuple[bytes, ...] = (b"\xff\xfe", b"\xfe\xff")++def _decode(raw: bytes) -> str:"""Text from bytes, trying the encodings that actually occur in the wild."""- for encoding in ("utf-8", "utf-8-sig", "utf-16", "cp1252", "latin-1"):+ encodings = ("utf-8", "utf-8-sig", "cp1252", "latin-1")+ if raw[:2] in _UTF16_BOMS:+ encodings = ("utf-16", *encodings)+ for encoding in encodings:try:return raw.decode(encoding)except (UnicodeDecodeError, LookupError):diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pyindex 258943c867..e38d951d37 100644--- a/tests/unit/ultrawiki/test_connectors.py+++ b/tests/unit/ultrawiki/test_connectors.py@@ -415,15 +415,43 @@ class TestLocalFolderFileTypes:"page.html",]- async def test_binary_files_are_still_ignored(self, tmp_path: Path):- (tmp_path / "photo.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32)- (tmp_path / "clip.mp4").write_bytes(b"\x00" * 64)+ async def test_machine_files_are_still_ignored(self, tmp_path: Path):+ """Installers and libraries are not memories and never become items."""+ (tmp_path / "setup.exe").write_bytes(b"MZ" + b"\x00" * 64)+ (tmp_path / "lib.dll").write_bytes(b"MZ" + b"\x00" * 64)+ (tmp_path / "cache.sqlite").write_bytes(b"SQLite format 3\x00" + b"\x00" * 32)(tmp_path / "note.md").write_text("keep", encoding="utf-8")items = await _collect(LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)})))assert [item.external_id for item in items] == ["note.md"]+ async def test_photos_and_recordings_ARE_captured(self, tmp_path: Path):+ """The opposite of the rule above, and the reason it had to be split.++ A photo library used to import as nothing at all — the largest and+ most personal pile of files most people own, invisible. It is captured+ with what the file states about itself and marked for the enrichment+ stage; nothing here claims to know what the picture shows.+ """+ (tmp_path / "photo.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32)+ (tmp_path / "voice.opus").write_bytes(b"OggS\x00\x02" + b"\x00" * 32)+ (tmp_path / "note.md").write_text("keep", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["note.md", "photo.png", "voice.opus"]++ photo = next(item for item in items if item.external_id == "photo.png")+ assert photo.metadata["media_kind"] == "image"+ assert photo.metadata["enrich_pending"] is True+ assert photo.metadata["media_ref_kind"] == "file"+ # The body carries facts the FILE states, never a guess about content.+ assert "photo.png" in photo.body++ voice = next(item for item in items if item.external_id == "voice.opus")+ assert voice.metadata["media_kind"] == "audio"+async def test_an_explicit_extensions_config_still_wins(self, tmp_path: Path):(tmp_path / "app.py").write_text("print('hi')", encoding="utf-8")(tmp_path / "note.md").write_text("keep", encoding="utf-8")@@ -479,10 +507,19 @@ class TestLocalFolderDocuments:)assert items[0].title == "ledger"- async def test_a_document_holding_no_readable_text_is_skipped(+ async def test_a_document_holding_no_readable_text_is_kept_but_marked(self, tmp_path: Path):- """An item with an empty body is worse than no item: it ranks and lies."""+ """An EMPTY body would rank and lie. A body of file facts does neither.++ This replaces "skip it": a scanned invoice with no OCR layer is exactly+ the document a person searches for by name and date, and dropping it+ made it unfindable forever — there was no record for a later run, with+ OCR available or the file repaired, to reclaim. The item therefore+ carries what the file itself states plus an explicit+ ``content_missing`` flag and the honest reason, and claims nothing+ about content it has not read.+ """import zipfilepath = tmp_path / "scan.docx"@@ -492,7 +529,13 @@ class TestLocalFolderDocuments:items = await _collect(LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)})))- assert [item.external_id for item in items] == ["real.md"]+ assert [item.external_id for item in items] == ["real.md", "scan.docx"]++ scan = next(item for item in items if item.external_id == "scan.docx")+ assert scan.metadata["content_missing"] is True+ assert scan.metadata["content_missing_reason"]+ assert scan.body.strip(), "an empty body is the thing this must never produce"+ assert "scan.docx" in scan.bodyasync def test_the_plain_text_size_cap_does_not_apply_to_documents(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch@@ -506,12 +549,18 @@ class TestLocalFolderDocuments:assert [item.external_id for item in items] == ["ledger.docx"]async def test_a_broken_document_never_ends_the_walk(self, tmp_path: Path):+ """The walk continuing is the point; what the broken file becomes is not.++ Content decides now, so a text file misnamed ``.docx`` is read as the+ text it is rather than discarded — the walk reaching ``b-good.md`` is+ what this test exists to protect.+ """(tmp_path / "a-broken.docx").write_bytes(b"not a zip")(tmp_path / "b-good.md").write_text("# Good", encoding="utf-8")items = await _collect(LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)})))- assert [item.external_id for item in items] == ["b-good.md"]+ assert "b-good.md" in [item.external_id for item in items]# ---------------------------------------------------------------------------diff --git a/tests/unit/ultrawiki/test_document_text.py b/tests/unit/ultrawiki/test_document_text.pyindex 58a8741808..1bf1c43dee 100644--- a/tests/unit/ultrawiki/test_document_text.py+++ b/tests/unit/ultrawiki/test_document_text.py@@ -124,10 +124,19 @@ class TestWordAndSlides:archive.writestr("[Content_Types].xml", "<Types/>")assert extract_document_text(path) is None- def test_a_docx_that_is_not_a_zip_is_skipped_not_raised(self, tmp_path: Path):+ def test_a_docx_that_is_not_a_zip_is_read_as_what_it_actually_is(+ self, tmp_path: Path+ ):+ """Not raising is the requirement; discarding it was never the point.++ Since this delegates to the shared extractor, content decides and the+ name is only a hint — so a text file somebody saved as ``.docx`` (an+ everyday mistake) now yields its text instead of being dropped. The+ contract this test guards is "never raises", and that still holds.+ """path = tmp_path / "broken.docx"path.write_bytes(b"this is not a zip at all")- assert extract_document_text(path) is None+ assert extract_document_text(path) == "this is not a zip at all"def test_malformed_xml_inside_a_docx_is_skipped_not_raised(self, tmp_path: Path):path = _make_docx(tmp_path / "torn.docx", document_xml="<w:document><w:body>")@@ -146,19 +155,33 @@ class TestHostileDocuments:"""def test_an_entity_bomb_is_refused_rather_than_expanded(self, tmp_path: Path):+ """Nine levels of ten: one billion characters if anything expands it.++ The assertion is on the SIZE of what comes back, not on it being+ ``None``. Returning nothing was how the old parser happened to survive+ a bomb; surviving is the actual requirement, and the shared extractor+ reaches it differently — the declaration is refused, so the reference+ stays an inert nine characters of raw text. A test pinned to ``None``+ would have failed a change that is equally safe and strictly better at+ salvaging damaged files.+ """+ declarations = ['<!ENTITY lol "lol">']+ for level in range(1, 10):+ previous = "lol" if level == 1 else f"lol{level - 1}"+ declarations.append(+ f'<!ENTITY lol{level} "' + f"&{previous};" * 10 + '">'+ )bomb = ('<?xml version="1.0"?>'- "<!DOCTYPE lolz ["- ' <!ENTITY lol "lol">'- ' <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">'- ' <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">'- "]>"+ "<!DOCTYPE lolz [" + "".join(declarations) + "]>"'<w:document xmlns:w="http://schemas.openxmlformats.org/'- 'wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>&lol2;'+ 'wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>&lol9;'"</w:t></w:r></w:p></w:body></w:document>")path = _make_docx(tmp_path / "bomb.docx", document_xml=bomb)- assert extract_document_text(path) is None+ text = extract_document_text(path) or ""+ assert len(text) < 1000, "the entity expanded — this is the bomb going off"+ assert "lollollol" not in textdef test_a_clean_document_still_parses_after_the_hardening(self, tmp_path: Pathdiff --git a/tests/unit/ultrawiki/test_export_import.py b/tests/unit/ultrawiki/test_export_import.pyindex 012453052d..aef6881373 100644--- a/tests/unit/ultrawiki/test_export_import.py+++ b/tests/unit/ultrawiki/test_export_import.py@@ -747,3 +747,167 @@ class TestFormatParity:assert isinstance(label, str) and label.strip(), (f"{name} has no label for the {fmt} format")+++# ---------------------------------------------------------------------------+# The half of Google Takeout that used to be refused+# ---------------------------------------------------------------------------+++def _tar_fixture(target: Path, members: dict[str, bytes], *, compress: bool) -> Path:+ """A tar written at test time, gzipped or not."""+ import io+ import tarfile++ mode = "w:gz" if compress else "w"+ with tarfile.open(target, mode) as archive:+ for name, payload in members.items():+ info = tarfile.TarInfo(name)+ info.size = len(payload)+ info.mtime = 1_700_000_000+ archive.addfile(info, io.BytesIO(payload))+ return target+++class TestTarArchives:+ """Takeout offers .zip AND .tgz, and .tgz used to be turned away.++ A compressed tar has no central directory, so it can only be read forward+ — which is why it needs its own walk rather than reusing the ZIP one.+ """++ async def test_a_gzipped_tar_is_walked_like_any_other_archive(self, tmp_path):+ _tar_fixture(+ tmp_path / "takeout-20240101.tgz",+ {+ "Takeout/Notes/readme.md": b"# Readme\n\nThe project notes.",+ "Takeout/Contacts/all.vcf": (+ b"BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Ada Lovelace\r\nEND:VCARD\r\n"+ ),+ },+ compress=True,+ )+ items = await _items(tmp_path)+ assert {item.metadata["format"] for item in items} == {"markdown", "vcard"}+ assert any("Ada Lovelace" in item.body for item in items)+ # Nothing was unpacked next to the archive.+ assert sorted(p.name for p in tmp_path.iterdir()) == ["takeout-20240101.tgz"]++ async def test_a_plain_tar_is_recognised_by_content_not_by_name(self, tmp_path):+ """The magic sits at offset 257, so even a misnamed tar is walked."""+ _tar_fixture(+ tmp_path / "archive.bin",+ {"notes/readme.md": b"# Readme\n\nStill readable."},+ compress=False,+ )+ items = await _items(tmp_path)+ assert [item.metadata["format"] for item in items] == ["markdown"]++ async def test_an_entry_too_large_to_buffer_is_refused_with_a_reason(+ self, tmp_path, monkeypatch+ ):+ """Refusing loudly beats an unbounded read; the rest still imports."""+ import jarvis.ultrawiki.connectors.export_import as module++ monkeypatch.setattr(module, "MAX_BUFFERED_TAR_ENTRY_BYTES", 32)+ _tar_fixture(+ tmp_path / "big.tgz",+ {+ "huge.md": b"# Huge\n\n" + b"x" * 500,+ "small.md": b"# Small\n\nfine",+ },+ compress=True,+ )+ items = await _items(tmp_path)+ assert [item.metadata["format"] for item in items] == ["markdown"]+ assert "Small" in items[0].body++ report = scan_export(tmp_path / "big.tgz")+ assert any("huge.md" in row["path"] for row in report["unreadable"])++ async def test_a_truncated_archive_keeps_everything_read_so_far(self, tmp_path):+ """A half-finished download is the normal way this ends."""+ full = _tar_fixture(+ tmp_path / "full.tgz",+ {f"notes/n{index}.md": b"# Note\n\nbody" for index in range(20)},+ compress=True,+ )+ data = full.read_bytes()+ (tmp_path / "full.tgz").write_bytes(data[: len(data) // 2])+ items = await _items(tmp_path)+ # Some prefix survived and nothing raised.+ assert all(item.metadata["format"] == "markdown" for item in items)+++# ---------------------------------------------------------------------------+# Documents and media through the shared extractor+# ---------------------------------------------------------------------------+++def _docx_bytes(paragraphs: list[str]) -> bytes:+ import io++ body = "".join(f"<w:p><w:r><w:t>{text}</w:t></w:r></w:p>" for text in paragraphs)+ document = (+ '<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/'+ f'wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>'+ )+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ archive.writestr("[Content_Types].xml", "<Types/>")+ archive.writestr("word/document.xml", document)+ return buffer.getvalue()+++class TestDocumentsAndMedia:+ async def test_a_word_file_in_a_drop_is_read_not_walked_as_an_archive(+ self, tmp_path+ ):+ """Every modern Office file IS a zip. Walking one would import a+ document as a heap of its own internal XML parts."""+ (tmp_path / "contract.docx").write_bytes(+ _docx_bytes(["The quarterly ledger", "reconciliation lives here."])+ )+ items = await _items(tmp_path)+ assert [item.metadata["format"] for item in items] == ["document"]+ assert "quarterly ledger" in items[0].body+ assert "word/document.xml" not in items[0].external_id++ async def test_a_photo_in_a_drop_is_captured_and_marked_for_description(+ self, tmp_path+ ):+ (tmp_path / "IMG_0001.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 64)+ items = await _items(tmp_path)+ assert [item.metadata["format"] for item in items] == ["image"]+ item = items[0]+ assert item.metadata["media_kind"] == "image"+ assert item.metadata["enrich_pending"] is True+ assert item.metadata["media_ref_kind"] == "file"+ assert "IMG_0001.png" in item.body++ async def test_a_photo_inside_a_zip_can_still_be_reopened_later(self, tmp_path):+ """Describing it happens days later, in another process — the item has+ to carry a way back to the exact bytes."""+ archive_path = tmp_path / "takeout.zip"+ with zipfile.ZipFile(archive_path, "w") as archive:+ archive.writestr("Photos/beach.png", b"\x89PNG\r\n\x1a\n" + b"\x00" * 64)+ items = await _items(tmp_path)+ assert [item.metadata["format"] for item in items] == ["image"]+ assert items[0].metadata["media_ref_kind"] == "zip-entry"+ assert items[0].metadata["media_ref_entry"] == "Photos/beach.png"+ assert Path(items[0].metadata["media_ref_path"]).name == "takeout.zip"++ async def test_a_photo_inside_a_tar_says_why_it_cannot_be_described(+ self, tmp_path+ ):+ """Silence would be the bug: a tar entry cannot be reopened, so the+ item states that instead of waiting forever in a queue."""+ _tar_fixture(+ tmp_path / "photos.tgz",+ {"Photos/beach.png": b"\x89PNG\r\n\x1a\n" + b"\x00" * 64},+ compress=True,+ )+ items = await _items(tmp_path)+ assert [item.metadata["format"] for item in items] == ["image"]+ assert items[0].metadata["enrich_pending"] is False+ assert items[0].metadata["enrich_blocked_reason"]