Coverage for app / documents / formats.py: 100%
9 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""The image formats a document may embed — the one list prompts and the
2normaliser both read.
4An image a document links is fetched once and re-encoded (``images.py``), so
5what matters is which formats can be *decoded* safely: raster formats Pillow
6reads, identified by their bytes. Vector images are refused — SVG is a
7document that can carry script and external references, and drawing one would
8mean parsing untrusted XML here — except where the host renders them to a
9raster itself (``image_sources.py``).
11Prompts name these through ``app.util.vocab`` (``vocab.one_of(ACCEPTED_FORMATS,
12quote="")``), never by hand; ``tests/test_prompt_vocabulary.py`` holds that.
13"""
15from __future__ import annotations
17from dataclasses import dataclass
20@dataclass(frozen=True)
21class RasterFormat:
22 #: Its media type, as its magic bytes are sniffed
23 #: (``app.util.document_images.sniff``).
24 mime: str
25 #: Pillow's name for its decoder — the only one ``Image.open`` may use.
26 pillow: str
29#: The formats an embedded image may arrive in, keyed by the name a model and
30#: a person know each by.
31ACCEPTED_FORMATS: dict[str, RasterFormat] = {
32 "PNG": RasterFormat("image/png", "PNG"),
33 "JPEG": RasterFormat("image/jpeg", "JPEG"),
34 "GIF": RasterFormat("image/gif", "GIF"),
35 "WebP": RasterFormat("image/webp", "WEBP"),
36}
38#: Media type → format, for a sniffed body.
39BY_MIME: dict[str, RasterFormat] = {f.mime: f for f in ACCEPTED_FORMATS.values()}
41#: The ``Accept`` header an image fetch sends: the accepted types, then
42#: anything (a host that ignores ``Accept`` is answered by the sniff).
43ACCEPT_HEADER = ", ".join([*BY_MIME, "*/*;q=0.5"])