decodo-sdk 2.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
decodo/http.py ADDED
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+ from urllib.parse import urlencode
6
+
7
+ import httpx
8
+
9
+ from .errors import (
10
+ AuthenticationError,
11
+ DecodoError,
12
+ RateLimitError,
13
+ TimeoutError,
14
+ ValidationError,
15
+ )
16
+
17
+
18
+ @dataclass
19
+ class BasicAuth:
20
+ type: str # "basic"
21
+ token: str
22
+
23
+
24
+ @dataclass
25
+ class ApiKeyAuth:
26
+ type: str # "apiKey"
27
+ api_key: str
28
+
29
+
30
+ @dataclass
31
+ class HttpClientConfig:
32
+ base_url: str
33
+ auth: BasicAuth | ApiKeyAuth
34
+ timeout_ms: int
35
+ integration_header: str | None = None
36
+
37
+
38
+ class HttpClient:
39
+ def __init__(self, config: HttpClientConfig) -> None:
40
+ self._base_url = config.base_url.rstrip("/")
41
+ self._timeout_ms = config.timeout_ms
42
+ self._integration_header = config.integration_header or "sdk-python"
43
+
44
+ if config.auth.type == "basic":
45
+ assert isinstance(config.auth, BasicAuth)
46
+ self._auth_header = f"Basic {config.auth.token}"
47
+ else:
48
+ assert isinstance(config.auth, ApiKeyAuth)
49
+ self._auth_header = config.auth.api_key
50
+
51
+ def request(self, method: str, path: str, body: Any = None) -> Any:
52
+ url = f"{self._base_url}{path}"
53
+ headers = {
54
+ "Authorization": self._auth_header,
55
+ "Content-Type": "application/json",
56
+ "Accept": "application/json",
57
+ "x-integration": self._integration_header,
58
+ }
59
+ timeout = self._timeout_ms / 1000.0
60
+
61
+ try:
62
+ response = httpx.request(
63
+ method,
64
+ url,
65
+ headers=headers,
66
+ json=body,
67
+ timeout=timeout,
68
+ )
69
+ except httpx.TimeoutException:
70
+ raise TimeoutError(
71
+ f"Request to {path} timed out after {self._timeout_ms}ms"
72
+ )
73
+
74
+ if response.is_success:
75
+ if response.status_code == 204:
76
+ return None
77
+ return response.json()
78
+
79
+ error_body: dict[str, Any] | None = None
80
+ try:
81
+ error_body = response.json()
82
+ except Exception:
83
+ pass
84
+
85
+ message: str = (
86
+ error_body.get("message", f"HTTP {response.status_code}")
87
+ if error_body
88
+ else f"HTTP {response.status_code}"
89
+ )
90
+
91
+ status_code = response.status_code
92
+
93
+ if status_code in (401, 403):
94
+ raise AuthenticationError(message)
95
+ if status_code == 429:
96
+ raise RateLimitError(message)
97
+ if status_code == 422 or (status_code == 400 and error_body and error_body.get("errors")):
98
+ raise ValidationError(message, error_body.get("errors") if error_body else None)
99
+
100
+ api_status: str | None = error_body.get("status") if error_body else None
101
+ raise DecodoError(message, status_code, api_status)
102
+
103
+ def post(self, path: str, body: Any) -> Any:
104
+ return self.request("POST", path, body)
105
+
106
+ def get(self, path: str, query: dict[str, str] | None = None) -> Any:
107
+ if query:
108
+ qs = urlencode(query)
109
+ if qs:
110
+ return self.request("GET", f"{path}?{qs}")
111
+ return self.request("GET", path)
decodo/py.typed ADDED
File without changes
@@ -0,0 +1,25 @@
1
+ from .bundled_schema import BundledSchema
2
+ from .remote_schema import RemoteSchema
3
+ from .types import (
4
+ CachedIr,
5
+ DecodoSchema,
6
+ GcsObjectList,
7
+ IrTarget,
8
+ LatestIrLocation,
9
+ RemoteIr,
10
+ RemoteSchemaLoadOptions,
11
+ TargetMeta,
12
+ )
13
+
14
+ __all__ = [
15
+ "BundledSchema",
16
+ "RemoteSchema",
17
+ "DecodoSchema",
18
+ "RemoteSchemaLoadOptions",
19
+ "TargetMeta",
20
+ "IrTarget",
21
+ "RemoteIr",
22
+ "CachedIr",
23
+ "GcsObjectList",
24
+ "LatestIrLocation",
25
+ ]
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from .types import IrTarget, TargetMeta
6
+
7
+
8
+ def _get_target_parameter_keys(parameter_schema: dict[str, Any]) -> list[str]:
9
+ properties: dict[str, Any] = parameter_schema.get("properties", {})
10
+ return [key for key in properties if key != "target"]
11
+
12
+
13
+ def build_target_meta(targets: dict[str, IrTarget]) -> dict[str, TargetMeta]:
14
+ meta: dict[str, TargetMeta] = {}
15
+
16
+ for target_key, target in targets.items():
17
+ meta[target_key] = TargetMeta(
18
+ group=target["group"],
19
+ response_format=target["response_format"],
20
+ parameters=_get_target_parameter_keys(target["parameter_schema"]),
21
+ )
22
+
23
+ return meta
@@ -0,0 +1,97 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, ClassVar, cast
8
+
9
+ from decodo.targets import targets
10
+
11
+ from .build_target_meta import build_target_meta
12
+ from .types import DecodoSchema, TargetMeta
13
+
14
+
15
+ def _load_target_meta() -> dict[str, Any] | None:
16
+ try:
17
+ from decodo.generated.targets import target_meta # noqa: PLC0415
18
+ return cast(dict[str, Any], target_meta)
19
+ except ImportError:
20
+ return None
21
+
22
+ _target_meta = _load_target_meta()
23
+
24
+ _BUNDLED_IR_PATH = Path(__file__).parent.parent / "generated" / "decodo.ir.json"
25
+
26
+
27
+ def _find_ir_path() -> Path | None:
28
+ env = os.environ.get("DECODO_IR_PATH")
29
+ if env:
30
+ p = Path(env)
31
+ if p.is_file():
32
+ return p
33
+ local = Path.cwd() / "decodo_generated" / "decodo.ir.json"
34
+ if local.is_file():
35
+ return local
36
+ if _BUNDLED_IR_PATH.is_file():
37
+ return _BUNDLED_IR_PATH
38
+ return None
39
+
40
+
41
+ def _load_ir_json() -> dict[str, Any] | None:
42
+ path = _find_ir_path()
43
+ if path is None:
44
+ return None
45
+ try:
46
+ with open(path, encoding="utf-8") as f:
47
+ return json.load(f) # type: ignore[no-any-return]
48
+ except (OSError, json.JSONDecodeError):
49
+ return None
50
+
51
+
52
+ class BundledSchema:
53
+ shared: ClassVar[BundledSchema]
54
+
55
+ def __init__(self) -> None:
56
+ ir = _load_ir_json()
57
+ if ir is not None:
58
+ api_targets = ir["apis"]["webScrapingApi"]["targets"]
59
+ self._request_schemas: dict[str, dict[str, Any]] = {
60
+ k: v["parameter_schema"] for k, v in api_targets.items()
61
+ }
62
+ self._target_meta = _target_meta if _target_meta is not None else build_target_meta(api_targets)
63
+ else:
64
+ warnings.warn(
65
+ "Decodo IR schema not found — payload validation is disabled. "
66
+ "Run: python -m decodo.codegen.codegen (editable install) or "
67
+ "python -m decodo.codegen.codegen --out-dir ./decodo_generated (pip install).",
68
+ RuntimeWarning,
69
+ stacklevel=2,
70
+ )
71
+ self._request_schemas = {}
72
+ self._target_meta = _target_meta or {}
73
+
74
+ def get_request_schema(self, target: str) -> dict[str, Any] | None:
75
+ return self._request_schemas.get(target)
76
+
77
+ def list_targets(self) -> list[str]:
78
+ return list(targets)
79
+
80
+ def get_target_meta(self, target: str) -> TargetMeta | None:
81
+ return cast(TargetMeta, self._target_meta.get(target))
82
+
83
+ def get_target_parameter_schema(self, target: str) -> dict[str, Any] | None:
84
+ return self._request_schemas.get(target)
85
+
86
+ def get_shared_parameters(self) -> dict[str, Any]:
87
+ return {}
88
+
89
+ @property
90
+ def version(self) -> str | None:
91
+ return None
92
+
93
+
94
+ BundledSchema.shared = BundledSchema()
95
+
96
+ # Satisfy DecodoSchema protocol
97
+ _: DecodoSchema = BundledSchema.shared
@@ -0,0 +1,5 @@
1
+ DEFAULT_IR_BUCKET = "decodo-sdk-config"
2
+ DEFAULT_IR_PREFIX = "decodo-ir-v"
3
+ DEFAULT_IR_BASE = "https://storage.googleapis.com/decodo-sdk-config"
4
+ DEFAULT_IR_LIST_URL = "https://storage.googleapis.com/storage/v1/b/decodo-sdk-config/o?prefix=decodo-ir-v"
5
+ DEFAULT_IR_CACHE_PATH = "~/.decodo/decodo.ir.json"
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+
7
+ def expand_path(path: str) -> str:
8
+ if path.startswith("~/"):
9
+ return str(Path.home() / path[2:])
10
+ if path == "~":
11
+ return str(Path.home())
12
+ return os.path.abspath(path)
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import time
6
+ from typing import Any, cast
7
+
8
+ import httpx
9
+
10
+ from .build_target_meta import build_target_meta
11
+ from .constants import DEFAULT_IR_CACHE_PATH
12
+ from .expand_path import expand_path
13
+ from .resolve_latest_ir import resolve_latest_ir
14
+ from .types import (
15
+ CachedIr,
16
+ DecodoSchema,
17
+ RemoteIr,
18
+ RemoteSchemaLoadOptions,
19
+ TargetMeta,
20
+ )
21
+
22
+
23
+ def _read_cached_ir(cache_path: str) -> CachedIr | None:
24
+ try:
25
+ with open(cache_path, encoding="utf-8") as f:
26
+ return cast(CachedIr, json.load(f))
27
+ except Exception:
28
+ return None
29
+
30
+
31
+ def _is_cache_fresh(cached: CachedIr, ttl_ms: int | None) -> bool:
32
+ if ttl_ms is None:
33
+ return True
34
+ return (time.time() * 1000 - cached["fetched_at"]) < ttl_ms
35
+
36
+
37
+ def _fetch_ir(url: str) -> RemoteIr:
38
+ response = httpx.get(url, headers={"Accept": "application/json"})
39
+ if not response.is_success:
40
+ raise RuntimeError(f"Failed to fetch IR from {url}: HTTP {response.status_code}")
41
+ return cast(RemoteIr, response.json())
42
+
43
+
44
+ def _write_cached_ir(cache_path: str, cached: CachedIr) -> None:
45
+ os.makedirs(os.path.dirname(cache_path), exist_ok=True)
46
+ with open(cache_path, "w", encoding="utf-8") as f:
47
+ json.dump(cached, f, indent=2)
48
+
49
+
50
+ def _resolve_ir_url(
51
+ options: RemoteSchemaLoadOptions,
52
+ ) -> tuple[str, str | None]:
53
+ url = options.get("url")
54
+ if url:
55
+ return url, None
56
+ latest = resolve_latest_ir()
57
+ return latest["url"], latest["version"]
58
+
59
+
60
+ def _load_ir(options: RemoteSchemaLoadOptions) -> RemoteIr:
61
+ cache_path = expand_path(options.get("cache_path") or DEFAULT_IR_CACHE_PATH)
62
+ cached = _read_cached_ir(cache_path)
63
+ resolved_url, resolved_version = _resolve_ir_url(options)
64
+ ttl_ms = options.get("ttl_ms")
65
+
66
+ if cached is not None and cached.get("resolved_url") == resolved_url:
67
+ if _is_cache_fresh(cached, ttl_ms):
68
+ return cached["ir"]
69
+
70
+ if options.get("url") or cached["ir"].get("version") == resolved_version:
71
+ return cached["ir"]
72
+
73
+ ir = _fetch_ir(resolved_url)
74
+ _write_cached_ir(
75
+ cache_path,
76
+ CachedIr(
77
+ fetched_at=int(time.time() * 1000),
78
+ resolved_url=resolved_url,
79
+ ir=ir,
80
+ ),
81
+ )
82
+ return ir
83
+
84
+
85
+ def _build_parameter_schemas(ir: RemoteIr) -> dict[str, dict[str, Any]]:
86
+ schemas: dict[str, dict[str, Any]] = {}
87
+ for target_key, target in ir["apis"]["webScrapingApi"]["targets"].items():
88
+ schemas[target_key] = target["parameter_schema"]
89
+ return schemas
90
+
91
+
92
+ class RemoteSchema:
93
+ def __init__(
94
+ self,
95
+ ir: RemoteIr,
96
+ parameter_schemas: dict[str, dict[str, Any]],
97
+ ) -> None:
98
+ self._version = ir["version"]
99
+ self._meta = build_target_meta(ir["apis"]["webScrapingApi"]["targets"])
100
+ self._parameter_schemas = parameter_schemas
101
+ self._request_schemas = {
102
+ k: v["parameter_schema"]
103
+ for k, v in ir["apis"]["webScrapingApi"]["targets"].items()
104
+ }
105
+ self._shared_parameters: dict[str, Any] = ir["apis"]["webScrapingApi"].get("parameters") or {}
106
+ self._target_keys = list(ir["apis"]["webScrapingApi"]["targets"].keys())
107
+
108
+ @classmethod
109
+ def load(cls, options: RemoteSchemaLoadOptions | None = None) -> RemoteSchema:
110
+ opts: RemoteSchemaLoadOptions = options or RemoteSchemaLoadOptions()
111
+ ir = _load_ir(opts)
112
+ parameter_schemas = _build_parameter_schemas(ir)
113
+ return cls(ir, parameter_schemas)
114
+
115
+ def get_request_schema(self, target: str) -> dict[str, Any] | None:
116
+ return self._request_schemas.get(target)
117
+
118
+ def list_targets(self) -> list[str]:
119
+ return list(self._target_keys)
120
+
121
+ def get_target_meta(self, target: str) -> TargetMeta | None:
122
+ return self._meta.get(target)
123
+
124
+ def get_target_parameter_schema(self, target: str) -> dict[str, Any] | None:
125
+ return self._parameter_schemas.get(target)
126
+
127
+ def get_shared_parameters(self) -> dict[str, Any]:
128
+ return self._shared_parameters
129
+
130
+ @property
131
+ def version(self) -> str | None:
132
+ return self._version
133
+
134
+
135
+ # Satisfy DecodoSchema protocol
136
+ _: DecodoSchema = RemoteSchema.__new__(RemoteSchema)
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+ import httpx
6
+
7
+ from .constants import DEFAULT_IR_BASE, DEFAULT_IR_LIST_URL, DEFAULT_IR_PREFIX
8
+ from .types import GcsObjectList, LatestIrLocation
9
+
10
+ _IR_OBJECT_PATTERN = re.compile(r"^decodo-ir-v(.+)\.json$")
11
+
12
+
13
+ def _parse_semver(version: str) -> tuple[int, int, int] | None:
14
+ match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version)
15
+ if not match:
16
+ return None
17
+ return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
18
+
19
+
20
+ def _compare_semver(left: str, right: str) -> int:
21
+ parsed_left = _parse_semver(left)
22
+ parsed_right = _parse_semver(right)
23
+
24
+ if parsed_left is None or parsed_right is None:
25
+ if left < right:
26
+ return -1
27
+ if left > right:
28
+ return 1
29
+ return 0
30
+
31
+ for lv, r in zip(parsed_left, parsed_right):
32
+ if lv != r:
33
+ return lv - r
34
+
35
+ return 0
36
+
37
+
38
+ def _parse_ir_versions(names: list[str]) -> list[str]:
39
+ versions: list[str] = []
40
+ for name in names:
41
+ match = _IR_OBJECT_PATTERN.match(name)
42
+ if match and _parse_semver(match.group(1)):
43
+ versions.append(match.group(1))
44
+ return versions
45
+
46
+
47
+ def resolve_latest_ir() -> LatestIrLocation:
48
+ response = httpx.get(DEFAULT_IR_LIST_URL, headers={"Accept": "application/json"})
49
+
50
+ if not response.is_success:
51
+ raise RuntimeError(
52
+ f"Failed to list IR versions from {DEFAULT_IR_LIST_URL}: HTTP {response.status_code}"
53
+ )
54
+
55
+ body: GcsObjectList = response.json()
56
+ names = [item["name"] for item in body.get("items", [])]
57
+ versions = _parse_ir_versions(names)
58
+
59
+ if not versions:
60
+ raise RuntimeError(
61
+ f'No versioned IR objects found in bucket with prefix "{DEFAULT_IR_PREFIX}".'
62
+ )
63
+
64
+ version = max(versions, key=lambda v: _parse_semver(v) or (0, 0, 0))
65
+
66
+ return LatestIrLocation(
67
+ version=version,
68
+ url=f"{DEFAULT_IR_BASE}/{DEFAULT_IR_PREFIX}{version}.json",
69
+ )
decodo/schema/types.py ADDED
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Protocol, TypedDict
4
+
5
+
6
+ class TargetMeta(TypedDict):
7
+ group: str
8
+ response_format: str
9
+ parameters: list[str]
10
+
11
+
12
+ class IrTarget(TypedDict):
13
+ group: str
14
+ response_format: str
15
+ parameter_schema: dict[str, Any]
16
+
17
+
18
+ class RemoteIr(TypedDict):
19
+ version: str
20
+ apis: RemoteIrApis
21
+
22
+
23
+ class RemoteIrApis(TypedDict):
24
+ webScrapingApi: WebScrapingApiIr
25
+
26
+
27
+ class WebScrapingApiIr(TypedDict):
28
+ parameters: dict[str, Any]
29
+ targets: dict[str, IrTarget]
30
+
31
+
32
+ class CachedIr(TypedDict):
33
+ fetched_at: int
34
+ resolved_url: str
35
+ ir: RemoteIr
36
+
37
+
38
+ class GcsObjectListItem(TypedDict):
39
+ name: str
40
+
41
+
42
+ class GcsObjectList(TypedDict, total=False):
43
+ items: list[GcsObjectListItem]
44
+
45
+
46
+ class LatestIrLocation(TypedDict):
47
+ version: str
48
+ url: str
49
+
50
+
51
+ class RemoteSchemaLoadOptions(TypedDict, total=False):
52
+ url: str
53
+ cache_path: str
54
+ ttl_ms: int
55
+
56
+
57
+ class DecodoSchema(Protocol):
58
+ def get_request_schema(self, target: str) -> dict[str, Any] | None: ...
59
+ def list_targets(self) -> list[str]: ...
60
+ def get_target_meta(self, target: str) -> TargetMeta | None: ...
61
+ def get_target_parameter_schema(self, target: str) -> dict[str, Any] | None: ...
62
+ def get_shared_parameters(self) -> dict[str, Any]: ...
63
+
64
+ @property
65
+ def version(self) -> str | None: ...
decodo/targets.py ADDED
@@ -0,0 +1,63 @@
1
+ # Minimal target enum — committed to source.
2
+ # Run `python -m decodo.codegen.codegen` to regenerate when the IR schema changes.
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+
7
+
8
+ class Target(StrEnum):
9
+ UniversalEcommerce = "universal_ecommerce"
10
+ GoogleSearch = "google_search"
11
+ GoogleTravelHotels = "google_travel_hotels"
12
+ GoogleTrendsExplore = "google_trends_explore"
13
+ GoogleShoppingSearch = "google_shopping_search"
14
+ GoogleShoppingProduct = "google_shopping_product"
15
+ Google = "google"
16
+ GoogleSuggest = "google_suggest"
17
+ GoogleMaps = "google_maps"
18
+ GoogleAiMode = "google_ai_mode"
19
+ GoogleAds = "google_ads"
20
+ GoogleLens = "google_lens"
21
+ BingSearch = "bing_search"
22
+ Bing = "bing"
23
+ YoutubeTranscript = "youtube_transcript"
24
+ AmazonProduct = "amazon_product"
25
+ AmazonPricing = "amazon_pricing"
26
+ AmazonSearch = "amazon_search"
27
+ AmazonSellers = "amazon_sellers"
28
+ AmazonBestsellers = "amazon_bestsellers"
29
+ Amazon = "amazon"
30
+ Ecommerce = "ecommerce"
31
+ WalmartProduct = "walmart_product"
32
+ WalmartSearch = "walmart_search"
33
+ Walmart = "walmart"
34
+ TargetProduct = "target_product"
35
+ TargetSearch = "target_search"
36
+ Target = "target"
37
+ LowesSearch = "lowes_search"
38
+ Universal = "universal"
39
+ Chatgpt = "chatgpt"
40
+ Perplexity = "perplexity"
41
+ Gemini = "gemini"
42
+ Bbb = "bbb"
43
+ Autotrader = "autotrader"
44
+ Mobile = "mobile"
45
+ Airbnb = "airbnb"
46
+ AppleAppStore = "apple_app_store"
47
+ InstagramGraphqlProfile = "instagram_graphql_profile"
48
+ TiktokPost = "tiktok_post"
49
+ TiktokShopSearch = "tiktok_shop_search"
50
+ TiktokShopProduct = "tiktok_shop_product"
51
+ Tiktok = "tiktok"
52
+ RedditPost = "reddit_post"
53
+ RedditSubreddit = "reddit_subreddit"
54
+ RedditUser = "reddit_user"
55
+ YoutubeVideo = "youtube_video"
56
+ YoutubeMetadata = "youtube_metadata"
57
+ YoutubeSearch = "youtube_search"
58
+ YoutubeSearchMax = "youtube_search_max"
59
+ YoutubeSubtitles = "youtube_subtitles"
60
+ YoutubeChannel = "youtube_channel"
61
+
62
+
63
+ targets: list[str] = [t.value for t in Target]
@@ -0,0 +1,27 @@
1
+ try:
2
+ from .requests import BatchRequest, ScrapeRequest
3
+ except ImportError:
4
+ pass
5
+ from .responses import (
6
+ AsyncTaskResponse,
7
+ BatchResponse,
8
+ ErrorResponse,
9
+ ResultEntry,
10
+ SyncResponse,
11
+ TaskMetadata,
12
+ TaskResultsResponse,
13
+ TaskStatus,
14
+ )
15
+
16
+ __all__ = [
17
+ "ScrapeRequest",
18
+ "BatchRequest",
19
+ "ResultEntry",
20
+ "SyncResponse",
21
+ "AsyncTaskResponse",
22
+ "BatchResponse",
23
+ "TaskStatus",
24
+ "TaskMetadata",
25
+ "TaskResultsResponse",
26
+ "ErrorResponse",
27
+ ]
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ try:
4
+ from decodo.generated.targets import BatchRequest, ScrapeRequest
5
+ __all__ = ["ScrapeRequest", "BatchRequest"]
6
+ except ImportError:
7
+ __all__ = []