Coverage for app / documents / image_sources.py: 95%

168 statements  

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

1"""Where an image link is fetched from — one class per host family that needs 

2more than the link itself. 

3 

4A model links an image the way it has seen it linked: a file's page, a 

5thumbnail, the original upload. Most links are fetched as they are. A host 

6that renders its files to a raster on request is better asked for that 

7rendering: Wikimedia draws an SVG as a PNG at a width it is asked for, and 

8serves a large photo the same way, so a document gets a picture it can embed 

9instead of a vector it would refuse or a file far larger than a page needs. 

10 

11The link the model wrote stays the image's key and its credit; only the 

12request changes. Adding a host is one registered class. 

13 

14A host can also say what a link that named no file most likely meant 

15(:meth:`ImageSource.find_missing`). A model writes a Wikimedia file name from 

16memory as often as from a search, and gets it slightly wrong: its case or 

17spelling (``Café_Wall_illusion.svg`` for ``Café_Wall_Illusion.svg``), its 

18format (``Rubin_vase.svg`` for ``Rubin vase.png``) or its wording 

19(``Hermann_grid.svg`` for ``HermannGrid.svg``). The host's file of that name, 

20or one whose name holds every word of it, is fetched instead — and the 

21document then links that file. Anything less certain is offered back to the 

22model as close matches, never swapped in: a model that never took one (gpt-oss, 

23three passes running) left its document with three images missing. 

24""" 

25 

26from __future__ import annotations 

27 

28import re 

29import unicodedata 

30from abc import ABC, abstractmethod 

31from collections.abc import Awaitable, Callable 

32from dataclasses import dataclass, field 

33from typing import Any 

34from urllib.parse import SplitResult, quote, unquote, urlencode, urlsplit 

35 

36#: Stock-photo libraries: a preview of theirs is licensed for sale and 

37#: watermarked, and is never embedded (the user's decision, 28 October 2026, 

38#: after an illusions PDF embedded iStock's). Matched with their subdomains 

39#: (``web_domains.covered``: ``media.istockphoto.com``). 

40STOCK_PHOTO_HOSTS: tuple[str, ...] = ( 

41 "istockphoto.com", 

42 "gettyimages.com", 

43 "gettyimages.co.uk", 

44 "shutterstock.com", 

45 "alamy.com", 

46 "stock.adobe.com", 

47 "ftcdn.net", 

48 "dreamstime.com", 

49 "depositphotos.com", 

50 "123rf.com", 

51) 

52 

53 

54def is_stock_photo(src: str) -> bool: 

55 """Whether ``src`` is a stock-photo library's file (``STOCK_PHOTO_HOSTS``).""" 

56 from app.util.web_domains import covered 

57 

58 try: 

59 host = (urlsplit(src).hostname or "").lower() 

60 except ValueError: 

61 return False 

62 return bool(host) and covered(host, STOCK_PHOTO_HOSTS) 

63 

64 

65#: A JSON GET under the caller's own fetcher and web policy: the parsed 

66#: object, or None when it could not be had. 

67Lookup = Callable[[str], Awaitable[dict[str, Any] | None]] 

68 

69 

70@dataclass(frozen=True) 

71class MissingFile: 

72 """What a link that named no file most likely meant.""" 

73 

74 #: The file to fetch instead, when one is certain enough. 

75 fetch_url: str | None = None 

76 #: That file's own page — what the document links in place of the link 

77 #: that named nothing. 

78 file_page: str | None = None 

79 #: Otherwise, links to close matches for the model to choose from. 

80 suggestions: list[str] = field(default_factory=list) 

81 

82 

83class ImageSource(ABC): 

84 """A host family whose image links are fetched another way.""" 

85 

86 #: How the source is named to a model and a person. 

87 label: str 

88 

89 @abstractmethod 

90 def handles(self, parts: SplitResult) -> bool: 

91 """Whether this source owns the link.""" 

92 

93 @abstractmethod 

94 def fetch_url(self, parts: SplitResult, settings: Any) -> str | None: 

95 """What to fetch for the link, or None to fetch it as it is.""" 

96 

97 async def find_missing( 

98 self, parts: SplitResult, settings: Any, lookup: Lookup 

99 ) -> MissingFile | None: 

100 """When the link named no file (404): the file of the same name, or 

101 close matches. None when the host offers no way to look.""" 

102 return None 

103 

104 

105#: Every source, keyed by label. 

106IMAGE_SOURCES: dict[str, ImageSource] = {} 

107 

108 

109def register(cls: type[ImageSource]) -> type[ImageSource]: 

110 """Class decorator adding one source to the registry.""" 

111 instance = cls() 

112 if instance.label in IMAGE_SOURCES: 

113 raise RuntimeError(f"Image source '{instance.label}' is already registered.") 

114 IMAGE_SOURCES[instance.label] = instance 

115 return cls 

116 

117 

118def source_for(src: str) -> ImageSource | None: 

119 """The source that owns the link ``src``, if any.""" 

120 try: 

121 parts = urlsplit(src) 

122 except ValueError: 

123 return None 

124 return next((s for s in IMAGE_SOURCES.values() if s.handles(parts)), None) 

125 

126 

127def fetch_url(src: str, settings: Any) -> str: 

128 """The URL to fetch for the image linked as ``src``.""" 

129 source = source_for(src) 

130 if source is None: 

131 return src 

132 return source.fetch_url(urlsplit(src), settings) or src 

133 

134 

135def same_name_key(name: str) -> str: 

136 """A file name as two spellings of the same name share it: case folded, 

137 accents dropped, and any run of spaces, underscores and hyphens one 

138 space. ``Café_Wall_illusion.svg`` and ``Cafe Wall Illusion.svg`` share 

139 one; ``Penrose_stairs.svg`` and ``Penrosetreppe.svg`` do not.""" 

140 return re.sub(r"[\s_\-]+", " ", _bare(unquote(name))).strip().casefold() 

141 

142 

143def _bare(text: str) -> str: 

144 decomposed = unicodedata.normalize("NFKD", text) 

145 return "".join(c for c in decomposed if not unicodedata.combining(c)) 

146 

147 

148#: A file name's extension: a short run of letters and digits after its last dot. 

149_EXTENSION = re.compile(r"\.[A-Za-z0-9]{1,5}$") 

150#: Where camelCase turns a word: ``HermannGrid`` is "Hermann Grid". 

151_CAMEL = re.compile(r"(?<=[a-z])(?=[A-Z])") 

152 

153 

154def _stem(name: str) -> str: 

155 """A file name without its extension.""" 

156 return _EXTENSION.sub("", unquote(name)) 

157 

158 

159def same_stem_key(name: str) -> str: 

160 """:func:`same_name_key` of the name without its extension: the same 

161 picture's name in any format (``Rubin_vase.svg``, ``Rubin vase.png``).""" 

162 return same_name_key(_stem(name)) 

163 

164 

165def name_words(name: str) -> list[str]: 

166 """The words of a file name, without its extension: camelCase split, 

167 accents dropped, case folded. ``HermannGrid.svg`` is 

168 ``["hermann", "grid"]``.""" 

169 text = _CAMEL.sub(" ", _bare(_stem(name))) 

170 return [w for w in re.split(r"[^0-9A-Za-z]+", text.casefold()) if w] 

171 

172 

173# --------------------------------------------------------------------------- 

174# Wikimedia 

175# --------------------------------------------------------------------------- 

176 

177_COMMONS = "commons.wikimedia.org" 

178_UPLOADS = "upload.wikimedia.org" 

179#: A language (or project) Wikipedia, desktop or mobile. 

180_WIKIPEDIA = re.compile(r"^([a-z][a-z0-9-]{1,30})(?:\.m)?\.wikipedia\.org$") 

181#: The namespaces a file page is under ("Image:" is the old alias). 

182_FILE_PAGE = re.compile(r"^(?:File|Image):(.+)$") 

183_FILE_PATH = "Special:FilePath/" 

184#: upload.wikimedia.org/wikipedia/<wiki>/[thumb/]<a>/<ab>/<name>[/<size>px-…] 

185_UPLOAD_PATH = re.compile( 

186 r"^/wikipedia/([a-z][a-z0-9-]{1,30})/(?:thumb/)?[0-9a-f]/[0-9a-f]{2}/([^/]+)" 

187) 

188 

189 

190#: How many search hits are read, and how many offered as close matches. 

191_SEARCH_LIMIT = 5 

192_SUGGESTIONS = 3 

193_FILE_PREFIX = "File:" 

194#: Commons' search keyword for pictures only: photographs and drawings, never 

195#: the PDFs, scans and videos a name's words also find. 

196_PICTURES = "filetype:bitmap|drawing" 

197#: A name of fewer words than this is matched by its whole name only: one 

198#: word ("Penrose") is too many pictures' name. 

199_MIN_MATCH_WORDS = 2 

200 

201 

202def _file_path_url(site: str, name: str, settings: Any) -> str: 

203 width = int(settings.document_image_wikimedia_width) 

204 return f"https://{site}/wiki/{_FILE_PATH}{name}?width={width}" 

205 

206 

207def _file_name(raw: str) -> str | None: 

208 """A file's name as Special:FilePath takes it, or None when it is not 

209 one (a file name never holds a slash).""" 

210 name = unquote(raw).strip().replace(" ", "_") 

211 if not name or "/" in name or len(name) > 255: 

212 return None 

213 return quote(name, safe="") 

214 

215 

216def _file_page(title: str) -> str: 

217 """A Commons file's own page — its picture, author and licence.""" 

218 return f"https://{_COMMONS}/wiki/{quote(_FILE_PREFIX + title.replace(' ', '_'), safe=':')}" 

219 

220 

221#: Wikimedia Commons, for a caller that searches it (``tools/web/commons``). 

222COMMONS = _COMMONS 

223#: Commons' search keyword for pictures only. 

224PICTURES_ONLY = _PICTURES 

225 

226 

227def commons_picture(title: str, settings: Any) -> tuple[str, str] | None: 

228 """A Commons file's own page and the picture link that embeds it 

229 (``Special:FilePath`` at the document width), for a file named 

230 ``title`` (without ``File:``); None when the name is no file's.""" 

231 name = _file_name(title) 

232 if name is None: 

233 return None 

234 return _file_page(title), _file_path_url(_COMMONS, name, settings) 

235 

236 

237def _closest(wanted: str, titles: list[str]) -> str | None: 

238 """Which of Commons' ``titles`` (best first) is the file ``wanted`` 

239 meant, or None when none is certain enough to fetch in its place: 

240 

241 1. the one file of the same name — case, accents and separators aside; 

242 2. else the first of the same name in another format; 

243 3. else the first whose name holds every word of ``wanted``, when it has 

244 at least :data:`_MIN_MATCH_WORDS` (``Hermann_grid.svg`` → 

245 ``HermannGrid.svg``). 

246 """ 

247 same = [t for t in titles if same_name_key(t) == same_name_key(wanted)] 

248 if len(same) == 1: 

249 return same[0] 

250 stem = same_stem_key(wanted) 

251 other_format = next((t for t in titles if same_stem_key(t) == stem), None) 

252 if other_format is not None: 

253 return other_format 

254 words = set(name_words(wanted)) 

255 if len(words) < _MIN_MATCH_WORDS: 

256 return None 

257 return next((t for t in titles if words <= set(name_words(t))), None) 

258 

259 

260@register 

261class Wikimedia(ImageSource): 

262 """Wikimedia Commons and Wikipedia: any link to a file — its page, an 

263 original upload, a thumbnail — is fetched from ``Special:FilePath`` at a 

264 standard width, which Wikimedia answers with a raster (an SVG drawn as a 

265 PNG) from its own cache.""" 

266 

267 label = "Wikimedia" 

268 

269 def handles(self, parts: SplitResult) -> bool: 

270 host = (parts.hostname or "").lower() 

271 return parts.scheme == "https" and ( 

272 host in (_COMMONS, "commons.m.wikimedia.org", _UPLOADS) 

273 or bool(_WIKIPEDIA.match(host)) 

274 ) 

275 

276 def fetch_url(self, parts: SplitResult, settings: Any) -> str | None: 

277 found = self._file(parts) 

278 if found is None: 

279 return None 

280 site, name = found 

281 return _file_path_url(site, name, settings) 

282 

283 async def find_missing( 

284 self, parts: SplitResult, settings: Any, lookup: Lookup 

285 ) -> MissingFile | None: 

286 found = self._file(parts) 

287 if found is None: 

288 return None 

289 _, name = found 

290 wanted = unquote(name) 

291 stem = _stem(wanted).replace("_", " ") 

292 titles = await self._search(lookup, f"{stem} {_PICTURES}") 

293 match = _closest(wanted, titles) 

294 if match is not None: 

295 file_name = _file_name(match) 

296 if file_name is not None: 

297 return MissingFile( 

298 fetch_url=_file_path_url(_COMMONS, file_name, settings), 

299 file_page=_file_page(match), 

300 ) 

301 if not titles: 

302 # Nothing has every word: the pictures with any of them, to 

303 # choose from — never fetched on a guess. 

304 words = name_words(wanted) 

305 if len(words) > 1: 

306 titles = await self._search(lookup, f"{' OR '.join(words)} {_PICTURES}") 

307 return MissingFile(suggestions=[_file_page(t) for t in titles[:_SUGGESTIONS]]) 

308 

309 @staticmethod 

310 async def _search(lookup: Lookup, terms: str) -> list[str]: 

311 """The file names Commons' search finds for ``terms``, best first.""" 

312 query = urlencode( 

313 { 

314 "action": "query", 

315 "list": "search", 

316 "srnamespace": 6, # File: 

317 "srlimit": _SEARCH_LIMIT, 

318 "srsearch": terms, 

319 "format": "json", 

320 "formatversion": 2, 

321 } 

322 ) 

323 answer = await lookup(f"https://{_COMMONS}/w/api.php?{query}") 

324 hits = (answer or {}).get("query", {}).get("search", []) 

325 return [ 

326 h["title"][len(_FILE_PREFIX) :] 

327 for h in hits 

328 if isinstance(h, dict) 

329 and isinstance(h.get("title"), str) 

330 and h["title"].startswith(_FILE_PREFIX) 

331 ] 

332 

333 def _file(self, parts: SplitResult) -> tuple[str, str] | None: 

334 """The wiki a link's file lives on, and its name as 

335 ``Special:FilePath`` takes it — or None when the link names no file.""" 

336 host = (parts.hostname or "").lower() 

337 if host == _UPLOADS: 

338 match = _UPLOAD_PATH.match(parts.path) 

339 if not match: 

340 return None 

341 wiki, raw = match.groups() 

342 site = _COMMONS if wiki == "commons" else f"{wiki}.wikipedia.org" 

343 else: 

344 site = _COMMONS if "wikimedia" in host else self._desktop(host) 

345 raw = self._from_wiki_link(parts) 

346 if raw is None: 

347 return None 

348 name = _file_name(raw) 

349 return (site, name) if name is not None else None 

350 

351 @staticmethod 

352 def _desktop(host: str) -> str: 

353 match = _WIKIPEDIA.match(host) 

354 return f"{match.group(1)}.wikipedia.org" if match else host 

355 

356 @staticmethod 

357 def _from_wiki_link(parts: SplitResult) -> str | None: 

358 # An article's media viewer: …/wiki/Article#/media/File:Name.jpg 

359 if parts.fragment.startswith("/media/"): 

360 page = _FILE_PAGE.match(unquote(parts.fragment[len("/media/") :])) 

361 return page.group(1) if page else None 

362 if not parts.path.startswith("/wiki/"): 

363 return None 

364 title = unquote(parts.path[len("/wiki/") :]) 

365 if title.startswith(_FILE_PATH): 

366 return title[len(_FILE_PATH) :] 

367 page = _FILE_PAGE.match(title) 

368 return page.group(1) if page else None