File size: 2,013 Bytes
4247de9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""Parameter API client: sends only {lat, lng, depth_m}, returns illuminant (x, y)."""

import json
import os
import urllib.error
import urllib.request
from dataclasses import dataclass

ALLOWED_REQUEST_KEYS = frozenset({"lat", "lng", "depth_m", "month"})
STUB_ILLUMINANT_XY = (0.25, 0.30)  # TODO(owner): replace with the live solver
ENV_API_URL = "SCUBAI_PARAM_API_URL"
ENV_API_TOKEN = "SCUBAI_PARAM_API_TOKEN"


@dataclass(frozen=True)
class Illuminant:
    x: float
    y: float

    def as_tuple(self):
        return (self.x, self.y)


def using_stub():
    return not os.environ.get(ENV_API_URL)


def _validate(x, y):
    x, y = float(x), float(y)
    if not (0.0 < x < 0.8 and 0.0 < y < 0.9 and (x + y) < 1.0):
        raise ValueError(f"illuminant out of range: x={x}, y={y}")
    return Illuminant(x, y)


def fetch_illuminant(lat, lng, depth_m, month=None, *, timeout=10.0):
    payload = {"lat": float(lat), "lng": float(lng), "depth_m": float(depth_m)}
    if month is not None:
        payload["month"] = int(month)  # omitted when EXIF has no date -> engine uses yearly data
    assert set(payload).issubset(ALLOWED_REQUEST_KEYS)  # only location/depth/date — never pixels

    url = os.environ.get(ENV_API_URL)
    if not url:
        return _validate(*STUB_ILLUMINANT_XY)

    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        url, data=data, method="POST", headers={"Content-Type": "application/json"}
    )
    token = os.environ.get(ENV_API_TOKEN)
    if token:
        req.add_header("Authorization", f"Bearer {token}")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            body = json.loads(resp.read().decode("utf-8"))
    except urllib.error.URLError as exc:
        raise RuntimeError(f"parameter API request failed: {exc}") from exc
    try:
        return _validate(body["x"], body["y"])
    except (KeyError, TypeError) as exc:
        raise RuntimeError(f"parameter API response missing x/y: {body!r}") from exc