Coverage for app / documents / images.py: 93%

354 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""The images a document shows: fetched once, checked, normalised, stored. 

2 

3``render_document`` embeds each image its body links (``![alt](https://…)``) 

4when the document is made, so the PDF and the document card can draw them 

5later without anything leaving the platform again: 

6 

71. the link is rewritten where its host renders files to a raster on request 

8 (``image_sources``); 

92. it is fetched with the hardened ``UrlFetcher`` under the agent's own web 

10 domain policy — https only, every redirect hop re-resolved to a public 

11 address, a byte cap; 

123. the bytes are identified by their magic number, then decoded by Pillow 

13 with only that format's decoder, refused past a pixel count *before* 

14 decoding (a decompression bomb is a small file that decodes to gigabytes); 

154. the picture is re-encoded: EXIF orientation applied, first frame only, 

16 transparency flattened onto white, the long edge capped, and every byte of 

17 metadata (camera, GPS) dropped — what is stored is a PNG or a JPEG this 

18 module wrote, never the file a site served; 

195. it is stored once under the SHA-256 of those bytes 

20 (``app/util/document_images.py``), which is the id the fence records. 

21 

22A link to a file its host does not have is looked up there 

23(``ImageSource.find_missing``): the host's file of that name, or one whose 

24name holds every word of it, is embedded instead, and the document is 

25relinked to that file (``found_as``, ``markdown.relink_images``). 

26 

27Every image ends with an outcome. Whatever could not be embedded is told to 

28the model (:meth:`EmbedReport.for_model`) so it can link something better in 

29the same turn; it is drawn as "Image not available" meanwhile. Nothing here 

30raises. 

31 

32Logs carry counts and problem names only — never a link, an alt text or any 

33of the document (``app/util/logger.py``). 

34""" 

35 

36from __future__ import annotations 

37 

38import asyncio 

39import io 

40import json 

41import logging 

42import warnings 

43from collections import Counter 

44from dataclasses import dataclass, replace 

45from enum import StrEnum 

46from typing import Any, Protocol 

47from urllib.parse import urlsplit 

48 

49import httpx 

50from PIL import Image, ImageOps, UnidentifiedImageError 

51from pydantic import ValidationError 

52 

53from app.common.settings import get_settings 

54from app.tools.web.fetch import ( 

55 FetchError, 

56 FetchTooLarge, 

57 Resolver, 

58 UnsafeUrlError, 

59 UrlFetcher, 

60 system_resolver, 

61) 

62from app.tools.web.models import SearchType 

63from app.tools.web.policy import DomainPolicy 

64from app.util import document_images, vocab 

65 

66from .formats import ACCEPT_HEADER, ACCEPTED_FORMATS, BY_MIME 

67from .image_sources import fetch_url as source_fetch_url 

68from .image_sources import IMAGE_SOURCES, is_stock_photo, source_for 

69from .markdown import ImageRef, image_refs, normalised_link, relink_images 

70from .pdf import EmbeddedImage 

71from .spec import MAX_DOCUMENT_IMAGES, DocumentImage, StoredDocument 

72 

73logger = logging.getLogger(__name__) 

74 

75 

76# --------------------------------------------------------------------------- 

77# Why an image was not embedded 

78# --------------------------------------------------------------------------- 

79 

80 

81class ImageProblem(StrEnum): 

82 not_a_link = "not_a_link" 

83 blocked = "blocked" 

84 unreachable = "unreachable" 

85 http_error = "http_error" 

86 too_large = "too_large" 

87 web_page = "web_page" 

88 vector = "vector" 

89 not_an_image = "not_an_image" 

90 unsupported_format = "unsupported_format" 

91 too_many_pixels = "too_many_pixels" 

92 damaged = "damaged" 

93 over_limit = "over_limit" 

94 out_of_time = "out_of_time" 

95 not_stored = "not_stored" 

96 stock_photo = "stock_photo" 

97 

98 

99_FORMATS = vocab.one_of(ACCEPTED_FORMATS, quote="") 

100#: The hosts whose files are linked by name (``image_sources``). 

101_SOURCES = vocab.one_of(IMAGE_SOURCES, quote="") 

102 

103#: What the model is told for each problem. 

104_PROBLEM_TEXT: dict[ImageProblem, str] = { 

105 ImageProblem.not_a_link: "not an https link to an image file", 

106 ImageProblem.blocked: ( 

107 "that address may not be fetched — a private address, or a site " 

108 "outside this agent's web policy or its workspace's rules" 

109 ), 

110 ImageProblem.unreachable: "the site could not be reached", 

111 ImageProblem.http_error: "the site did not return it", 

112 ImageProblem.too_large: "the file is too large", 

113 ImageProblem.web_page: ( 

114 "the link is a web page, not an image file — link the image itself" 

115 ), 

116 ImageProblem.vector: f"an SVG drawing, which cannot be embedded — link a {_FORMATS} version", 

117 ImageProblem.not_an_image: "the link did not return an image", 

118 ImageProblem.unsupported_format: f"not a {_FORMATS} image", 

119 ImageProblem.too_many_pixels: "the picture is too large to decode", 

120 ImageProblem.damaged: "the image file is damaged", 

121 ImageProblem.over_limit: f"a document embeds at most {MAX_DOCUMENT_IMAGES} images", 

122 ImageProblem.out_of_time: "it took too long to fetch", 

123 ImageProblem.not_stored: "it could not be stored — try again", 

124 ImageProblem.stock_photo: ( 

125 "a stock-photo library's preview, licensed and watermarked — use an " 

126 f"open-licence image instead, {_SOURCES} first" 

127 ), 

128} 

129vocab.check(_PROBLEM_TEXT, ImageProblem) 

130 

131#: Problems a second try might not have: never remembered for the run. 

132_TRANSIENT = frozenset( 

133 {ImageProblem.unreachable, ImageProblem.out_of_time, ImageProblem.not_stored} 

134) 

135 

136 

137#: The most a host's lookup answer may be. 

138_LOOKUP_MAX_BYTES = 256 * 1024 

139 

140 

141class _Refused(Exception): 

142 def __init__(self, problem: ImageProblem) -> None: 

143 super().__init__(problem.value) 

144 self.problem = problem 

145 

146 

147# --------------------------------------------------------------------------- 

148# Normalising 

149# --------------------------------------------------------------------------- 

150 

151#: Other image formats, recognised only to say so. 

152_OTHER_IMAGES: tuple[tuple[bytes, int], ...] = ( 

153 (b"II*\x00", 0), # TIFF 

154 (b"MM\x00*", 0), 

155 (b"BM", 0), # BMP 

156 (b"ftypavif", 4), 

157 (b"ftypheic", 4), 

158 (b"ftypheix", 4), 

159 (b"ftypmif1", 4), 

160) 

161 

162 

163@dataclass(frozen=True) 

164class Normalised: 

165 data: bytes 

166 media_type: str 

167 width: int 

168 height: int 

169 

170 

171def _refusal(data: bytes, media_type: str | None, declared_type: str) -> _Refused: 

172 """Why bytes that are not an accepted raster were refused.""" 

173 head = data[:4096].lstrip().lower() 

174 if "svg" in declared_type or b"<svg" in head: 

175 return _Refused(ImageProblem.vector) 

176 if "html" in declared_type or head.startswith((b"<!doctype html", b"<html")): 

177 return _Refused(ImageProblem.web_page) 

178 if media_type is not None or any( 

179 data[offset : offset + len(sig)] == sig for sig, offset in _OTHER_IMAGES 

180 ): 

181 return _Refused(ImageProblem.unsupported_format) 

182 return _Refused(ImageProblem.not_an_image) 

183 

184 

185def _flatten(picture: Image.Image) -> Image.Image: 

186 """The picture on white, in RGB or greyscale. Transparent line art — an 

187 SVG Wikimedia drew, say — would otherwise vanish on a dark card.""" 

188 if picture.mode in ("RGBA", "LA", "PA") or ( 

189 picture.mode == "P" and "transparency" in picture.info 

190 ): 

191 rgba = picture.convert("RGBA") 

192 white = Image.new("RGBA", rgba.size, (255, 255, 255, 255)) 

193 return Image.alpha_composite(white, rgba).convert("RGB") 

194 if picture.mode not in ("RGB", "L"): 

195 return picture.convert("RGB") 

196 return picture 

197 

198 

199def _encode(picture: Image.Image, fmt: str) -> bytes: 

200 out = io.BytesIO() 

201 if fmt == "JPEG": 

202 picture.save(out, "JPEG", quality=85, optimize=True) 

203 else: 

204 picture.save(out, "PNG") 

205 return out.getvalue() 

206 

207 

208def normalise(data: bytes, *, settings: Any, declared_type: str = "") -> Normalised: 

209 """``data`` as a stored copy: a PNG or JPEG this module wrote, with no 

210 metadata. Raises :class:`_Refused` with the reason when it cannot be one.""" 

211 media_type = document_images.sniff(data) 

212 fmt = BY_MIME.get(media_type or "") 

213 if fmt is None: 

214 raise _refusal(data, media_type, (declared_type or "").lower()) 

215 with warnings.catch_warnings(): 

216 # Pillow's own bomb guard warns before it refuses; refuse at once. 

217 warnings.simplefilter("error", Image.DecompressionBombWarning) 

218 try: 

219 picture = Image.open(io.BytesIO(data), formats=[fmt.pillow]) 

220 width, height = picture.size 

221 if width < 1 or height < 1: 

222 raise _Refused(ImageProblem.damaged) 

223 if width * height > settings.document_image_max_pixels: 

224 raise _Refused(ImageProblem.too_many_pixels) 

225 picture.load() # the first frame of an animation 

226 picture = ImageOps.exif_transpose(picture) 

227 except _Refused: 

228 raise 

229 except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc: 

230 raise _Refused(ImageProblem.too_many_pixels) from exc 

231 except ( 

232 UnidentifiedImageError, 

233 OSError, 

234 ValueError, 

235 SyntaxError, 

236 EOFError, 

237 ) as exc: 

238 raise _Refused(ImageProblem.damaged) from exc 

239 picture = _flatten(picture) 

240 edge = settings.document_image_max_edge_px 

241 picture.thumbnail((edge, edge), Image.Resampling.LANCZOS) 

242 target = "JPEG" if fmt.pillow == "JPEG" else "PNG" 

243 encoded = _encode(picture, target) 

244 if target == "PNG" and len(encoded) > settings.document_image_max_stored_bytes: 

245 target, encoded = "JPEG", _encode(picture, "JPEG") 

246 if len(encoded) > settings.document_image_max_stored_bytes: 

247 raise _Refused(ImageProblem.too_large) 

248 return Normalised( 

249 encoded, 

250 "image/jpeg" if target == "JPEG" else "image/png", 

251 picture.width, 

252 picture.height, 

253 ) 

254 

255 

256# --------------------------------------------------------------------------- 

257# Storing and loading 

258# --------------------------------------------------------------------------- 

259 

260 

261class ImageStore(Protocol): 

262 def exists(self, asset: str) -> bool: ... 

263 

264 def put(self, asset: str, data: bytes, media_type: str) -> None: ... 

265 

266 def get(self, asset: str) -> bytes | None: ... 

267 

268 

269class MinioImageStore: 

270 """The knowledge bucket, under ``document-images/``. Connects on first use.""" 

271 

272 def exists(self, asset: str) -> bool: 

273 from app.util import minio_client 

274 

275 return minio_client.exists_named(document_images.object_key(asset)) 

276 

277 def put(self, asset: str, data: bytes, media_type: str) -> None: 

278 from app.util import minio_client 

279 

280 minio_client.put_named(document_images.object_key(asset), data, media_type) 

281 

282 def get(self, asset: str) -> bytes | None: 

283 from app.util import minio_client 

284 

285 return minio_client.read_named(document_images.object_key(asset)) 

286 

287 

288def _pixel_size(data: bytes) -> tuple[int, int] | None: 

289 try: 

290 with Image.open(io.BytesIO(data), formats=["PNG", "JPEG"]) as picture: 

291 width, height = picture.size 

292 except (UnidentifiedImageError, OSError, ValueError, SyntaxError): 

293 return None 

294 if not (1 <= width <= 4096 and 1 <= height <= 4096): 

295 return None 

296 return width, height 

297 

298 

299def load_for_pdf( 

300 document: StoredDocument, store: ImageStore | None = None 

301) -> dict[str, EmbeddedImage]: 

302 """The stored copies of ``document``'s images, keyed by each image's link, 

303 for :func:`~.pdf.render_pdf`. Only bytes that hash to their id and are a 

304 PNG or JPEG are kept; anything missing or unreadable is left out, and the 

305 PDF draws that image as its alt text.""" 

306 if not document.images: 

307 return {} 

308 store = store or MinioImageStore() 

309 loaded: dict[str, EmbeddedImage] = {} 

310 unreadable = 0 

311 for image in document.images: 

312 try: 

313 data = store.get(image.asset) 

314 except Exception: # noqa: BLE001 — storage down: alt text, not a failed PDF 

315 data = None 

316 size = ( 

317 _pixel_size(data) if document_images.verified(image.asset, data) else None 

318 ) 

319 if data is None or size is None: 

320 unreadable += 1 

321 continue 

322 loaded[image.src] = EmbeddedImage(data, *size) 

323 if unreadable: 

324 logger.warning( 

325 "[documents] %d of %d stored images could not be drawn", 

326 unreadable, 

327 len(document.images), 

328 ) 

329 return loaded 

330 

331 

332# --------------------------------------------------------------------------- 

333# Embedding 

334# --------------------------------------------------------------------------- 

335 

336#: Where a run keeps what each image link came to, so synthesis, a revision 

337#: or a skill's document step rendering the same document fetches nothing 

338#: twice. Each of those builds its own tool; the run is what they share. 

339CONFIG_KEY = "__chainr_document_images" 

340 

341 

342@dataclass(frozen=True) 

343class _Fetched: 

344 image: Normalised | None = None 

345 asset: str | None = None 

346 problem: ImageProblem | None = None 

347 status: int | None = None 

348 #: Close matches the link's host offered for a file it does not have. 

349 suggestions: tuple[str, ...] = () 

350 #: The page of the file embedded in place of one the link named but its 

351 #: host does not have; None when the link's own file was embedded. 

352 found_as: str | None = None 

353 

354 

355class ImageCache(dict[str, _Fetched]): 

356 """A run's image outcomes, by the URL fetched.""" 

357 

358 

359def current_cache() -> ImageCache | None: 

360 """The cache of the run this code is part of, or None outside a run.""" 

361 from langchain_core.runnables.config import var_child_runnable_config 

362 

363 config = var_child_runnable_config.get() 

364 if not isinstance(config, dict): 

365 return None 

366 found = (config.get("configurable") or {}).get(CONFIG_KEY) 

367 return found if isinstance(found, ImageCache) else None 

368 

369 

370@dataclass(frozen=True) 

371class EmbedOutcome: 

372 ref: ImageRef 

373 image: DocumentImage | None = None 

374 problem: ImageProblem | None = None 

375 status: int | None = None 

376 suggestions: tuple[str, ...] = () 

377 #: The file page the image was found as (``_Fetched.found_as``). 

378 found_as: str | None = None 

379 

380 

381#: The most failures listed back to the model. 

382_MAX_LISTED = 10 

383_MAX_SRC_SHOWN = 160 

384 

385 

386@dataclass(frozen=True) 

387class EmbedReport: 

388 outcomes: tuple[EmbedOutcome, ...] 

389 

390 @property 

391 def images(self) -> list[DocumentImage]: 

392 return [o.image for o in self.outcomes if o.image is not None] 

393 

394 @property 

395 def relinks(self) -> dict[str, str]: 

396 """Each embedded image found under another name: its link as the 

397 body has it → the page of the file embedded.""" 

398 return { 

399 o.ref.src: o.found_as 

400 for o in self.outcomes 

401 if o.image is not None and o.found_as 

402 } 

403 

404 def apply(self, body: str) -> tuple[str, list[DocumentImage]]: 

405 """``body`` linking the file each image was found as, and the stored 

406 images keyed by the links it now has — once each. An image the body 

407 could not be relinked for keeps the link it had.""" 

408 body, replaced = relink_images(body, self.relinks) 

409 images: dict[str, DocumentImage] = {} 

410 for outcome in self.outcomes: 

411 image = outcome.image 

412 if image is None: 

413 continue 

414 if outcome.found_as and outcome.ref.src not in replaced: 

415 image = image.model_copy(update={"src": outcome.ref.src}) 

416 images.setdefault(image.src, image) 

417 return body, list(images.values()) 

418 

419 def for_model(self) -> str | None: 

420 """What the model is told about the images, or None when the body 

421 linked none.""" 

422 if not self.outcomes: 

423 return None 

424 failed = [o for o in self.outcomes if o.image is None] 

425 lines = [f"Images: {len(self.images)} of {len(self.outcomes)} embedded."] 

426 found = [o for o in self.outcomes if o.image is not None and o.found_as] 

427 if found: 

428 lines.append( 

429 "Linked to a file that does not exist, so the closest file of " 

430 "that name was embedded, and the document now links it:" 

431 ) 

432 lines.extend( 

433 f"- {_shown(o.ref.src)} → {_shown(o.found_as or '')}" for o in found 

434 ) 

435 if not failed: 

436 return "\n".join(lines) 

437 lines.append( 

438 'Not embedded — each reads "Image not available" unless you fix ' 

439 "it and call render_document again:" 

440 ) 

441 for outcome in failed[:_MAX_LISTED]: 

442 src = _shown(outcome.ref.src) 

443 problem = outcome.problem or ImageProblem.not_an_image 

444 reason = _PROBLEM_TEXT[problem] 

445 if problem is ImageProblem.http_error and outcome.status: 

446 reason = f"{reason} (HTTP {outcome.status})" 

447 if outcome.suggestions: 

448 reason = f"{reason}; close matches: {', '.join(outcome.suggestions)}" 

449 lines.append(f"- ![{outcome.ref.alt}]({src}) — {reason}") 

450 if len(failed) > _MAX_LISTED: 

451 lines.append(f"- … and {len(failed) - _MAX_LISTED} more") 

452 lines.append( 

453 "Fix them in one more render_document call: a close match above, a " 

454 f"{_SOURCES} file linked by name, or an image file ({_FORMATS}) from " 

455 f'web_search with search_type "{vocab.member(SearchType, "images")}" — ' 

456 "never a guessed path. If one cannot be fixed, say in your answer " 

457 "which image is missing." 

458 ) 

459 return "\n".join(lines) 

460 

461 

462def _shown(src: str) -> str: 

463 return src if len(src) <= _MAX_SRC_SHOWN else src[:_MAX_SRC_SHOWN] + "…" 

464 

465 

466def _https(src: str) -> bool: 

467 try: 

468 parts = urlsplit(src) 

469 except ValueError: 

470 return False 

471 return parts.scheme == "https" and bool(parts.hostname) 

472 

473 

474class DocumentImageEmbedder: 

475 """Embeds the images one agent's documents link, under its web policy.""" 

476 

477 def __init__( 

478 self, 

479 policy: DomainPolicy, 

480 *, 

481 settings: Any | None = None, 

482 store: ImageStore | None = None, 

483 resolver: Resolver = system_resolver, 

484 transport: httpx.AsyncBaseTransport | None = None, 

485 ) -> None: 

486 self._settings = settings or get_settings() 

487 self._store = store or MinioImageStore() 

488 self._fetcher = UrlFetcher( 

489 policy, 

490 max_bytes=self._settings.document_image_max_bytes, 

491 user_agent=self._settings.url_fetch_user_agent, 

492 timeout_s=self._settings.document_image_fetch_timeout_s, 

493 resolver=resolver, 

494 transport=transport, 

495 ) 

496 #: Asks a host's API what a missing file most likely was 

497 #: (``ImageSource.find_missing``): JSON, small, the same policy. 

498 self._api = UrlFetcher( 

499 policy, 

500 max_bytes=_LOOKUP_MAX_BYTES, 

501 user_agent=self._settings.url_fetch_user_agent, 

502 timeout_s=self._settings.document_image_fetch_timeout_s, 

503 resolver=resolver, 

504 transport=transport, 

505 ) 

506 #: Outside a run (a tool called on its own), the tool's own memory. 

507 self._cache = ImageCache() 

508 

509 async def embed(self, body: str) -> EmbedReport: 

510 refs = image_refs(body) 

511 outcomes: dict[int, EmbedOutcome] = {} 

512 work: list[tuple[int, ImageRef]] = [] 

513 for index, ref in enumerate(refs): 

514 if index >= MAX_DOCUMENT_IMAGES: 

515 outcomes[index] = EmbedOutcome(ref, problem=ImageProblem.over_limit) 

516 elif not _https(ref.src): 

517 outcomes[index] = EmbedOutcome(ref, problem=ImageProblem.not_a_link) 

518 elif is_stock_photo(ref.src): 

519 # Refused before any fetch: a stock preview is never embedded. 

520 outcomes[index] = EmbedOutcome(ref, problem=ImageProblem.stock_photo) 

521 else: 

522 work.append((index, ref)) 

523 if work: 

524 outcomes.update(await self._embed_all(work)) 

525 for index, ref in work: 

526 outcomes.setdefault( 

527 index, EmbedOutcome(ref, problem=ImageProblem.out_of_time) 

528 ) 

529 report = EmbedReport(tuple(outcomes[i] for i in range(len(refs)))) 

530 if refs: 

531 problems = Counter(o.problem.value for o in report.outcomes if o.problem) 

532 logger.info( 

533 "[documents] images linked=%d embedded=%d problems=%s", 

534 len(refs), 

535 len(report.images), 

536 dict(sorted(problems.items())), 

537 ) 

538 return report 

539 

540 async def _embed_all( 

541 self, work: list[tuple[int, ImageRef]] 

542 ) -> dict[int, EmbedOutcome]: 

543 gate = asyncio.Semaphore(max(1, int(self._settings.document_image_concurrency))) 

544 

545 async def one(ref: ImageRef) -> EmbedOutcome: 

546 async with gate: 

547 fetched = await self._fetch(ref.src) 

548 return self._outcome(ref, fetched) 

549 

550 tasks = {asyncio.create_task(one(ref)): (index, ref) for index, ref in work} 

551 done, pending = await asyncio.wait( 

552 tasks, timeout=self._settings.document_image_budget_s 

553 ) 

554 for task in pending: 

555 task.cancel() 

556 if pending: 

557 await asyncio.gather(*pending, return_exceptions=True) 

558 results: dict[int, EmbedOutcome] = {} 

559 for task in done: 

560 index, ref = tasks[task] 

561 try: 

562 results[index] = task.result() 

563 except Exception: # noqa: BLE001 — never fail the document for an image 

564 results[index] = EmbedOutcome(ref, problem=ImageProblem.unreachable) 

565 return results 

566 

567 @staticmethod 

568 def _outcome(ref: ImageRef, fetched: _Fetched) -> EmbedOutcome: 

569 if fetched.image is None or fetched.asset is None: 

570 return EmbedOutcome( 

571 ref, 

572 problem=fetched.problem, 

573 status=fetched.status, 

574 suggestions=fetched.suggestions, 

575 ) 

576 src = ref.src 

577 if fetched.found_as: 

578 # The document will link the file it shows (``relink_images``): 

579 # the stored copy is keyed by that link as the parser reads it. 

580 src = normalised_link(fetched.found_as) 

581 try: 

582 image = DocumentImage( 

583 src=src, 

584 asset=fetched.asset, 

585 media_type=fetched.image.media_type, # type: ignore[arg-type] 

586 width=fetched.image.width, 

587 height=fetched.image.height, 

588 ) 

589 except ValidationError: 

590 return EmbedOutcome(ref, problem=ImageProblem.not_a_link) 

591 return EmbedOutcome(ref, image=image, found_as=fetched.found_as) 

592 

593 async def _fetch(self, src: str) -> _Fetched: 

594 url = source_fetch_url(src, self._settings) 

595 cache = current_cache() 

596 if cache is None: 

597 cache = self._cache 

598 if url in cache: 

599 return cache[url] 

600 fetched = await self._fetch_and_store(url) 

601 if fetched.problem is ImageProblem.http_error and fetched.status == 404: 

602 fetched = await self._find_missing(src, fetched) 

603 if fetched.problem not in _TRANSIENT: 

604 cache[url] = fetched 

605 return fetched 

606 

607 async def _find_missing(self, src: str, missing: _Fetched) -> _Fetched: 

608 """A link that named no file: the host's file of that name, or one 

609 whose name holds every word of it (``found_as``) — else its close 

610 matches, for the model to choose from.""" 

611 source = source_for(src) 

612 if source is None: 

613 return missing 

614 try: 

615 found = await source.find_missing( 

616 urlsplit(src), self._settings, self._lookup 

617 ) 

618 except Exception: # noqa: BLE001 — a lookup that fails is no lookup 

619 found = None 

620 if found is None: 

621 return missing 

622 if found.fetch_url: 

623 again = await self._fetch_and_store(found.fetch_url) 

624 if again.image is not None: 

625 return replace(again, found_as=found.file_page) 

626 if found.file_page: 

627 return replace(missing, suggestions=(found.file_page,)) 

628 return replace(missing, suggestions=tuple(found.suggestions)) 

629 

630 async def _lookup(self, url: str) -> dict[str, Any] | None: 

631 try: 

632 resource = await self._api.fetch( 

633 url, headers={"Accept": "application/json"} 

634 ) 

635 # An API's response, not a model's reply: read exactly. 

636 answer = json.loads(resource.body) 

637 except Exception: # noqa: BLE001 — unreachable, refused or not JSON 

638 return None 

639 return answer if isinstance(answer, dict) else None 

640 

641 async def _fetch_and_store(self, url: str) -> _Fetched: 

642 try: 

643 resource = await self._fetcher.fetch(url, headers={"Accept": ACCEPT_HEADER}) 

644 except UnsafeUrlError: 

645 return _Fetched(problem=ImageProblem.blocked) 

646 except FetchTooLarge: 

647 return _Fetched(problem=ImageProblem.too_large) 

648 except FetchError as exc: 

649 if exc.status: 

650 return _Fetched(problem=ImageProblem.http_error, status=exc.status) 

651 return _Fetched(problem=ImageProblem.unreachable) 

652 except Exception: # noqa: BLE001 — httpx and DNS failures alike 

653 return _Fetched(problem=ImageProblem.unreachable) 

654 try: 

655 image = await asyncio.to_thread( 

656 normalise, 

657 resource.body, 

658 settings=self._settings, 

659 declared_type=resource.content_type, 

660 ) 

661 except _Refused as refused: 

662 return _Fetched(problem=refused.problem) 

663 asset = document_images.asset_id_of(image.data) 

664 try: 

665 if not await asyncio.to_thread(self._store.exists, asset): 

666 await asyncio.to_thread( 

667 self._store.put, asset, image.data, image.media_type 

668 ) 

669 except Exception: # noqa: BLE001 — storage down: the model may retry 

670 return _Fetched(problem=ImageProblem.not_stored) 

671 return _Fetched(image=image, asset=asset)