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/__init__.py +292 -0
- decodo/api/__init__.py +3 -0
- decodo/api/web_scraping_api.py +74 -0
- decodo/client.py +58 -0
- decodo/codegen/__init__.py +0 -0
- decodo/codegen/codegen.py +71 -0
- decodo/codegen/web_scraping_api/__init__.py +0 -0
- decodo/codegen/web_scraping_api/generate_parameters.py +124 -0
- decodo/codegen/web_scraping_api/generate_targets.py +223 -0
- decodo/codegen/web_scraping_api/shared.py +65 -0
- decodo/codegen/web_scraping_api/types.py +26 -0
- decodo/errors.py +36 -0
- decodo/generated/__init__.py +0 -0
- decodo/generated/decodo.ir.json +2775 -0
- decodo/generated/parameters.py +93 -0
- decodo/generated/targets.py +1585 -0
- decodo/http.py +111 -0
- decodo/py.typed +0 -0
- decodo/schema/__init__.py +25 -0
- decodo/schema/build_target_meta.py +23 -0
- decodo/schema/bundled_schema.py +97 -0
- decodo/schema/constants.py +5 -0
- decodo/schema/expand_path.py +12 -0
- decodo/schema/remote_schema.py +136 -0
- decodo/schema/resolve_latest_ir.py +69 -0
- decodo/schema/types.py +65 -0
- decodo/targets.py +63 -0
- decodo/types/__init__.py +27 -0
- decodo/types/requests.py +7 -0
- decodo/types/responses.py +71 -0
- decodo_sdk-2.2.0.dist-info/METADATA +459 -0
- decodo_sdk-2.2.0.dist-info/RECORD +35 -0
- decodo_sdk-2.2.0.dist-info/WHEEL +5 -0
- decodo_sdk-2.2.0.dist-info/licenses/LICENSE +21 -0
- decodo_sdk-2.2.0.dist-info/top_level.txt +1 -0
decodo/__init__.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
from .api.web_scraping_api import WebScrapingApi
|
|
2
|
+
from .client import DecodoClient, DecodoConfig, WebScrapingApiConfig
|
|
3
|
+
from .errors import (
|
|
4
|
+
AuthenticationError,
|
|
5
|
+
DecodoError,
|
|
6
|
+
RateLimitError,
|
|
7
|
+
TimeoutError,
|
|
8
|
+
ValidationError,
|
|
9
|
+
)
|
|
10
|
+
from .schema.bundled_schema import BundledSchema
|
|
11
|
+
from .schema.remote_schema import RemoteSchema
|
|
12
|
+
from .schema.types import DecodoSchema, RemoteSchemaLoadOptions
|
|
13
|
+
from .targets import Target, targets
|
|
14
|
+
from .types.responses import (
|
|
15
|
+
AsyncTaskResponse,
|
|
16
|
+
BatchResponse,
|
|
17
|
+
ResultEntry,
|
|
18
|
+
SyncResponse,
|
|
19
|
+
TaskMetadata,
|
|
20
|
+
TaskResultsResponse,
|
|
21
|
+
TaskStatus,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
_codegen_available = False
|
|
25
|
+
try:
|
|
26
|
+
from .generated.parameters import ParameterMeta, parameter_meta # noqa: F401
|
|
27
|
+
from .generated.targets import ( # noqa: F401
|
|
28
|
+
AirbnbBatchParams,
|
|
29
|
+
AirbnbParams,
|
|
30
|
+
AmazonBatchParams,
|
|
31
|
+
AmazonBestsellersBatchParams,
|
|
32
|
+
AmazonBestsellersParams,
|
|
33
|
+
AmazonParams,
|
|
34
|
+
AmazonPricingBatchParams,
|
|
35
|
+
AmazonPricingParams,
|
|
36
|
+
AmazonProductBatchParams,
|
|
37
|
+
AmazonProductParams,
|
|
38
|
+
AmazonSearchBatchParams,
|
|
39
|
+
AmazonSearchParams,
|
|
40
|
+
AmazonSellersBatchParams,
|
|
41
|
+
AmazonSellersParams,
|
|
42
|
+
AppleAppStoreBatchParams,
|
|
43
|
+
AppleAppStoreParams,
|
|
44
|
+
AutotraderBatchParams,
|
|
45
|
+
AutotraderParams,
|
|
46
|
+
BatchRequest,
|
|
47
|
+
BbbBatchParams,
|
|
48
|
+
BbbParams,
|
|
49
|
+
BingBatchParams,
|
|
50
|
+
BingParams,
|
|
51
|
+
BingSearchBatchParams,
|
|
52
|
+
BingSearchParams,
|
|
53
|
+
ChatgptBatchParams,
|
|
54
|
+
ChatgptParams,
|
|
55
|
+
EcommerceBatchParams,
|
|
56
|
+
EcommerceParams,
|
|
57
|
+
GeminiBatchParams,
|
|
58
|
+
GeminiParams,
|
|
59
|
+
GoogleAdsBatchParams,
|
|
60
|
+
GoogleAdsParams,
|
|
61
|
+
GoogleAiModeBatchParams,
|
|
62
|
+
GoogleAiModeParams,
|
|
63
|
+
GoogleBatchParams,
|
|
64
|
+
GoogleLensBatchParams,
|
|
65
|
+
GoogleLensParams,
|
|
66
|
+
GoogleMapsBatchParams,
|
|
67
|
+
GoogleMapsParams,
|
|
68
|
+
GoogleParams,
|
|
69
|
+
GoogleSearchBatchParams,
|
|
70
|
+
GoogleSearchParams,
|
|
71
|
+
GoogleShoppingProductBatchParams,
|
|
72
|
+
GoogleShoppingProductParams,
|
|
73
|
+
GoogleShoppingSearchBatchParams,
|
|
74
|
+
GoogleShoppingSearchParams,
|
|
75
|
+
GoogleSuggestBatchParams,
|
|
76
|
+
GoogleSuggestParams,
|
|
77
|
+
GoogleTravelHotelsBatchParams,
|
|
78
|
+
GoogleTravelHotelsParams,
|
|
79
|
+
GoogleTrendsExploreBatchParams,
|
|
80
|
+
GoogleTrendsExploreParams,
|
|
81
|
+
InstagramGraphqlProfileBatchParams,
|
|
82
|
+
InstagramGraphqlProfileParams,
|
|
83
|
+
LowesSearchBatchParams,
|
|
84
|
+
LowesSearchParams,
|
|
85
|
+
MobileBatchParams,
|
|
86
|
+
MobileParams,
|
|
87
|
+
PerplexityBatchParams,
|
|
88
|
+
PerplexityParams,
|
|
89
|
+
RedditPostBatchParams,
|
|
90
|
+
RedditPostParams,
|
|
91
|
+
RedditSubredditBatchParams,
|
|
92
|
+
RedditSubredditParams,
|
|
93
|
+
RedditUserBatchParams,
|
|
94
|
+
RedditUserParams,
|
|
95
|
+
ScrapeRequest,
|
|
96
|
+
TargetProductBatchParams,
|
|
97
|
+
TargetProductParams,
|
|
98
|
+
TargetSearchBatchParams,
|
|
99
|
+
TargetSearchParams,
|
|
100
|
+
TargetStoreBatchParams,
|
|
101
|
+
TargetStoreParams,
|
|
102
|
+
TiktokBatchParams,
|
|
103
|
+
TiktokParams,
|
|
104
|
+
TiktokPostBatchParams,
|
|
105
|
+
TiktokPostParams,
|
|
106
|
+
TiktokShopProductBatchParams,
|
|
107
|
+
TiktokShopProductParams,
|
|
108
|
+
TiktokShopSearchBatchParams,
|
|
109
|
+
TiktokShopSearchParams,
|
|
110
|
+
UniversalBatchParams,
|
|
111
|
+
UniversalEcommerceBatchParams,
|
|
112
|
+
UniversalEcommerceParams,
|
|
113
|
+
UniversalParams,
|
|
114
|
+
WalmartBatchParams,
|
|
115
|
+
WalmartParams,
|
|
116
|
+
WalmartProductBatchParams,
|
|
117
|
+
WalmartProductParams,
|
|
118
|
+
WalmartSearchBatchParams,
|
|
119
|
+
WalmartSearchParams,
|
|
120
|
+
YoutubeChannelBatchParams,
|
|
121
|
+
YoutubeChannelParams,
|
|
122
|
+
YoutubeMetadataBatchParams,
|
|
123
|
+
YoutubeMetadataParams,
|
|
124
|
+
YoutubeSearchBatchParams,
|
|
125
|
+
YoutubeSearchMaxBatchParams,
|
|
126
|
+
YoutubeSearchMaxParams,
|
|
127
|
+
YoutubeSearchParams,
|
|
128
|
+
YoutubeSubtitlesBatchParams,
|
|
129
|
+
YoutubeSubtitlesParams,
|
|
130
|
+
YoutubeTranscriptBatchParams,
|
|
131
|
+
YoutubeTranscriptParams,
|
|
132
|
+
YoutubeVideoBatchParams,
|
|
133
|
+
YoutubeVideoParams,
|
|
134
|
+
target_meta,
|
|
135
|
+
)
|
|
136
|
+
_codegen_available = True
|
|
137
|
+
except ImportError:
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
_CODEGEN_NAMES: frozenset[str] = frozenset(
|
|
141
|
+
[
|
|
142
|
+
"AirbnbBatchParams",
|
|
143
|
+
"AirbnbParams",
|
|
144
|
+
"AmazonBatchParams",
|
|
145
|
+
"AmazonBestsellersBatchParams",
|
|
146
|
+
"AmazonBestsellersParams",
|
|
147
|
+
"AmazonParams",
|
|
148
|
+
"AmazonPricingBatchParams",
|
|
149
|
+
"AmazonPricingParams",
|
|
150
|
+
"AmazonProductBatchParams",
|
|
151
|
+
"AmazonProductParams",
|
|
152
|
+
"AmazonSearchBatchParams",
|
|
153
|
+
"AmazonSearchParams",
|
|
154
|
+
"AmazonSellersBatchParams",
|
|
155
|
+
"AmazonSellersParams",
|
|
156
|
+
"AppleAppStoreBatchParams",
|
|
157
|
+
"AppleAppStoreParams",
|
|
158
|
+
"AutotraderBatchParams",
|
|
159
|
+
"AutotraderParams",
|
|
160
|
+
"BatchRequest",
|
|
161
|
+
"BbbBatchParams",
|
|
162
|
+
"BbbParams",
|
|
163
|
+
"BingBatchParams",
|
|
164
|
+
"BingParams",
|
|
165
|
+
"BingSearchBatchParams",
|
|
166
|
+
"BingSearchParams",
|
|
167
|
+
"ChatgptBatchParams",
|
|
168
|
+
"ChatgptParams",
|
|
169
|
+
"EcommerceBatchParams",
|
|
170
|
+
"EcommerceParams",
|
|
171
|
+
"GeminiBatchParams",
|
|
172
|
+
"GeminiParams",
|
|
173
|
+
"GoogleAdsBatchParams",
|
|
174
|
+
"GoogleAdsParams",
|
|
175
|
+
"GoogleAiModeBatchParams",
|
|
176
|
+
"GoogleAiModeParams",
|
|
177
|
+
"GoogleBatchParams",
|
|
178
|
+
"GoogleLensBatchParams",
|
|
179
|
+
"GoogleLensParams",
|
|
180
|
+
"GoogleMapsBatchParams",
|
|
181
|
+
"GoogleMapsParams",
|
|
182
|
+
"GoogleParams",
|
|
183
|
+
"GoogleSearchBatchParams",
|
|
184
|
+
"GoogleSearchParams",
|
|
185
|
+
"GoogleShoppingProductBatchParams",
|
|
186
|
+
"GoogleShoppingProductParams",
|
|
187
|
+
"GoogleShoppingSearchBatchParams",
|
|
188
|
+
"GoogleShoppingSearchParams",
|
|
189
|
+
"GoogleSuggestBatchParams",
|
|
190
|
+
"GoogleSuggestParams",
|
|
191
|
+
"GoogleTravelHotelsBatchParams",
|
|
192
|
+
"GoogleTravelHotelsParams",
|
|
193
|
+
"GoogleTrendsExploreBatchParams",
|
|
194
|
+
"GoogleTrendsExploreParams",
|
|
195
|
+
"InstagramGraphqlProfileBatchParams",
|
|
196
|
+
"InstagramGraphqlProfileParams",
|
|
197
|
+
"LowesSearchBatchParams",
|
|
198
|
+
"LowesSearchParams",
|
|
199
|
+
"MobileBatchParams",
|
|
200
|
+
"MobileParams",
|
|
201
|
+
"ParameterMeta",
|
|
202
|
+
"PerplexityBatchParams",
|
|
203
|
+
"PerplexityParams",
|
|
204
|
+
"RedditPostBatchParams",
|
|
205
|
+
"RedditPostParams",
|
|
206
|
+
"RedditSubredditBatchParams",
|
|
207
|
+
"RedditSubredditParams",
|
|
208
|
+
"RedditUserBatchParams",
|
|
209
|
+
"RedditUserParams",
|
|
210
|
+
"ScrapeRequest",
|
|
211
|
+
"TargetProductBatchParams",
|
|
212
|
+
"TargetProductParams",
|
|
213
|
+
"TargetSearchBatchParams",
|
|
214
|
+
"TargetSearchParams",
|
|
215
|
+
"TargetStoreBatchParams",
|
|
216
|
+
"TargetStoreParams",
|
|
217
|
+
"TiktokBatchParams",
|
|
218
|
+
"TiktokParams",
|
|
219
|
+
"TiktokPostBatchParams",
|
|
220
|
+
"TiktokPostParams",
|
|
221
|
+
"TiktokShopProductBatchParams",
|
|
222
|
+
"TiktokShopProductParams",
|
|
223
|
+
"TiktokShopSearchBatchParams",
|
|
224
|
+
"TiktokShopSearchParams",
|
|
225
|
+
"UniversalBatchParams",
|
|
226
|
+
"UniversalEcommerceBatchParams",
|
|
227
|
+
"UniversalEcommerceParams",
|
|
228
|
+
"UniversalParams",
|
|
229
|
+
"WalmartBatchParams",
|
|
230
|
+
"WalmartParams",
|
|
231
|
+
"WalmartProductBatchParams",
|
|
232
|
+
"WalmartProductParams",
|
|
233
|
+
"WalmartSearchBatchParams",
|
|
234
|
+
"WalmartSearchParams",
|
|
235
|
+
"YoutubeChannelBatchParams",
|
|
236
|
+
"YoutubeChannelParams",
|
|
237
|
+
"YoutubeMetadataBatchParams",
|
|
238
|
+
"YoutubeMetadataParams",
|
|
239
|
+
"YoutubeSearchBatchParams",
|
|
240
|
+
"YoutubeSearchMaxBatchParams",
|
|
241
|
+
"YoutubeSearchMaxParams",
|
|
242
|
+
"YoutubeSearchParams",
|
|
243
|
+
"YoutubeSubtitlesBatchParams",
|
|
244
|
+
"YoutubeSubtitlesParams",
|
|
245
|
+
"YoutubeTranscriptBatchParams",
|
|
246
|
+
"YoutubeTranscriptParams",
|
|
247
|
+
"YoutubeVideoBatchParams",
|
|
248
|
+
"YoutubeVideoParams",
|
|
249
|
+
"parameter_meta",
|
|
250
|
+
"target_meta",
|
|
251
|
+
]
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def __getattr__(name: str) -> object:
|
|
256
|
+
if name in _CODEGEN_NAMES:
|
|
257
|
+
raise ImportError(
|
|
258
|
+
f"'{name}' requires generated types. "
|
|
259
|
+
"Editable install: run python -m decodo.codegen.codegen, then use 'from decodo import ...'. "
|
|
260
|
+
"Pip install: run python -m decodo.codegen.codegen --out-dir ./decodo_generated, "
|
|
261
|
+
"then use 'from decodo_generated.targets import ...'."
|
|
262
|
+
)
|
|
263
|
+
raise AttributeError(f"module 'decodo' has no attribute {name!r}")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
__all__ = [
|
|
267
|
+
"DecodoClient",
|
|
268
|
+
"DecodoConfig",
|
|
269
|
+
"WebScrapingApiConfig",
|
|
270
|
+
"WebScrapingApi",
|
|
271
|
+
"BundledSchema",
|
|
272
|
+
"RemoteSchema",
|
|
273
|
+
"DecodoSchema",
|
|
274
|
+
"RemoteSchemaLoadOptions",
|
|
275
|
+
"Target",
|
|
276
|
+
"targets",
|
|
277
|
+
"SyncResponse",
|
|
278
|
+
"AsyncTaskResponse",
|
|
279
|
+
"BatchResponse",
|
|
280
|
+
"TaskMetadata",
|
|
281
|
+
"TaskResultsResponse",
|
|
282
|
+
"TaskStatus",
|
|
283
|
+
"ResultEntry",
|
|
284
|
+
"DecodoError",
|
|
285
|
+
"AuthenticationError",
|
|
286
|
+
"RateLimitError",
|
|
287
|
+
"ValidationError",
|
|
288
|
+
"TimeoutError",
|
|
289
|
+
]
|
|
290
|
+
|
|
291
|
+
if _codegen_available:
|
|
292
|
+
__all__ += list(_CODEGEN_NAMES)
|
decodo/api/__init__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
5
|
+
|
|
6
|
+
import jsonschema
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
import decodo.errors
|
|
10
|
+
from decodo.http import HttpClient
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from decodo.generated.targets import BatchRequest, ScrapeRequest
|
|
14
|
+
from decodo.schema.bundled_schema import BundledSchema
|
|
15
|
+
from decodo.schema.types import DecodoSchema
|
|
16
|
+
from decodo.types.responses import (
|
|
17
|
+
AsyncTaskResponse,
|
|
18
|
+
BatchResponse,
|
|
19
|
+
SyncResponse,
|
|
20
|
+
TaskMetadata,
|
|
21
|
+
TaskResultsResponse,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _to_payload(params: ScrapeRequest | BatchRequest | Mapping[str, Any]) -> dict[str, Any]:
|
|
26
|
+
if isinstance(params, BaseModel):
|
|
27
|
+
return params.model_dump(by_alias=True, exclude_none=True, mode="json")
|
|
28
|
+
return dict(params)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class WebScrapingApi:
|
|
32
|
+
def __init__(self, http: HttpClient, schema: DecodoSchema = BundledSchema.shared) -> None:
|
|
33
|
+
self._http = http
|
|
34
|
+
self._schema = schema
|
|
35
|
+
|
|
36
|
+
def _validate(self, payload: dict[str, Any]) -> None:
|
|
37
|
+
if self._schema is None:
|
|
38
|
+
return
|
|
39
|
+
if "target" not in payload:
|
|
40
|
+
raise decodo.errors.ValidationError("missing required field 'target'")
|
|
41
|
+
schema = self._schema.get_request_schema(payload.get("target")) # type: ignore[arg-type]
|
|
42
|
+
if not schema:
|
|
43
|
+
target = payload["target"]
|
|
44
|
+
valid = self._schema.list_targets()
|
|
45
|
+
if target not in valid:
|
|
46
|
+
raise decodo.errors.ValidationError(
|
|
47
|
+
f"unknown target {target!r}. Valid targets: {', '.join(sorted(valid))}"
|
|
48
|
+
)
|
|
49
|
+
return
|
|
50
|
+
try:
|
|
51
|
+
jsonschema.validate(payload, schema)
|
|
52
|
+
except jsonschema.ValidationError as e:
|
|
53
|
+
raise decodo.errors.ValidationError(str(e)) from e
|
|
54
|
+
|
|
55
|
+
def scrape(self, params: ScrapeRequest | Mapping[str, Any]) -> SyncResponse:
|
|
56
|
+
payload = _to_payload(params)
|
|
57
|
+
self._validate(payload)
|
|
58
|
+
return cast(SyncResponse, self._http.post("/v2/scrape", payload))
|
|
59
|
+
|
|
60
|
+
def scrape_async(self, params: ScrapeRequest | Mapping[str, Any]) -> AsyncTaskResponse:
|
|
61
|
+
payload = _to_payload(params)
|
|
62
|
+
self._validate(payload)
|
|
63
|
+
return cast(AsyncTaskResponse, self._http.post("/v3/task", payload))
|
|
64
|
+
|
|
65
|
+
def scrape_batch(self, params: BatchRequest | Mapping[str, Any]) -> BatchResponse:
|
|
66
|
+
payload = _to_payload(params)
|
|
67
|
+
return cast(BatchResponse, self._http.post("/v3/task/batch", payload))
|
|
68
|
+
|
|
69
|
+
def get_status(self, task_id: str) -> TaskMetadata:
|
|
70
|
+
return cast(TaskMetadata, self._http.get(f"/v3/task/{task_id}"))
|
|
71
|
+
|
|
72
|
+
def get_results(self, task_id: str) -> TaskResultsResponse | None:
|
|
73
|
+
result = self._http.get(f"/v3/task/{task_id}/results")
|
|
74
|
+
return cast(TaskResultsResponse, result) if result is not None else None
|
decodo/client.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .api.web_scraping_api import WebScrapingApi
|
|
7
|
+
from .http import BasicAuth, HttpClient, HttpClientConfig
|
|
8
|
+
from .schema.bundled_schema import BundledSchema
|
|
9
|
+
from .schema.types import DecodoSchema
|
|
10
|
+
|
|
11
|
+
WEB_API_BASE_URL = "https://scraper-api.decodo.com"
|
|
12
|
+
DEFAULT_TIMEOUT_MS = 180_000
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class WebScrapingApiConfig:
|
|
17
|
+
token: str
|
|
18
|
+
integration_header: str | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class DecodoConfig:
|
|
23
|
+
web_scraping_api: WebScrapingApiConfig | None = None
|
|
24
|
+
timeout_ms: int = DEFAULT_TIMEOUT_MS
|
|
25
|
+
schema: DecodoSchema | None = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _not_configured(namespace: str, hint: str) -> Any:
|
|
29
|
+
raise RuntimeError(f"{namespace} is not configured. {hint}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _UnconfiguredWebScrapingApi:
|
|
33
|
+
def __getattr__(self, name: str) -> Any:
|
|
34
|
+
_not_configured(
|
|
35
|
+
"web_scraping_api",
|
|
36
|
+
"Provide web_scraping_api in DecodoConfig.",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DecodoClient:
|
|
41
|
+
web_scraping_api: WebScrapingApi
|
|
42
|
+
|
|
43
|
+
def __init__(self, config: DecodoConfig) -> None:
|
|
44
|
+
timeout_ms = config.timeout_ms
|
|
45
|
+
schema: DecodoSchema = config.schema if config.schema is not None else BundledSchema.shared
|
|
46
|
+
|
|
47
|
+
if config.web_scraping_api is not None:
|
|
48
|
+
http = HttpClient(
|
|
49
|
+
HttpClientConfig(
|
|
50
|
+
base_url=WEB_API_BASE_URL,
|
|
51
|
+
auth=BasicAuth(type="basic", token=config.web_scraping_api.token),
|
|
52
|
+
timeout_ms=timeout_ms,
|
|
53
|
+
integration_header=config.web_scraping_api.integration_header,
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
self.web_scraping_api = WebScrapingApi(http, schema)
|
|
57
|
+
else:
|
|
58
|
+
self.web_scraping_api = _UnconfiguredWebScrapingApi() # type: ignore[assignment]
|
|
File without changes
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .web_scraping_api.generate_parameters import generate_parameters_file
|
|
10
|
+
from .web_scraping_api.generate_targets import generate_targets_enum_file, generate_targets_file
|
|
11
|
+
from .web_scraping_api.shared import local_ir_path
|
|
12
|
+
from .web_scraping_api.shared import out_dir as _default_out_dir
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _in_site_packages() -> bool:
|
|
16
|
+
return "site-packages" in str(Path(__file__).resolve())
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main() -> None:
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
prog="python -m decodo.codegen.codegen",
|
|
22
|
+
description="Generate typed parameter classes from the Decodo IR schema.",
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--out-dir",
|
|
26
|
+
metavar="PATH",
|
|
27
|
+
default=None,
|
|
28
|
+
help=(
|
|
29
|
+
"Directory to write generated files into. "
|
|
30
|
+
"Defaults to the package's built-in generated/ directory "
|
|
31
|
+
"(editable installs only). Required for non-editable installs."
|
|
32
|
+
),
|
|
33
|
+
)
|
|
34
|
+
args = parser.parse_args()
|
|
35
|
+
|
|
36
|
+
if args.out_dir is not None:
|
|
37
|
+
out_dir = str(Path(args.out_dir).resolve())
|
|
38
|
+
elif _in_site_packages():
|
|
39
|
+
print(
|
|
40
|
+
"error: running from a non-editable install.\n"
|
|
41
|
+
"Generated files would be written into site-packages and silently reverted\n"
|
|
42
|
+
"on the next `pip install --upgrade`.\n"
|
|
43
|
+
"Use --out-dir <path> to specify a project-local output directory.",
|
|
44
|
+
file=sys.stderr,
|
|
45
|
+
)
|
|
46
|
+
sys.exit(1)
|
|
47
|
+
else:
|
|
48
|
+
out_dir = _default_out_dir
|
|
49
|
+
|
|
50
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
51
|
+
init_path = os.path.join(out_dir, "__init__.py")
|
|
52
|
+
if not os.path.exists(init_path):
|
|
53
|
+
open(init_path, "w").close()
|
|
54
|
+
|
|
55
|
+
generate_parameters_file(out_dir)
|
|
56
|
+
# The Target enum lives in decodo/targets.py (committed source). Only regenerate
|
|
57
|
+
# it when we have write access to the source tree (editable install). Non-editable
|
|
58
|
+
# installs already ship the enum baked into the package.
|
|
59
|
+
if not _in_site_packages():
|
|
60
|
+
generate_targets_enum_file()
|
|
61
|
+
generate_targets_file(out_dir)
|
|
62
|
+
|
|
63
|
+
# Copy the downloaded IR JSON into generated/ so BundledSchema can load
|
|
64
|
+
# schemas directly at runtime without a generated Python file.
|
|
65
|
+
ir_out_path = os.path.join(out_dir, "decodo.ir.json")
|
|
66
|
+
shutil.copy2(local_ir_path, ir_out_path)
|
|
67
|
+
print(f"Saved IR JSON to {ir_out_path}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
if __name__ == "__main__":
|
|
71
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .shared import (
|
|
8
|
+
fetch_intermediate_representation,
|
|
9
|
+
local_ir_path,
|
|
10
|
+
out_dir,
|
|
11
|
+
)
|
|
12
|
+
from .types import WebScrapingApiIR
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _ParameterMeta:
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
type: str,
|
|
19
|
+
max_length: int | None = None,
|
|
20
|
+
minimum: float | None = None,
|
|
21
|
+
maximum: float | None = None,
|
|
22
|
+
enum: list[Any] | None = None,
|
|
23
|
+
items: dict[str, Any] | None = None,
|
|
24
|
+
) -> None:
|
|
25
|
+
self.type = type
|
|
26
|
+
self.max_length = max_length
|
|
27
|
+
self.minimum = minimum
|
|
28
|
+
self.maximum = maximum
|
|
29
|
+
self.enum = enum
|
|
30
|
+
self.items = items
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _to_parameter_meta(schema: dict[str, Any]) -> _ParameterMeta:
|
|
34
|
+
meta = _ParameterMeta(type=str(schema.get("type", "string")))
|
|
35
|
+
if schema.get("maxLength") is not None:
|
|
36
|
+
meta.max_length = schema["maxLength"]
|
|
37
|
+
if schema.get("minimum") is not None:
|
|
38
|
+
meta.minimum = schema["minimum"]
|
|
39
|
+
if schema.get("maximum") is not None:
|
|
40
|
+
meta.maximum = schema["maximum"]
|
|
41
|
+
if isinstance(schema.get("enum"), list):
|
|
42
|
+
meta.enum = schema["enum"]
|
|
43
|
+
if schema.get("type") == "array" and schema.get("items"):
|
|
44
|
+
items = schema["items"]
|
|
45
|
+
if isinstance(items, list):
|
|
46
|
+
items = items[0] if items else {}
|
|
47
|
+
if isinstance(items, dict) and "type" in items:
|
|
48
|
+
meta.items = {"type": str(items["type"])}
|
|
49
|
+
return meta
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _format_parameter_meta(meta: _ParameterMeta) -> str:
|
|
53
|
+
parts: list[str] = []
|
|
54
|
+
parts.append(f"type={json.dumps(meta.type)}")
|
|
55
|
+
if meta.max_length is not None:
|
|
56
|
+
parts.append(f"max_length={meta.max_length}")
|
|
57
|
+
if meta.minimum is not None:
|
|
58
|
+
parts.append(f"minimum={meta.minimum}")
|
|
59
|
+
if meta.maximum is not None:
|
|
60
|
+
parts.append(f"maximum={meta.maximum}")
|
|
61
|
+
if meta.enum is not None:
|
|
62
|
+
enum_vals = ", ".join(json.dumps(v) for v in meta.enum)
|
|
63
|
+
parts.append(f"enum=[{enum_vals}]")
|
|
64
|
+
if meta.items is not None:
|
|
65
|
+
parts.append(f"items={{'type': {json.dumps(meta.items['type'])}}}")
|
|
66
|
+
return f"ParameterMeta({', '.join(parts)})"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _collect_parameter_meta(api: WebScrapingApiIR) -> dict[str, _ParameterMeta]:
|
|
70
|
+
collected: dict[str, _ParameterMeta] = {}
|
|
71
|
+
for target in api["targets"].values():
|
|
72
|
+
properties: dict[str, Any] = target["parameter_schema"].get("properties", {})
|
|
73
|
+
for name, schema in properties.items():
|
|
74
|
+
if name == "target":
|
|
75
|
+
continue
|
|
76
|
+
if name in collected:
|
|
77
|
+
continue
|
|
78
|
+
collected[name] = _to_parameter_meta(schema)
|
|
79
|
+
return collected
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def get_parameters_file(api: WebScrapingApiIR) -> str:
|
|
83
|
+
lines: list[str] = []
|
|
84
|
+
|
|
85
|
+
lines.append("# Auto-generated by src/decodo/codegen/web_scraping_api/generate_parameters.py — do not edit")
|
|
86
|
+
lines.append("from __future__ import annotations")
|
|
87
|
+
lines.append("")
|
|
88
|
+
lines.append("from typing import Any, TypedDict")
|
|
89
|
+
lines.append("")
|
|
90
|
+
lines.append("")
|
|
91
|
+
lines.append("class ParameterMeta(TypedDict, total=False):")
|
|
92
|
+
lines.append(" type: str")
|
|
93
|
+
lines.append(" max_length: int")
|
|
94
|
+
lines.append(" minimum: float")
|
|
95
|
+
lines.append(" maximum: float")
|
|
96
|
+
lines.append(" enum: list[Any]")
|
|
97
|
+
lines.append(" items: dict[str, Any]")
|
|
98
|
+
lines.append("")
|
|
99
|
+
lines.append("")
|
|
100
|
+
|
|
101
|
+
collected = _collect_parameter_meta(api)
|
|
102
|
+
lines.append("parameter_meta: dict[str, ParameterMeta] = {")
|
|
103
|
+
for key, meta in collected.items():
|
|
104
|
+
lines.append(f" {json.dumps(key)}: {_format_parameter_meta(meta)},")
|
|
105
|
+
lines.append("}")
|
|
106
|
+
lines.append("")
|
|
107
|
+
|
|
108
|
+
return "\n".join(lines)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def generate_parameters_file(dest_dir: str | None = None) -> None:
|
|
112
|
+
ir = fetch_intermediate_representation()
|
|
113
|
+
api = ir["apis"]["webScrapingApi"]
|
|
114
|
+
file_contents = get_parameters_file(api)
|
|
115
|
+
|
|
116
|
+
target = dest_dir if dest_dir is not None else out_dir
|
|
117
|
+
os.makedirs(target, exist_ok=True)
|
|
118
|
+
out_path = os.path.join(target, "parameters.py")
|
|
119
|
+
with open(out_path, "w", encoding="utf-8") as f:
|
|
120
|
+
f.write(file_contents)
|
|
121
|
+
|
|
122
|
+
count = len(_collect_parameter_meta(api))
|
|
123
|
+
print(f"Generated parameters from {local_ir_path}:")
|
|
124
|
+
print(f" {out_path} ({count} parameters)")
|