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
|
@@ -0,0 +1,223 @@
|
|
|
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
|
+
targets_enum_path,
|
|
12
|
+
to_enum_member_name,
|
|
13
|
+
to_pascal_case,
|
|
14
|
+
)
|
|
15
|
+
from .types import WebScrapingApiIR
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _json_schema_type_to_python(schema: dict[str, Any]) -> str:
|
|
19
|
+
if "const" in schema:
|
|
20
|
+
return f"Literal[{json.dumps(schema['const'])}]"
|
|
21
|
+
schema_type = schema.get("type")
|
|
22
|
+
enum_vals = schema.get("enum")
|
|
23
|
+
if isinstance(enum_vals, list) and schema_type == "string":
|
|
24
|
+
literals = ", ".join(json.dumps(v) for v in enum_vals)
|
|
25
|
+
return f"Literal[{literals}]"
|
|
26
|
+
if schema_type == "string":
|
|
27
|
+
return "str"
|
|
28
|
+
if schema_type == "number":
|
|
29
|
+
return "float"
|
|
30
|
+
if schema_type == "integer":
|
|
31
|
+
return "int"
|
|
32
|
+
if schema_type == "boolean":
|
|
33
|
+
return "bool"
|
|
34
|
+
if schema_type == "array":
|
|
35
|
+
return "list[Any]"
|
|
36
|
+
return "Any"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_valid_identifier(name: str) -> bool:
|
|
40
|
+
return name.isidentifier() and not name[0].isdigit()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _sanitize_field_name(name: str) -> str:
|
|
44
|
+
if _is_valid_identifier(name):
|
|
45
|
+
return name
|
|
46
|
+
return f"f{name}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get_target_parameter_keys(parameter_schema: dict[str, Any]) -> list[str]:
|
|
50
|
+
properties: dict[str, Any] = parameter_schema.get("properties", {})
|
|
51
|
+
return [k for k in properties if k != "target"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _get_targets_enum_file_contents(api: WebScrapingApiIR) -> str:
|
|
55
|
+
lines: list[str] = []
|
|
56
|
+
|
|
57
|
+
lines.append("# Minimal target enum — committed to source.")
|
|
58
|
+
lines.append("# Run `python -m decodo.codegen.codegen` to regenerate when the IR schema changes.")
|
|
59
|
+
lines.append("from __future__ import annotations")
|
|
60
|
+
lines.append("")
|
|
61
|
+
lines.append("from enum import StrEnum")
|
|
62
|
+
lines.append("")
|
|
63
|
+
lines.append("")
|
|
64
|
+
|
|
65
|
+
target_keys = list(api["targets"].keys())
|
|
66
|
+
|
|
67
|
+
lines.append("class Target(StrEnum):")
|
|
68
|
+
if target_keys:
|
|
69
|
+
for key in target_keys:
|
|
70
|
+
member = to_enum_member_name(key)
|
|
71
|
+
lines.append(f" {member} = {json.dumps(key)}")
|
|
72
|
+
else:
|
|
73
|
+
lines.append(" pass")
|
|
74
|
+
lines.append("")
|
|
75
|
+
lines.append("")
|
|
76
|
+
|
|
77
|
+
lines.append("targets: list[str] = [t.value for t in Target]")
|
|
78
|
+
lines.append("")
|
|
79
|
+
|
|
80
|
+
return "\n".join(lines)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _get_targets_file_contents(api: WebScrapingApiIR) -> str:
|
|
84
|
+
lines: list[str] = []
|
|
85
|
+
|
|
86
|
+
lines.append("# Auto-generated by src/decodo/codegen/web_scraping_api/generate_targets.py — do not edit")
|
|
87
|
+
lines.append("from __future__ import annotations")
|
|
88
|
+
lines.append("")
|
|
89
|
+
lines.append("from typing import Annotated, Any, Literal, Union")
|
|
90
|
+
lines.append("")
|
|
91
|
+
lines.append("import pydantic")
|
|
92
|
+
lines.append("")
|
|
93
|
+
lines.append("from decodo.targets import Target")
|
|
94
|
+
lines.append("")
|
|
95
|
+
|
|
96
|
+
target_keys = list(api["targets"].keys())
|
|
97
|
+
|
|
98
|
+
# Override class names for target keys that conflict with reserved names
|
|
99
|
+
CLASS_NAME_OVERRIDES: dict[str, str] = {
|
|
100
|
+
"target": "TargetStoreParams",
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
BATCH_CLASS_NAME_OVERRIDES: dict[str, str] = {
|
|
104
|
+
"target": "TargetStoreBatchParams",
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
def _class_name(target_key: str) -> str:
|
|
108
|
+
if target_key in CLASS_NAME_OVERRIDES:
|
|
109
|
+
return CLASS_NAME_OVERRIDES[target_key]
|
|
110
|
+
return f"{to_pascal_case(target_key)}Params"
|
|
111
|
+
|
|
112
|
+
def _batch_class_name(target_key: str) -> str:
|
|
113
|
+
if target_key in BATCH_CLASS_NAME_OVERRIDES:
|
|
114
|
+
return BATCH_CLASS_NAME_OVERRIDES[target_key]
|
|
115
|
+
return f"{to_pascal_case(target_key)}BatchParams"
|
|
116
|
+
|
|
117
|
+
# Emit per-target sync Params classes
|
|
118
|
+
for target_key, target in api["targets"].items():
|
|
119
|
+
type_name = _class_name(target_key)
|
|
120
|
+
member = to_enum_member_name(target_key)
|
|
121
|
+
properties: dict[str, Any] = target["parameter_schema"].get("properties", {})
|
|
122
|
+
|
|
123
|
+
lines.append(f"class {type_name}(pydantic.BaseModel):")
|
|
124
|
+
lines.append(" model_config = pydantic.ConfigDict(populate_by_name=True, extra='forbid')")
|
|
125
|
+
lines.append(f" target: Literal[Target.{member}] = Target.{member}")
|
|
126
|
+
params = {k: v for k, v in properties.items() if k != "target"}
|
|
127
|
+
if params:
|
|
128
|
+
for param_key, param_schema in params.items():
|
|
129
|
+
python_type = _json_schema_type_to_python(param_schema)
|
|
130
|
+
field_name = _sanitize_field_name(param_key)
|
|
131
|
+
if field_name != param_key:
|
|
132
|
+
lines.append(
|
|
133
|
+
f" {field_name}: {python_type} | None = pydantic.Field(None, alias={json.dumps(param_key)})"
|
|
134
|
+
) # noqa: E501
|
|
135
|
+
else:
|
|
136
|
+
lines.append(f" {field_name}: {python_type} | None = None")
|
|
137
|
+
lines.append("")
|
|
138
|
+
|
|
139
|
+
# Emit per-target batch Params classes (url/query become list[str])
|
|
140
|
+
for target_key, target in api["targets"].items():
|
|
141
|
+
batch_type_name = _batch_class_name(target_key)
|
|
142
|
+
member = to_enum_member_name(target_key)
|
|
143
|
+
properties = target["parameter_schema"].get("properties", {})
|
|
144
|
+
|
|
145
|
+
lines.append(f"class {batch_type_name}(pydantic.BaseModel):")
|
|
146
|
+
lines.append(" model_config = pydantic.ConfigDict(populate_by_name=True, extra='forbid')")
|
|
147
|
+
lines.append(f" target: Literal[Target.{member}] = Target.{member}")
|
|
148
|
+
params = {k: v for k, v in properties.items() if k != "target"}
|
|
149
|
+
if params:
|
|
150
|
+
for param_key, param_schema in params.items():
|
|
151
|
+
field_name = _sanitize_field_name(param_key)
|
|
152
|
+
if param_key in ("url", "query"):
|
|
153
|
+
python_type = "list[str]"
|
|
154
|
+
else:
|
|
155
|
+
python_type = _json_schema_type_to_python(param_schema)
|
|
156
|
+
if field_name != param_key:
|
|
157
|
+
lines.append(
|
|
158
|
+
f" {field_name}: {python_type} | None = pydantic.Field(None, alias={json.dumps(param_key)})"
|
|
159
|
+
) # noqa: E501
|
|
160
|
+
else:
|
|
161
|
+
lines.append(f" {field_name}: {python_type} | None = None")
|
|
162
|
+
lines.append("")
|
|
163
|
+
|
|
164
|
+
# target_meta as plain dict-of-dicts (no TargetMeta class here)
|
|
165
|
+
lines.append("target_meta: dict[str, dict[str, Any]] = {")
|
|
166
|
+
for target_key, target in api["targets"].items():
|
|
167
|
+
member = to_enum_member_name(target_key)
|
|
168
|
+
param_keys = _get_target_parameter_keys(target["parameter_schema"])
|
|
169
|
+
params_list = ", ".join(json.dumps(p) for p in param_keys)
|
|
170
|
+
lines.append(f" Target.{member}.value: {{")
|
|
171
|
+
lines.append(f' "group": {json.dumps(target["group"])},')
|
|
172
|
+
lines.append(f' "response_format": {json.dumps(target["response_format"])},')
|
|
173
|
+
lines.append(f' "parameters": [{params_list}],')
|
|
174
|
+
lines.append(" },")
|
|
175
|
+
lines.append("}")
|
|
176
|
+
lines.append("")
|
|
177
|
+
|
|
178
|
+
# Discriminated union for ScrapeRequest
|
|
179
|
+
union_parts = " | ".join(_class_name(k) for k in target_keys)
|
|
180
|
+
lines.append("ScrapeRequest = Annotated[")
|
|
181
|
+
lines.append(f" Union[{union_parts}],")
|
|
182
|
+
lines.append(" pydantic.Field(discriminator='target'),")
|
|
183
|
+
lines.append("]")
|
|
184
|
+
lines.append("")
|
|
185
|
+
|
|
186
|
+
# Discriminated union for BatchRequest
|
|
187
|
+
batch_union_parts = " | ".join(_batch_class_name(k) for k in target_keys)
|
|
188
|
+
lines.append("BatchRequest = Annotated[")
|
|
189
|
+
lines.append(f" Union[{batch_union_parts}],")
|
|
190
|
+
lines.append(" pydantic.Field(discriminator='target'),")
|
|
191
|
+
lines.append("]")
|
|
192
|
+
lines.append("")
|
|
193
|
+
|
|
194
|
+
return "\n".join(lines)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def generate_targets_enum_file() -> None:
|
|
198
|
+
ir = fetch_intermediate_representation()
|
|
199
|
+
api = ir["apis"]["webScrapingApi"]
|
|
200
|
+
file_contents = _get_targets_enum_file_contents(api)
|
|
201
|
+
|
|
202
|
+
with open(targets_enum_path, "w", encoding="utf-8") as f:
|
|
203
|
+
f.write(file_contents)
|
|
204
|
+
|
|
205
|
+
target_count = len(api["targets"])
|
|
206
|
+
print(f"Generated Target enum from {local_ir_path}:")
|
|
207
|
+
print(f" {targets_enum_path} ({target_count} targets)")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def generate_targets_file(dest_dir: str | None = None) -> None:
|
|
211
|
+
ir = fetch_intermediate_representation()
|
|
212
|
+
api = ir["apis"]["webScrapingApi"]
|
|
213
|
+
file_contents = _get_targets_file_contents(api)
|
|
214
|
+
|
|
215
|
+
target = dest_dir if dest_dir is not None else out_dir
|
|
216
|
+
os.makedirs(target, exist_ok=True)
|
|
217
|
+
out_path = os.path.join(target, "targets.py")
|
|
218
|
+
with open(out_path, "w", encoding="utf-8") as f:
|
|
219
|
+
f.write(file_contents)
|
|
220
|
+
|
|
221
|
+
target_count = len(api["targets"])
|
|
222
|
+
print(f"Generated target Params from {local_ir_path}:")
|
|
223
|
+
print(f" {out_path} ({target_count} targets)")
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import warnings
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import cast
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from decodo.schema.resolve_latest_ir import resolve_latest_ir
|
|
13
|
+
|
|
14
|
+
from .types import IR
|
|
15
|
+
|
|
16
|
+
_THIS_DIR = Path(__file__).parent
|
|
17
|
+
|
|
18
|
+
local_ir_path = str((_THIS_DIR / "../../../.." / "inputs" / "decodo.ir.json").resolve())
|
|
19
|
+
out_dir = str((_THIS_DIR / "../../generated").resolve())
|
|
20
|
+
targets_enum_path = str((_THIS_DIR / "../../targets.py").resolve())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def to_pascal_case(s: str) -> str:
|
|
24
|
+
s = re.sub(r"([a-z])([A-Z])", r"\1_\2", s)
|
|
25
|
+
parts = re.split(r"[_\s-]+", s)
|
|
26
|
+
return "".join(w[0].upper() + w[1:].lower() for w in parts if w)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def to_enum_member_name(target_key: str) -> str:
|
|
30
|
+
pascal = to_pascal_case(target_key)
|
|
31
|
+
if re.match(r"^[0-9]", pascal) or not re.match(r"^[A-Za-z_]", pascal):
|
|
32
|
+
return f"_{pascal}"
|
|
33
|
+
return pascal
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def prop_key(key: str) -> str:
|
|
37
|
+
if re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", key):
|
|
38
|
+
return key
|
|
39
|
+
return json.dumps(key)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def fetch_intermediate_representation() -> IR:
|
|
43
|
+
try:
|
|
44
|
+
location = resolve_latest_ir()
|
|
45
|
+
url = location["url"]
|
|
46
|
+
response = httpx.get(url)
|
|
47
|
+
if not response.is_success:
|
|
48
|
+
raise RuntimeError(f"HTTP {response.status_code}")
|
|
49
|
+
raw = response.text
|
|
50
|
+
os.makedirs(os.path.dirname(local_ir_path), exist_ok=True)
|
|
51
|
+
with open(local_ir_path, "w", encoding="utf-8") as f:
|
|
52
|
+
f.write(raw)
|
|
53
|
+
return cast(IR, json.loads(raw))
|
|
54
|
+
except Exception as err:
|
|
55
|
+
message = str(err)
|
|
56
|
+
if os.path.exists(local_ir_path):
|
|
57
|
+
warnings.warn(
|
|
58
|
+
f"Warning: failed to fetch IR ({message}). Using cached local file.",
|
|
59
|
+
stacklevel=2,
|
|
60
|
+
)
|
|
61
|
+
with open(local_ir_path, encoding="utf-8") as f:
|
|
62
|
+
return cast(IR, json.load(f))
|
|
63
|
+
raise RuntimeError(
|
|
64
|
+
f"Failed to fetch IR ({message}) and no local cache found at {local_ir_path}."
|
|
65
|
+
) from None
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, TypedDict
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class IRTarget(TypedDict):
|
|
7
|
+
group: str
|
|
8
|
+
response_format: str
|
|
9
|
+
parameter_schema: dict[str, Any]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class WebScrapingApiIR(TypedDict):
|
|
13
|
+
label: str
|
|
14
|
+
baseUrl: str
|
|
15
|
+
auth: dict[str, Any]
|
|
16
|
+
endpoints: dict[str, dict[str, str]]
|
|
17
|
+
targets: dict[str, IRTarget]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class IR(TypedDict):
|
|
21
|
+
version: str
|
|
22
|
+
apis: IRApis
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class IRApis(TypedDict):
|
|
26
|
+
webScrapingApi: WebScrapingApiIR
|
decodo/errors.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class DecodoError(Exception):
|
|
7
|
+
status_code: int
|
|
8
|
+
api_status: str | None
|
|
9
|
+
|
|
10
|
+
def __init__(self, message: str, status_code: int, api_status: str | None = None) -> None:
|
|
11
|
+
super().__init__(message)
|
|
12
|
+
self.status_code = status_code
|
|
13
|
+
self.api_status = api_status
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AuthenticationError(DecodoError):
|
|
17
|
+
def __init__(self, message: str = "Authentication failed. Check your credentials.") -> None:
|
|
18
|
+
super().__init__(message, 401, "failed")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RateLimitError(DecodoError):
|
|
22
|
+
def __init__(self, message: str = "Rate limit exceeded. Slow down your request rate.") -> None:
|
|
23
|
+
super().__init__(message, 429, "failed")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ValidationError(DecodoError):
|
|
27
|
+
errors: list[Any] | None
|
|
28
|
+
|
|
29
|
+
def __init__(self, message: str, errors: list[Any] | None = None) -> None:
|
|
30
|
+
super().__init__(message, 422, "failed")
|
|
31
|
+
self.errors = errors
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TimeoutError(Exception):
|
|
35
|
+
def __init__(self, message: str = "The request timed out.") -> None:
|
|
36
|
+
super().__init__(message)
|
|
File without changes
|