Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER7# File : sdk/python/spider_sdk/requests.py8# Module : Sdk9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Typed builders of SPIDER request bodies.4243Each ``*_request`` function returns the JSON body of one endpoint, with unset options left out so44the server's defaults apply. Option groups are small dataclasses; a plain mapping with the same45keys is accepted wherever a dataclass is.4647Mandatory policies: SPIDER always honours ``robots.txt`` and always stops on an access denial48(login wall, CAPTCHA, paywall, 401/403). The server refuses any request that tries to switch these49off, and this SDK offers no option to do it: :class:`PolicyOptions` has no such field, and a mapping50carrying ``respect_robots_txt`` or ``stop_on_access_denied`` set to anything but ``True`` is refused51locally with :class:`ValueError`.52"""53from __future__ import annotations5455import dataclasses56from collections.abc import Mapping, Sequence57from dataclasses import dataclass58from typing import Any, Literal5960Render = Literal["auto", "http", "browser"]61Profile = Literal["desktop", "mobile", "tablet"]62Format = Literal["markdown", "json", "text", "html", "links", "tables", "structured", "media"]63VisionMode = Literal["off", "on_conflict", "always"]64WebhookEvent = Literal["job.finished", "job.progress", "change.detected"]65WatchKind = Literal["content", "layout", "fields", "visual"]66BatchKind = Literal["scrape", "screenshot", "extract", "deep_capture"]67MANDATORY_POLICIES = ("respect_robots_txt", "stop_on_access_denied")68_ALIASES = {"json_schema": "schema"}697071def _clean(value: Any) -> Any:72 """Dataclasses and mappings to plain JSON, dropping unset (None) options."""73 if dataclasses.is_dataclass(value) and not isinstance(value, type):74 value = {f.name: getattr(value, f.name) for f in dataclasses.fields(value)}75 if isinstance(value, Mapping):76 return {_ALIASES.get(k, k): _clean(v) for k, v in value.items() if v is not None}77 if isinstance(value, (list, tuple)):78 return [_clean(v) for v in value]79 return value808182@dataclass(frozen=True)83class Budgets:84 max_pages: int | None = None85 max_depth: int | None = None86 max_states_per_page: int | None = None87 max_actions_per_page: int | None = None88 max_bytes: int | None = None89 max_duration_s: int | None = None90 max_urls_per_pattern: int | None = None919293@dataclass(frozen=True)94class CaptureOptions:95 viewport: bool | None = None96 full_page: bool | None = None97 tiles: bool | None = None98 tile_height: int | None = None99 tile_width: int | None = None100 tile_overlap: int | None = None101 elements: Sequence[str] | None = None102 sections: bool | None = None103 interactive_states: bool | None = None104 profiles: Sequence[Profile] | None = None105 engine: Literal["chromium", "webkit"] | None = None106 device_scale_factor: float | None = None107 locale: str | None = None108 timezone: str | None = None109 webp_derivatives: bool | None = None110 pdf: bool | None = None111112113@dataclass(frozen=True)114class ExtractOptions:115 """``json_schema`` is sent as ``schema`` (a JSON Schema of type object, ``x-aliases`` supported)."""116 formats: Sequence[Format] | None = None117 ocr: bool | None = None118 ocr_languages: Sequence[str] | None = None119 vision: VisionMode | None = None120 include_evidence: bool | None = None121 json_schema: Mapping[str, Any] | None = None122 schema_id: str | None = None123 rules: Mapping[str, Any] | None = None124 connector_id: str | None = None125126127@dataclass(frozen=True)128class PolicyOptions:129 """Scope and politeness. robots.txt compliance and stop-on-access-denial are not options."""130 same_origin_only: bool | None = None131 include_subdomains: bool | None = None132 allow_domains: Sequence[str] | None = None133 exclude_paths: Sequence[str] | None = None134 include_paths: Sequence[str] | None = None135 min_delay_ms: int | None = None136137138@dataclass(frozen=True)139class WebhookOptions:140 url: str141 events: Sequence[WebhookEvent] | None = None142143144@dataclass(frozen=True)145class BatchItem:146 """One job of a batch; ``request`` is the body of the corresponding endpoint (use the builders)."""147 kind: BatchKind148 request: Mapping[str, Any]149150151BudgetsLike = Budgets | Mapping[str, Any]152CaptureLike = CaptureOptions | Mapping[str, Any]153ExtractLike = ExtractOptions | Mapping[str, Any]154PolicyLike = PolicyOptions | Mapping[str, Any]155WebhookLike = WebhookOptions | Mapping[str, Any]156157158def _policy(policy: PolicyLike | None) -> dict[str, Any] | None:159 if policy is None:160 return None161 out = _clean(policy)162 for name in MANDATORY_POLICIES:163 if name in out and out[name] is not True:164 raise ValueError(f"{name} is a mandatory policy of SPIDER and cannot be disabled")165 return out166167168def _body(**fields: Any) -> dict[str, Any]:169 if "policy" in fields:170 fields["policy"] = _policy(fields["policy"])171 return _clean(fields)172173174def scrape_request(url: str, *, render: Render | None = None, capture: CaptureLike | None = None,175 extract: ExtractLike | None = None, policy: PolicyLike | None = None,176 webhook: WebhookLike | None = None, priority: int | None = None,177 metadata: Mapping[str, str] | None = None, timeout_s: int | None = None) -> dict[str, Any]:178 return _body(url=url, render=render, capture=capture, extract=extract, policy=policy, webhook=webhook,179 priority=priority, metadata=metadata, timeout_s=timeout_s)180181182def crawl_request(url: str | None = None, *, urls: Sequence[str] | None = None, sitemap: str | None = None,183 strategy: Literal["bfs", "dfs", "priority"] | None = None, render: Render | None = None,184 max_depth: int | None = None, max_pages: int | None = None,185 max_states_per_page: int | None = None, budgets: BudgetsLike | None = None,186 capture: CaptureLike | None = None, extract: ExtractLike | None = None,187 use_sitemaps: bool | None = None, policy: PolicyLike | None = None,188 webhook: WebhookLike | None = None, priority: int | None = None,189 metadata: Mapping[str, str] | None = None) -> dict[str, Any]:190 if not (url or urls or sitemap):191 raise ValueError("one of url, urls or sitemap is required")192 return _body(url=url, urls=urls, sitemap=sitemap, strategy=strategy, render=render, max_depth=max_depth,193 max_pages=max_pages, max_states_per_page=max_states_per_page, budgets=budgets, capture=capture,194 extract=extract, use_sitemaps=use_sitemaps, policy=policy, webhook=webhook, priority=priority,195 metadata=metadata)196197198def map_request(url: str, *, budgets: BudgetsLike | None = None, use_sitemaps: bool | None = None,199 render: Literal["http", "browser"] | None = None, policy: PolicyLike | None = None,200 webhook: WebhookLike | None = None, priority: int | None = None,201 metadata: Mapping[str, str] | None = None) -> dict[str, Any]:202 return _body(url=url, budgets=budgets, use_sitemaps=use_sitemaps, render=render, policy=policy,203 webhook=webhook, priority=priority, metadata=metadata)204205206def screenshot_request(url: str, *, capture: CaptureLike | None = None, policy: PolicyLike | None = None,207 webhook: WebhookLike | None = None, priority: int | None = None,208 metadata: Mapping[str, str] | None = None, timeout_s: int | None = None) -> dict[str, Any]:209 return _body(url=url, capture=capture, policy=policy, webhook=webhook, priority=priority, metadata=metadata,210 timeout_s=timeout_s)211212213def deep_capture_request(url: str, *, capture: CaptureLike | None = None, budgets: BudgetsLike | None = None,214 extract: ExtractLike | None = None, policy: PolicyLike | None = None,215 webhook: WebhookLike | None = None, priority: int | None = None,216 metadata: Mapping[str, str] | None = None, timeout_s: int | None = None) -> dict[str, Any]:217 return _body(url=url, capture=capture, budgets=budgets, extract=extract, policy=policy, webhook=webhook,218 priority=priority, metadata=metadata, timeout_s=timeout_s)219220221def extract_request(url: str, extract: ExtractLike, *, render: Render | None = None,222 policy: PolicyLike | None = None, webhook: WebhookLike | None = None,223 priority: int | None = None, metadata: Mapping[str, str] | None = None) -> dict[str, Any]:224 ex = _clean(extract)225 if not (ex.get("schema") or ex.get("schema_id") or ex.get("connector_id")):226 raise ValueError("extract needs a schema (json_schema), a schema_id or a connector_id")227 return _body(url=url, extract=ex, render=render, policy=policy, webhook=webhook, priority=priority,228 metadata=metadata)229230231def ocr_request(artifact_id: str, *, languages: Sequence[str] | None = None, fast: bool | None = None232 ) -> dict[str, Any]:233 return _body(artifact_id=artifact_id, languages=languages, fast=fast)234235236def vision_request(artifact_ids: Sequence[str], *, task: Literal["describe", "fields"] | None = None,237 json_schema: Mapping[str, Any] | None = None, model: str | None = None) -> dict[str, Any]:238 if not 1 <= len(artifact_ids) <= 4:239 raise ValueError("vision takes 1 to 4 artifact ids")240 return _body(artifact_ids=list(artifact_ids), task=task, json_schema=json_schema, model=model)241242243def _nested(request: Mapping[str, Any]) -> dict[str, Any]:244 """A request body embedded in another one (monitor, batch): same mandatory-policy guard."""245 out = _clean(request)246 if "policy" in out:247 _policy(out["policy"])248 return out249250251def batch_request(items: Sequence[BatchItem | Mapping[str, Any]]) -> dict[str, Any]:252 if not items:253 raise ValueError("a batch needs at least one item")254 out = []255 for item in items:256 it = _clean(item)257 out.append({"kind": it["kind"], "request": _nested(it["request"])})258 return {"items": out}259260261def monitor_request(name: str, request: Mapping[str, Any], *, interval_s: int | None = None,262 watch: Sequence[WatchKind] | None = None, ignore_selectors: Sequence[str] | None = None,263 cooldown_s: int | None = None, enabled: bool | None = None) -> dict[str, Any]:264 """``request`` is a scrape body: build it with :func:`scrape_request`."""265 return _body(name=name, request=_nested(request), interval_s=interval_s, watch=watch,266 ignore_selectors=ignore_selectors, cooldown_s=cooldown_s, enabled=enabled)267268269def diff_request(snapshot_a: str, snapshot_b: str, *, visual: bool | None = None,270 ignore_selectors: Sequence[str] | None = None) -> dict[str, Any]:271 return _body(snapshot_a=snapshot_a, snapshot_b=snapshot_b, visual=visual, ignore_selectors=ignore_selectors)272273274def search_request(query: str, *, site_id: str | None = None, domain: str | None = None, since: str | None = None,275 until: str | None = None, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:276 return _body(query=query, site_id=site_id, domain=domain, since=since, until=until, limit=limit, cursor=cursor)277