"""AcreEyes API v1 — Python client. Standard library only (Python 3.9+): copy this one file into your project. from acreeyes_client import AcreEyes ae = AcreEyes() # ACREEYES_API_KEY / ACREEYES_API_URL from the environment report = ae.analyze(pin="RP58N02E070150A", state="ID", on_event=lambda ev: print(ev.name, ev.data)) print(report["score"]["grade"], report["flags"]) Docs: https://acreeyes.com/developers/ (what the API does and returns). The key is sent in the Authorization header only — never in a URL. Retries: GETs, and run starts (each carries an Idempotency-Key, so a retried start returns the same run instead of starting and charging a second one), are retried on connection errors, 5xx, and 429 (honouring Retry-After). Nothing else is. """ from __future__ import annotations import json import os import socket import time import urllib.error import urllib.parse import urllib.request import uuid from dataclasses import dataclass from typing import Any, Callable, Iterator, Optional __version__ = "1.0.0" DEFAULT_URL = "https://acreeyes.com/api/v1" FINISHED = ("done", "failed", "cancelled", "interrupted", "rejected") # --- errors -------------------------------------------------------------------- class AcreEyesError(Exception): """An error answer from the API: `status`, `code` (the API's `error`), `message`, `request_id` (quote it when asking for help) and `retry_after` (seconds, or None).""" def __init__(self, status: int, code: str, message: str, request_id: Optional[str] = None, retry_after: Optional[float] = None): super().__init__(f"{status} {code}: {message}" + (f" (request {request_id})" if request_id else "")) self.status, self.code, self.message = status, code, message self.request_id, self.retry_after = request_id, retry_after class AuthError(AcreEyesError): """401: missing, unknown, revoked or expired key.""" class PlanError(AcreEyesError): """403: the plan doesn't allow it — `quota` (monthly reports used), `missing_scope`, `not_subscribed`, `api_closed`.""" class NotFound(AcreEyesError): """404: no such run or analysis (or not yours).""" class BadRequest(AcreEyesError): """400: the request was invalid; `message` says which field and why.""" class Busy(AcreEyesError): """429: rate limited, or a run is already pending for this key. See `retry_after`.""" class Unavailable(AcreEyesError): """5xx, or the API couldn't be reached.""" class RunFailed(AcreEyesError): """`analyze()`: the run finished without a report. `run` is the final run; its `error.code` is e.g. `parcel_not_found`, `ambiguous_pin` (see `run["choices"]` or `choices`) or `run_failed`.""" def __init__(self, run: dict): err = run.get("error") or {} super().__init__(200, err.get("code") or run.get("status") or "failed", err.get("message") or f"run {run.get('id')} ended {run.get('status')}") self.run = run self.choices = run.get("choices") _BY_STATUS = {400: BadRequest, 401: AuthError, 403: PlanError, 404: NotFound, 429: Busy} @dataclass class Event: """One server-sent event from a run stream. `name` is None for a plain log line (`data` is the line), else "stage", "flag", "result", "choices" or "end".""" name: Optional[str] data: Any # --- client -------------------------------------------------------------------- class AcreEyes: def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, *, timeout: float = 60.0, max_retries: int = 3, user_agent: Optional[str] = None): self.api_key = (api_key or os.environ.get("ACREEYES_API_KEY") or "").strip() if not self.api_key: raise ValueError("an API key is required: pass api_key= or set ACREEYES_API_KEY") self.base_url = (base_url or os.environ.get("ACREEYES_API_URL") or DEFAULT_URL).rstrip("/") self.timeout, self.max_retries = timeout, max_retries self.user_agent = user_agent or f"acreeyes-python/{__version__}" self.last_request_id: Optional[str] = None # --- transport --------------------------------------------------------------- def _url(self, path: str, params: Optional[dict] = None) -> str: if path.startswith("/v1/"): # links the API returns are /v1-relative path = path[3:] q = {k: ("true" if v is True else "false" if v is False else v) for k, v in (params or {}).items() if v is not None} return self.base_url + path + ("?" + urllib.parse.urlencode(q) if q else "") def _open(self, method: str, path: str, *, params=None, body=None, headers=None, retry: bool = False, timeout: Optional[float] = None): """The raw response (caller closes it). Raises AcreEyesError subclasses.""" data = json.dumps(body).encode() if body is not None else None hdrs = {"Authorization": f"Bearer {self.api_key}", "User-Agent": self.user_agent, "Accept": "application/json", **(headers or {})} if data is not None: hdrs["Content-Type"] = "application/json" attempts = 1 + (self.max_retries if retry else 0) for attempt in range(attempts): req = urllib.request.Request(self._url(path, params), data=data, headers=hdrs, method=method) try: resp = urllib.request.urlopen(req, timeout=timeout or self.timeout) self.last_request_id = resp.headers.get("X-Request-Id") return resp except urllib.error.HTTPError as e: err = self._error(e) if attempt + 1 < attempts and (e.code == 429 or e.code >= 500): time.sleep(self._backoff(attempt, err.retry_after)) continue raise err from None except (urllib.error.URLError, socket.timeout, ConnectionError) as e: if attempt + 1 < attempts: time.sleep(self._backoff(attempt, None)) continue raise Unavailable(0, "unreachable", f"could not reach {self.base_url}: {e}") from None raise AssertionError("unreachable") @staticmethod def _backoff(attempt: int, retry_after: Optional[float]) -> float: return min(60.0, retry_after if retry_after else 2 ** attempt) def _error(self, e: urllib.error.HTTPError) -> AcreEyesError: try: doc = json.loads(e.read() or b"{}") except ValueError: doc = {} ra = e.headers.get("Retry-After") if e.headers else None try: retry_after = float(ra) if ra else None except ValueError: retry_after = None rid = doc.get("request_id") or (e.headers.get("X-Request-Id") if e.headers else None) self.last_request_id = rid cls = _BY_STATUS.get(e.code, Unavailable if e.code >= 500 else AcreEyesError) return cls(e.code, doc.get("error") or "http_error", doc.get("message") or str(e.reason), rid, retry_after) def _json(self, method: str, path: str, **kw): with self._open(method, path, **kw) as resp: return json.loads(resp.read() or b"null") def _get(self, path: str, **params): return self._json("GET", path, params=params, retry=True) # --- account ------------------------------------------------------------------- def health(self) -> dict: return self._get("/health") def me(self) -> dict: """Your key, scopes and plan: `plan.used`, `plan.remaining`, `plan.resets`.""" return self._get("/me") def usage(self, month: Optional[str] = None) -> dict: """Charged runs for a month (YYYY-MM; default this one, UTC).""" return self._get("/usage", month=month) def regions(self) -> dict: """States and their status; only `supported` ones can be analyzed.""" return self._get("/regions") def profiles(self) -> dict: """Weighting profiles and the eye names `weights` accepts.""" return self._get("/profiles") # --- runs ------------------------------------------------------------------------ def resolve(self, parcel: str, *, state: str = "ID", county: Optional[str] = None) -> dict: """Check a PIN or address resolves to a parcel before spending a report (free). Always answers with a `status` (verified / unverified / not_found / unavailable).""" return self._json("POST", "/resolve", body={"parcel": parcel, "state": state, "county": county}, retry=True) def start_run(self, *, pin: Optional[str] = None, address: Optional[str] = None, point: Optional[tuple] = None, state: str = "ID", county: Optional[str] = None, profile: Optional[str] = None, weights: Optional[dict] = None, idempotency_key: Optional[str] = None, **options) -> dict: """Start an analysis; give exactly one of pin, address or point=(lon, lat). Returns the run (status `queued`/`running`). A repeated `idempotency_key` returns the original run; one is generated per call, so retries are safe.""" body = {"state": state, **options} for k, v in (("pin", pin), ("address", address), ("county", county), ("profile", profile), ("weights", weights)): if v is not None: body[k] = v if point is not None: body["point"] = [float(point[0]), float(point[1])] return self._json("POST", "/runs", body=body, retry=True, headers={"Idempotency-Key": idempotency_key or f"py-{uuid.uuid4().hex}"}) def run(self, run_id: str) -> dict: return self._get(f"/runs/{run_id}") def runs(self, *, status: Optional[str] = None, since: Optional[str] = None, limit: int = 50) -> Iterator[dict]: """Your runs, newest first, following the cursor across pages.""" before = None while True: page = self._get("/runs", status=status, since=since, before=before, limit=limit) yield from page["runs"] before = page.get("next") if not before: return def cancel(self, run_id: str) -> dict: """Cancel a queued or running run. A cancelled run is never charged.""" return self._json("POST", f"/runs/{run_id}/cancel") def logs(self, run_id: str, after: int = 0) -> dict: """Output lines from line `after`: {"lines", "next", "finished"}.""" return self._get(f"/runs/{run_id}/logs", after=after) def debug(self, run_id: str) -> dict: """Where the time went and which public sources failed or were slow.""" return self._get(f"/runs/{run_id}/debug") def stream(self, run_id: str, *, timeout: float = 120.0) -> Iterator[Event]: """Live events until the run ends (the last is `end`, carrying the run). `timeout` is per read; the server sends a keep-alive every 15 s.""" with self._open("GET", f"/runs/{run_id}/stream", headers={"Accept": "text/event-stream"}, timeout=timeout) as resp: name, data = None, [] for raw in resp: line = raw.decode("utf-8").rstrip("\r\n") if not line: # a blank line ends one event if data: yield Event(name, json.loads("\n".join(data))) name, data = None, [] elif line.startswith(":"): continue # keep-alive comment elif line.startswith("event:"): name = line[6:].strip() elif line.startswith("data:"): data.append(line[5:].lstrip()) def wait(self, run_id: str, *, timeout: float = 1800.0, on_event: Optional[Callable[[Event], None]] = None, poll: float = 5.0) -> dict: """Block until the run finishes; returns the final run. Streams events to `on_event` when given; falls back to polling if the stream drops.""" deadline = time.monotonic() + timeout if on_event is not None: try: for ev in self.stream(run_id): on_event(ev) if ev.name == "end": return ev.data except (AcreEyesError, OSError, ValueError): pass # the stream dropped: poll below while True: run = self.run(run_id) if run["status"] in FINISHED: return run if time.monotonic() > deadline: raise TimeoutError(f"run {run_id} still {run['status']} after {timeout:g}s") time.sleep(poll) # --- analyses ---------------------------------------------------------------------- def analyses(self, *, profile: Optional[str] = None) -> list: return self._get("/analyses", profile=profile)["analyses"] def analysis(self, analysis_id: str) -> dict: """The raw engine result: {"summary", "result", "geometry", "disclaimer"}.""" return self._get(f"/analyses/{analysis_id}") def report(self, analysis_id: str, *, hide_owner: bool = False, profile: Optional[str] = None) -> dict: """The full report as JSON (schema acreeyes.report/2 for customer keys; owner keys acreeyes.report/1).""" return self._get(f"/analyses/{analysis_id}/report.json", hide_owner=hide_owner, profile=profile) def pdf(self, analysis_id: str, path: str, *, brand: Optional[str] = None, hide_owner: bool = False) -> str: """Download the PDF report to `path`; returns the path.""" with self._open("GET", f"/analyses/{analysis_id}/pdf", retry=True, timeout=max(self.timeout, 180), params={"brand": brand, "hide_owner": hide_owner}) as resp, open(path, "wb") as fh: while True: chunk = resp.read(65536) if not chunk: break fh.write(chunk) return path def share(self, analysis_id: str, *, prepared_for: Optional[str] = None, brand: Optional[str] = None, hide_owner: bool = True, listing_url: Optional[str] = None) -> dict: """Mint a public share link: {"code", "url"}. `listing_url`: your listing, linked from the page and PDF.""" return self._json("POST", f"/analyses/{analysis_id}/share", body={"prepared_for": prepared_for, "brand": brand, "hide_owner": hide_owner, "listing_url": listing_url}) # --- one call ------------------------------------------------------------------------ def analyze(self, *, timeout: float = 1800.0, on_event: Optional[Callable[[Event], None]] = None, hide_owner: bool = False, **run_args) -> dict: """Start a run, wait for it, and return its report. Raises RunFailed when it ends without one. The report's `analysis.id` is the saved analysis.""" run = self.start_run(**run_args) final = self.wait(run["id"], timeout=timeout, on_event=on_event) result = final.get("result") or {} if final["status"] != "done" or result.get("kind") != "analysis": raise RunFailed(final) return self.report(result["id"], hide_owner=hide_owner)