"""Zero-dependency Python SDK for GPU-x402 Autonomous AI & Data Micro-APIs.""" import json import os import urllib.error import urllib.request from typing import Any class PaymentRequiredError(Exception): """Raised when the API responds with HTTP 402 Payment Required (x402 payload).""" def __init__(self, payload: dict[str, Any]): self.payload = payload super().__init__(payload.get("error", "HTTP 402 Payment Required")) class GPUx402Client: def __init__( self, base_url: str | None = None, api_key: str | None = None, timeout: int = 120, ): self.base_url = (base_url or os.getenv("GPU_X402_URL", "")).rstrip("/") if not self.base_url: raise ValueError("Set base_url or GPU_X402_URL environment variable.") self.api_key = api_key or os.getenv("GPU_X402_API_KEY", "") self.timeout = timeout def _post( self, path: str, body: dict[str, Any], tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: headers = { "Content-Type": "application/json", "User-Agent": "gpu-x402-sdk/1.0", } if self.api_key: headers["X-API-Key"] = self.api_key if tx_hash: headers["X-PAYMENT-TX"] = tx_hash headers["X-PAYMENT-CHAIN"] = chain req = urllib.request.Request( f"{self.base_url}{path}", data=json.dumps(body).encode("utf-8"), headers=headers, method="POST", ) try: with urllib.request.urlopen(req, timeout=self.timeout) as resp: return json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: raw = e.read().decode("utf-8", errors="ignore") try: parsed = json.loads(raw) except Exception: parsed = {"error": raw or str(e)} if e.code == 402: raise PaymentRequiredError(parsed) from e raise RuntimeError(f"HTTP {e.code}: {parsed}") from e def discover(self) -> dict[str, Any]: with urllib.request.urlopen(f"{self.base_url}/.well-known/x402", timeout=15) as resp: return json.loads(resp.read().decode("utf-8")) def web_markdown( self, url: str | None = None, html: str | None = None, max_chars: int = 24000, include_links: bool = True, tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post( "/v1/web/markdown", {"url": url, "html": html, "max_chars": max_chars, "include_links": include_links}, tx_hash, chain, ) def chain_wallet( self, address: str, chains: list[str] | None = None, tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post( "/v1/chain/wallet", {"address": address, "chains": chains or ["base", "polygon"]}, tx_hash, chain, ) def extract( self, url: str | None = None, html: str | None = None, schema_hint: str = "Extract title, summary, key entities, prices/metrics, and links as clean JSON.", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post("/v1/extract", {"url": url, "html": html, "schema_hint": schema_hint}, tx_hash, chain) def vision( self, image_url: str | None = None, image_base64: str | None = None, prompt: str = "Analyze this image and return structured JSON with objects, OCR text, and details.", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post( "/v1/vision", {"image_url": image_url, "image_base64": image_base64, "prompt": prompt}, tx_hash, chain, ) def code_audit( self, code: str, language: str = "auto", focus: str = "security vulnerabilities, logic bugs, edge cases, performance", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post("/v1/code/audit", {"code": code, "language": language, "focus": focus}, tx_hash, chain) def generate_image( self, prompt: str, width: int = 1024, height: int = 1024, steps: int = 4, seed: int | None = None, tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post( "/v1/image/generate", {"prompt": prompt, "width": width, "height": height, "steps": steps, "seed": seed}, tx_hash, chain, ) def render_reel( self, headline: str, subheadline: str = "", image_url: str | None = None, image_base64: str | None = None, duration_sec: int = 8, accent_color: str = "0x06b6d4", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post( "/v1/video/reel", { "headline": headline, "subheadline": subheadline, "image_url": image_url, "image_base64": image_base64, "duration_sec": duration_sec, "accent_color": accent_color, }, tx_hash, chain, ) def pdf_extract( self, pdf_url: str | None = None, pdf_base64: str | None = None, schema_hint: str = "Extract document_type, date, parties, line_items, totals, and key_summary as clean JSON.", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post("/v1/pdf/extract", {"pdf_url": pdf_url, "pdf_base64": pdf_base64, "schema_hint": schema_hint}, tx_hash, chain) def translate_json( self, data: dict[str, Any], target_language: str = "Spanish", tone: str = "natural, professional", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post("/v1/translate/json", {"data": data, "target_language": target_language, "tone": tone}, tx_hash, chain) def batch_extract( self, urls: list[str], schema_hint: str = "Extract name, price, summary, and key_features as a JSON array with one object per URL.", tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post("/v1/batch/extract", {"urls": urls, "schema_hint": schema_hint}, tx_hash, chain) def virtual_stage( self, room_or_subject: str, style: str = "modern_luxury", width: int = 1024, height: int = 1024, steps: int = 4, tx_hash: str | None = None, chain: str = "base", ) -> dict[str, Any]: return self._post( "/v1/image/stage", {"room_or_subject": room_or_subject, "style": style, "width": width, "height": height, "steps": steps}, tx_hash, chain, ) def claim_credits(self, tx_hash: str, chain: str = "base", existing_key: str | None = None) -> dict[str, Any]: res = self._post("/v1/credits/claim", {"tx_hash": tx_hash, "chain": chain, "api_key": existing_key}) if res.get("api_key"): self.api_key = res["api_key"] return res