cleanedweb 0.1.0__tar.gz → 0.2.0__tar.gz
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.
- cleanedweb-0.2.0/CHANGELOG.md +29 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/PKG-INFO +67 -8
- cleanedweb-0.2.0/README.md +150 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/__init__.py +19 -0
- cleanedweb-0.2.0/src/cleanedweb/_apis_async.py +273 -0
- cleanedweb-0.2.0/src/cleanedweb/_apis_sync.py +270 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/_async.py +70 -5
- cleanedweb-0.2.0/src/cleanedweb/_builds.py +132 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/_core.py +46 -6
- cleanedweb-0.2.0/src/cleanedweb/_schedules.py +69 -0
- cleanedweb-0.2.0/src/cleanedweb/_schedules_async.py +169 -0
- cleanedweb-0.2.0/src/cleanedweb/_schedules_sync.py +167 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/_sync.py +71 -6
- cleanedweb-0.2.0/src/cleanedweb/_version.py +1 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/exceptions.py +91 -2
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/models.py +224 -0
- cleanedweb-0.2.0/src/cleanedweb/seen.py +329 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/tests/conftest.py +59 -0
- cleanedweb-0.2.0/tests/test_apis.py +420 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/tests/test_async.py +10 -0
- cleanedweb-0.2.0/tests/test_schedules.py +372 -0
- cleanedweb-0.2.0/tests/test_seen.py +211 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/tests/test_sync.py +50 -0
- cleanedweb-0.1.0/CHANGELOG.md +0 -10
- cleanedweb-0.1.0/README.md +0 -91
- cleanedweb-0.1.0/src/cleanedweb/_version.py +0 -1
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/.gitignore +0 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/LICENSE +0 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/pyproject.toml +0 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/src/cleanedweb/py.typed +0 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/tests/__init__.py +0 -0
- {cleanedweb-0.1.0 → cleanedweb-0.2.0}/tests/test_live.py +0 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0 - 2026-11-25
|
|
4
|
+
|
|
5
|
+
- `apis`: build an API from a URL (`create`, `resume`, `get_build`, `get_draft`, `create_many`), sync and async.
|
|
6
|
+
Drives the key-authorized builder routes on `app_url`: preview, inspection, create, build job, result
|
|
7
|
+
(`source_id`, `version`, `schema`). Waiting only reads: the create request is sent once and `draft_id` /
|
|
8
|
+
`job_id` are the resume handles. New `Build` and `Draft` models; `BuildFailedError` (`code`, `reason`,
|
|
9
|
+
`stage`), `PreviewLimitError` (a `RateLimitError` with `cause`, `limit`, `retry_after`) and
|
|
10
|
+
`ScopeRequiredError` (a `PermissionDeniedError` naming `missing_scopes`). `create_many` waits out the
|
|
11
|
+
hourly preview limit. Needs a personal key with the `discover` and `build` scopes.
|
|
12
|
+
- `schedules`: `create`, `list`, `get`, `pause`, `resume`, `delete` against `/v1/schedules`, with the idempotency
|
|
13
|
+
key handling of the other SDKs (`schedule.replayed`, `schedule.idempotency_key`), plus `runs`.
|
|
14
|
+
- Only new records, on the client: `SeenStore` (JSON or SQLite file, atomic writes), `sources.run(..., new_only=)`
|
|
15
|
+
and `schedules.new_records(schedule_id, store)`. Identity is the contract's `record_identity_path(s)`, else a hash
|
|
16
|
+
of the record. Runs are still billed for every record they deliver.
|
|
17
|
+
- `catalog.find(site=)` matches the site's `aliases` (new optional field of the catalog `site` object) on host
|
|
18
|
+
boundaries and normalizes the input (scheme, path, `www.`, trailing dot, case): `seek.com.au` finds an API listed
|
|
19
|
+
as `au.seek.com`, and `notseek.com.au` is not a match. `CatalogApi.site_aliases`; responses without aliases work.
|
|
20
|
+
- `Run` carries `source_id`, `definition_version`, `created_at` and `finished_at`.
|
|
21
|
+
|
|
22
|
+
## 0.1.0 - 2026-11-20
|
|
23
|
+
|
|
24
|
+
- First version: sync `CleanedWeb` and async `AsyncCleanedWeb` clients for the public catalog
|
|
25
|
+
(`list`, `get`, `find`, `run`, `result`), runs (`get`, `items`, `result`, `abort`, `list`) and
|
|
26
|
+
private sources (`run`).
|
|
27
|
+
- `catalog.run` generates and returns an idempotency key, follows `202` + `Retry-After` by
|
|
28
|
+
reading `/result` with the same key, and never resends the POST while it waits.
|
|
29
|
+
- Typed exceptions for the documented error codes.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cleanedweb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Python client for CleanedWeb: maintained REST APIs that return structured records from public websites.
|
|
5
5
|
Project-URL: Homepage, https://cleanedweb.com/?utm_source=github&utm_medium=cleanedweb-python
|
|
6
6
|
Project-URL: Documentation, https://cleanedweb.com/docs/python/?utm_source=github&utm_medium=cleanedweb-python
|
|
@@ -46,8 +46,6 @@ Runs are charged per record delivered.
|
|
|
46
46
|
pip install cleanedweb # Python 3.10+
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
> Not on PyPI yet; until it is, use `pip install git+https://github.com/cleanedweb/cleanedweb-python`.
|
|
50
|
-
|
|
51
49
|
## Quick start
|
|
52
50
|
|
|
53
51
|
Create an API key with the `run` scope in the [console](https://app.cleanedweb.com/) and export it:
|
|
@@ -86,25 +84,86 @@ async with AsyncCleanedWeb() as cw:
|
|
|
86
84
|
| --- | --- |
|
|
87
85
|
| `catalog.list(q=, category=, sort=, limit=, offset=)` / `catalog.iter(...)` | The live published list (no key). |
|
|
88
86
|
| `catalog.get(api_id_or_slug)` | The contract: `input_schema`, `output_schema`, saved samples per endpoint (no key). |
|
|
89
|
-
| `catalog.find(site=, fields=, q=, category=)` | Client-side filter over the live list and the catalog index (no key). |
|
|
87
|
+
| `catalog.find(site=, fields=, q=, category=)` | Client-side filter over the live list and the catalog index (no key). `site` is a domain, a URL or a name; it also matches the site's other hosts (`site.aliases`), so `seek.com.au` finds an API listed as `au.seek.com`. |
|
|
90
88
|
| `catalog.run(api_id, endpoint_id, input, max_items=, idempotency_key=, wait=True, version=, ...)` | Run a catalog API. Needs a key with the `run` scope. |
|
|
91
89
|
| `catalog.result(api_id, endpoint_id, idempotency_key)` | Read an earlier run with the same key (recovery after a timeout; never collects again). |
|
|
92
90
|
| `runs.get(run_id)`, `runs.result(run_id)`, `runs.abort(run_id)` | Read, wait for, or stop a run. |
|
|
93
91
|
| `runs.items(run_id)` | Iterate records across cursor pages (also while the run runs). |
|
|
94
92
|
| `runs.list(...)` / `runs.iter(...)` | Your runs, newest first. |
|
|
95
|
-
| `sources.run(source_id, input, expected_version=, ...)` | Run one of your own private APIs. |
|
|
93
|
+
| `sources.run(source_id, input, expected_version=, new_only=, ...)` | Run one of your own private APIs; `new_only=` keeps only records you have not seen. |
|
|
94
|
+
| `apis.create(url, want=, wait=True, poll_timeout=, on_progress=)` | Build an API of your own from a URL (a careers page, a listing). Needs a key with `discover` and `build`. |
|
|
95
|
+
| `apis.resume(draft_id= / job_id=)`, `apis.get_build(job_id)`, `apis.get_draft(draft_id)`, `apis.create_many(urls)` | Continue, read, or build several (sequentially, waiting out the preview limit). |
|
|
96
|
+
| `schedules.create(source_id= / api_id=, endpoint_id=, every=, at_utc=, ...)` | Run an API on a schedule (hour, day, week; UTC). |
|
|
97
|
+
| `schedules.list()`, `.get(id)`, `.pause(id)`, `.resume(id)`, `.delete(id)` | Manage schedules (`read` scope for reads, `run` for changes). |
|
|
98
|
+
| `schedules.runs(id)`, `schedules.new_records(id, store)` | The runs a schedule started; only the records not seen before. |
|
|
99
|
+
| `SeenStore(path)` | The client-side memory of records already handled (JSON or SQLite file). |
|
|
96
100
|
|
|
97
101
|
Pass `wait=False` to return as soon as the run is accepted (`result.complete` is `False`), or
|
|
98
102
|
`poll_timeout=` to stop waiting after some seconds; continue later with `catalog.result(...)`.
|
|
99
103
|
|
|
104
|
+
## From a careers page to "only the new jobs", from code
|
|
105
|
+
|
|
106
|
+
The whole job from Python: turn a URL into an API, run it every day, read only what is new.
|
|
107
|
+
Build keys need the creation scopes `discover` and `build` (the console's "Create APIs" option, personal
|
|
108
|
+
keys only); scheduling and running need `run` (and `read` to list schedules).
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from cleanedweb import CleanedWeb, SeenStore
|
|
112
|
+
|
|
113
|
+
cw = CleanedWeb() # CLEANEDWEB_API_KEY
|
|
114
|
+
|
|
115
|
+
# 1. URL -> API. Takes minutes; on_progress sees each step. Never starts a second build while waiting.
|
|
116
|
+
build = cw.apis.create(
|
|
117
|
+
"https://careers.example.org/jobs",
|
|
118
|
+
want="open job postings",
|
|
119
|
+
on_progress=lambda b: print(b.state),
|
|
120
|
+
)
|
|
121
|
+
print(build.source_id, build.version) # your API; build.schema is its record schema
|
|
122
|
+
# Several sites: builds one after the other and waits out the hourly preview limit (429 Retry-After).
|
|
123
|
+
# builds = cw.apis.create_many(urls) # a failed page comes back as a Build with state "failed"
|
|
124
|
+
|
|
125
|
+
# 2. Run it every morning at 06:30 UTC. Each slot is an ordinary run, charged per record delivered.
|
|
126
|
+
schedule = cw.schedules.create(
|
|
127
|
+
source_id=build.source_id,
|
|
128
|
+
every="day",
|
|
129
|
+
at_utc="06:30",
|
|
130
|
+
max_items=500,
|
|
131
|
+
name="Careers page, daily",
|
|
132
|
+
idempotency_key="careers-daily-1", # a retry with the same key never makes a second schedule
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# 3. Each morning: only the records you have not seen before.
|
|
136
|
+
store = SeenStore("seen-records.json") # or "seen-records.sqlite"
|
|
137
|
+
for job in cw.schedules.new_records(schedule.schedule_id, store):
|
|
138
|
+
print(job["title"], job["url"])
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
If the process stops mid-build, resume from the handles instead of starting again:
|
|
142
|
+
`cw.apis.resume(draft_id=build.draft_id)` or `cw.apis.resume(job_id=build.job_id)`. `poll_timeout=` returns the
|
|
143
|
+
unfinished `Build` after that many seconds. Failures are typed: `BuildFailedError` (`code`, `reason`, `stage`),
|
|
144
|
+
`PreviewLimitError` (429; `cause`, `limit`, `retry_after`) and `ScopeRequiredError` (403; `missing_scopes`).
|
|
145
|
+
|
|
146
|
+
**Only new records is done on the client.** The server has no "since" read yet, so every run still delivers, and
|
|
147
|
+
bills, all of its records; `SeenStore` only saves your own processing. A record is "the same" by the identity the
|
|
148
|
+
API's contract declares (`record_identity_path`, read with the `read` scope), else by a hash of the whole record,
|
|
149
|
+
where any changed field counts as new (`result.identity` says which). `new_records` reads the schedule source's
|
|
150
|
+
finished runs newer than the last one a previous call handled, so a run is read once; it marks records seen before
|
|
151
|
+
it returns, or pass `mark=False` and call `.commit()` after you handled them. Runs listed for a schedule are all
|
|
152
|
+
finished runs of its source, manual runs included. Without a schedule:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
result = cw.sources.run(source_id, {"query": "python"}, new_only="seen-records.json")
|
|
156
|
+
print(len(result.records), "delivered,", len(result.new_records), "new")
|
|
157
|
+
```
|
|
158
|
+
|
|
100
159
|
## Errors
|
|
101
160
|
|
|
102
161
|
Every error derives from `CleanedWebError`; API errors derive from `APIStatusError` (`status_code`,
|
|
103
|
-
`code`, `detail`, `retry_after`): `AuthenticationError` (401), `PermissionDeniedError` (403),
|
|
104
|
-
`InsufficientCreditError` (402, `required`/`available`), `RateLimitError` (429, `retry_after`),
|
|
162
|
+
`code`, `detail`, `retry_after`): `AuthenticationError` (401), `PermissionDeniedError` (403; `ScopeRequiredError` names the missing scopes),
|
|
163
|
+
`InsufficientCreditError` (402, `required`/`available`), `RateLimitError` (429, `retry_after`; `PreviewLimitError` for the hourly build previews),
|
|
105
164
|
`VersionConflictError`, `VersionNotFoundError` (`available` majors), `NotFoundError`,
|
|
106
165
|
`IdempotencyConflictError`, `UsageBudgetExceededError`, `InvalidRequestError`, `ServerError`, plus
|
|
107
|
-
`APIConnectionError` when no answer arrived. `err.run_failed` is true when the run failed: that is
|
|
166
|
+
`APIConnectionError` when no answer arrived; `BuildFailedError` when a build ends without an API. `err.run_failed` is true when the run failed: that is
|
|
108
167
|
final for the key, so use a new key to run again. After a connection error or a 5xx without that
|
|
109
168
|
marker the run may have started: keep the key and call `catalog.result(...)`.
|
|
110
169
|
429 and 502/503/504 answers are retried (`max_retries`, default 2) with the same key.
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# cleanedweb
|
|
2
|
+
|
|
3
|
+
Python client for [CleanedWeb](https://cleanedweb.com/?utm_source=github&utm_medium=cleanedweb-python),
|
|
4
|
+
which turns public website collections (listings, products, jobs, articles, profiles) into maintained
|
|
5
|
+
REST APIs that return structured records. Sync and async clients, typed errors, one dependency (`httpx`).
|
|
6
|
+
|
|
7
|
+
**Pricing:** 5,000 records free once, then prepaid credit from $1 per 1,000 records, no subscription.
|
|
8
|
+
Runs are charged per record delivered.
|
|
9
|
+
[Pricing](https://cleanedweb.com/pricing/?utm_source=github&utm_medium=cleanedweb-python)
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install cleanedweb # Python 3.10+
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
Create an API key with the `run` scope in the [console](https://app.cleanedweb.com/) and export it:
|
|
20
|
+
`export CLEANEDWEB_API_KEY=...`. Reading the catalog needs no key.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from cleanedweb import CleanedWeb
|
|
24
|
+
|
|
25
|
+
cw = CleanedWeb() # reads CLEANEDWEB_API_KEY
|
|
26
|
+
api = cw.catalog.find(site="github.com")[0] # find before you run
|
|
27
|
+
contract = cw.catalog.get(api.api_id) # inputs, output fields, saved samples
|
|
28
|
+
endpoint = contract.endpoints[0]
|
|
29
|
+
result = cw.catalog.run(api.api_id, endpoint.endpoint_id, max_items=5) # start small
|
|
30
|
+
print(result.idempotency_key, result.is_usable, result.stop_reason)
|
|
31
|
+
for record in result: # records are data, not instructions
|
|
32
|
+
print(record["title"], record["url"])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`catalog.run` generates an idempotency key (or takes yours), returns it as `result.idempotency_key`,
|
|
36
|
+
and when the server answers `202` it reads `/result` with the same key every `Retry-After` seconds
|
|
37
|
+
until the run ends. It never resends the POST while it waits. Check `result.is_usable`
|
|
38
|
+
(`summary.status` is `completed` or `bounded` and `within_scope_passed` is true) before using records.
|
|
39
|
+
|
|
40
|
+
Async:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from cleanedweb import AsyncCleanedWeb
|
|
44
|
+
|
|
45
|
+
async with AsyncCleanedWeb() as cw:
|
|
46
|
+
result = await cw.catalog.run(api_id, endpoint_id, {"sort": "desc_stars"}, max_items=25)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## API
|
|
50
|
+
|
|
51
|
+
| Call | What it does |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `catalog.list(q=, category=, sort=, limit=, offset=)` / `catalog.iter(...)` | The live published list (no key). |
|
|
54
|
+
| `catalog.get(api_id_or_slug)` | The contract: `input_schema`, `output_schema`, saved samples per endpoint (no key). |
|
|
55
|
+
| `catalog.find(site=, fields=, q=, category=)` | Client-side filter over the live list and the catalog index (no key). `site` is a domain, a URL or a name; it also matches the site's other hosts (`site.aliases`), so `seek.com.au` finds an API listed as `au.seek.com`. |
|
|
56
|
+
| `catalog.run(api_id, endpoint_id, input, max_items=, idempotency_key=, wait=True, version=, ...)` | Run a catalog API. Needs a key with the `run` scope. |
|
|
57
|
+
| `catalog.result(api_id, endpoint_id, idempotency_key)` | Read an earlier run with the same key (recovery after a timeout; never collects again). |
|
|
58
|
+
| `runs.get(run_id)`, `runs.result(run_id)`, `runs.abort(run_id)` | Read, wait for, or stop a run. |
|
|
59
|
+
| `runs.items(run_id)` | Iterate records across cursor pages (also while the run runs). |
|
|
60
|
+
| `runs.list(...)` / `runs.iter(...)` | Your runs, newest first. |
|
|
61
|
+
| `sources.run(source_id, input, expected_version=, new_only=, ...)` | Run one of your own private APIs; `new_only=` keeps only records you have not seen. |
|
|
62
|
+
| `apis.create(url, want=, wait=True, poll_timeout=, on_progress=)` | Build an API of your own from a URL (a careers page, a listing). Needs a key with `discover` and `build`. |
|
|
63
|
+
| `apis.resume(draft_id= / job_id=)`, `apis.get_build(job_id)`, `apis.get_draft(draft_id)`, `apis.create_many(urls)` | Continue, read, or build several (sequentially, waiting out the preview limit). |
|
|
64
|
+
| `schedules.create(source_id= / api_id=, endpoint_id=, every=, at_utc=, ...)` | Run an API on a schedule (hour, day, week; UTC). |
|
|
65
|
+
| `schedules.list()`, `.get(id)`, `.pause(id)`, `.resume(id)`, `.delete(id)` | Manage schedules (`read` scope for reads, `run` for changes). |
|
|
66
|
+
| `schedules.runs(id)`, `schedules.new_records(id, store)` | The runs a schedule started; only the records not seen before. |
|
|
67
|
+
| `SeenStore(path)` | The client-side memory of records already handled (JSON or SQLite file). |
|
|
68
|
+
|
|
69
|
+
Pass `wait=False` to return as soon as the run is accepted (`result.complete` is `False`), or
|
|
70
|
+
`poll_timeout=` to stop waiting after some seconds; continue later with `catalog.result(...)`.
|
|
71
|
+
|
|
72
|
+
## From a careers page to "only the new jobs", from code
|
|
73
|
+
|
|
74
|
+
The whole job from Python: turn a URL into an API, run it every day, read only what is new.
|
|
75
|
+
Build keys need the creation scopes `discover` and `build` (the console's "Create APIs" option, personal
|
|
76
|
+
keys only); scheduling and running need `run` (and `read` to list schedules).
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from cleanedweb import CleanedWeb, SeenStore
|
|
80
|
+
|
|
81
|
+
cw = CleanedWeb() # CLEANEDWEB_API_KEY
|
|
82
|
+
|
|
83
|
+
# 1. URL -> API. Takes minutes; on_progress sees each step. Never starts a second build while waiting.
|
|
84
|
+
build = cw.apis.create(
|
|
85
|
+
"https://careers.example.org/jobs",
|
|
86
|
+
want="open job postings",
|
|
87
|
+
on_progress=lambda b: print(b.state),
|
|
88
|
+
)
|
|
89
|
+
print(build.source_id, build.version) # your API; build.schema is its record schema
|
|
90
|
+
# Several sites: builds one after the other and waits out the hourly preview limit (429 Retry-After).
|
|
91
|
+
# builds = cw.apis.create_many(urls) # a failed page comes back as a Build with state "failed"
|
|
92
|
+
|
|
93
|
+
# 2. Run it every morning at 06:30 UTC. Each slot is an ordinary run, charged per record delivered.
|
|
94
|
+
schedule = cw.schedules.create(
|
|
95
|
+
source_id=build.source_id,
|
|
96
|
+
every="day",
|
|
97
|
+
at_utc="06:30",
|
|
98
|
+
max_items=500,
|
|
99
|
+
name="Careers page, daily",
|
|
100
|
+
idempotency_key="careers-daily-1", # a retry with the same key never makes a second schedule
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# 3. Each morning: only the records you have not seen before.
|
|
104
|
+
store = SeenStore("seen-records.json") # or "seen-records.sqlite"
|
|
105
|
+
for job in cw.schedules.new_records(schedule.schedule_id, store):
|
|
106
|
+
print(job["title"], job["url"])
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
If the process stops mid-build, resume from the handles instead of starting again:
|
|
110
|
+
`cw.apis.resume(draft_id=build.draft_id)` or `cw.apis.resume(job_id=build.job_id)`. `poll_timeout=` returns the
|
|
111
|
+
unfinished `Build` after that many seconds. Failures are typed: `BuildFailedError` (`code`, `reason`, `stage`),
|
|
112
|
+
`PreviewLimitError` (429; `cause`, `limit`, `retry_after`) and `ScopeRequiredError` (403; `missing_scopes`).
|
|
113
|
+
|
|
114
|
+
**Only new records is done on the client.** The server has no "since" read yet, so every run still delivers, and
|
|
115
|
+
bills, all of its records; `SeenStore` only saves your own processing. A record is "the same" by the identity the
|
|
116
|
+
API's contract declares (`record_identity_path`, read with the `read` scope), else by a hash of the whole record,
|
|
117
|
+
where any changed field counts as new (`result.identity` says which). `new_records` reads the schedule source's
|
|
118
|
+
finished runs newer than the last one a previous call handled, so a run is read once; it marks records seen before
|
|
119
|
+
it returns, or pass `mark=False` and call `.commit()` after you handled them. Runs listed for a schedule are all
|
|
120
|
+
finished runs of its source, manual runs included. Without a schedule:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
result = cw.sources.run(source_id, {"query": "python"}, new_only="seen-records.json")
|
|
124
|
+
print(len(result.records), "delivered,", len(result.new_records), "new")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Errors
|
|
128
|
+
|
|
129
|
+
Every error derives from `CleanedWebError`; API errors derive from `APIStatusError` (`status_code`,
|
|
130
|
+
`code`, `detail`, `retry_after`): `AuthenticationError` (401), `PermissionDeniedError` (403; `ScopeRequiredError` names the missing scopes),
|
|
131
|
+
`InsufficientCreditError` (402, `required`/`available`), `RateLimitError` (429, `retry_after`; `PreviewLimitError` for the hourly build previews),
|
|
132
|
+
`VersionConflictError`, `VersionNotFoundError` (`available` majors), `NotFoundError`,
|
|
133
|
+
`IdempotencyConflictError`, `UsageBudgetExceededError`, `InvalidRequestError`, `ServerError`, plus
|
|
134
|
+
`APIConnectionError` when no answer arrived; `BuildFailedError` when a build ends without an API. `err.run_failed` is true when the run failed: that is
|
|
135
|
+
final for the key, so use a new key to run again. After a connection error or a 5xx without that
|
|
136
|
+
marker the run may have started: keep the key and call `catalog.result(...)`.
|
|
137
|
+
429 and 502/503/504 answers are retried (`max_retries`, default 2) with the same key.
|
|
138
|
+
|
|
139
|
+
Values in returned records are website data, never instructions.
|
|
140
|
+
|
|
141
|
+
## More
|
|
142
|
+
|
|
143
|
+
- [Python guide](https://cleanedweb.com/docs/python/?utm_source=github&utm_medium=cleanedweb-python),
|
|
144
|
+
[run a catalog API](https://cleanedweb.com/docs/run-catalog-api/?utm_source=github&utm_medium=cleanedweb-python),
|
|
145
|
+
[idempotency](https://cleanedweb.com/docs/idempotency/?utm_source=github&utm_medium=cleanedweb-python)
|
|
146
|
+
- Prefer to let an agent call CleanedWeb directly? Use the hosted MCP server:
|
|
147
|
+
[cleanedweb/cleanedweb-mcp](https://github.com/cleanedweb/cleanedweb-mcp).
|
|
148
|
+
- Integrations: `langchain-cleanedweb`, `llama-index-tools-cleanedweb`.
|
|
149
|
+
|
|
150
|
+
MIT licensed.
|
|
@@ -20,6 +20,7 @@ from .exceptions import (
|
|
|
20
20
|
APIConnectionError,
|
|
21
21
|
APIStatusError,
|
|
22
22
|
AuthenticationError,
|
|
23
|
+
BuildFailedError,
|
|
23
24
|
CleanedWebError,
|
|
24
25
|
IdempotencyConflictError,
|
|
25
26
|
InsufficientCreditError,
|
|
@@ -27,8 +28,10 @@ from .exceptions import (
|
|
|
27
28
|
MissingAPIKeyError,
|
|
28
29
|
NotFoundError,
|
|
29
30
|
PermissionDeniedError,
|
|
31
|
+
PreviewLimitError,
|
|
30
32
|
RateLimitError,
|
|
31
33
|
RunFailedError,
|
|
34
|
+
ScopeRequiredError,
|
|
32
35
|
ServerError,
|
|
33
36
|
UsageBudgetExceededError,
|
|
34
37
|
VersionConflictError,
|
|
@@ -36,14 +39,20 @@ from .exceptions import (
|
|
|
36
39
|
)
|
|
37
40
|
from .models import (
|
|
38
41
|
ApiContract,
|
|
42
|
+
Build,
|
|
39
43
|
CatalogApi,
|
|
40
44
|
CatalogEndpoint,
|
|
45
|
+
Draft,
|
|
41
46
|
EndpointContract,
|
|
42
47
|
Run,
|
|
43
48
|
RunItemsPage,
|
|
44
49
|
RunList,
|
|
45
50
|
RunResult,
|
|
51
|
+
Schedule,
|
|
52
|
+
ScheduleDeleted,
|
|
53
|
+
ScheduleList,
|
|
46
54
|
)
|
|
55
|
+
from .seen import NewRecords, SeenStore
|
|
47
56
|
|
|
48
57
|
__all__ = [
|
|
49
58
|
"APIConnectionError",
|
|
@@ -51,23 +60,33 @@ __all__ = [
|
|
|
51
60
|
"ApiContract",
|
|
52
61
|
"AsyncCleanedWeb",
|
|
53
62
|
"AuthenticationError",
|
|
63
|
+
"Build",
|
|
64
|
+
"BuildFailedError",
|
|
54
65
|
"CatalogApi",
|
|
55
66
|
"CatalogEndpoint",
|
|
56
67
|
"CleanedWeb",
|
|
57
68
|
"CleanedWebError",
|
|
69
|
+
"Draft",
|
|
58
70
|
"EndpointContract",
|
|
59
71
|
"IdempotencyConflictError",
|
|
60
72
|
"InsufficientCreditError",
|
|
61
73
|
"InvalidRequestError",
|
|
62
74
|
"MissingAPIKeyError",
|
|
75
|
+
"NewRecords",
|
|
63
76
|
"NotFoundError",
|
|
64
77
|
"PermissionDeniedError",
|
|
78
|
+
"PreviewLimitError",
|
|
65
79
|
"RateLimitError",
|
|
66
80
|
"Run",
|
|
67
81
|
"RunFailedError",
|
|
68
82
|
"RunItemsPage",
|
|
69
83
|
"RunList",
|
|
70
84
|
"RunResult",
|
|
85
|
+
"Schedule",
|
|
86
|
+
"ScheduleDeleted",
|
|
87
|
+
"ScheduleList",
|
|
88
|
+
"ScopeRequiredError",
|
|
89
|
+
"SeenStore",
|
|
71
90
|
"ServerError",
|
|
72
91
|
"UsageBudgetExceededError",
|
|
73
92
|
"VersionConflictError",
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""``client.apis``: build an API from a URL (asynchronous)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional
|
|
8
|
+
|
|
9
|
+
from . import _builds as b
|
|
10
|
+
from . import _core as core
|
|
11
|
+
from .exceptions import BuildFailedError, CleanedWebError, PreviewLimitError
|
|
12
|
+
from .models import Build, Draft
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from ._async import AsyncCleanedWeb
|
|
16
|
+
|
|
17
|
+
ProgressCallback = Callable[[Build], Any] # a plain function or a coroutine function
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Apis:
|
|
21
|
+
"""Turn a URL into an API of your own: inspect the page, build it, read its ``source_id``.
|
|
22
|
+
|
|
23
|
+
Needs a personal API key with the creation scopes ``discover`` and ``build`` (the console's
|
|
24
|
+
"Create APIs" option); a key with only ``run`` raises ``ScopeRequiredError``. The key is sent
|
|
25
|
+
to ``app_url``. The create request is sent once per page: waiting only reads, and
|
|
26
|
+
``draft_id`` / ``job_id`` are the handles to continue with (``resume``, ``get_build``).
|
|
27
|
+
Builds are slow (minutes); previews are limited per hour (``PreviewLimitError``).
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, client: AsyncCleanedWeb) -> None:
|
|
31
|
+
self._c = client
|
|
32
|
+
|
|
33
|
+
# -- plumbing ----------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
async def _call(
|
|
36
|
+
self, method: str, suffix: str, *, json: Optional[Dict[str, Any]] = None, hold: bool = False
|
|
37
|
+
) -> Dict[str, Any]:
|
|
38
|
+
_, data = await self._c._send(
|
|
39
|
+
method,
|
|
40
|
+
f"{self._c.app_url}{b.BUILDER}{suffix}",
|
|
41
|
+
auth=True,
|
|
42
|
+
json=json,
|
|
43
|
+
params={"wait": b.HOLD_SECONDS} if hold else None,
|
|
44
|
+
timeout=core.http_timeout_for(b.HOLD_SECONDS, self._c.timeout) if hold else None,
|
|
45
|
+
)
|
|
46
|
+
if not isinstance(data, dict):
|
|
47
|
+
raise CleanedWebError(f"{method} {b.BUILDER}{suffix} answered without a JSON object")
|
|
48
|
+
return data
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
async def _notify(on_progress: Optional[ProgressCallback], build: Build) -> None:
|
|
52
|
+
if on_progress is not None:
|
|
53
|
+
outcome = on_progress(build)
|
|
54
|
+
if inspect.isawaitable(outcome):
|
|
55
|
+
await outcome
|
|
56
|
+
|
|
57
|
+
def _draft(self, data: Dict[str, Any]) -> Draft:
|
|
58
|
+
draft = Draft.from_dict(data)
|
|
59
|
+
if not draft.draft_id:
|
|
60
|
+
raise CleanedWebError("the preview answer carried no draft_id")
|
|
61
|
+
return draft
|
|
62
|
+
|
|
63
|
+
# -- reads -------------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
async def get_draft(self, draft_id: str) -> Draft:
|
|
66
|
+
"""The preview (``GET /api/builder/previews/{draft_id}``): its inspection and failure."""
|
|
67
|
+
return self._draft(await self._call("GET", f"/previews/{core.seg(draft_id)}"))
|
|
68
|
+
|
|
69
|
+
async def get_build(self, job_id: str, *, wait: bool = False) -> Build:
|
|
70
|
+
"""One read of a build job. A succeeded build also carries ``source_id``, ``version`` and
|
|
71
|
+
``schema``. A failed build is returned, not raised. ``wait`` lets the server hold the
|
|
72
|
+
read up to 30 seconds for a change."""
|
|
73
|
+
job = await self._call("GET", f"/builds/{core.seg(job_id)}", hold=wait)
|
|
74
|
+
build = Build.from_job(job)
|
|
75
|
+
build.job_id = build.job_id or job_id
|
|
76
|
+
return await self._with_result(build) if build.succeeded else build
|
|
77
|
+
|
|
78
|
+
async def _with_result(self, build: Build) -> Build:
|
|
79
|
+
assert build.job_id
|
|
80
|
+
result = await self._call("GET", f"/builds/{core.seg(build.job_id)}/result")
|
|
81
|
+
build.source_id = result.get("source_id") or build.source_id
|
|
82
|
+
build.version = result.get("version") or build.version
|
|
83
|
+
schema = result.get("schema")
|
|
84
|
+
build.schema = schema if isinstance(schema, dict) else build.schema
|
|
85
|
+
build.raw = {**build.raw, "result": result}
|
|
86
|
+
return build
|
|
87
|
+
|
|
88
|
+
# -- building ----------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
async def create(
|
|
91
|
+
self,
|
|
92
|
+
url: str,
|
|
93
|
+
*,
|
|
94
|
+
want: Optional[str] = None,
|
|
95
|
+
page_kind: Optional[str] = None,
|
|
96
|
+
country: Optional[str] = None,
|
|
97
|
+
wait: bool = True,
|
|
98
|
+
poll_timeout: Optional[float] = None,
|
|
99
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
100
|
+
) -> Build:
|
|
101
|
+
"""Build an API from ``url`` (a careers page, a listing, a catalog page).
|
|
102
|
+
|
|
103
|
+
Inspects the page, starts the build with the router's choice (every observed field) and
|
|
104
|
+
waits until the build ends, then returns it with ``source_id``, ``version`` and ``schema``.
|
|
105
|
+
``want`` says in your own words what the records are. ``on_progress(build)`` is called at
|
|
106
|
+
each read. ``wait=False`` returns right after the preview is accepted; ``poll_timeout``
|
|
107
|
+
stops waiting after some seconds and returns the unfinished build: continue it with
|
|
108
|
+
``resume`` (it never starts a second build). Raises ``BuildFailedError`` when the page
|
|
109
|
+
cannot be built or the build fails, ``PreviewLimitError`` (429) when the hourly preview
|
|
110
|
+
limit is used up, ``ScopeRequiredError`` for a key without ``discover`` and ``build``.
|
|
111
|
+
"""
|
|
112
|
+
body = b.preview_body(url, want=want, page_kind=page_kind, country=country)
|
|
113
|
+
draft = self._draft(await self._call("POST", "/previews", json=body))
|
|
114
|
+
if not wait:
|
|
115
|
+
return Build(draft_id=draft.draft_id, state="inspecting", raw=draft.raw)
|
|
116
|
+
return await self._drive(draft, core.deadline_after(poll_timeout), on_progress, post_create=True)
|
|
117
|
+
|
|
118
|
+
async def resume(
|
|
119
|
+
self,
|
|
120
|
+
*,
|
|
121
|
+
draft_id: Optional[str] = None,
|
|
122
|
+
job_id: Optional[str] = None,
|
|
123
|
+
poll_timeout: Optional[float] = None,
|
|
124
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
125
|
+
) -> Build:
|
|
126
|
+
"""Continue a build from its handle (``job_id`` wins over ``draft_id``) and wait for its end.
|
|
127
|
+
|
|
128
|
+
With a ``draft_id`` it reads where the build stands: waiting for the page, for the build to
|
|
129
|
+
start, or for the job; the create request is sent again only when nothing started it.
|
|
130
|
+
"""
|
|
131
|
+
deadline = core.deadline_after(poll_timeout)
|
|
132
|
+
if job_id is not None:
|
|
133
|
+
return await self._follow(draft_id, job_id, deadline, on_progress)
|
|
134
|
+
if draft_id is None:
|
|
135
|
+
raise ValueError("give draft_id or job_id")
|
|
136
|
+
draft = await self.get_draft(draft_id)
|
|
137
|
+
return await self._drive(draft, deadline, on_progress, post_create=None)
|
|
138
|
+
|
|
139
|
+
async def create_many(
|
|
140
|
+
self,
|
|
141
|
+
urls: Iterable[str],
|
|
142
|
+
*,
|
|
143
|
+
want: Optional[str] = None,
|
|
144
|
+
page_kind: Optional[str] = None,
|
|
145
|
+
country: Optional[str] = None,
|
|
146
|
+
poll_timeout: Optional[float] = None,
|
|
147
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
148
|
+
wait_for_limit: bool = True,
|
|
149
|
+
max_limit_wait: Optional[float] = None,
|
|
150
|
+
) -> List[Build]:
|
|
151
|
+
"""Build one API per URL, one after the other, and return a ``Build`` per URL in order.
|
|
152
|
+
|
|
153
|
+
A failed build is returned (``state`` ``failed``, ``failure``), not raised, so one bad page
|
|
154
|
+
does not stop the rest. When the hourly preview limit answers 429 the call waits the
|
|
155
|
+
server's ``Retry-After`` and sends the same URL again (``wait_for_limit=False`` raises
|
|
156
|
+
``PreviewLimitError`` instead; so does a wait above ``max_limit_wait`` seconds).
|
|
157
|
+
"""
|
|
158
|
+
builds: List[Build] = []
|
|
159
|
+
for url in urls:
|
|
160
|
+
while True:
|
|
161
|
+
try:
|
|
162
|
+
build = await self.create(
|
|
163
|
+
url,
|
|
164
|
+
want=want,
|
|
165
|
+
page_kind=page_kind,
|
|
166
|
+
country=country,
|
|
167
|
+
poll_timeout=poll_timeout,
|
|
168
|
+
on_progress=on_progress,
|
|
169
|
+
)
|
|
170
|
+
except PreviewLimitError as exc:
|
|
171
|
+
delay = exc.retry_after if exc.retry_after is not None else core.DEFAULT_POLL_SECONDS
|
|
172
|
+
if not wait_for_limit or (max_limit_wait is not None and delay > max_limit_wait):
|
|
173
|
+
raise
|
|
174
|
+
await asyncio.sleep(max(delay, core.MIN_POLL_SECONDS))
|
|
175
|
+
continue
|
|
176
|
+
except BuildFailedError as exc:
|
|
177
|
+
build = exc.build or Build(state="failed")
|
|
178
|
+
break
|
|
179
|
+
builds.append(build)
|
|
180
|
+
return builds
|
|
181
|
+
|
|
182
|
+
# -- the stages --------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
async def _drive(
|
|
185
|
+
self,
|
|
186
|
+
draft: Draft,
|
|
187
|
+
deadline: Optional[float],
|
|
188
|
+
on_progress: Optional[ProgressCallback],
|
|
189
|
+
*,
|
|
190
|
+
post_create: Optional[bool],
|
|
191
|
+
) -> Build:
|
|
192
|
+
"""Inspect, start and follow. ``post_create`` None: decide from the create status."""
|
|
193
|
+
draft_id = draft.draft_id
|
|
194
|
+
job_id = draft.job_id
|
|
195
|
+
if job_id is None:
|
|
196
|
+
delay = b.INSPECTION_POLL_FIRST
|
|
197
|
+
while draft.inspection_status in b.INSPECTING and draft.failure is None:
|
|
198
|
+
await self._notify(on_progress, Build(draft_id=draft_id, state="inspecting", raw=draft.raw))
|
|
199
|
+
if core.out_of_time(deadline, delay):
|
|
200
|
+
return Build(draft_id=draft_id, state="inspecting", raw=draft.raw)
|
|
201
|
+
await asyncio.sleep(delay)
|
|
202
|
+
delay = min(b.INSPECTION_POLL_CEILING, delay * 1.5)
|
|
203
|
+
draft = await self.get_draft(draft_id)
|
|
204
|
+
error = b.inspection_error(draft)
|
|
205
|
+
if error is not None:
|
|
206
|
+
raise error
|
|
207
|
+
job_id = draft.job_id
|
|
208
|
+
if job_id is None:
|
|
209
|
+
if draft.failure is not None: # the creation already ended on a failure: not resent
|
|
210
|
+
raise b.create_refusal({}, draft)
|
|
211
|
+
job_id = await self._start(draft_id, deadline, on_progress, post_create)
|
|
212
|
+
if job_id is None:
|
|
213
|
+
return Build(draft_id=draft_id, state="creating")
|
|
214
|
+
return await self._follow(draft_id, job_id, deadline, on_progress)
|
|
215
|
+
|
|
216
|
+
async def _start(
|
|
217
|
+
self,
|
|
218
|
+
draft_id: str,
|
|
219
|
+
deadline: Optional[float],
|
|
220
|
+
on_progress: Optional[ProgressCallback],
|
|
221
|
+
post_create: Optional[bool],
|
|
222
|
+
) -> Optional[str]:
|
|
223
|
+
"""The job id of the build of this draft, starting it once if nothing did."""
|
|
224
|
+
path = f"/previews/{core.seg(draft_id)}/create"
|
|
225
|
+
if post_create:
|
|
226
|
+
status = await self._call("POST", path, json={})
|
|
227
|
+
else:
|
|
228
|
+
status = await self._call("GET", path)
|
|
229
|
+
if status.get("state") == "idle" and not b.create_job_id(status):
|
|
230
|
+
draft = await self.get_draft(draft_id)
|
|
231
|
+
if draft.job_id:
|
|
232
|
+
return draft.job_id
|
|
233
|
+
if draft.failure is not None:
|
|
234
|
+
raise b.create_refusal(status, draft)
|
|
235
|
+
status = await self._call("POST", path, json={})
|
|
236
|
+
while True:
|
|
237
|
+
job_id = b.create_job_id(status)
|
|
238
|
+
if job_id:
|
|
239
|
+
return job_id
|
|
240
|
+
if status.get("state") == "idle": # it ended with no job: the draft says why
|
|
241
|
+
draft = await self.get_draft(draft_id)
|
|
242
|
+
if draft.job_id:
|
|
243
|
+
return draft.job_id
|
|
244
|
+
raise b.create_refusal(status, draft)
|
|
245
|
+
progress = Build(draft_id=draft_id, state="creating", raw=status)
|
|
246
|
+
position = status.get("queue_position")
|
|
247
|
+
progress.queue_position = position if isinstance(position, int) else None
|
|
248
|
+
await self._notify(on_progress, progress)
|
|
249
|
+
if core.out_of_time(deadline, b.MIN_BUILD_POLL_SECONDS):
|
|
250
|
+
return None
|
|
251
|
+
await asyncio.sleep(b.MIN_BUILD_POLL_SECONDS)
|
|
252
|
+
status = await self._call("GET", path, hold=True)
|
|
253
|
+
|
|
254
|
+
async def _follow(
|
|
255
|
+
self,
|
|
256
|
+
draft_id: Optional[str],
|
|
257
|
+
job_id: str,
|
|
258
|
+
deadline: Optional[float],
|
|
259
|
+
on_progress: Optional[ProgressCallback],
|
|
260
|
+
) -> Build:
|
|
261
|
+
path = f"/builds/{core.seg(job_id)}"
|
|
262
|
+
while True:
|
|
263
|
+
build = Build.from_job(await self._call("GET", path, hold=True), draft_id=draft_id)
|
|
264
|
+
build.job_id = build.job_id or job_id
|
|
265
|
+
await self._notify(on_progress, build)
|
|
266
|
+
if build.terminal:
|
|
267
|
+
break
|
|
268
|
+
if core.out_of_time(deadline, b.MIN_BUILD_POLL_SECONDS):
|
|
269
|
+
return build
|
|
270
|
+
await asyncio.sleep(b.MIN_BUILD_POLL_SECONDS)
|
|
271
|
+
if not build.succeeded:
|
|
272
|
+
raise b.job_error(build)
|
|
273
|
+
return await self._with_result(build)
|