#!/usr/bin/env python3 """Analyze a parcel through the AcreEyes API and print the result. export ACREEYES_API_KEY=ae_live_… python acreeyes.py --pin RP00N00E000000A python acreeyes.py --address "1234 Cross Mtn Rd, Sandpoint, ID" --pdf report.pdf python acreeyes.py --point -116.55 48.27 --json report.json python acreeyes.py --me # your key and this month's usage Local console instead of acreeyes.com: --base-url http://127.0.0.1:7430/v1 (or ACREEYES_API_URL). Uses acreeyes_client.py from this directory. Exit codes: 0 report ready · 1 run failed · 2 parcel not found / ambiguous · 3 key or plan refused (auth, quota, scope) · 4 API unreachable or busy. """ from __future__ import annotations import argparse import json import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from acreeyes_client import (AcreEyes, AcreEyesError, AuthError, BadRequest, Busy, PlanError, # noqa: E402 RunFailed, Unavailable) def _args(argv=None): p = argparse.ArgumentParser(description="Analyze a parcel through the AcreEyes API.") where = p.add_mutually_exclusive_group(required=True) where.add_argument("--pin", help="Parcel number (PIN/APN); comma-separate adjoining parcels.") where.add_argument("--address", help="Site address.") where.add_argument("--point", nargs=2, type=float, metavar=("LON", "LAT"), help="A point on the parcel.") where.add_argument("--me", action="store_true", help="Show your key, plan and usage, then exit.") where.add_argument("--run", metavar="RUN_ID", help="Show an existing run (and its report if done).") p.add_argument("--state", default="ID", help="Two-letter state (default ID; see GET /v1/regions).") p.add_argument("--county", help="County, when a PIN exists in several.") p.add_argument("--profile", help="Weighting profile (see GET /v1/profiles).") p.add_argument("--weight", action="append", default=[], metavar="EYE=X", help="Multiply one eye's weight, e.g. --weight water=2 (repeatable).") p.add_argument("--check", action="store_true", help="Check the parcel resolves first (free).") p.add_argument("--json", metavar="PATH", help="Save the full report JSON here ('-' = stdout).") p.add_argument("--pdf", metavar="PATH", help="Save the PDF report here.") p.add_argument("--hide-owner", action="store_true", help="Leave the owner of record out.") p.add_argument("--idempotency-key", help="Reuse to make a retried start return the same run.") p.add_argument("--quiet", "-q", action="store_true", help="No live progress.") p.add_argument("--key", help="API key (default $ACREEYES_API_KEY).") p.add_argument("--base-url", help="API base (default $ACREEYES_API_URL or https://acreeyes.com/api/v1).") p.add_argument("--timeout", type=float, default=1800, help="Seconds to wait for the run (default 1800).") return p.parse_args(argv) def _weights(pairs): out = {} for pair in pairs: eye, _, x = pair.partition("=") try: out[eye.strip()] = float(x) except ValueError: raise SystemExit(f"--weight wants EYE=NUMBER, got {pair!r}") return out or None def _progress(quiet): t0 = time.monotonic() def on_event(ev): if quiet: return if ev.name == "stage": t = ev.data.get("t") print(f" [{t if t is not None else time.monotonic() - t0:6.1f}s] {ev.data['stage']}", file=sys.stderr) elif ev.name == "flag": print(f" ⚠ {ev.data['text']}", file=sys.stderr) return on_event def _print_report(rep): p, s = rep["parcel"], rep["score"] place = ", ".join(str(x) for x in (p.get("county"), p.get("state")) if x) print(f"\nPIN {p.get('pin')} · {place} · {p.get('acres_gis')} acres (GIS)") if p.get("site_address"): print(f"Site address: {p['site_address']}") if p.get("owner"): print(f"Owner of record: {p['owner']} ({p.get('owner_source')})") if s.get("grade") and s.get("status") != "incomplete": print(f"Screening score: {s['grade']} ({s.get('overall')}/100) · evidence coverage " f"{round((s.get('coverage') or 0) * 100)}%") else: print("Screening score: not graded — too little evidence answered (see not checked below)") print("\nEyes:") for e in rep["eyes"]: grade = "—" if e.get("unscored") and not e.get("grade") else (e.get("grade") or "—") line = f" {e['name']:<12} {grade:<3}" if e.get("headlines"): line += f" {e['headlines'][0]}" print(line) for n in e.get("not_checked") or []: print(f" not checked: {n['label']} {n['text']}".rstrip()) flags = rep.get("flags") or [] print(f"\nWorth investigating ({len(flags)}):" if flags else "\nNo issues flagged in what could be checked.") for f in flags: print(f" ⚠ {f}") print(f"\n{rep.get('disclaimer') or ''}") def main(argv=None) -> int: a = _args(argv) try: ae = AcreEyes(api_key=a.key, base_url=a.base_url) except ValueError as e: print(f"acreeyes: {e}", file=sys.stderr) return 3 try: if a.me: me = ae.me() plan = me["plan"] print(f"{me['key']['name']} ({me['key']['role']}) · scopes: {', '.join(me['key']['scopes'])}") used = (f"{plan['used']} reports (no monthly quota)" if plan["quota_month"] is None else f"{plan['used']} of {plan['quota_month']} reports used, {plan['remaining']} left") print(f"This month: {used} · {plan['pending']} running · resets {plan['resets']}") return 0 if a.run: final = ae.run(a.run) print(json.dumps({k: final.get(k) for k in ("id", "status", "charged", "result", "error", "upstream")}, indent=2)) if final["status"] != "done" or not final.get("result"): return 0 if final["status"] in ("queued", "running") else 1 rid = final["result"]["id"] else: parcel = a.pin or a.address if a.check and parcel: chk = ae.resolve(parcel, state=a.state, county=a.county) print(f"parcel check: {chk.get('status')}", file=sys.stderr) if chk.get("status") == "not_found": return 2 run = ae.start_run(pin=a.pin, address=a.address, point=tuple(a.point) if a.point else None, state=a.state, county=a.county, profile=a.profile, weights=_weights(a.weight), idempotency_key=a.idempotency_key) print(f"run {run['id']} {run['status']}", file=sys.stderr) final = ae.wait(run["id"], timeout=a.timeout, on_event=_progress(a.quiet)) up = final.get("upstream") or {} if not a.quiet: print(f"run {final['id']} {final['status']}" + (f" in {up['duration_s']:.0f}s" if up.get("duration_s") else "") + (" · charged" if final.get("charged") else ""), file=sys.stderr) if final["status"] != "done" or (final.get("result") or {}).get("kind") != "analysis": raise RunFailed(final) rid = final["result"]["id"] rep = ae.report(rid, hide_owner=a.hide_owner) if a.json == "-": print(json.dumps(rep, indent=2, ensure_ascii=False)) else: _print_report(rep) if a.json: Path(a.json).write_text(json.dumps(rep, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(f"\nreport JSON: {a.json}", file=sys.stderr) if a.pdf: ae.pdf(rid, a.pdf, hide_owner=a.hide_owner) print(f"PDF: {a.pdf}", file=sys.stderr) print(f"analysis: {rid}", file=sys.stderr) return 0 except RunFailed as e: print(f"acreeyes: {e.code}: {e.message}", file=sys.stderr) for c in (e.choices or {}).get("candidates") or []: print(f" --county \"{c.get('county')}\" ({c.get('acres')} ac, {c.get('address') or 'no address'})", file=sys.stderr) return 2 if e.code in ("parcel_not_found", "ambiguous_pin") else 1 except (AuthError, PlanError) as e: print(f"acreeyes: {e}", file=sys.stderr) return 3 except BadRequest as e: print(f"acreeyes: {e.message}", file=sys.stderr) return 1 except (Busy, Unavailable) as e: print(f"acreeyes: {e}", file=sys.stderr) return 4 except TimeoutError as e: print(f"acreeyes: {e}", file=sys.stderr) return 4 except AcreEyesError as e: print(f"acreeyes: {e}", file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())