Coverage for app / tools / web / commons.py: 95%
79 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"""An image search asks Wikimedia Commons first.
3The document tool and the prompts tell a model to show open-licence images,
4Wikimedia Commons first, and refuse stock-photo previews. The engines' image
5verticals rarely return Commons: in scenario run 7, seven image searches
6(some naming "Wikimedia Commons") returned an Etsy listing, abc-people.com
7and a Guardian photo, and two of five images would not embed. So an image
8search of the web also asks Commons' own search, the one a document's
9missing file is looked up with (``documents.image_sources``), and its files
10come first.
12Each is a file page (with its author and licence) and a picture link the
13document tool embeds (``Special:FilePath``, a raster at the document width).
14Commons is asked through the run's hardened fetcher and web policy, so a
15workspace whose Tools rules leave Commons out never asks it. Its descriptions
16are third-party text, shown as any result's snippet.
17"""
19from __future__ import annotations
21import html
22import json
23import logging
24import re
25from typing import Any
26from urllib.parse import urlencode
28from app.common.settings import get_settings
29from app.documents import image_sources
30from app.tools.web.fetch import UrlFetcher
31from app.tools.web.models import SearchResult
32from app.tools.web.policy import DomainPolicy, Verdict
34logger = logging.getLogger(__name__)
36#: How large an API answer may be: a few results' metadata.
37_MAX_BYTES = 512 * 1024
38#: Seconds to wait for Commons: the engines are asked at the same time.
39_TIMEOUT_S = 8.0
40#: What a model writes to aim an engine at Commons, which Commons' own
41#: search needs no telling: ``site:`` clauses and the site's name.
42_AIMED_AT = re.compile(
43 r"\bsite:\S+|\bwikimedia\s+commons\b|\bwikimedia\b|\bwiki\s+commons\b",
44 re.IGNORECASE,
45)
46_TAG = re.compile(r"<[^>]*>")
47_DESCRIPTION_CHARS = 240
50def asks_commons(policy: DomainPolicy, domains: list[str] | None) -> bool:
51 """Whether a search may ask Commons: its policy (and the domains the
52 call named) permit Commons' pages."""
53 url = f"https://{image_sources.COMMONS}/wiki/"
54 return policy.verdict(url, domains) is Verdict.PERMITTED
57def terms(query: str) -> str:
58 """``query`` as Commons is asked it: without what aimed an engine at
59 Commons."""
60 return " ".join(_AIMED_AT.sub(" ", query).split())
63def _plain(value: Any) -> str:
64 """An ``extmetadata`` value, which is HTML, as text."""
65 text = value.get("value") if isinstance(value, dict) else value
66 if not isinstance(text, str):
67 return ""
68 return " ".join(html.unescape(_TAG.sub(" ", text)).split())
71def _clip(text: str, limit: int) -> str:
72 if len(text) <= limit:
73 return text
74 return text[:limit].rsplit(" ", 1)[0] + "…"
77def results(answer: Any, settings: Any) -> list[SearchResult]:
78 """Commons' API answer as search results, in its search order."""
79 pages = ((answer or {}).get("query") or {}).get("pages") or []
80 found: list[tuple[int, SearchResult]] = []
81 for page in pages if isinstance(pages, list) else []:
82 if not isinstance(page, dict):
83 continue
84 title = str(page.get("title") or "")
85 if not title.startswith("File:"):
86 continue
87 name = title[len("File:") :]
88 picture = image_sources.commons_picture(name, settings)
89 if picture is None:
90 continue
91 file_page, image = picture
92 info = (page.get("imageinfo") or [{}])[0]
93 info = info if isinstance(info, dict) else {}
94 meta = info.get("extmetadata") or {}
95 meta = meta if isinstance(meta, dict) else {}
96 licence = _plain(meta.get("LicenseShortName"))
97 artist = _plain(meta.get("Artist"))
98 credit = ", ".join(
99 part
100 for part in (
101 f"Licence: {licence}" if licence else "",
102 f"by {_clip(artist, 80)}" if artist else "",
103 )
104 if part
105 )
106 description = _clip(_plain(meta.get("ImageDescription")), _DESCRIPTION_CHARS)
107 snippet = " — ".join(part for part in (description, credit) if part)
108 width, height = info.get("width"), info.get("height")
109 stem = name.rsplit(".", 1)[0] if "." in name else name
110 found.append(
111 (
112 int(page.get("index") or 0),
113 SearchResult(
114 title=stem.replace("_", " "),
115 url=file_page,
116 snippet=snippet,
117 source="Wikimedia Commons",
118 image_url=image,
119 width=width if isinstance(width, int) else None,
120 height=height if isinstance(height, int) else None,
121 ),
122 )
123 )
124 found.sort(key=lambda pair: pair[0])
125 return [result for _, result in found]
128def _request_url(query: str, count: int, settings: Any) -> str:
129 params = {
130 "action": "query",
131 "format": "json",
132 "formatversion": 2,
133 "generator": "search",
134 "gsrnamespace": 6, # File:
135 "gsrlimit": count,
136 "gsrsearch": f"{query} {image_sources.PICTURES_ONLY}",
137 "prop": "imageinfo",
138 "iiprop": "size|extmetadata",
139 "iiextmetadatafilter": "LicenseShortName|Artist|ImageDescription",
140 }
141 return f"https://{image_sources.COMMONS}/w/api.php?{urlencode(params)}"
144async def search(
145 query: str,
146 count: int,
147 policy: DomainPolicy,
148 *,
149 settings: Any | None = None,
150 fetcher: UrlFetcher | None = None,
151) -> list[SearchResult]:
152 """The pictures Commons' search finds for ``query``, best first: none
153 when it cannot be asked, has none, or does not answer in time."""
154 settings = settings or get_settings()
155 words = terms(query)
156 if not words:
157 return []
158 fetcher = fetcher or UrlFetcher(
159 policy,
160 max_bytes=_MAX_BYTES,
161 user_agent=settings.url_fetch_user_agent,
162 timeout_s=_TIMEOUT_S,
163 )
164 try:
165 resource = await fetcher.fetch(
166 _request_url(words, count, settings),
167 headers={"Accept": "application/json"},
168 )
169 # An API's answer, not a model's reply: read exactly.
170 answer = json.loads(resource.body)
171 except Exception as exc: # noqa: BLE001 — unreachable, refused or not JSON
172 logger.info("[web_search] commons not asked (%s)", type(exc).__name__)
173 return []
174 found = results(answer, settings)
175 logger.info("[web_search] commons pictures=%d", len(found))
176 return found
179__all__ = ["asks_commons", "results", "search", "terms"]