UWColorKit / client.py
budzynski's picture
Hugging face demo v1
4247de9
Raw
History Blame Contribute Delete
2.01 kB
"""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