webcite 0.1.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.
webcite/_client.py ADDED
@@ -0,0 +1,440 @@
1
+ """Synchronous client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Iterator, List, Mapping, Optional, Sequence, cast
7
+
8
+ import httpx
9
+
10
+ from . import _requests as R
11
+ from ._base import (
12
+ SSEDecoder,
13
+ StreamTracker,
14
+ TimeoutArg,
15
+ default_headers,
16
+ parse_json,
17
+ request_kwargs,
18
+ resolve_config,
19
+ retry_delay,
20
+ should_retry,
21
+ )
22
+ from ._errors import (
23
+ IncompleteStreamError,
24
+ WebciteConnectionError,
25
+ WebciteTimeoutError,
26
+ error_from_response,
27
+ )
28
+ from .types import (
29
+ AskJob,
30
+ Balance,
31
+ CitationList,
32
+ ExtractResponse,
33
+ JSONObject,
34
+ StreamEvent,
35
+ UploadResponse,
36
+ VerifyResponse,
37
+ )
38
+
39
+
40
+ class Webcite:
41
+ """Client for the Webcite API.
42
+
43
+ ``api_key`` defaults to ``WEBCITE_API_KEY``; ``base_url`` defaults to ``WEBCITE_API_URL`` or
44
+ https://api.webcite.co. GET requests and verifications (sent with an Idempotency-Key) are
45
+ retried on 429 and 5xx; other calls are never repeated automatically.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ api_key: Optional[str] = None,
51
+ *,
52
+ base_url: Optional[str] = None,
53
+ timeout: TimeoutArg = None,
54
+ max_retries: Optional[int] = None,
55
+ http_client: Optional[httpx.Client] = None,
56
+ ) -> None:
57
+ self._config = resolve_config(api_key, base_url, timeout, max_retries)
58
+ self._http = http_client or httpx.Client()
59
+ self._owns_http = http_client is None
60
+
61
+ @property
62
+ def base_url(self) -> str:
63
+ return self._config.base_url
64
+
65
+ def close(self) -> None:
66
+ if self._owns_http:
67
+ self._http.close()
68
+
69
+ def __enter__(self) -> Webcite:
70
+ return self
71
+
72
+ def __exit__(self, *_: object) -> None:
73
+ self.close()
74
+
75
+ # -- transport ---------------------------------------------------------------------------
76
+
77
+ def _build(self, spec: R.RequestSpec) -> httpx.Request:
78
+ kwargs = request_kwargs(spec)
79
+ headers = {**default_headers(self._config.api_key), **kwargs.pop("headers")}
80
+ return self._http.build_request(
81
+ spec.method,
82
+ self._config.base_url + spec.path,
83
+ headers=headers,
84
+ timeout=self._config.timeout,
85
+ **kwargs,
86
+ )
87
+
88
+ def _send_raw(self, spec: R.RequestSpec, stream: bool = False) -> httpx.Response:
89
+ attempt = 0
90
+ while True:
91
+ status: Optional[int] = None
92
+ wait_hint: Optional[float] = None
93
+ try:
94
+ response = self._http.send(self._build(spec), stream=stream)
95
+ if response.status_code < 400:
96
+ return response
97
+ if stream:
98
+ response.read()
99
+ status = response.status_code
100
+ error = error_from_response(status, response.headers, response.text)
101
+ wait_hint = error.retry_after
102
+ if not should_retry(spec, status, attempt, self._config.max_retries):
103
+ raise error
104
+ except httpx.TimeoutException as exc:
105
+ if not should_retry(spec, None, attempt, self._config.max_retries):
106
+ raise WebciteTimeoutError(_timeout_message(spec)) from exc
107
+ except httpx.TransportError as exc:
108
+ if not should_retry(spec, None, attempt, self._config.max_retries):
109
+ raise WebciteConnectionError(f"Could not reach {self.base_url}: {exc}") from exc
110
+ time.sleep(retry_delay(attempt, wait_hint))
111
+ attempt += 1
112
+
113
+ def _send(self, spec: R.RequestSpec) -> Any:
114
+ return parse_json(self._send_raw(spec))
115
+
116
+ def _stream(self, spec: R.RequestSpec) -> Iterator[StreamEvent]:
117
+ response = self._send_raw(spec, stream=True)
118
+ tracker, decoder = StreamTracker(), SSEDecoder()
119
+ try:
120
+ for line in response.iter_lines():
121
+ event = decoder.feed(line)
122
+ if event is None:
123
+ continue
124
+ failure = tracker.add(event)
125
+ yield cast(StreamEvent, event)
126
+ if failure:
127
+ raise IncompleteStreamError(failure, tracker.events)
128
+ except httpx.HTTPError as exc:
129
+ raise IncompleteStreamError(
130
+ f"Verification stream disconnected: {exc}", tracker.events
131
+ ) from exc
132
+ finally:
133
+ response.close()
134
+ reason = tracker.final_failure()
135
+ if reason:
136
+ raise IncompleteStreamError(reason, tracker.events)
137
+
138
+ # -- verification ------------------------------------------------------------------------
139
+
140
+ def verify(
141
+ self,
142
+ claim: str,
143
+ *,
144
+ source_urls: Optional[Sequence[str]] = None,
145
+ filters: Optional[Mapping[str, Any]] = None,
146
+ thread_id: Optional[str] = None,
147
+ include_stance: Optional[bool] = None,
148
+ include_verdict: Optional[bool] = None,
149
+ decompose_claim: Optional[bool] = None,
150
+ include_numeric_assess: Optional[bool] = None,
151
+ include_source_reads: Optional[bool] = None,
152
+ evidence_scope: Optional[Mapping[str, Any]] = None,
153
+ idempotency_key: Optional[str] = None,
154
+ ) -> VerifyResponse:
155
+ """Verify one claim against web sources (POST /api/v1/verify). 4 credits by default."""
156
+ return cast(
157
+ VerifyResponse,
158
+ self._send(
159
+ R.verify(
160
+ claim,
161
+ source_urls=source_urls,
162
+ filters=filters,
163
+ thread_id=thread_id,
164
+ include_stance=include_stance,
165
+ include_verdict=include_verdict,
166
+ decompose_claim=decompose_claim,
167
+ include_numeric_assess=include_numeric_assess,
168
+ include_source_reads=include_source_reads,
169
+ evidence_scope=evidence_scope,
170
+ idempotency_key=idempotency_key,
171
+ )
172
+ ),
173
+ )
174
+
175
+ def verify_stream(
176
+ self,
177
+ claim: str,
178
+ *,
179
+ source_urls: Optional[Sequence[str]] = None,
180
+ filters: Optional[Mapping[str, Any]] = None,
181
+ thread_id: Optional[str] = None,
182
+ include_stance: Optional[bool] = None,
183
+ include_verdict: Optional[bool] = None,
184
+ decompose_claim: Optional[bool] = None,
185
+ ) -> Iterator[StreamEvent]:
186
+ """Stream verification events. Raises IncompleteStreamError without result and done."""
187
+ return self._stream(
188
+ R.verify(
189
+ claim,
190
+ source_urls=source_urls,
191
+ filters=filters,
192
+ thread_id=thread_id,
193
+ include_stance=include_stance,
194
+ include_verdict=include_verdict,
195
+ decompose_claim=decompose_claim,
196
+ stream=True,
197
+ )
198
+ )
199
+
200
+ def verify_batch(
201
+ self,
202
+ items: Sequence[Mapping[str, Any]],
203
+ *,
204
+ evidence_scope: Optional[Mapping[str, Any]] = None,
205
+ ) -> List[JSONObject]:
206
+ """Check quotes against their sources in one call (POST /api/v1/verify/batch)."""
207
+ return cast(
208
+ List[JSONObject], self._send(R.verify_batch(items, evidence_scope=evidence_scope))
209
+ )
210
+
211
+ def verify_feedback(self, token: str, verdict: str, note: Optional[str] = None) -> JSONObject:
212
+ """Record correct, incorrect or unsure on a verification result."""
213
+ return cast(JSONObject, self._send(R.verify_feedback(token, verdict, note)))
214
+
215
+ def verify_numeric(self, body: Mapping[str, Any]) -> JSONObject:
216
+ """Check numeric arithmetic (POST /api/v2/verify/numeric)."""
217
+ return cast(JSONObject, self._send(R.verify_numeric(body)))
218
+
219
+ def search(
220
+ self,
221
+ query: str,
222
+ *,
223
+ limit: Optional[int] = None,
224
+ filters: Optional[Mapping[str, Any]] = None,
225
+ ) -> VerifyResponse:
226
+ """Search for sources (POST /api/v1/sources/search)."""
227
+ return cast(VerifyResponse, self._send(R.search(query, limit=limit, filters=filters)))
228
+
229
+ # -- citations -----------------------------------------------------------------------
230
+
231
+ def list_citations(
232
+ self,
233
+ *,
234
+ page: Optional[int] = None,
235
+ limit: Optional[int] = None,
236
+ fields: Optional[str] = None,
237
+ thread_id: Optional[str] = None,
238
+ ) -> CitationList:
239
+ return cast(
240
+ CitationList,
241
+ self._send(
242
+ R.list_citations(page=page, limit=limit, fields=fields, thread_id=thread_id)
243
+ ),
244
+ )
245
+
246
+ def get_citation(self, citation_id: str) -> JSONObject:
247
+ return cast(JSONObject, self._send(R.get_citation(citation_id)))
248
+
249
+ def source_preview(
250
+ self,
251
+ *,
252
+ url: Optional[str] = None,
253
+ asset_id: Optional[str] = None,
254
+ page: Optional[int] = None,
255
+ quote: Optional[str] = None,
256
+ **fields: Any,
257
+ ) -> JSONObject:
258
+ """Show the evidence passage at a URL or in an uploaded file."""
259
+ return cast(
260
+ JSONObject,
261
+ self._send(
262
+ R.source_preview(
263
+ {"url": url, "asset_id": asset_id, "page": page, "quote": quote, **fields}
264
+ )
265
+ ),
266
+ )
267
+
268
+ # -- documents -----------------------------------------------------------------------
269
+
270
+ def upload(self, file: R.FileInput, *, filename: Optional[str] = None) -> UploadResponse:
271
+ """Store a file (path, bytes or binary file object). Free. Keep data.asset_id."""
272
+ return cast(UploadResponse, self._send(R.upload(file, filename)))
273
+
274
+ def upload_url(self, url: str, *, filename: Optional[str] = None) -> UploadResponse:
275
+ """Store the file at a public HTTPS URL."""
276
+ return cast(UploadResponse, self._send(R.upload_url(url, filename)))
277
+
278
+ def extract(
279
+ self,
280
+ asset_id: Optional[str] = None,
281
+ *,
282
+ asset_url: Optional[str] = None,
283
+ mode: Optional[str] = None,
284
+ refresh: Optional[bool] = None,
285
+ ) -> ExtractResponse:
286
+ """Read a document as Markdown with per-page units. Runs until every page is read."""
287
+ return cast(
288
+ ExtractResponse,
289
+ self._send(R.extract("", asset_id, asset_url, mode=mode, refresh=refresh)),
290
+ )
291
+
292
+ def extract_visual_rendition(
293
+ self,
294
+ asset_id: Optional[str] = None,
295
+ *,
296
+ asset_url: Optional[str] = None,
297
+ source_version_id: Optional[str] = None,
298
+ refresh: Optional[bool] = None,
299
+ ) -> JSONObject:
300
+ return cast(
301
+ JSONObject,
302
+ self._send(
303
+ R.extract(
304
+ "/visual-rendition",
305
+ asset_id,
306
+ asset_url,
307
+ visual_rendition=True,
308
+ source_version_id=source_version_id,
309
+ refresh=refresh,
310
+ )
311
+ ),
312
+ )
313
+
314
+ def extract_pages(
315
+ self,
316
+ asset_id: Optional[str] = None,
317
+ *,
318
+ asset_url: Optional[str] = None,
319
+ mode: Optional[str] = None,
320
+ ) -> JSONObject:
321
+ """Extract anchored chunks ready to index and cite."""
322
+ return cast(JSONObject, self._send(R.extract("/pages", asset_id, asset_url, mode=mode)))
323
+
324
+ def extract_figures(
325
+ self, asset_id: Optional[str] = None, *, asset_url: Optional[str] = None
326
+ ) -> JSONObject:
327
+ """Extract every recognised number as a tagged, source-grounded figure."""
328
+ return cast(JSONObject, self._send(R.extract("/figures", asset_id, asset_url)))
329
+
330
+ def classify(
331
+ self,
332
+ asset_id: Optional[str] = None,
333
+ *,
334
+ asset_url: Optional[str] = None,
335
+ taxonomy: Optional[str] = None,
336
+ ) -> JSONObject:
337
+ return cast(JSONObject, self._send(R.classify(asset_id, asset_url, taxonomy)))
338
+
339
+ def gaps(
340
+ self,
341
+ category: str,
342
+ docs: Sequence[Mapping[str, Any]],
343
+ *,
344
+ stage: Optional[str] = None,
345
+ taxonomy: Optional[str] = None,
346
+ ) -> JSONObject:
347
+ return cast(JSONObject, self._send(R.gaps(category, docs, stage=stage, taxonomy=taxonomy)))
348
+
349
+ def ask(
350
+ self,
351
+ question: str,
352
+ document_text: str,
353
+ *,
354
+ document_name: Optional[str] = None,
355
+ has_text_layer: Optional[bool] = None,
356
+ top_k: Optional[int] = None,
357
+ ) -> AskJob:
358
+ """Queue a question over document text. Poll with get_ask() or wait_for_ask()."""
359
+ return cast(
360
+ AskJob,
361
+ self._send(
362
+ R.ask(
363
+ question,
364
+ document_text,
365
+ document_name=document_name,
366
+ has_text_layer=has_text_layer,
367
+ top_k=top_k,
368
+ )
369
+ ),
370
+ )
371
+
372
+ def get_ask(self, job_id: str) -> AskJob:
373
+ return cast(AskJob, self._send(R.get_ask(job_id)))
374
+
375
+ def wait_for_ask(
376
+ self, job_id: str, *, poll_interval: float = 2.0, max_wait: Optional[float] = 600.0
377
+ ) -> AskJob:
378
+ """Poll until done or failed. After max_wait, returns the latest job view unchanged."""
379
+ started = time.monotonic()
380
+ while True:
381
+ job = self.get_ask(job_id)
382
+ if job.get("status") in R.ASK_TERMINAL:
383
+ return job
384
+ if max_wait is not None and time.monotonic() - started >= max_wait:
385
+ return job
386
+ time.sleep(poll_interval)
387
+
388
+ def analyze_conflicts(
389
+ self,
390
+ figures: Sequence[Mapping[str, Any]],
391
+ *,
392
+ fx_rates: Optional[Sequence[Mapping[str, Any]]] = None,
393
+ precedence_rules: Optional[Sequence[Mapping[str, Any]]] = None,
394
+ ) -> JSONObject:
395
+ return cast(
396
+ JSONObject,
397
+ self._send(
398
+ R.analyze_conflicts(figures, fx_rates=fx_rates, precedence_rules=precedence_rules)
399
+ ),
400
+ )
401
+
402
+ def analyze_document(self, asset_id: str) -> JSONObject:
403
+ return cast(JSONObject, self._send(R.analyze_document(asset_id)))
404
+
405
+ def accuracy(self) -> JSONObject:
406
+ return cast(JSONObject, self._send(R.accuracy()))
407
+
408
+ def balance(self) -> Balance:
409
+ """Read remaining, used and total credits. Free."""
410
+ return cast(Balance, self._send(R.balance()))
411
+
412
+ # -- retained sources (v2) -----------------------------------------------------------
413
+
414
+ def register_source(
415
+ self, asset_id: str, file: R.FileInput, *, filename: Optional[str] = None
416
+ ) -> JSONObject:
417
+ return cast(JSONObject, self._send(R.register_source(asset_id, file, filename)))
418
+
419
+ def publish_text_representation(self, version_id: str) -> JSONObject:
420
+ return cast(JSONObject, self._send(R.publish_text_representation(version_id)))
421
+
422
+ def latest_representation(self, version_id: str) -> JSONObject:
423
+ return cast(JSONObject, self._send(R.latest_representation(version_id)))
424
+
425
+ def source_unit(self, version_id: str, representation_id: str, unit_id: str) -> JSONObject:
426
+ return cast(JSONObject, self._send(R.source_unit(version_id, representation_id, unit_id)))
427
+
428
+ def prepare_ocr_rescue(self, version_id: str, representation_id: str) -> JSONObject:
429
+ return cast(JSONObject, self._send(R.prepare_ocr_rescue(version_id, representation_id)))
430
+
431
+
432
+ def _timeout_message(spec: R.RequestSpec) -> str:
433
+ return (
434
+ f"{spec.method} {spec.path} did not answer within the client timeout. The server may "
435
+ "still have completed the work; keep any operation IDs and check before repeating a "
436
+ "paid call. Raise timeout= for long documents."
437
+ )
438
+
439
+
440
+ __all__ = ["Webcite"]
webcite/_errors.py ADDED
@@ -0,0 +1,207 @@
1
+ """Typed errors. Each carries the server's message and the next step to take."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from typing import Any, Dict, List, Mapping, Optional, Tuple, Type
8
+
9
+ ERRORS_DOC = "https://webcite.co/api-docs/errors"
10
+ AUTH_DOC = "https://webcite.co/api-docs/authentication"
11
+ CREDITS_DOC = "https://webcite.co/api-docs/credits"
12
+ KEYS_PAGE = "https://webcite.co/api-keys"
13
+
14
+ _CREDITS_RE = re.compile(
15
+ r"insufficient credits|credit.balance.exhausted|credit limit exceeded|INSUFFICIENT_CREDITS",
16
+ re.IGNORECASE,
17
+ )
18
+
19
+
20
+ class WebciteError(Exception):
21
+ """Base class for every error raised by this package."""
22
+
23
+ def __init__(
24
+ self,
25
+ message: str,
26
+ *,
27
+ status: Optional[int] = None,
28
+ code: Optional[str] = None,
29
+ doc_url: Optional[str] = None,
30
+ retry_after: Optional[float] = None,
31
+ next_step: Optional[str] = None,
32
+ body: Any = None,
33
+ ) -> None:
34
+ super().__init__(message if not next_step else f"{message} Next step: {next_step}")
35
+ self.message = message
36
+ self.status = status
37
+ self.code = code
38
+ self.doc_url = doc_url
39
+ self.retry_after = retry_after
40
+ self.next_step = next_step
41
+ self.body = body
42
+
43
+
44
+ class APIError(WebciteError):
45
+ """The API answered with a non-2xx status."""
46
+
47
+
48
+ class BadRequestError(APIError):
49
+ pass
50
+
51
+
52
+ class AuthenticationError(APIError):
53
+ pass
54
+
55
+
56
+ class PermissionDeniedError(APIError):
57
+ pass
58
+
59
+
60
+ class NotFoundError(APIError):
61
+ pass
62
+
63
+
64
+ class ConflictError(APIError):
65
+ pass
66
+
67
+
68
+ class PayloadTooLargeError(APIError):
69
+ pass
70
+
71
+
72
+ class RateLimitError(APIError):
73
+ pass
74
+
75
+
76
+ class InsufficientCreditsError(APIError):
77
+ pass
78
+
79
+
80
+ class ServerError(APIError):
81
+ pass
82
+
83
+
84
+ class WebciteConnectionError(WebciteError):
85
+ """The request did not reach the API or the connection dropped."""
86
+
87
+
88
+ class WebciteTimeoutError(WebciteConnectionError):
89
+ """The client timeout passed before the API answered."""
90
+
91
+
92
+ class IncompleteStreamError(WebciteError):
93
+ """A verification stream ended without a result and a done event."""
94
+
95
+ def __init__(self, message: str, events: List[Dict[str, Any]], **kw: Any) -> None:
96
+ super().__init__(message, **kw)
97
+ self.events = events
98
+
99
+
100
+ MISSING_KEY_STEP = f"Create a key at {KEYS_PAGE} (sign-in required)."
101
+
102
+ _STEPS: Dict[int, Tuple[Type[APIError], str, str, str]] = {
103
+ 401: (
104
+ AuthenticationError,
105
+ "unauthorized",
106
+ AUTH_DOC,
107
+ f"Check the API key. Create one at {KEYS_PAGE} (sign-in required). "
108
+ "A key works only against the environment that issued it.",
109
+ ),
110
+ 403: (
111
+ PermissionDeniedError,
112
+ "forbidden",
113
+ AUTH_DOC,
114
+ f"This key may not use this resource (app keys cannot upload or extract). "
115
+ f"Use an account API key from {KEYS_PAGE}.",
116
+ ),
117
+ 404: (
118
+ NotFoundError,
119
+ "not_found",
120
+ ERRORS_DOC,
121
+ "Confirm the ID exists and belongs to the account that owns this key.",
122
+ ),
123
+ 409: (
124
+ ConflictError,
125
+ "conflict",
126
+ ERRORS_DOC,
127
+ "The Idempotency-Key was used with a different payload. "
128
+ "Resend the original payload, or use a new key for a new request.",
129
+ ),
130
+ 413: (
131
+ PayloadTooLargeError,
132
+ "payload_too_large",
133
+ ERRORS_DOC,
134
+ "Reduce the input. Files can be at most 100 MB.",
135
+ ),
136
+ }
137
+
138
+
139
+ def _parse_body(text: str) -> Any:
140
+ try:
141
+ return json.loads(text)
142
+ except ValueError:
143
+ return text
144
+
145
+
146
+ def _server_message(body: Any, status: int) -> str:
147
+ if isinstance(body, dict):
148
+ msg = body.get("message")
149
+ if isinstance(msg, list):
150
+ return "; ".join(str(m) for m in msg)
151
+ if isinstance(msg, str) and msg:
152
+ return msg
153
+ if isinstance(body, str) and body.strip():
154
+ return body.strip()[:500]
155
+ return f"HTTP {status}"
156
+
157
+
158
+ def parse_retry_after(headers: Mapping[str, str], body: Any) -> Optional[float]:
159
+ raw: Any = headers.get("retry-after")
160
+ if raw is None and isinstance(body, dict):
161
+ raw = body.get("retryAfter")
162
+ try:
163
+ return max(0.0, float(raw)) if raw is not None else None
164
+ except (TypeError, ValueError):
165
+ return None
166
+
167
+
168
+ def error_from_response(status: int, headers: Mapping[str, str], text: str) -> APIError:
169
+ body = _parse_body(text)
170
+ message = _server_message(body, status)
171
+ server_code = body.get("error") if isinstance(body, dict) else None
172
+ retry_after = parse_retry_after(headers, body)
173
+ kw: Dict[str, Any] = {"status": status, "body": body, "retry_after": retry_after}
174
+ if status in (400, 402, 429) and _CREDITS_RE.search(text):
175
+ return InsufficientCreditsError(
176
+ message,
177
+ code="insufficient_credits",
178
+ doc_url=CREDITS_DOC,
179
+ next_step="Stop paid calls and keep completed results. Check the balance with "
180
+ "balance(); an account owner can add credits or enable overage where the plan "
181
+ "allows it.",
182
+ **kw,
183
+ )
184
+ if status in _STEPS:
185
+ cls, code, doc, step = _STEPS[status]
186
+ return cls(message, code=code, doc_url=doc, next_step=step, **kw)
187
+ if status == 429:
188
+ wait = f"Wait {retry_after:g} seconds" if retry_after is not None else "Wait"
189
+ return RateLimitError(
190
+ message, code="rate_limited", doc_url=ERRORS_DOC, next_step=f"{wait} and retry.", **kw
191
+ )
192
+ if status >= 500:
193
+ return ServerError(
194
+ message,
195
+ code=str(server_code or "server_error"),
196
+ doc_url=ERRORS_DOC,
197
+ next_step="Inspect saved operation IDs before repeating a paid "
198
+ "call. A verify retry is safe with the same Idempotency-Key.",
199
+ **kw,
200
+ )
201
+ return BadRequestError(
202
+ message,
203
+ code=str(server_code or "bad_request"),
204
+ doc_url=ERRORS_DOC,
205
+ next_step="Check the request fields against the endpoint reference.",
206
+ **kw,
207
+ )