1"""Fetch a web page as it is served in a chosen country, with proof of where the request left from.
2
3Shared by the Apify Actors in this folder. The canonical copy is shared/geo_core.py; `dev/sync.sh` copies it into
4each Actor's src/ before a run or a push. Edit it here only.
5
6How a country fetch works
7- Each (URL, country) gets a fresh sticky residential session in that country.
8- Before the page is fetched, the session's exit is checked with an IP-location service through the same session.
9 A session that exits in the wrong country is dropped and a new one is tried. If none lands in the country, the
10 row says `countryUnavailable` and is not charged.
11- A page that comes back as a bot wall or 401/403/407/429/503 is retried from a new address; if every try is
12 blocked, the row says `blocked` and is not charged.
13
14Proxies
15- On Apify: Apify Proxy, group RESIDENTIAL, with the country code and a session id.
16- Locally (development only): a residential provider set through environment variables that stay on this Mac
17 (`GEO_LOCAL_PROXY_TEMPLATE`, `GEO_LOCAL_PROXY_USER`, `GEO_LOCAL_PROXY_PASS`). No login of ours is in the Actors.
18"""
19
20from __future__ import annotations
21
22import datetime as dt
23import json
24import os
25import random
26import re
27import string
28from dataclasses import dataclass, field
29from typing import Any
30from urllib.parse import quote, urljoin, urlsplit
31
32from curl_cffi.requests import AsyncSession
33from markdownify import markdownify
34from selectolax.parser import HTMLParser
35
36
37
38
39
40GEO_SOURCES = (
41 ("https://ipinfo.io/json", "country", "city", "org"),
42 ("https://ifconfig.co/json", "country_iso", "city", "asn_org"),
43 ("https://ipapi.co/json/", "country_code", "city", "org"),
44 ("https://api.country.is/", "country", None, None),
45)
46
47
48
49BLOCK_MARKERS = (
50 "<title>just a moment...</title>", "attention required! | cloudflare", "_cf_chl_opt", "cf-chl-widget",
51 "challenge-platform/h/",
52 "px-captcha", "captcha-delivery.com", "verify you are human", "are you a robot",
53 "request unsuccessful. incapsula", "<title>access denied</title>", "pardon our interruption",
54 "errors.edgesuite.net", "<title>hang tight! routing to checkout",
55)
56BLOCK_STATUSES = {401, 403, 407, 429, 503}
57TEXT_TYPES = ("text/html", "application/xhtml", "text/plain", "application/xml", "text/xml", "application/json",
58 "application/ld+json")
59
60
61LANG_BY_COUNTRY = {
62 "us": "en-US,en;q=0.9", "gb": "en-GB,en;q=0.9", "ie": "en-IE,en;q=0.9", "au": "en-AU,en;q=0.9",
63 "nz": "en-NZ,en;q=0.9", "ca": "en-CA,en;q=0.9,fr-CA;q=0.7", "za": "en-ZA,en;q=0.9,af;q=0.6",
64 "in": "en-IN,en;q=0.9,hi;q=0.7", "sg": "en-SG,en;q=0.9", "de": "de-DE,de;q=0.9,en;q=0.7",
65 "at": "de-AT,de;q=0.9,en;q=0.7", "ch": "de-CH,de;q=0.9,fr-CH;q=0.8,en;q=0.6", "fr": "fr-FR,fr;q=0.9,en;q=0.6",
66 "be": "nl-BE,nl;q=0.9,fr-BE;q=0.8,en;q=0.6", "nl": "nl-NL,nl;q=0.9,en;q=0.7", "es": "es-ES,es;q=0.9,en;q=0.6",
67 "it": "it-IT,it;q=0.9,en;q=0.6", "pt": "pt-PT,pt;q=0.9,en;q=0.6", "br": "pt-BR,pt;q=0.9,en;q=0.6",
68 "mx": "es-MX,es;q=0.9,en;q=0.6", "ar": "es-AR,es;q=0.9,en;q=0.6", "cl": "es-CL,es;q=0.9,en;q=0.6",
69 "co": "es-CO,es;q=0.9,en;q=0.6", "pl": "pl-PL,pl;q=0.9,en;q=0.6", "cz": "cs-CZ,cs;q=0.9,en;q=0.6",
70 "se": "sv-SE,sv;q=0.9,en;q=0.7", "no": "nb-NO,nb;q=0.9,en;q=0.7", "dk": "da-DK,da;q=0.9,en;q=0.7",
71 "fi": "fi-FI,fi;q=0.9,en;q=0.7", "jp": "ja-JP,ja;q=0.9,en;q=0.6", "kr": "ko-KR,ko;q=0.9,en;q=0.6",
72 "cn": "zh-CN,zh;q=0.9,en;q=0.6", "tw": "zh-TW,zh;q=0.9,en;q=0.6", "hk": "zh-HK,zh;q=0.9,en;q=0.7",
73 "tr": "tr-TR,tr;q=0.9,en;q=0.6", "ae": "en-AE,en;q=0.9,ar;q=0.7", "sa": "ar-SA,ar;q=0.9,en;q=0.7",
74 "il": "he-IL,he;q=0.9,en;q=0.7", "ng": "en-NG,en;q=0.9", "ke": "en-KE,en;q=0.9,sw;q=0.6",
75 "eg": "ar-EG,ar;q=0.9,en;q=0.7", "id": "id-ID,id;q=0.9,en;q=0.7", "my": "en-MY,en;q=0.9,ms;q=0.7",
76 "ph": "en-PH,en;q=0.9,fil;q=0.7", "th": "th-TH,th;q=0.9,en;q=0.6", "vn": "vi-VN,vi;q=0.9,en;q=0.6",
77 "ua": "uk-UA,uk;q=0.9,en;q=0.6", "ro": "ro-RO,ro;q=0.9,en;q=0.6", "gr": "el-GR,el;q=0.9,en;q=0.6",
78 "hu": "hu-HU,hu;q=0.9,en;q=0.6", "pk": "en-PK,en;q=0.9,ur;q=0.7",
79}
80
81_SESSION_CHARS = string.ascii_lowercase + string.digits
82
83
84def now_iso() -> str:
85 return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
86
87
88def new_session_id(prefix: str) -> str:
89 return prefix + "".join(random.choice(_SESSION_CHARS) for _ in range(12))
90
91
92def normalise_country(value: Any) -> str | None:
93 code = str(value or "").strip().lower()
94 if code == "uk":
95 code = "gb"
96 return code if re.fullmatch(r"[a-z]{2}", code) else None
97
98
99def url_problem(url: str) -> str | None:
100 """Why a URL can't be fetched, or None. Local and private addresses are refused."""
101 import ipaddress
102
103 parts = urlsplit(url)
104 if parts.scheme not in ("http", "https") or not parts.hostname:
105 return "not an http(s) URL"
106 host = parts.hostname.lower().rstrip(".")
107 if host == "localhost" or host.endswith((".localhost", ".local", ".internal")):
108 return "local addresses are not fetched"
109 try:
110 ip = ipaddress.ip_address(host)
111 except ValueError:
112 return None
113 if not ip.is_global:
114 return "private or reserved addresses are not fetched"
115 return None
116
117
118def _wire(r: Any) -> int:
119 """Bytes on the wire for a response and its redirects (compressed body + headers + request)."""
120 total = 0
121 for x in [*(getattr(r, "history", None) or []), r]:
122 total += int(getattr(x, "request_size", 0) or 0) + int(getattr(x, "response_size", 0) or 0)
123 return total
124
125
126@dataclass
127class Exit:
128 country: str | None = None
129 city: str | None = None
130 network: str | None = None
131 verified: bool = False
132 sources: list[str] = field(default_factory=list)
133 disagreement: str | None = None
134 checked_at: str | None = None
135
136 def as_dict(self) -> dict[str, Any]:
137 return {"country": self.country.upper() if self.country else None, "city": self.city,
138 "network": self.network, "verified": self.verified, "checkedWith": self.sources,
139 "checkedAt": self.checked_at}
140
141
142@dataclass
143class FetchResult:
144 url: str
145 requested_country: str
146 exit: Exit = field(default_factory=Exit)
147 final_url: str | None = None
148 status: int | None = None
149 content_type: str | None = None
150 redirects: list[dict[str, Any]] = field(default_factory=list)
151 blocked: bool = False
152 popups_hidden: int = 0
153 country_unavailable: bool = False
154 error: str | None = None
155 html: str = ""
156 sessions_tried: int = 0
157 wrong_exits: list[str] = field(default_factory=list)
158 wire_bytes: int = 0
159 fetched_at: str | None = None
160
161 @property
162 def delivered(self) -> bool:
163 """A real page from the site, fetched from the requested country: the only case that is charged."""
164 return (self.exit.verified and not self.country_unavailable and not self.blocked and self.error is None
165 and self.status is not None and self.status < 400 and self.is_text)
166
167 @property
168 def is_text(self) -> bool:
169 ct = (self.content_type or "text/html").lower()
170 return any(ct.startswith(t) for t in TEXT_TYPES)
171
172 def base_row(self) -> dict[str, Any]:
173 return {
174 "url": self.url,
175 "country": self.requested_country,
176 "delivered": self.delivered,
177 "status": self.status,
178 "finalUrl": self.final_url,
179 "redirects": self.redirects,
180 "contentType": self.content_type,
181 "exit": self.exit.as_dict(),
182 "blocked": self.blocked,
183 "countryUnavailable": self.country_unavailable,
184 "error": self.error,
185 "fetchedAt": self.fetched_at,
186 }
187
188
189class ProxySource:
190 """Hands out a proxy URL for (country, session). Apify Proxy on the platform; env-configured locally."""
191
192 def __init__(self, actor: Any | None = None):
193 self.actor = actor
194 self.local_template = os.environ.get("GEO_LOCAL_PROXY_TEMPLATE")
195 self._configs: dict[str, Any] = {}
196
197 @property
198 def mode(self) -> str:
199 return "local" if self.local_template else "apify"
200
201 async def url(self, country: str, session_id: str) -> str:
202 cc = country.lower()
203 if self.local_template:
204 return self.local_template.format(
205 cc=cc, sid=session_id, user=os.environ.get("GEO_LOCAL_PROXY_USER", ""),
206 pw=quote(os.environ.get("GEO_LOCAL_PROXY_PASS", ""), safe=""))
207 if cc not in self._configs:
208 self._configs[cc] = await self.actor.create_proxy_configuration(
209 groups=["RESIDENTIAL"], country_code=cc.upper())
210 cfg = self._configs[cc]
211 if cfg is None:
212 raise RuntimeError("Apify Proxy is not available to this run")
213 return await cfg.new_url(session_id=session_id)
214
215
216async def check_exit(session: AsyncSession, proxy_url: str) -> tuple[Exit, int]:
217 """Ask IP-location services where this session exits; verified only when two of them agree on the country.
218
219 Returns the exit and the bytes the checks cost. If only one service answers, the exit is not verified."""
220 spent = 0
221 answers: list[tuple[str, str, str | None, str | None]] = []
222 for url, cf, cityf, netf in GEO_SOURCES:
223 try:
224 r = await session.get(url, proxy=proxy_url, timeout=15)
225 spent += _wire(r)
226 if r.status_code != 200:
227 continue
228 d = r.json()
229 code = (d.get(cf) or "").strip().lower()
230 if len(code) != 2:
231 continue
232 net = d.get(netf) if netf else None
233 if netf == "asn_org" and d.get("asn"):
234 net = f"{d['asn']} {net or ''}".strip()
235 answers.append((code, urlsplit(url).hostname or url, (d.get(cityf) if cityf else None) or None,
236 net or None))
237 except Exception:
238 continue
239 if len(answers) >= 2:
240 break
241 ex = Exit(checked_at=now_iso())
242 if not answers:
243 return ex, spent
244 first = answers[0]
245 ex.country, ex.city, ex.network = first[0], first[2], first[3]
246 ex.sources = [a[1] for a in answers]
247 if len(answers) >= 2 and answers[0][0] == answers[1][0]:
248 ex.verified = True
249 elif len(answers) >= 2:
250 ex.disagreement = f"{answers[0][1]} says {answers[0][0].upper()}, {answers[1][1]} says {answers[1][0].upper()}"
251 return ex, spent
252
253
254def looks_blocked(status: int | None, html: str) -> bool:
255 if status in BLOCK_STATUSES:
256 return True
257 if len(html) > 300_000:
258 return False
259 head = html[:30_000].lower()
260 return any(m in head for m in BLOCK_MARKERS)
261
262
263async def fetch_in_country(url: str, country: str, proxies: ProxySource, *, max_sessions: int = 4,
264 timeout: int = 40, accept_language: str | None = None) -> FetchResult:
265 """Fetch `url` through a residential session whose exit is verified to be in `country`.
266
267 Tries up to `max_sessions` addresses: a session that exits elsewhere, a network failure or a bot wall moves on
268 to a new address. Only the last attempt's page is kept.
269 """
270 cc = country.lower()
271 res = FetchResult(url=url, requested_country=cc.upper())
272 problem = url_problem(url)
273 if problem:
274 res.error = problem
275 return res
276 lang = accept_language or LANG_BY_COUNTRY.get(cc, "en-US,en;q=0.9")
277 async with AsyncSession(impersonate="chrome", headers={"Accept-Language": lang}) as s:
278 for _ in range(max_sessions):
279 s.cookies.clear()
280 res.sessions_tried += 1
281 try:
282 proxy_url = await proxies.url(cc, new_session_id(f"g{cc}"))
283 except Exception as e:
284 res.error = f"proxy unavailable: {e}"[:200]
285 return res
286 exit_, spent = await check_exit(s, proxy_url)
287 res.wire_bytes += spent
288 if not (exit_.verified and exit_.country == cc):
289 res.wrong_exits.append(exit_.disagreement or (exit_.country.upper() if exit_.country else "unknown"))
290 continue
291 res.exit, res.country_unavailable = exit_, False
292 res.error, res.blocked, res.status, res.html = None, False, None, ""
293 try:
294 r = await s.get(url, proxy=proxy_url, timeout=timeout, allow_redirects=True, max_redirects=10)
295 except Exception as e:
296 res.error = f"fetch failed: {type(e).__name__}: {str(e)[:200]}"
297 continue
298 res.wire_bytes += _wire(r)
299 res.fetched_at = now_iso()
300 res.status = r.status_code
301 res.final_url = str(r.url)
302 res.content_type = (r.headers.get("content-type") or "").split(";")[0].strip() or None
303 res.redirects = [{"url": str(h.url), "status": h.status_code} for h in (getattr(r, "history", None) or [])]
304 res.html = r.text if res.is_text else ""
305 res.blocked = looks_blocked(r.status_code, res.html)
306 if not res.blocked:
307 break
308 if not res.exit.verified or res.exit.country != cc:
309 res.country_unavailable = True
310 seen = ", ".join(res.wrong_exits) or "none"
311 res.error = f"no address confirmed in {cc.upper()} after {res.sessions_tried} tries (seen: {seen})"
312 if res.blocked and res.error is None:
313 res.error = f"blocked by the site (HTTP {res.status}) on every try"
314 elif res.error is None and res.status is not None and res.status >= 400:
315 res.error = f"HTTP {res.status}"
316 elif res.error is None and not res.is_text:
317 res.error = f"not a web page ({res.content_type})"
318 return res
319
320
321
322
323def page_facts(html: str, base_url: str | None = None) -> dict[str, Any]:
324 tree = HTMLParser(html) if html else None
325 if tree is None:
326 return {}
327
328 def meta(*sels: str) -> str | None:
329 for sel in sels:
330 el = tree.css_first(sel)
331 if el is not None and (el.attributes.get("content") or "").strip():
332 return el.attributes["content"].strip()
333 return None
334
335 def absolute(href: str | None) -> str | None:
336 if not href:
337 return None
338 return urljoin(base_url, href) if base_url else href
339
340 title = tree.css_first("title")
341 html_el = tree.css_first("html")
342 canon = tree.css_first('link[rel="canonical"]')
343 alternates = []
344 for el in tree.css('link[rel="alternate"][hreflang]'):
345 href = absolute(el.attributes.get("href"))
346 if href:
347 alternates.append({"hreflang": el.attributes.get("hreflang"), "href": href})
348 return {
349 "title": (title.text(deep=True).strip() if title else None) or None,
350 "description": meta('meta[name="description"]', 'meta[property="og:description"]'),
351 "language": (html_el.attributes.get("lang") if html_el else None) or None,
352 "ogLocale": meta('meta[property="og:locale"]'),
353 "canonicalUrl": absolute(canon.attributes.get("href")) if canon is not None else None,
354 "robots": meta('meta[name="robots"]'),
355 "hreflang": alternates[:200],
356 }
357
358
359def _remove_top_most(nodes: list[Any]) -> None:
360 """Remove matched nodes, top-most only. Decomposing a match that sits inside another match frees it twice, and the
361 Modest parser then silently corrupts the tree (a Wikipedia article came out as 1,463 of 7,193 words, 4 Oct 2026)."""
362 ids = {n.mem_id for n in nodes}
363 seen: set[int] = set()
364 for n in nodes:
365 p, inside = n.parent, False
366 while p is not None:
367 if p.mem_id in ids:
368 inside = True
369 break
370 p = p.parent
371 if inside or n.mem_id in seen:
372 continue
373 seen.add(n.mem_id)
374 try:
375 n.decompose()
376 except Exception:
377 continue
378
379
380def page_markdown(html: str, max_chars: int) -> str:
381 tree = HTMLParser(html) if html else None
382 if tree is None:
383 return ""
384 _remove_top_most(list(tree.css("script, style, noscript, svg, iframe, template, nav, footer, form, "
385 "[aria-hidden=true], [hidden]")))
386 root = tree.css_first("main") or tree.css_first("article") or tree.body or tree.root
387 md = markdownify(root.html or "", heading_style="ATX", strip=["img"])
388 md = re.sub(r"[ \t]+\n", "\n", md)
389 md = re.sub(r"\n{3,}", "\n\n", md).strip()
390 return md[:max_chars]
391
392
393
394
395def _walk_jsonld(node: Any, out: list[dict[str, Any]], depth: int = 0) -> None:
396 if depth > 12:
397 return
398 if isinstance(node, list):
399 for n in node:
400 _walk_jsonld(n, out, depth + 1)
401 elif isinstance(node, dict):
402 out.append(node)
403 for k in ("@graph", "offers", "mainEntity", "itemListElement", "hasVariant", "item", "subjectOf"):
404 if k in node:
405 _walk_jsonld(node[k], out, depth + 1)
406
407
408def parse_amount(v: Any) -> float | None:
409 """'1.299,00' -> 1299.0; '1,299.00' -> 1299.0; '19,99' -> 19.99; '1 299' -> 1299.0."""
410 if v is None or isinstance(v, bool):
411 return None
412 if isinstance(v, (int, float)):
413 return float(v)
414 s = re.sub(r"[^\d.,]", "", str(v).replace(" ", " ").replace(" ", " "))
415 if not s or not re.search(r"\d", s):
416 return None
417 if "," in s and "." in s:
418 s = s.replace(",", "") if s.rfind(".") > s.rfind(",") else s.replace(".", "").replace(",", ".")
419 elif "," in s:
420 tail = s.split(",")[-1]
421 s = s.replace(",", ".") if len(tail) in (1, 2) and s.count(",") == 1 else s.replace(",", "")
422 elif s.count(".") > 1:
423 s = s.replace(".", "")
424 try:
425 return float(s)
426 except ValueError:
427 return None
428
429
430def _availability(v: Any) -> str | None:
431 if isinstance(v, list):
432 v = v[0] if v else None
433 if not v:
434 return None
435 return str(v).rstrip("/").rsplit("/", 1)[-1] or None
436
437
438def _types(node: dict[str, Any]) -> list[str]:
439 t = node.get("@type")
440 return [str(x) for x in (t if isinstance(t, list) else [t]) if x]
441
442
443PRODUCT_TYPES = ("Product", "ProductGroup", "IndividualProduct", "Vehicle", "Book", "SoftwareApplication", "VideoGame")
444
445
446def extract_prices(html: str, variant_url: str | None = None) -> list[dict[str, Any]]:
447 """Every price the page states about itself in structured data, the price a shopper is shown first.
448
449 `variant_url` (the requested or final URL) picks a Shopify variant named in `?variant=`; otherwise the variant in
450 the page's add-to-cart form. On Shopify the store's own product record corrects a mislabelled currency or an
451 amount in minor units; each correction is stated in the offer's `note`."""
452 out: list[dict[str, Any]] = []
453 tree = HTMLParser(html) if html else None
454 if tree is None:
455 return out
456
457 for node in tree.css('script[type="application/ld+json"]'):
458 raw = (node.text(deep=True) or "").strip()
459 if not raw:
460 continue
461 try:
462 data = json.loads(raw)
463 except Exception:
464 try:
465 data = json.loads(re.sub(r"[\x00-\x1f]", " ", raw))
466 except Exception:
467 continue
468 items: list[dict[str, Any]] = []
469 _walk_jsonld(data, items)
470 name = sku = None
471 for it in items:
472 types = _types(it)
473 if any(t in PRODUCT_TYPES for t in types):
474
475 name = name or it.get("name")
476 sku = sku or it.get("sku") or it.get("gtin13") or it.get("gtin")
477 if any(t in ("Offer", "AggregateOffer") for t in types):
478 price = parse_amount(it.get("price") if it.get("price") not in (None, "") else it.get("lowPrice"))
479 currency = it.get("priceCurrency")
480 spec = it.get("priceSpecification")
481 if isinstance(spec, list):
482 spec = spec[0] if spec else None
483 if isinstance(spec, dict):
484 if price is None:
485 price = parse_amount(spec.get("price"))
486 currency = currency or spec.get("priceCurrency")
487 if price is not None:
488 own_sku = it.get("sku") if isinstance(it.get("sku"), str) else None
489 out.append({"price": price, "currency": currency,
490 "availability": _availability(it.get("availability")),
491 "name": name if isinstance(name, str) else None,
492 "sku": own_sku or (sku if isinstance(sku, str) else None), "source": "json-ld",
493 "_url": it.get("url") if isinstance(it.get("url"), str) else None})
494
495 for el in tree.css('[itemprop="price"]'):
496 price = parse_amount(el.attributes.get("content") or el.text())
497 if price is None:
498 continue
499 scope, cur = el.parent, None
500 for _ in range(6):
501 if scope is None:
502 break
503 c = scope.css_first('[itemprop="priceCurrency"]')
504 if c is not None:
505 cur = (c.attributes.get("content") or c.text() or "").strip() or None
506 break
507 scope = scope.parent
508 avail_el = tree.css_first('[itemprop="availability"]')
509 avail = (avail_el.attributes.get("href") or avail_el.attributes.get("content")) if avail_el is not None else None
510 out.append({"price": price, "currency": cur, "availability": _availability(avail), "name": None, "sku": None,
511 "source": "microdata"})
512 break
513
514 amount = tree.css_first('meta[property="product:price:amount"], meta[property="og:price:amount"], '
515 'meta[property="product:sale_price:amount"]')
516 if amount is not None:
517 price = parse_amount(amount.attributes.get("content"))
518 cur = tree.css_first('meta[property="product:price:currency"], meta[property="og:price:currency"]')
519 avail = tree.css_first('meta[property="product:availability"], meta[property="og:availability"]')
520 if price is not None:
521 out.append({"price": price, "currency": cur.attributes.get("content") if cur is not None else None,
522 "availability": _availability(avail.attributes.get("content")) if avail is not None else None,
523 "name": None, "sku": None, "source": "meta"})
524
525
526
527
528 active = None
529 m = re.search(r'Shopify\.currency\s*=\s*(\{[^}]+\})', html)
530 if m:
531 try:
532 active = (json.loads(m.group(1)).get("active") or "").strip().upper()[:3] or None
533 except Exception:
534 active = None
535 for o in out:
536 if not o.get("currency") and active:
537 o["currency"] = active
538 variants: list[dict[str, Any]] = []
539 product: dict[str, Any] = {}
540 if active:
541 m = re.search(r'(?:ShopifyAnalytics\.meta|var meta)\s*=\s*(\{"product":.*?\});', html, re.S)
542 if m:
543 try:
544 product = json.loads(m.group(1)).get("product") or {}
545 except Exception:
546 product = {}
547 variants = [v for v in product.get("variants") or [] if isinstance(v.get("price"), (int, float))]
548 wanted = re.search(r"[?&]variant=(\d+)", variant_url or "")
549 sel_id = wanted.group(1) if wanted else None
550 if sel_id is None and variants:
551 field = tree.css_first('form[action*="/cart/add"] [name="id"]')
552 if field is not None:
553 opt = (field.css_first("option[selected]") or field.css_first("option")) if field.tag == "select" else field
554 sel_id = (opt.attributes.get("value") or "").strip() or None if opt is not None else None
555 selected = next((v for v in variants if sel_id and str(v.get("id")) == str(sel_id)), None)
556 if selected is None and variants and not wanted:
557
558
559 selected = variants[0]
560
561 def near(a: float, b: float | None) -> bool:
562 return b is not None and abs(a - b) <= max(0.011, 0.005 * abs(b))
563
564 store_amounts = [v["price"] / 100 for v in variants]
565 refs = store_amounts or [o["price"] for o in out if o["source"] in ("meta", "microdata")]
566 for o in out:
567 if o["source"] != "json-ld":
568 continue
569 if refs and not any(near(o["price"], r) for r in refs) and any(near(o["price"] / 100, r) for r in refs):
570 o["note"] = f"amount corrected: the page's structured data says {o['price']:g} (minor units)"
571 o["price"] = round(o["price"] / 100, 2)
572 cur = str(o.get("currency") or "").strip().upper()[:3]
573 if active and cur and cur != active and any(near(o["price"], r) for r in store_amounts):
574 o["note"] = f"currency corrected: the page's structured data says {cur}, the store served {active}"
575 o["currency"] = active
576
577 first = None
578 if selected is not None:
579 shown = selected["price"] / 100
580 first = next((o for o in out if o.get("_url") and f"variant={sel_id}" in o["_url"]), None) \
581 or next((o for o in out if o["source"] == "json-ld" and selected.get("sku")
582 and o.get("sku") == selected.get("sku")), None) \
583 or next((o for o in out if near(o["price"], shown) and o.get("currency") in (None, active)), None)
584 if first is not None and not near(first["price"], shown):
585 first = None
586 if first is None:
587 first = {"price": shown, "currency": active, "availability": None,
588 "name": (selected.get("name") or "").split(" - ")[0] or None,
589 "sku": selected.get("sku") or None, "source": "shopify"}
590 out.append(first)
591 elif not out and variants:
592 v = variants[0]
593 out.append({"price": v["price"] / 100, "currency": active, "availability": None,
594 "name": (v.get("name") or "").split(" - ")[0] or None, "sku": v.get("sku") or None,
595 "source": "shopify"})
596 else:
597
598 ref = next((o["price"] for o in out if o["source"] == "meta"), None)
599 if ref is None:
600 ref = next((o["price"] for o in out if o["source"] == "microdata"), None)
601 if ref is not None and sum(1 for o in out if o["source"] == "json-ld") > 1:
602 first = next((o for o in out if o["source"] == "json-ld" and near(o["price"], ref)), None)
603 if first is not None and selected is not None:
604 title = selected.get("public_title") or ((selected.get("name") or "").split(" - ", 1)[1:] or [None])[0]
605 if title:
606 first["variant"] = title
607 if first is not None and out and out[0] is not first:
608 out.remove(first)
609 out.insert(0, first)
610 seen, uniq = set(), []
611 for o in out:
612 if o.get("currency"):
613 o["currency"] = str(o["currency"]).strip().upper()[:3] or None
614 o.pop("_url", None)
615 key = (round(o["price"], 4), o.get("currency") or "")
616 if key in seen:
617 continue
618 seen.add(key)
619 uniq.append(o)
620 return uniq
621
622
623
624
625async def usd_rates() -> tuple[dict[str, float], str | None, str | None]:
626 """Units of each currency per 1 USD, the rates' date and their source. Empty if no source answers."""
627 ecb = None
628 async with AsyncSession(impersonate="chrome") as s:
629 try:
630 r = await s.get("https://api.frankfurter.dev/v1/latest?base=USD", timeout=20)
631 if r.status_code == 200:
632 d = r.json()
633 rates = {k.upper(): float(v) for k, v in (d.get("rates") or {}).items()}
634 rates["USD"] = 1.0
635 ecb = (rates, d.get("date"), "European Central Bank (via frankfurter.dev)")
636 except Exception:
637 pass
638 try:
639 r = await s.get("https://open.er-api.com/v6/latest/USD", timeout=20)
640 d = r.json() if r.status_code == 200 else {}
641 if d.get("result") == "success":
642 rates = {k.upper(): float(v) for k, v in (d.get("rates") or {}).items()}
643 if ecb:
644 return {**rates, **ecb[0]}, ecb[1], ecb[2] + "; other currencies open.er-api.com"
645 day = dt.datetime.fromtimestamp(int(d.get("time_last_update_unix") or 0), dt.timezone.utc).date()
646 return rates, day.isoformat(), "open.er-api.com"
647 except Exception:
648 pass
649 return ecb if ecb else ({}, None, None)
650
651
652def convert(amount: float | None, currency: str | None, to: str, rates: dict[str, float]) -> float | None:
653 if amount is None or not currency or not rates:
654 return None
655 cur, to = currency.upper(), to.upper()
656 if cur not in rates or to not in rates or rates[cur] == 0:
657 return None
658 return round(amount / rates[cur] * rates[to], 2)