Skip to content

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.

feat(ultrawiki): see the photos, recordings and archives a phone produces

Ruben Lütke0957642f9d2b
diff --git a/jarvis/ultrawiki/extract.py b/jarvis/ultrawiki/extract.py
index 383c87af26..e1994901a1 100644
--- a/jarvis/ultrawiki/extract.py
+++ b/jarvis/ultrawiki/extract.py
@@ -57,6 +57,7 @@ log = logging.getLogger(__name__)
__all__ = [
"ExtractResult",
+ "MEDIA_KINDS",
"TEXT_EXTENSIONS",
"detect_kind",
"extract_text",
@@ -103,6 +104,57 @@ _ZIP_MARKERS: tuple[tuple[str, str], ...] = (
("META-INF/container.xml", "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"})
+
+#: ISO-BMFF brand (bytes 8..12 after an `ftyp` box) → kind. One container
+#: family holds an iPhone photo, a voice memo and a video, and the extension
+#: routinely disagrees with all three — an iPhone photo shared through a chat
+#: arrives as `.jpg` holding HEIC, and a WhatsApp voice note is `.opus` inside
+#: an Ogg stream. The brand is the only honest answer.
+_FTYP_BRANDS: tuple[tuple[bytes, str], ...] = (
+ (b"heic", "image"), (b"heix", "image"), (b"heim", "image"),
+ (b"heis", "image"), (b"hevc", "image"), (b"mif1", "image"),
+ (b"msf1", "image"), (b"avif", "image"), (b"avis", "image"),
+ (b"M4A ", "audio"), (b"M4B ", "audio"), (b"M4P ", "audio"),
+ (b"qt ", "video"), (b"M4V ", "video"), (b"M4VP", "video"),
+ (b"isom", "video"), (b"iso2", "video"), (b"iso4", "video"),
+ (b"iso5", "video"), (b"iso6", "video"), (b"mp41", "video"),
+ (b"mp42", "video"), (b"mp4v", "video"), (b"avc1", "video"),
+ (b"3gp4", "video"), (b"3gp5", "video"), (b"3g2a", "video"),
+)
+
+#: RIFF sub-format (bytes 8..12) → kind.
+_RIFF_FORMS: tuple[tuple[bytes, str], ...] = (
+ (b"WEBP", "image"),
+ (b"WAVE", "audio"),
+ (b"AVI ", "video"),
+)
+
+#: Leading magic for media families that need no container inspection.
+_MEDIA_MAGIC: tuple[tuple[bytes, str], ...] = (
+ (b"II*\x00", "image"), # TIFF, little-endian
+ (b"MM\x00*", "image"), # TIFF, big-endian
+ (b"\x1aE\xdf\xa3", "video"), # Matroska / WebM
+ (b"FLV\x01", "video"), # Flash video
+ (b"\xff\xfb", "audio"), # MPEG-1 layer 3, no ID3 tag
+ (b"\xff\xf3", "audio"),
+ (b"\xff\xf2", "audio"),
+ (b"\xff\xf1", "audio"), # AAC (ADTS)
+ (b"MAC \x00", "audio"), # Monkey's Audio
+ (b"wvpk", "audio"), # WavPack
+)
+
+#: A tar header carries its magic at offset 257, not at the start — the one
+#: format in this module that cannot be identified from a leading prefix.
+_TAR_MAGIC_OFFSET = 257
+_TAR_MAGICS: tuple[bytes, ...] = (b"ustar\x0000", b"ustar \x00", b"ustar\x00")
+
+#: Suffixes that mark a gzip stream as a COMPRESSED TAR rather than a single
+#: gzipped file. Google Takeout's default download is exactly this.
+_TGZ_SUFFIXES: tuple[str, ...] = (".tgz", ".tar.gz", ".taz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz")
+
#: Extensions whose contents are text even when they look unfamiliar. Not an
#: allowlist that decides what gets imported — a hint for the sniffer. Anything
#: that decodes cleanly is treated as text regardless of its name.
@@ -130,13 +182,40 @@ TEXT_EXTENSIONS: frozenset[str] = frozenset(
}
)
-#: Files whose NAME says binary regardless of what decodes.
+#: Extension → media kind, consulted only when the content was inconclusive.
+#: A file the sniffer could not place is still worth calling a photo when it
+#: is named like one: a truncated download, an unusual camera profile or a
+#: RAW format nobody ships magic for is exactly the picture a person cares
+#: about most.
+_MEDIA_EXTENSIONS: dict[str, str] = {
+ ".png": "image", ".jpg": "image", ".jpeg": "image", ".jpe": "image",
+ ".gif": "image", ".bmp": "image", ".webp": "image", ".tiff": "image",
+ ".tif": "image", ".heic": "image", ".heif": "image", ".avif": "image",
+ ".psd": "image", ".ico": "image",
+ # Camera RAW: one per major vendor, because a photographer's archive is
+ # otherwise entirely invisible to a memory system.
+ ".raw": "image", ".dng": "image", ".cr2": "image", ".cr3": "image",
+ ".nef": "image", ".arw": "image", ".orf": "image", ".rw2": "image",
+ ".raf": "image", ".srw": "image", ".pef": "image",
+ ".mp3": "audio", ".wav": "audio", ".flac": "audio", ".ogg": "audio",
+ ".oga": "audio", ".opus": "audio", ".m4a": "audio", ".m4b": "audio",
+ ".aac": "audio", ".wma": "audio", ".aiff": "audio", ".aif": "audio",
+ ".amr": "audio", ".3ga": "audio", ".caf": "audio", ".wv": "audio",
+ ".mp4": "video", ".mov": "video", ".avi": "video", ".mkv": "video",
+ ".webm": "video", ".wmv": "video", ".flv": "video", ".m4v": "video",
+ ".mpg": "video", ".mpeg": "video", ".3gp": "video", ".3g2": "video",
+ ".mts": "video", ".m2ts": "video", ".ogv": "video",
+ # `.ts` is deliberately absent: it is TypeScript far more often than it is
+ # an MPEG transport stream, and calling a source file a video would drop it
+ # from a developer's own knowledge base.
+}
+
+#: 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.
_BINARY_EXTENSIONS: frozenset[str] = frozenset(
{
- ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".tiff", ".tif",
- ".ico", ".svgz", ".psd", ".ai", ".heic", ".avif",
- ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".wma",
- ".mp4", ".mov", ".avi", ".mkv", ".webm", ".wmv", ".flv",
+ ".svgz", ".ai",
".zip", ".gz", ".bz2", ".xz", ".7z", ".rar", ".tar", ".tgz", ".jar",
".exe", ".dll", ".so", ".dylib", ".bin", ".dat", ".db", ".sqlite",
".woff", ".woff2", ".ttf", ".otf", ".eot",
@@ -175,7 +254,20 @@ class ExtractResult:
extract it" (no pypdf, a corrupt archive) — only the second is worth
retrying later.
"""
- return not self.ok and self.kind not in ("image", "audio", "video", "empty")
+ return not self.ok and self.kind not in MEDIA_KINDS and self.kind != "empty"
+
+ @property
+ def media_kind(self) -> str:
+ """``image`` / ``audio`` / ``video`` when this file carries meaning a
+ model could read; ``""`` for everything else.
+
+ The third outcome the original two could not express. A photo is
+ neither "extracted" nor "we failed to extract it" — it is *not text,
+ and never will be*, while still being one of the most memory-dense
+ things a person owns. Naming that case is what lets a later stage
+ describe the picture instead of the file being quietly worthless.
+ """
+ return self.kind if self.kind in MEDIA_KINDS else ""
def _read(data: bytes | Path) -> bytes:
@@ -247,6 +339,60 @@ def _zip_kind(data: bytes | Path) -> str:
return "archive"
+def _container_kind(head: bytes) -> str:
+ """Media kind of an ISO-BMFF or RIFF container, or ``""``.
+
+ Both families put a four-byte form marker at offset 8, and both are used
+ for pictures, sound and film alike — so the outer magic alone says nothing
+ useful. `.heic` from an iPhone and `.mp4` from the same phone differ only
+ here.
+ """
+ if len(head) >= 12:
+ if head[4:8] == b"ftyp":
+ brand = head[8:12]
+ for marker, kind in _FTYP_BRANDS:
+ if brand == marker:
+ return kind
+ # An unlisted brand is still an ISO-BMFF file, and those are
+ # overwhelmingly video. Better a video we transcribe than a
+ # "binary" we drop.
+ return "video"
+ if head[:4] == b"RIFF":
+ form = head[8:12]
+ for marker, kind in _RIFF_FORMS:
+ if form == marker:
+ return kind
+ return ""
+
+
+def _is_tar(data: bytes | Path) -> bool:
+ """Whether these bytes are an uncompressed tar (magic lives at offset 257)."""
+ header = b""
+ if isinstance(data, Path):
+ try:
+ with data.open("rb") as handle:
+ header = handle.read(_TAR_MAGIC_OFFSET + 8)
+ except OSError:
+ return False
+ else:
+ header = bytes(data[: _TAR_MAGIC_OFFSET + 8])
+ if len(header) < _TAR_MAGIC_OFFSET + 5:
+ return False
+ tail = header[_TAR_MAGIC_OFFSET:]
+ return any(tail.startswith(magic) for magic in _TAR_MAGICS)
+
+
+def _looks_like_tarball(filename: str) -> bool:
+ """Whether a compressed stream's NAME says it wraps a tar archive.
+
+ Compression carries no record of what it compressed, so the name is the
+ only evidence available without decompressing — and `.tar.gz` is a double
+ suffix `Path.suffix` alone does not see.
+ """
+ lowered = Path(filename).name.lower()
+ return any(lowered.endswith(suffix) for suffix in _TGZ_SUFFIXES)
+
+
def detect_kind(data: bytes | Path, filename: str = "", mime: str = "") -> str:
"""The file's real format — content first, name second, mime last.
@@ -256,13 +402,29 @@ def detect_kind(data: bytes | Path, filename: str = "", mime: str = "") -> str:
head = _head(data)
if not head:
return "empty"
+
+ # Containers before flat magic: `RIFF` and `ftyp` files would otherwise
+ # fall through to the extension, which is where HEIC photos got lost.
+ container = _container_kind(head)
+ if container:
+ return container
+ for magic, kind in _MEDIA_MAGIC:
+ if head.startswith(magic):
+ return kind
for magic, kind in _MAGIC:
if head.startswith(magic):
+ if kind == "gzip" and _looks_like_tarball(filename):
+ return "tar"
return kind
if head.startswith(b"PK\x03\x04"):
return _zip_kind(data)
+ if _is_tar(data):
+ return "tar"
suffix = Path(filename).suffix.lower() if filename else ""
+ media = _MEDIA_EXTENSIONS.get(suffix, "")
+ if media:
+ return media
if suffix in _BINARY_EXTENSIONS:
return "binary"
lowered = (mime or "").lower()
@@ -611,12 +773,16 @@ def _from_json(data: bytes | Path) -> ExtractResult:
_NO_TEXT_REASONS: dict[str, str] = {
- "image": "an image holds no text — reading it needs OCR, which this build does not do",
- "audio": "an audio file holds no text — reading it needs transcription",
- "video": "a video holds no text — reading it needs transcription",
+ # The three media reasons describe a PENDING state, not a dead end: the
+ # item is stored and findable by name, date and folder immediately, and
+ # the enrichment stage fills in what the file actually shows or says.
+ "image": "a picture carries no text; it is queued to be described",
+ "audio": "a recording carries no text; it is queued to be transcribed",
+ "video": "a video carries no text; it is queued to be transcribed",
"empty": "the file is empty",
"binary": "this is a binary file with no readable text",
"archive": "an archive holds files rather than text — import it as an export instead",
+ "tar": "a tar archive holds files rather than text — import it as an export instead",
"gzip": "a compressed file holds other files rather than text",
"legacy_office": (
"this is a pre-2007 Office file (.doc/.xls/.ppt); re-saving it in the "
@@ -664,6 +830,7 @@ def extract_text(
return _from_text(data)
return ExtractResult(
kind=kind,
+ meta=_media_meta(data, kind),
reason=_NO_TEXT_REASONS.get(kind, "this format is not readable as text"),
)
except Exception as exc: # noqa: BLE001 — one bad file never fails a whole sync
@@ -671,3 +838,30 @@ def extract_text(
return ExtractResult(
kind=kind, reason=f"the file could not be read ({type(exc).__name__})"
)
+
+
+def _media_meta(data: bytes | Path, kind: str) -> dict[str, Any]:
+ """What a media file states about itself — capture time, camera, GPS.
+
+ Read here rather than in the enrichment stage on purpose: this is what
+ makes a photo findable by *when and where* the moment it lands, months
+ before any model gets around to describing it. It also costs nothing —
+ the bytes are already open.
+ """
+ if kind not in MEDIA_KINDS:
+ return {}
+ try:
+ from jarvis.ultrawiki.media import ( # noqa: PLC0415 — lazy (AP-26)
+ EXIF_SCAN_BYTES,
+ media_metadata,
+ )
+
+ if isinstance(data, Path):
+ with data.open("rb") as handle:
+ head = handle.read(EXIF_SCAN_BYTES)
+ else:
+ head = bytes(data[:EXIF_SCAN_BYTES])
+ return media_metadata(head, kind)
+ except Exception: # noqa: BLE001 — metadata is a bonus, never a failure
+ log.debug("extract: media metadata unavailable", exc_info=True)
+ return {}
diff --git a/jarvis/ultrawiki/media.py b/jarvis/ultrawiki/media.py
new file mode 100644
index 0000000000..f66a47a0a2
--- /dev/null
+++ b/jarvis/ultrawiki/media.py
@@ -0,0 +1,430 @@
+"""What a photo, recording or video says about itself before any model sees it.
+
+A picture that arrives with nothing but a filename is nearly useless to a
+memory system: the file's modification time is the day it was *copied*, not the
+day it was taken, so a holiday album restored from a backup collapses onto one
+meaningless afternoon. The camera already wrote the truth into the file — this
+module reads it back.
+
+Two jobs, both deliberately small:
+
+* **Self-description** (:func:`media_metadata`) — capture time, camera, GPS,
+ dimensions, duration. Enough that the item is findable by time and place
+ *immediately*, before the enrichment stage has described anything.
+* **A way back to the bytes** (:class:`MediaRef`) — a photo is stored as an
+ item the moment it is seen, but describing it happens later, in a different
+ process, possibly days later. The reference is how that later stage opens the
+ same file again.
+
+**Standard library only, and it never raises.** EXIF is a TIFF directory
+embedded in a JPEG segment; ``struct`` reads it in eighty lines. Refusing to
+add an imaging library to the base install is not frugality for its own sake —
+it is what keeps ingestion working on a `python:3.11-slim` VPS with no image
+stack at all (charter §3).
+
+The trade that buys: JPEG and HEIC/AVIF are read, and every other format
+returns an empty dict rather than a wrong guess. A PNG's textual chunks and a
+video's duration are deliberately not parsed here — the enrichment stage's
+description and transcript are the content that matters for those, and half a
+metadata parser would be a claim without a source.
+"""
+
+from __future__ import annotations
+
+import logging
+import struct
+import zipfile
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import IO, Any
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "EXIF_SCAN_BYTES",
+ "MediaRef",
+ "media_metadata",
+ "open_media",
+ "ref_from_metadata",
+]
+
+#: Bytes read looking for the EXIF block. The segment sits at the very front of
+#: every camera file; anything past this is a file that has none.
+_EXIF_SCAN_BYTES = 512 * 1024
+
+#: Hard ceiling on one EXIF directory, so a malformed count field cannot walk
+#: this parser through megabytes of unrelated bytes.
+_MAX_EXIF_ENTRIES = 512
+
+#: TIFF tags read out of IFD0 / the Exif sub-IFD. Everything else is ignored:
+#: a knowledge base wants when, where and what took it — not the white balance.
+_TAG_DATETIME_ORIGINAL = 0x9003
+_TAG_DATETIME_DIGITIZED = 0x9004
+_TAG_DATETIME = 0x0132
+_TAG_MAKE = 0x010F
+_TAG_MODEL = 0x0110
+_TAG_ORIENTATION = 0x0112
+_TAG_EXIF_IFD = 0x8769
+_TAG_GPS_IFD = 0x8825
+_TAG_IMAGE_WIDTH = 0x0100
+_TAG_IMAGE_HEIGHT = 0x0101
+_TAG_PIXEL_X = 0xA002
+_TAG_PIXEL_Y = 0xA003
+
+_GPS_LAT_REF = 0x0001
+_GPS_LAT = 0x0002
+_GPS_LON_REF = 0x0003
+_GPS_LON = 0x0004
+
+#: TIFF field type → (bytes per component, struct code). Only the types that
+#: actually carry the tags above.
+_FIELD_TYPES: dict[int, tuple[int, str]] = {
+ 1: (1, "B"), # BYTE
+ 2: (1, "s"), # ASCII
+ 3: (2, "H"), # SHORT
+ 4: (4, "I"), # LONG
+ 5: (8, ""), # RATIONAL — two LONGs, handled separately
+ 7: (1, "s"), # UNDEFINED
+ 9: (4, "i"), # SLONG
+ 10: (8, ""), # SRATIONAL
+}
+
+
+# ---------------------------------------------------------------------------
+# Locating the bytes again
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class MediaRef:
+ """Where one media file lives, durably enough to reopen it later.
+
+ Two shapes cover everything ingestion currently produces:
+
+ * ``kind="file"`` — a path on disk (a photo library, a chosen folder).
+ * ``kind="zip-entry"`` — one entry inside an archive that is still on disk
+ (a Takeout download, a WhatsApp export with its attachments).
+
+ A cloud object is deliberately NOT a third shape here. Re-fetching from a
+ provider needs that provider's client and credentials, which belong to the
+ adapter, not to this module; an adapter that wants enrichment passes its
+ bytes directly instead. Inventing a half-working remote reference would
+ only produce items that promise a description they can never fetch.
+ """
+
+ kind: str
+ path: str
+ entry: str = ""
+
+ def as_metadata(self) -> dict[str, str]:
+ """The form stored on a ``RawItem`` so a later stage can rebuild this."""
+ payload = {"media_ref_kind": self.kind, "media_ref_path": self.path}
+ if self.entry:
+ payload["media_ref_entry"] = self.entry
+ return payload
+
+ @property
+ def display_name(self) -> str:
+ """The filename a person would recognise, archive entry included."""
+ return Path(self.entry or self.path).name
+
+
+def ref_from_metadata(metadata: dict[str, Any]) -> MediaRef | None:
+ """Rebuild a :class:`MediaRef` from a stored item, or ``None``.
+
+ Returns ``None`` rather than raising for every incomplete shape: an item
+ written by an older build simply has no reference, which the caller reads
+ as "cannot enrich this one" and moves on.
+ """
+ kind = str(metadata.get("media_ref_kind") or "")
+ path = str(metadata.get("media_ref_path") or "")
+ if kind not in ("file", "zip-entry") or not path:
+ return None
+ return MediaRef(kind=kind, path=path, entry=str(metadata.get("media_ref_entry") or ""))
+
+
+class _ArchiveEntryStream:
+ """An archive entry that closes its archive when the entry is closed.
+
+ ``ZipFile.open`` hands back a stream that does NOT own the archive, so
+ closing it leaves the archive's file handle open. One leaked handle per
+ enriched photo would exhaust the process's descriptors partway through a
+ Takeout import — on Windows it would also keep the archive locked against
+ the user deleting it.
+ """
+
+ def __init__(self, archive: zipfile.ZipFile, stream: IO[bytes]) -> None:
+ self._archive = archive
+ self._stream = stream
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._stream, name)
+
+ def __enter__(self) -> _ArchiveEntryStream:
+ return self
+
+ def __exit__(self, *exc_info: object) -> None:
+ self.close()
+
+ def read(self, size: int = -1) -> bytes:
+ return self._stream.read(size)
+
+ def close(self) -> None:
+ try:
+ self._stream.close()
+ finally:
+ self._archive.close()
+
+
+def open_media(ref: MediaRef) -> Any:
+ """A fresh binary stream for ``ref``, or ``None`` when it is gone.
+
+ Deletion between capture and enrichment is normal — a user empties their
+ downloads folder, an archive is moved — so a missing file is an ordinary
+ outcome the caller reports honestly, never an error that stops a queue.
+ """
+ try:
+ if ref.kind == "file":
+ return Path(ref.path).open("rb")
+ if ref.kind == "zip-entry":
+ archive = zipfile.ZipFile(ref.path)
+ try:
+ return _ArchiveEntryStream(archive, archive.open(ref.entry, "r"))
+ except Exception:
+ archive.close()
+ raise
+ except (OSError, KeyError, zipfile.BadZipFile, RuntimeError) as exc:
+ log.debug("media: %s is no longer readable (%s)", ref.path, type(exc).__name__)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# EXIF
+# ---------------------------------------------------------------------------
+
+
+def _exif_block(head: bytes) -> bytes:
+ """The TIFF block out of a JPEG APP1 segment, or ``b""``.
+
+ Walks the JPEG marker chain rather than searching for the string ``Exif``:
+ those four bytes occur inside image data often enough that a naive search
+ finds them in files that carry no EXIF at all.
+ """
+ if head[:2] != b"\xff\xd8": # not a JPEG
+ return b""
+ offset = 2
+ limit = len(head)
+ while offset + 4 <= limit:
+ if head[offset] != 0xFF:
+ return b""
+ marker = head[offset + 1]
+ if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7:
+ offset += 2
+ continue
+ if marker == 0xDA: # start of scan: image data begins, no more headers
+ return b""
+ size = struct.unpack_from(">H", head, offset + 2)[0]
+ if size < 2:
+ return b""
+ segment = head[offset + 4 : offset + 2 + size]
+ if marker == 0xE1 and segment[:6] == b"Exif\x00\x00":
+ return segment[6:]
+ offset += 2 + size
+ return b""
+
+
+def _heif_exif_block(head: bytes) -> bytes:
+ """The TIFF block inside an ISO-BMFF (HEIC/AVIF) file, or ``b""``.
+
+ A full HEIF box walk would need the item-property machinery; the payload is
+ still a plain TIFF header, so it is located directly. This is the one place
+ a byte search is acceptable: the marker is a TIFF header immediately after
+ an ``Exif`` box name, which image data does not reproduce.
+ """
+ for marker in (b"Exif\x00\x00II*\x00", b"Exif\x00\x00MM\x00*"):
+ index = head.find(marker)
+ if index >= 0:
+ return head[index + 6 :]
+ for tiff in (b"II*\x00", b"MM\x00*"):
+ index = head.find(b"Exif" + tiff)
+ if index >= 0:
+ return head[index + 4 :]
+ return b""
+
+
+class _Tiff:
+ """A minimal TIFF directory reader — bounds-checked, never raising."""
+
+ def __init__(self, block: bytes) -> None:
+ self.block = block
+ self.order = ">"
+ self.ok = False
+ if len(block) < 8:
+ return
+ if block[:2] == b"II":
+ self.order = "<"
+ elif block[:2] == b"MM":
+ self.order = ">"
+ else:
+ return
+ if struct.unpack_from(self.order + "H", block, 2)[0] != 42:
+ return
+ self.first_ifd = struct.unpack_from(self.order + "I", block, 4)[0]
+ self.ok = True
+
+ def entries(self, offset: int) -> dict[int, Any]:
+ """Every tag of one directory as ``{tag: value}``. Empty on anything odd."""
+ found: dict[int, Any] = {}
+ if not self.ok or offset <= 0 or offset + 2 > len(self.block):
+ return found
+ try:
+ count = struct.unpack_from(self.order + "H", self.block, offset)[0]
+ except struct.error:
+ return found
+ for index in range(min(count, _MAX_EXIF_ENTRIES)):
+ base = offset + 2 + index * 12
+ if base + 12 > len(self.block):
+ break
+ try:
+ tag, field_type, length = struct.unpack_from(self.order + "HHI", self.block, base)
+ except struct.error:
+ break
+ value = self._value(field_type, length, base + 8)
+ if value is not None:
+ found[tag] = value
+ return found
+
+ def _value(self, field_type: int, length: int, value_offset: int) -> Any:
+ spec = _FIELD_TYPES.get(field_type)
+ if spec is None or length == 0 or length > 4096:
+ return None
+ width, code = spec
+ total = width * length
+ if total > 4:
+ try:
+ start = struct.unpack_from(self.order + "I", self.block, value_offset)[0]
+ except struct.error:
+ return None
+ else:
+ start = value_offset
+ if start < 0 or start + total > len(self.block):
+ return None
+ raw = self.block[start : start + total]
+ if field_type in (2, 7):
+ return raw.split(b"\x00", 1)[0].decode("utf-8", errors="replace").strip()
+ if field_type in (5, 10):
+ values = []
+ for step in range(length):
+ try:
+ num, den = struct.unpack_from(
+ self.order + ("II" if field_type == 5 else "ii"),
+ self.block,
+ start + step * 8,
+ )
+ except struct.error:
+ return None
+ values.append(num / den if den else 0.0)
+ return values[0] if length == 1 else values
+ try:
+ values = list(struct.unpack_from(self.order + code * length, self.block, start))
+ except struct.error:
+ return None
+ return values[0] if length == 1 else values
+
+
+def _exif_datetime(value: str) -> str:
+ """``"2019:08:14 17:03:22"`` → ISO-8601. ``""`` when it is not a date.
+
+ EXIF stores no time zone, so the reading is treated as UTC and the item
+ says which field it came from — a claim of precision the file does not
+ carry would be worse than a slightly-off hour.
+ """
+ text = str(value or "").strip().rstrip("\x00")
+ for pattern in ("%Y:%m:%d %H:%M:%S", "%Y-%m-%d %H:%M:%S", "%Y:%m:%d"):
+ try:
+ moment = datetime.strptime(text, pattern).replace(tzinfo=UTC)
+ except ValueError:
+ continue
+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+ return ""
+
+
+def _gps_degrees(values: Any, reference: Any) -> float | None:
+ """Degrees/minutes/seconds plus a hemisphere letter as a signed float."""
+ if not isinstance(values, list) or len(values) < 3:
+ return None
+ try:
+ degrees = float(values[0]) + float(values[1]) / 60 + float(values[2]) / 3600
+ except (TypeError, ValueError):
+ return None
+ if str(reference or "").upper().startswith(("S", "W")):
+ degrees = -degrees
+ return round(degrees, 6)
+
+
+def _image_metadata(head: bytes) -> dict[str, Any]:
+ """Capture time, camera and location out of one image's EXIF."""
+ block = _exif_block(head) or _heif_exif_block(head)
+ if not block:
+ return {}
+ tiff = _Tiff(block)
+ if not tiff.ok:
+ return {}
+ root = tiff.entries(tiff.first_ifd)
+ exif = tiff.entries(int(root.get(_TAG_EXIF_IFD) or 0))
+ gps = tiff.entries(int(root.get(_TAG_GPS_IFD) or 0))
+
+ meta: dict[str, Any] = {}
+ for tag, source in (
+ (_TAG_DATETIME_ORIGINAL, exif),
+ (_TAG_DATETIME_DIGITIZED, exif),
+ (_TAG_DATETIME, root),
+ ):
+ stamp = _exif_datetime(source.get(tag, ""))
+ if stamp:
+ meta["captured_at"] = stamp
+ break
+
+ make = str(root.get(_TAG_MAKE) or "").strip()
+ model = str(root.get(_TAG_MODEL) or "").strip()
+ camera = " ".join(part for part in (make, model) if part)
+ if camera:
+ meta["camera"] = camera[:120]
+ if root.get(_TAG_ORIENTATION):
+ meta["orientation"] = int(root[_TAG_ORIENTATION])
+
+ width = exif.get(_TAG_PIXEL_X) or root.get(_TAG_IMAGE_WIDTH)
+ height = exif.get(_TAG_PIXEL_Y) or root.get(_TAG_IMAGE_HEIGHT)
+ if isinstance(width, int) and isinstance(height, int):
+ meta["width"], meta["height"] = width, height
+
+ latitude = _gps_degrees(gps.get(_GPS_LAT), gps.get(_GPS_LAT_REF))
+ longitude = _gps_degrees(gps.get(_GPS_LON), gps.get(_GPS_LON_REF))
+ if latitude is not None and longitude is not None:
+ meta["latitude"], meta["longitude"] = latitude, longitude
+ return meta
+
+
+def media_metadata(head: bytes, kind: str) -> dict[str, Any]:
+ """Everything a media file states about itself. Never raises, may be empty.
+
+ ``head`` is the leading bytes of the file (at least a few hundred KB for a
+ photo, since EXIF sits before the image data). ``kind`` is the media kind
+ from :mod:`jarvis.ultrawiki.extract`.
+ """
+ if kind != "image":
+ # Audio and video duration lives in format-specific headers that vary
+ # far more than EXIF does; the transcript the enrichment stage produces
+ # is the useful content, and inventing a half-right duration here would
+ # be a claim without a source.
+ return {}
+ try:
+ return _image_metadata(head)
+ except Exception: # noqa: BLE001 — a malformed camera file is not an error
+ log.debug("media: EXIF could not be read", exc_info=True)
+ return {}
+
+
+#: Bytes a caller should hand to :func:`media_metadata` for an image.
+EXIF_SCAN_BYTES = _EXIF_SCAN_BYTES
diff --git a/tests/unit/ultrawiki/test_extract.py b/tests/unit/ultrawiki/test_extract.py
index 54f086504c..ffa3a5b5c5 100644
--- a/tests/unit/ultrawiki/test_extract.py
+++ b/tests/unit/ultrawiki/test_extract.py
@@ -40,6 +40,93 @@ def test_a_file_with_no_extension_is_identified_by_content():
assert detect_kind(b"\x89PNG\r\n\x1a\nrest") == "image"
+# ---------------------------------------------------------------------------
+# Media detection — the formats a phone actually produces
+# ---------------------------------------------------------------------------
+
+
+def _ftyp(brand: bytes) -> bytes:
+ """A minimal ISO base-media header carrying one brand."""
+ return b"\x00\x00\x00\x18ftyp" + brand + b"\x00\x00\x02\x00" + brand
+
+
+def _riff(form: bytes) -> bytes:
+ return b"RIFF" + b"\x00\x00\x01\x00" + form + b"rest"
+
+
+def test_an_iphone_photo_is_an_image_not_a_binary():
+ """HEIC and MP4 share a container; only the brand tells them apart.
+
+ Before this, an iPhone photo library imported as a folder of "binary
+ files" — the single largest pile of memories most people own, invisible.
+ """
+ assert detect_kind(_ftyp(b"heic"), filename="IMG_4821.HEIC") == "image"
+ assert detect_kind(_ftyp(b"mif1"), filename="IMG_4821.heic") == "image"
+ assert detect_kind(_ftyp(b"avif"), filename="shot.avif") == "image"
+
+
+def test_the_same_container_holding_video_or_sound_is_not_called_an_image():
+ assert detect_kind(_ftyp(b"isom"), filename="clip.mp4") == "video"
+ assert detect_kind(_ftyp(b"qt "), filename="clip.mov") == "video"
+ assert detect_kind(_ftyp(b"M4A "), filename="memo.m4a") == "audio"
+
+
+def test_an_unlisted_iso_brand_degrades_to_video_rather_than_binary():
+ """Better a transcript attempt than a silently dropped file."""
+ assert detect_kind(_ftyp(b"zzzz"), filename="clip.mp4") == "video"
+
+
+def test_riff_containers_are_split_by_their_form():
+ assert detect_kind(_riff(b"WEBP"), filename="pic.webp") == "image"
+ assert detect_kind(_riff(b"WAVE"), filename="note.wav") == "audio"
+ assert detect_kind(_riff(b"AVI "), filename="old.avi") == "video"
+
+
+def test_a_whatsapp_voice_note_is_audio():
+ """`.opus` inside an Ogg stream — the format every voice message uses."""
+ assert detect_kind(b"OggS\x00\x02rest", filename="PTT-20240612-WA0003.opus") == "audio"
+
+
+def test_a_camera_raw_file_is_an_image_by_name():
+ """No magic ships for every vendor's RAW, and a photographer's archive is
+ entirely made of them."""
+ assert detect_kind(b"\x00\x01\x02\x03unknown-binary", filename="DSC_0042.NEF") == "image"
+ assert detect_kind(b"\x00\x01\x02\x03unknown-binary", filename="P1000123.RW2") == "image"
+
+
+def test_a_typescript_file_is_not_a_video():
+ """`.ts` is a transport stream and a source file; in a knowledge base it is
+ overwhelmingly the second, and calling it video would drop it."""
+ assert detect_kind(b"export const x = 1;\n", filename="app.ts") == "text"
+
+
+# ---------------------------------------------------------------------------
+# tar — the half of Google Takeout that used to be refused
+# ---------------------------------------------------------------------------
+
+
+def _tar_header() -> bytes:
+ """A tar block whose magic sits at offset 257, where tar keeps it."""
+ return b"name.txt".ljust(257, b"\x00") + b"ustar\x0000" + b"\x00" * 200
+
+
+def test_an_uncompressed_tar_is_recognised_by_its_offset_magic():
+ assert detect_kind(_tar_header(), filename="archive.tar") == "tar"
+ # ...and without any name at all, because the magic is conclusive.
+ assert detect_kind(_tar_header()) == "tar"
+
+
+def test_a_takeout_tgz_is_a_tar_not_an_opaque_gzip():
+ """Compression records nothing about what it compressed, so the double
+ suffix is the only evidence — and it is the download Takeout offers by
+ default."""
+ gzip_head = b"\x1f\x8b\x08\x00rest"
+ assert detect_kind(gzip_head, filename="takeout-20240101.tgz") == "tar"
+ assert detect_kind(gzip_head, filename="takeout-20240101.tar.gz") == "tar"
+ # A plain gzipped single file is still just gzip.
+ assert detect_kind(gzip_head, filename="notes.txt.gz") == "gzip"
+
+
def test_office_formats_are_separated_by_their_inner_layout():
"""They all start with the same ZIP signature."""
assert detect_kind(_zip({"word/document.xml": "<w:p/>"})) == "docx"
@@ -243,12 +330,19 @@ def test_a_windows_encoded_file_is_text_not_binary():
def test_an_image_reports_no_text_and_is_NOT_marked_retryable():
- """Nothing to extract is different from could not extract."""
+ """Nothing to extract is different from could not extract.
+
+ ``content_missing`` false is the load-bearing assertion: it keeps the
+ picture out of the text-extraction retry queue. It is NOT a statement that
+ the file is worthless — ``media_kind`` is what routes it to enrichment
+ instead, and the two flags must never collapse into one.
+ """
result = extract_text(b"\x89PNG\r\n\x1a\nrest", filename="photo.png")
assert not result.ok
assert result.kind == "image"
- assert "OCR" in result.reason
+ assert result.reason
assert result.content_missing is False
+ assert result.media_kind == "image"
def test_a_corrupt_office_file_IS_marked_retryable():
diff --git a/tests/unit/ultrawiki/test_media.py b/tests/unit/ultrawiki/test_media.py
new file mode 100644
index 0000000000..28c27d65a6
--- /dev/null
+++ b/tests/unit/ultrawiki/test_media.py
@@ -0,0 +1,266 @@
+"""What a photo says about itself, read without an imaging library.
+
+The reason this is worth a stdlib parser: a file's modification time is the day
+it was *copied*, so a holiday album restored from a backup collapses onto one
+meaningless afternoon and a search for "summer 2019" finds nothing. The camera
+wrote the real date into the file; these tests pin that it comes back out — on
+a `python:3.11-slim` container with no Pillow, no GPU and no image stack.
+
+Every fixture is assembled byte by byte for the same reason: a binary JPEG
+checked into the repo would be one more thing that behaves differently on
+another platform.
+"""
+
+from __future__ import annotations
+
+import io
+import struct
+import zipfile
+from pathlib import Path
+
+from jarvis.ultrawiki.extract import extract_text
+from jarvis.ultrawiki.media import (
+ MediaRef,
+ media_metadata,
+ open_media,
+ ref_from_metadata,
+)
+
+# ---------------------------------------------------------------------------
+# A tiny TIFF/EXIF writer — the inverse of the parser under test
+# ---------------------------------------------------------------------------
+
+_ASCII, _SHORT, _LONG, _RATIONAL = 2, 3, 4, 5
+
+
+class _TiffBuilder:
+ """Assembles a little-endian TIFF block with IFD0, Exif and GPS sub-IFDs.
+
+ Offsets are computed rather than hand-counted so a new tag in one test
+ cannot silently corrupt the layout of another.
+ """
+
+ def __init__(self) -> None:
+ self.ifd0: list[tuple[int, int, object]] = []
+ self.exif: list[tuple[int, int, object]] = []
+ self.gps: list[tuple[int, int, object]] = []
+
+ def add(self, where: str, tag: int, field_type: int, value: object) -> None:
+ getattr(self, where).append((tag, field_type, value))
+
+ def _encode(self, field_type: int, value: object) -> tuple[int, bytes]:
+ if field_type == _ASCII:
+ raw = str(value).encode("ascii") + b"\x00"
+ return len(raw), raw
+ if field_type == _SHORT:
+ return 1, struct.pack("<H", int(value)) + b"\x00\x00"
+ if field_type == _LONG:
+ return 1, struct.pack("<I", int(value))
+ if field_type == _RATIONAL:
+ parts = list(value) # type: ignore[arg-type]
+ return len(parts), b"".join(
+ struct.pack("<II", int(round(part * 10000)), 10000) for part in parts
+ )
+ raise AssertionError(f"unsupported field type {field_type}")
+
+ def _ifd(self, entries: list[tuple[int, int, object]], start: int) -> tuple[bytes, bytes]:
+ """One directory plus its overflow area, laid out from ``start``."""
+ directory_size = 2 + 12 * len(entries) + 4
+ overflow = bytearray()
+ body = bytearray(struct.pack("<H", len(entries)))
+ for tag, field_type, value in sorted(entries, key=lambda item: item[0]):
+ count, raw = self._encode(field_type, value)
+ if len(raw) <= 4:
+ payload = raw.ljust(4, b"\x00")
+ else:
+ payload = struct.pack("<I", start + directory_size + len(overflow))
+ overflow += raw
+ body += struct.pack("<HHI", tag, field_type, count) + payload
+ body += struct.pack("<I", 0)
+ return bytes(body), bytes(overflow)
+
+ def build(self) -> bytes:
+ header = b"II" + struct.pack("<HI", 42, 8)
+ # Sub-IFDs are laid out after IFD0, so their offsets must be known
+ # before IFD0 is encoded: measure IFD0 with placeholder pointers first.
+ probe = list(self.ifd0)
+ if self.exif:
+ probe.append((0x8769, _LONG, 0))
+ if self.gps:
+ probe.append((0x8825, _LONG, 0))
+ ifd0_body, ifd0_overflow = self._ifd(probe, 8)
+ cursor = 8 + len(ifd0_body) + len(ifd0_overflow)
+
+ entries = list(self.ifd0)
+ exif_block = gps_block = b""
+ if self.exif:
+ body, overflow = self._ifd(self.exif, cursor)
+ exif_block = body + overflow
+ entries.append((0x8769, _LONG, cursor))
+ cursor += len(exif_block)
+ if self.gps:
+ body, overflow = self._ifd(self.gps, cursor)
+ gps_block = body + overflow
+ entries.append((0x8825, _LONG, cursor))
+ cursor += len(gps_block)
+
+ ifd0_body, ifd0_overflow = self._ifd(entries, 8)
+ return header + ifd0_body + ifd0_overflow + exif_block + gps_block
+
+
+def _jpeg_with_exif(tiff: bytes) -> bytes:
+ """A JPEG whose APP1 segment carries ``tiff``, followed by fake scan data."""
+ payload = b"Exif\x00\x00" + tiff
+ segment = b"\xff\xe1" + struct.pack(">H", len(payload) + 2) + payload
+ return b"\xff\xd8" + segment + b"\xff\xda\x00\x08" + b"\x00" * 64
+
+
+def _photo(**fields: object) -> bytes:
+ builder = _TiffBuilder()
+ if "camera" in fields:
+ make, _, model = str(fields["camera"]).partition(" ")
+ builder.add("ifd0", 0x010F, _ASCII, make)
+ builder.add("ifd0", 0x0110, _ASCII, model)
+ if "taken" in fields:
+ builder.add("exif", 0x9003, _ASCII, fields["taken"])
+ if "gps" in fields:
+ latitude, longitude = fields["gps"] # type: ignore[misc]
+ builder.add("gps", 0x0001, _ASCII, "N" if latitude >= 0 else "S")
+ builder.add("gps", 0x0002, _RATIONAL, _dms(abs(latitude)))
+ builder.add("gps", 0x0003, _ASCII, "E" if longitude >= 0 else "W")
+ builder.add("gps", 0x0004, _RATIONAL, _dms(abs(longitude)))
+ return _jpeg_with_exif(builder.build())
+
+
+def _dms(value: float) -> list[float]:
+ degrees = int(value)
+ minutes_full = (value - degrees) * 60
+ minutes = int(minutes_full)
+ seconds = (minutes_full - minutes) * 60
+ return [float(degrees), float(minutes), round(seconds, 4)]
+
+
+# ---------------------------------------------------------------------------
+# Capture time — the reason this module exists
+# ---------------------------------------------------------------------------
+
+
+def test_the_capture_date_survives_being_copied():
+ """The camera's date, not the filesystem's."""
+ meta = media_metadata(_photo(taken="2019:08:14 17:03:22"), "image")
+ assert meta["captured_at"] == "2019-08-14T17:03:22Z"
+
+
+def test_the_camera_is_named_when_the_file_says_so():
+ meta = media_metadata(_photo(camera="Apple iPhone15,3", taken="2024:01:02 03:04:05"), "image")
+ assert meta["camera"] == "Apple iPhone15,3"
+ assert meta["captured_at"] == "2024-01-02T03:04:05Z"
+
+
+def test_where_the_photo_was_taken_comes_back_as_signed_degrees():
+ """Hemisphere letters, not negative numbers, is how EXIF stores it."""
+ meta = media_metadata(_photo(taken="2020:05:01 12:00:00", gps=(48.8584, 2.2945)), "image")
+ assert abs(meta["latitude"] - 48.8584) < 0.001
+ assert abs(meta["longitude"] - 2.2945) < 0.001
+
+
+def test_a_southern_western_location_is_negative():
+ meta = media_metadata(_photo(taken="2020:05:01 12:00:00", gps=(-22.9519, -43.2105)), "image")
+ assert meta["latitude"] < 0
+ assert meta["longitude"] < 0
+
+
+# ---------------------------------------------------------------------------
+# Never raising is a hard requirement: this runs inside an import walk
+# ---------------------------------------------------------------------------
+
+
+def test_a_photo_without_exif_yields_nothing_rather_than_failing():
+ assert media_metadata(b"\xff\xd8\xff\xdb\x00C\x00" + b"\x00" * 100, "image") == {}
+
+
+def test_truncated_and_garbage_exif_is_survived():
+ """A partially downloaded photo is a normal thing to find in a folder."""
+ full = _photo(taken="2019:08:14 17:03:22", gps=(1.0, 2.0))
+ for cut in (8, 20, 40, 64, len(full) // 2, len(full) - 3):
+ assert isinstance(media_metadata(full[:cut], "image"), dict)
+ garbage = b"\xff\xd8\xff\xe1\xff\xffExif\x00\x00II*\x00\xff\xff\xff\xff"
+ assert media_metadata(garbage, "image") == {}
+
+
+def test_a_declared_entry_count_far_past_the_data_cannot_walk_off_the_end():
+ """A malformed count is the one field that could turn this into a scanner."""
+ tiff = bytearray(_photo(taken="2019:08:14 17:03:22"))
+ index = tiff.find(b"II*\x00")
+ struct.pack_into("<H", tiff, index + 8, 60000) # IFD0 claims 60k entries
+ assert isinstance(media_metadata(bytes(tiff), "image"), dict)
+
+
+def test_sound_and_video_report_nothing_rather_than_guessing():
+ """Duration lives in format-specific headers; a guess would be a claim
+ without a source, and the transcript is the content that matters."""
+ assert media_metadata(b"OggS\x00\x02", "audio") == {}
+ assert media_metadata(b"\x00\x00\x00\x18ftypisom", "video") == {}
+
+
+# ---------------------------------------------------------------------------
+# The extractor hands the metadata through
+# ---------------------------------------------------------------------------
+
+
+def test_extract_text_attaches_the_capture_date_to_a_photo():
+ """A picture is findable by WHEN long before any model describes it."""
+ result = extract_text(_photo(taken="2021:12:24 18:30:00"), filename="IMG_1.jpg")
+ assert result.media_kind == "image"
+ assert result.ok is False
+ assert result.meta["captured_at"] == "2021-12-24T18:30:00Z"
+
+
+# ---------------------------------------------------------------------------
+# Getting back to the bytes later
+# ---------------------------------------------------------------------------
+
+
+def test_a_reference_survives_a_round_trip_through_item_metadata():
+ ref = MediaRef(kind="zip-entry", path="C:/take.zip", entry="Photos/a.jpg")
+ restored = ref_from_metadata(dict(ref.as_metadata()))
+ assert restored == ref
+ assert restored.display_name == "a.jpg"
+
+
+def test_an_item_written_before_references_existed_simply_has_none():
+ """Older items must read as "cannot enrich", never as a crash."""
+ assert ref_from_metadata({}) is None
+ assert ref_from_metadata({"media_ref_kind": "cloud", "media_ref_path": "x"}) is None
+ assert ref_from_metadata({"media_ref_kind": "file"}) is None
+
+
+def test_a_file_that_was_deleted_between_capture_and_enrichment_is_not_an_error(tmp_path: Path):
+ assert open_media(MediaRef(kind="file", path=str(tmp_path / "gone.jpg"))) is None
+
+
+def test_a_photo_inside_an_archive_is_reopened_and_the_archive_is_released(tmp_path: Path):
+ """The handle matters: one leak per photo exhausts descriptors partway
+ through a Takeout import, and on Windows it locks the archive."""
+ archive_path = tmp_path / "take.zip"
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("Photos/a.jpg", b"\xff\xd8payload")
+ archive_path.write_bytes(buffer.getvalue())
+
+ stream = open_media(MediaRef(kind="zip-entry", path=str(archive_path), entry="Photos/a.jpg"))
+ assert stream is not None
+ with stream:
+ assert stream.read() == b"\xff\xd8payload"
+ # The archive is closed, so the file can be replaced — which is what a
+ # leaked handle would prevent on Windows.
+ archive_path.write_bytes(b"replaced")
+
+
+def test_a_missing_entry_inside_a_real_archive_is_not_an_error(tmp_path: Path):
+ archive_path = tmp_path / "take.zip"
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("Photos/a.jpg", b"x")
+ archive_path.write_bytes(buffer.getvalue())
+ assert open_media(MediaRef(kind="zip-entry", path=str(archive_path), entry="nope.jpg")) is None