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 what a picture SAYS, not just what it looks like
Ruben Lütke67ecb67e1b34
diff --git a/jarvis/ultrawiki/media_enrich.py b/jarvis/ultrawiki/media_enrich.pyindex c21463d5f6..d4ceb8dc38 100644--- a/jarvis/ultrawiki/media_enrich.py+++ b/jarvis/ultrawiki/media_enrich.py@@ -34,8 +34,14 @@ log = logging.getLogger(__name__)__all__ = ["CANNOT_SEE_MARKER",+ "NO_TEXT_MARKER",+ "PROGRAM_DIR_NAMES","EnrichResult",+ "ImageReading","describe_image",+ "image_prompt",+ "parse_image_answer",+ "skip_reason_for_image","transcribe_recording","vision_chain",]@@ -52,28 +58,164 @@ MAX_AUDIO_BYTES = 24 * 1024 * 1024#: Characters kept from a description or transcript.MAX_DESCRIPTION_CHARS = 4000++#: Characters kept from ONE picture's transcription + description together.+#: Larger than a description cap on purpose: a screenshot of a page carries a+#: page of words, and cutting it to caption length would discard exactly the+#: content this stage exists to recover.+MAX_READING_CHARS = 24_000MAX_TRANSCRIPT_CHARS = 40_000_DEFAULT_TIMEOUT_S = 90.0_VISION_SYSTEM = (- "You describe images for a personal search index. Write plainly and only "- "about what is actually visible."+ "You read and describe images for a personal search index. Transcribe "+ "what is written, and describe only what is actually visible.")-_VISION_PROMPT = (- "Describe this image so its owner can find it again by searching in their "- "own words months from now.\n\n"- "Cover, in one short paragraph: what kind of picture it is (photo, "- "screenshot, document scan, diagram), the setting, the notable objects, "- "roughly how many people are in it and what they are doing, and the mood "- "or occasion if it is evident. Then, if the image contains readable text, "- "add a line 'Text:' followed by that text verbatim.\n\n"- "Do not guess names of people or places. Do not invent details you cannot "- "see. Write in English.\n\n"- f"If no image reached you, reply with exactly {CANNOT_SEE_MARKER} and "- "nothing else."+#: The exact token a model answers in the TEXT block when a picture carries no+#: writing. Without one, a model narrates a sunset into the transcript slot and+#: an invented caption becomes indexed content.+NO_TEXT_MARKER = "NO_TEXT_IN_IMAGE"++#: Block headings of the answer. TEXT comes FIRST on purpose: a reply that+#: runs into the token ceiling loses its tail, and the tail must never be the+#: transcription — that is the part no other stage can reconstruct.+_TEXT_HEADING = "TEXT:"+_DESCRIPTION_HEADING = "DESCRIPTION:"+++def image_prompt() -> str:+ """What the model is asked of one picture: read it first, then describe it.++ A description alone ("a screenshot of an application window") is+ unsearchable by anything its owner would actually type; for screenshots,+ scans and photographed notes the writing IS the content. So the answer is+ two blocks, transcription first.+ """+ return (+ "This picture belongs to someone's personal archive. Answer in exactly "+ "two blocks, in this order.\n\n"+ f"{_TEXT_HEADING}\n"+ "Every word visible in the image, transcribed VERBATIM - keep the "+ "original language, spelling, line breaks and reading order. Include "+ "menus, labels, captions, handwriting and numbers. Do not summarise, "+ "translate or correct anything. If the picture contains no readable "+ f"writing at all, put exactly {NO_TEXT_MARKER} here and nothing else.\n\n"+ f"{_DESCRIPTION_HEADING}\n"+ "One or two sentences: what kind of picture it is (photo, screenshot, "+ "scan, diagram), the setting, the notable objects, roughly how many "+ "people are in it and what they are doing.\n\n"+ "Do not guess names of people or places, and never invent detail you "+ "cannot see. Write the description in English; leave the transcription "+ "in its own language.\n\n"+ f"If no image reached you, reply with exactly {CANNOT_SEE_MARKER} and "+ "nothing else."+ )+++#: Pictures below this are decoration, not content: icons, sprites, spacers,+#: cache thumbnails. Each one would still cost a full model call.+MIN_IMAGE_BYTES = 20 * 1024++#: Path SEGMENTS that mean "this file belongs to a program, not to the user".+#: Matched segment-wise and case-blind, so ``my-database-notes`` survives while+#: ``data/`` does not. The measured motivation: one real Desktop held 218,419+#: wake-word debug clips under ``data/wake_debug`` - the image side has the+#: same shape in caches and build output.+PROGRAM_DIR_NAMES: frozenset[str] = frozenset(+ {+ "data",+ "cache",+ ".cache",+ "caches",+ "logs",+ "dist",+ "build",+ "target",+ "out",+ "node_modules",+ "__pycache__",+ "site-packages",+ "appdata",+ "thumbnails",+ "coverage",+ })+# Deliberately NOT here: "tmp" / "temp". Every downloaded photo passes through+# a temp folder on some machine, and on this one every test path lives under+# one — a rule that broad stops being a noise filter and starts being the+# reason nothing is ever described.+++def skip_reason_for_image(name: str, *, size_bytes: int) -> str:+ """Why this picture is not worth a model call, or ``""`` to read it.++ The cheap gate in front of the expensive stage. Deliberately only two+ rules — size and provenance — because both are decidable from the item+ itself, offline, without opening the file.+ """+ if size_bytes < MIN_IMAGE_BYTES:+ return (+ f"the picture is too small to hold readable content "+ f"({size_bytes} bytes); icons and thumbnails are skipped"+ )+ parts = [p.strip().lower() for p in str(name).replace("\\", "/").split("/")]+ for segment in parts[:-1]: # the filename itself is never a folder+ if segment in PROGRAM_DIR_NAMES:+ return (+ f"it sits in a program folder ({segment}/), which holds "+ "generated files rather than your own pictures"+ )+ return ""+++@dataclass(slots=True)+class ImageReading:+ """What one picture turned out to say, split from how it looks."""++ text: str = ""+ description: str = ""++ def as_body(self) -> str:+ """The indexed body: what was READ first, then what it looks like."""+ return "\n\n".join(part for part in (self.text, self.description) if part)+++def parse_image_answer(answer: str) -> ImageReading:+ """Split the two-block reply; tolerate a model that drops the scaffolding.++ An answer with no headings is treated as a description rather than as a+ transcription: mistaking prose for verbatim text would quietly file a+ model's paraphrase as if it were the words on the page.+ """+ raw = str(answer or "").strip()+ if not raw:+ return ImageReading()+ upper = raw.upper()+ text_at = upper.find(_TEXT_HEADING)+ desc_at = upper.find(_DESCRIPTION_HEADING)+ if text_at < 0 and desc_at < 0:+ return ImageReading(description=_clean(raw))+ if text_at < 0:+ preamble = _clean(raw[:desc_at])+ body = _clean(raw[desc_at + len(_DESCRIPTION_HEADING) :])+ return ImageReading(description=_join(preamble, body))+ text_end = desc_at if desc_at > text_at else len(raw)+ text = _clean(raw[text_at + len(_TEXT_HEADING) : text_end])+ described = _clean(raw[desc_at + len(_DESCRIPTION_HEADING) :]) if desc_at > text_at else ""+ # Anything ahead of the first heading is description a model wrote before+ # following the format. Dropping it would silently lose the whole+ # description for every model that answers description-first.+ description = _join(_clean(raw[:text_at]), described)+ if NO_TEXT_MARKER in text.upper():+ text = ""+ return ImageReading(text=text, description=description)+++def _join(*parts: str) -> str:+ return "\n\n".join(part for part in parts if part)+#: MIME types by media kind, from the filename. Providers need one, and a#: wrong one is rejected by some APIs, so an unknown suffix falls back to the@@ -215,7 +357,7 @@ async def describe_image(messages=(BrainMessage(role="user",- content=_VISION_PROMPT,+ content=image_prompt(),images=(ImageBlock(mime=_image_mime(filename),@@ -226,7 +368,9 @@ async def describe_image(),system=_VISION_SYSTEM,temperature=0.1, # description, not creativity- max_tokens=900,+ # A full screen of text is several thousand tokens; the old 900 was+ # sized for a caption and would cut a transcription off mid-sentence.+ max_tokens=4000,stream=True,)@@ -242,8 +386,21 @@ async def describe_image(if result is None:return EnrichResult(reason="no provider that can read images returned a usable description")aggregated, provider = result- text = _clean(str(getattr(aggregated, "text", "") or ""))[:MAX_DESCRIPTION_CHARS]- return EnrichResult(text=text, ok=True, provider=provider)+ reading = parse_image_answer(str(getattr(aggregated, "text", "") or ""))+ # The transcription is bounded like a document, not like a caption: a+ # screenshot of a page legitimately carries more words than a description+ # ever would, and truncating it to caption length would lose the content+ # this stage exists to recover.+ body = reading.as_body()[:MAX_READING_CHARS]+ return EnrichResult(+ text=body,+ ok=True,+ provider=provider,+ meta={+ "read_chars": len(reading.text),+ "described_chars": len(reading.description),+ },+ )def _aggregate(chunks: Any) -> Any:diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.pyindex b692522202..d37f5ea38f 100644--- a/jarvis/ultrawiki/pipeline.py+++ b/jarvis/ultrawiki/pipeline.py@@ -873,6 +873,18 @@ class PipelineWorker:filename = reference.display_nameif kind == "image":+ # The cheap gate BEFORE the expensive call: most picture files on a+ # real machine are icons, sprites and cache thumbnails, and each one+ # would still cost a full model call. Permanent, because a 200-byte+ # icon never becomes worth reading.+ skip = media_enrich.skip_reason_for_image(+ self._media_path_for(item, filename), size_bytes=len(data)+ )+ if skip:+ await self._record_media_outcome(+ item, text="", reason=skip, retryable=False+ )+ returnresult = await media_enrich.describe_image(data, filename=filename, cfg=self._cfg)@@ -900,6 +912,19 @@ class PipelineWorker:item, text=result.text, reason="", provider=result.provider, kind=kind)+ @staticmethod+ def _media_path_for(item: dict[str, Any], filename: str) -> str:+ """The path the skip rules judge: the one INSIDE the chosen source.++ Deliberately the ``external_id`` and never the absolute path. An+ absolute path is mostly the machine's own structure - on Windows every+ temp file sits under ``AppData`` - so judging it would skip files the+ user deliberately pointed at. The external id is what the user's own+ folder looks like, which is what "this belongs to a program" must be+ read from.+ """+ return str(item.get("external_id") or "") or filename+async def _record_media_outcome(self,item: dict[str, Any],diff --git a/tests/unit/ultrawiki/test_media_enrich.py b/tests/unit/ultrawiki/test_media_enrich.pyindex ec227abd7c..72f432ce72 100644--- a/tests/unit/ultrawiki/test_media_enrich.py+++ b/tests/unit/ultrawiki/test_media_enrich.py@@ -285,3 +285,166 @@ async def test_silence_is_a_permanent_outcome_not_a_retry():def test_enrich_result_defaults_to_retryable():"""A new failure mode must default to "try again", never to "give up"."""assert EnrichResult().retryable is True+++# ---------------------------------------------------------------------------+# Reading a picture, not just describing it+# ---------------------------------------------------------------------------+#+# A description answers "what does this look like". For the pictures a real+# folder is full of - screenshots, scanned pages, photographed whiteboards -+# the content IS the text, and a paragraph about "a screenshot of an+# application window" is unsearchable by anything the user would actually+# type. So the reading comes first and verbatim, and the description is the+# short second half.+++class TestPictureText:+ async def test_the_prompt_asks_for_the_text_before_the_description(self):+ """Order is load-bearing: a truncated answer must keep the TEXT."""+ prompt = media_enrich.image_prompt()+ assert prompt.index("TEXT") < prompt.index("DESCRIPTION")+ assert "verbatim" in prompt.lower()++ async def test_the_prompt_offers_a_way_to_say_there_is_no_text(self):+ """Without an explicit token, a model invents captions for a sunset."""+ assert media_enrich.NO_TEXT_MARKER in media_enrich.image_prompt()++ def test_a_two_block_answer_splits_into_text_and_description(self):+ answer = (+ "TEXT:\n"+ "Invoice 2026-114\nTotal due: 48,20 EUR\n\n"+ "DESCRIPTION:\n"+ "A scanned invoice on white paper."+ )+ parsed = media_enrich.parse_image_answer(answer)+ assert parsed.text == "Invoice 2026-114\nTotal due: 48,20 EUR"+ assert parsed.description == "A scanned invoice on white paper."++ def test_the_no_text_marker_yields_a_description_only(self):+ answer = (+ f"TEXT:\n{media_enrich.NO_TEXT_MARKER}\n\n"+ "DESCRIPTION:\nTwo people on a beach at sunset."+ )+ parsed = media_enrich.parse_image_answer(answer)+ assert parsed.text == ""+ assert "beach" in parsed.description++ def test_an_answer_without_headings_counts_as_the_description(self):+ """Models drop the scaffolding sometimes; that must not lose content."""+ parsed = media_enrich.parse_image_answer("A mountain range at dawn.")+ assert parsed.text == ""+ assert parsed.description == "A mountain range at dawn."++ def test_prose_before_the_first_heading_survives_as_description(self):+ """Some models answer description-first whatever the prompt asks.++ Everything ahead of the first heading has to be kept: dropping it+ would silently lose the entire description for those models.+ """+ parsed = media_enrich.parse_image_answer(+ "A photo of two people on a beach, holding surfboards.\n"+ "TEXT: Malibu 2019"+ )+ assert parsed.text == "Malibu 2019"+ assert "surfboards" in parsed.description++ def test_the_stored_body_leads_with_the_words_that_were_read(self):+ """Search hits the beginning hardest, and the text is the real content."""+ parsed = media_enrich.parse_image_answer(+ "TEXT:\nQuarterly ledger reconciliation\n\n"+ "DESCRIPTION:\nA screenshot of a spreadsheet."+ )+ body = parsed.as_body()+ assert body.index("Quarterly ledger") < body.index("screenshot")++ def test_a_picture_with_no_text_still_stores_its_description(self):+ parsed = media_enrich.parse_image_answer(+ f"TEXT:\n{media_enrich.NO_TEXT_MARKER}\n\nDESCRIPTION:\nA red bicycle."+ )+ assert parsed.as_body().strip() == "A red bicycle."++ async def test_a_screenshot_answer_keeps_all_of_its_text(+ self, all_credential_ready, monkeypatch+ ):+ """End to end: what the model read must survive into the result."""+ lines = "\n".join(f"Row {n}: telescope maintenance" for n in range(40))++ async def _fake_complete(**kwargs: Any) -> Any:+ answer = kwargs["aggregate"](+ f"TEXT:\n{lines}\n\nDESCRIPTION:\nA screenshot of a table."+ )+ assert kwargs["validate"](answer)+ return answer, "seeing"++ import jarvis.memory.wiki.provider_chain as chain_mod++ monkeypatch.setattr(chain_mod, "complete_with_fallback", _fake_complete)+ result = await describe_image(+ PNG, filename="shot.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})+ )+ assert result.ok is True+ assert result.text.count("telescope maintenance") == 40+ assert result.meta.get("read_chars", 0) > 0++ async def test_a_blind_model_answer_is_still_refused(+ self, all_credential_ready, monkeypatch+ ):+ """The invented-photo guard must survive the new answer shape."""++ async def _fake_complete(**kwargs: Any) -> Any:+ answer = kwargs["aggregate"](f"TEXT:\n{CANNOT_SEE_MARKER}")+ assert not kwargs["validate"](answer)+ return None++ import jarvis.memory.wiki.provider_chain as chain_mod++ monkeypatch.setattr(chain_mod, "complete_with_fallback", _fake_complete)+ result = await describe_image(+ PNG, filename="a.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})+ )+ assert result.ok is False+++class TestWhichPicturesAreWorthReading:+ """A model call per file is the expensive part; most files are not worth it.++ Measured on a real Desktop: 218,419 of the audio files were one-second+ wake-word debug clips under a program data folder, and the image side has+ the same shape - icons, sprites and cache thumbnails outnumber the photos.+ """++ def test_a_tiny_icon_is_not_worth_a_model_call(self):+ skip = media_enrich.skip_reason_for_image("icon.png", size_bytes=900)+ assert skip+ assert "small" in skip.lower()++ def test_an_ordinary_screenshot_is_worth_reading(self):+ assert media_enrich.skip_reason_for_image("shot.png", size_bytes=400_000) == ""++ def test_a_picture_inside_a_program_data_folder_is_skipped(self):+ skip = media_enrich.skip_reason_for_image(+ "Personal Jarvis/data/wake_debug/frame.png", size_bytes=400_000+ )+ assert skip+ assert "data" in skip.lower() or "program" in skip.lower()++ def test_a_cache_or_build_folder_is_skipped_too(self):+ for folder in ("cache", "dist", "build", "node_modules", "__pycache__"):+ skip = media_enrich.skip_reason_for_image(+ f"project/{folder}/img.png", size_bytes=400_000+ )+ assert skip, folder++ def test_a_users_own_pictures_folder_is_never_skipped(self):+ for path in ("Pictures/holiday.jpg", "Desktop/scan.png", "Documents/x.jpeg"):+ assert media_enrich.skip_reason_for_image(path, size_bytes=400_000) == "", path++ def test_the_folder_match_is_case_blind(self):+ assert media_enrich.skip_reason_for_image("App/Data/x.png", size_bytes=400_000)++ def test_a_folder_merely_containing_the_word_is_not_skipped(self):+ """'data' as a path SEGMENT, never as a substring of a real name."""+ assert media_enrich.skip_reason_for_image(+ "my-database-notes/diagram.png", size_bytes=400_000+ ) == ""diff --git a/tests/unit/ultrawiki/test_pipeline_media.py b/tests/unit/ultrawiki/test_pipeline_media.pyindex b61cafbfc8..d96b8c7ed6 100644--- a/tests/unit/ultrawiki/test_pipeline_media.py+++ b/tests/unit/ultrawiki/test_pipeline_media.py@@ -13,6 +13,7 @@ Two things are pinned here that nothing else could catch:from __future__ import annotations+import dataclassesfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -23,7 +24,10 @@ from jarvis.ultrawiki.pipeline import PipelineWorkerfrom jarvis.ultrawiki.store import UltraStorefrom jarvis.ultrawiki.types import ConsentState, ItemState, RawItem-PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32+#: A stand-in photo. Sized like a real one on purpose: the enrichment lane+#: skips pictures too small to hold readable content, so a 40-byte fixture+#: would exercise the skip path instead of the description path.+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 80_000#: These workers use an INJECTED distiller, so the production credential probe#: must never run — a test whose outcome depends on the host's keys is the@@ -322,3 +326,76 @@ class TestMediaPass:# content changed, so re-embedding it would be pure waste.assert after["content_hash"] == before["content_hash"]assert after["state"] == before["state"]+++class TestNotEveryPictureIsWorthAModelCall:+ """The cheap gate in front of the expensive stage.++ A photo library is tens of thousands of model calls, and most of the+ picture files on a real machine are not photos at all: icons, sprites and+ cache thumbnails. Measured on one real Desktop, the audio side had 218,419+ one-second wake-word clips under a program data folder — the image side has+ the same shape. Skipping them must be PERMANENT (they will never become+ worth reading) and must state its reason.+ """++ async def test_a_tiny_icon_is_skipped_without_calling_a_model(+ self, store, tmp_path, monkeypatch+ ):+ icon = tmp_path / "icon.png"+ icon.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 200)+ await store.upsert_items("src1", [photo_item(1, icon)])++ async def _never(data, *, filename, cfg, **kwargs):+ raise AssertionError("a 200-byte icon must never reach a model")++ patch_describe(monkeypatch, _never)+ assert await worker_for(store, media_cfg())._media_pass() == 1++ item = await only_item(store)+ assert item["metadata"]["enrich_pending"] is False, "must not be retried"+ assert "small" in item["metadata"]["enrich_error"].lower()++ async def test_a_picture_in_a_program_folder_is_skipped(+ self, store, tmp_path, monkeypatch+ ):+ """Judged on the path INSIDE the chosen folder, not the absolute one."""+ folder = tmp_path / "data" / "wake_debug"+ folder.mkdir(parents=True)+ frame = folder / "frame.png"+ frame.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 60_000)+ item = photo_item(1, frame)+ item = dataclasses.replace(item, external_id="data/wake_debug/frame.png")+ await store.upsert_items("src1", [item])++ async def _never(data, *, filename, cfg, **kwargs):+ raise AssertionError("a program-folder file must never reach a model")++ patch_describe(monkeypatch, _never)+ await worker_for(store, media_cfg())._media_pass()++ item = await only_item(store)+ assert item["metadata"]["enrich_pending"] is False+ assert "program folder" in item["metadata"]["enrich_error"].lower()++ async def test_a_real_photo_still_reaches_the_model(+ self, store, tmp_path, monkeypatch+ ):+ """The gate must not become the reason nothing is ever described."""+ photo = tmp_path / "holiday.png"+ photo.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 400_000)+ await store.upsert_items("src1", [photo_item(1, photo)])+ seen: list[str] = []++ async def _describe(data, *, filename, cfg, **kwargs):+ from jarvis.ultrawiki.media_enrich import EnrichResult++ seen.append(filename)+ return EnrichResult(text="A beach at sunset.", ok=True, provider="seeing")++ patch_describe(monkeypatch, _describe)+ await worker_for(store, media_cfg())._media_pass()++ assert seen == ["holiday.png"]+ item = await only_item(store)+ assert "A beach at sunset." in item["body_raw"]