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/_requests.py ADDED
@@ -0,0 +1,283 @@
1
+ """Request builders shared by the sync and async clients.
2
+
3
+ Each builder returns a RequestSpec. The clients only send specs, so both clients call the same
4
+ paths with the same bodies. ``tests/test_contract.py`` checks every path and method here
5
+ against the public OpenAPI document.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import uuid
12
+ from dataclasses import dataclass
13
+ from typing import IO, Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
14
+ from urllib.parse import quote
15
+
16
+ FileInput = Union[str, "os.PathLike[str]", bytes, IO[bytes]]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RequestSpec:
21
+ method: str
22
+ path: str
23
+ json: Optional[Mapping[str, Any]] = None
24
+ params: Optional[Mapping[str, Any]] = None
25
+ files: Optional[Mapping[str, Tuple[str, Any]]] = None
26
+ data: Optional[Mapping[str, str]] = None
27
+ idempotency_key: Optional[str] = None
28
+ stream: bool = False
29
+
30
+ @property
31
+ def retryable(self) -> bool:
32
+ """GET requests and keyed verifications are safe to repeat."""
33
+ return self.method == "GET" or self.idempotency_key is not None
34
+
35
+
36
+ def _seg(value: str) -> str:
37
+ if not isinstance(value, str) or not value:
38
+ raise ValueError("Path identifiers must be non-empty strings.")
39
+ return quote(value, safe="")
40
+
41
+
42
+ def _compact(**fields: Any) -> Dict[str, Any]:
43
+ """Drop arguments the caller did not pass, so server defaults apply."""
44
+ return {k: v for k, v in fields.items() if v is not None}
45
+
46
+
47
+ def _asset(asset_id: Optional[str], asset_url: Optional[str]) -> Dict[str, Any]:
48
+ if not asset_id and not asset_url:
49
+ raise ValueError("Pass asset_id (from upload) or asset_url.")
50
+ return _compact(asset_id=asset_id, asset_url=asset_url)
51
+
52
+
53
+ def read_file(file: FileInput, filename: Optional[str]) -> Tuple[str, bytes]:
54
+ if isinstance(file, bytes):
55
+ if not filename:
56
+ raise ValueError("Pass filename= with bytes; its extension decides how it is read.")
57
+ return filename, file
58
+ if isinstance(file, (str, os.PathLike)):
59
+ path = os.fspath(file)
60
+ with open(path, "rb") as handle:
61
+ return filename or os.path.basename(path), handle.read()
62
+ name = filename or os.path.basename(str(getattr(file, "name", "")))
63
+ if not name:
64
+ raise ValueError("Pass filename= for a file object without a name.")
65
+ return name, file.read()
66
+
67
+
68
+ def verify(
69
+ claim: str,
70
+ *,
71
+ source_urls: Optional[Sequence[str]] = None,
72
+ filters: Optional[Mapping[str, Any]] = None,
73
+ thread_id: Optional[str] = None,
74
+ include_stance: Optional[bool] = None,
75
+ include_verdict: Optional[bool] = None,
76
+ decompose_claim: Optional[bool] = None,
77
+ include_numeric_assess: Optional[bool] = None,
78
+ include_source_reads: Optional[bool] = None,
79
+ evidence_scope: Optional[Mapping[str, Any]] = None,
80
+ idempotency_key: Optional[str] = None,
81
+ stream: bool = False,
82
+ ) -> RequestSpec:
83
+ body = _compact(
84
+ claim=claim,
85
+ source_urls=list(source_urls) if source_urls else None,
86
+ filters=filters,
87
+ thread_id=thread_id,
88
+ include_stance=include_stance,
89
+ include_verdict=include_verdict,
90
+ decompose_claim=decompose_claim,
91
+ include_numeric_assess=include_numeric_assess,
92
+ include_source_reads=include_source_reads,
93
+ evidence_scope=evidence_scope,
94
+ )
95
+ if stream:
96
+ return RequestSpec("POST", "/api/v1/verify/stream", json=body, stream=True)
97
+ return RequestSpec(
98
+ "POST", "/api/v1/verify", json=body, idempotency_key=idempotency_key or str(uuid.uuid4())
99
+ )
100
+
101
+
102
+ def verify_batch(
103
+ items: Sequence[Mapping[str, Any]], *, evidence_scope: Optional[Mapping[str, Any]] = None
104
+ ) -> RequestSpec:
105
+ body = _compact(items=[dict(i) for i in items], evidence_scope=evidence_scope)
106
+ return RequestSpec("POST", "/api/v1/verify/batch", json=body)
107
+
108
+
109
+ def verify_feedback(token: str, verdict: str, note: Optional[str] = None) -> RequestSpec:
110
+ return RequestSpec(
111
+ "POST", "/api/v1/verify/feedback", json=_compact(token=token, verdict=verdict, note=note)
112
+ )
113
+
114
+
115
+ def verify_numeric(body: Mapping[str, Any]) -> RequestSpec:
116
+ return RequestSpec("POST", "/api/v2/verify/numeric", json=dict(body))
117
+
118
+
119
+ def search(
120
+ query: str, *, limit: Optional[int] = None, filters: Optional[Mapping[str, Any]] = None
121
+ ) -> RequestSpec:
122
+ return RequestSpec(
123
+ "POST", "/api/v1/sources/search", json=_compact(query=query, limit=limit, filters=filters)
124
+ )
125
+
126
+
127
+ def list_citations(
128
+ *,
129
+ page: Optional[int] = None,
130
+ limit: Optional[int] = None,
131
+ fields: Optional[str] = None,
132
+ thread_id: Optional[str] = None,
133
+ ) -> RequestSpec:
134
+ return RequestSpec(
135
+ "GET",
136
+ "/api/v1/citations",
137
+ params=_compact(page=page, limit=limit, fields=fields, thread_id=thread_id),
138
+ )
139
+
140
+
141
+ def get_citation(citation_id: str) -> RequestSpec:
142
+ return RequestSpec("GET", f"/api/v1/citations/{_seg(citation_id)}")
143
+
144
+
145
+ def source_preview(fields: Mapping[str, Any]) -> RequestSpec:
146
+ body = _compact(**fields)
147
+ if not body:
148
+ raise ValueError("Pass url, or asset_id with page, quote or source_unit_id.")
149
+ return RequestSpec("POST", "/api/v1/citations/source-preview", json=body)
150
+
151
+
152
+ def upload(file: FileInput, filename: Optional[str] = None) -> RequestSpec:
153
+ name, content = read_file(file, filename)
154
+ return RequestSpec("POST", "/api/v1/upload", files={"file": (name, content)})
155
+
156
+
157
+ def upload_url(url: str, filename: Optional[str] = None) -> RequestSpec:
158
+ return RequestSpec("POST", "/api/v1/upload/url", json=_compact(url=url, filename=filename))
159
+
160
+
161
+ def extract(
162
+ path: str, asset_id: Optional[str], asset_url: Optional[str], **options: Any
163
+ ) -> RequestSpec:
164
+ return RequestSpec(
165
+ "POST",
166
+ f"/api/v1/extract{path}",
167
+ json={**_asset(asset_id, asset_url), **_compact(**options)},
168
+ )
169
+
170
+
171
+ def classify(
172
+ asset_id: Optional[str], asset_url: Optional[str], taxonomy: Optional[str]
173
+ ) -> RequestSpec:
174
+ return RequestSpec(
175
+ "POST",
176
+ "/api/v1/classify",
177
+ json={**_asset(asset_id, asset_url), **_compact(taxonomy=taxonomy)},
178
+ )
179
+
180
+
181
+ def gaps(
182
+ category: str,
183
+ docs: Sequence[Mapping[str, Any]],
184
+ *,
185
+ stage: Optional[str] = None,
186
+ taxonomy: Optional[str] = None,
187
+ ) -> RequestSpec:
188
+ return RequestSpec(
189
+ "POST",
190
+ "/api/v1/gaps",
191
+ json=_compact(
192
+ category=category, docs=[dict(d) for d in docs], stage=stage, taxonomy=taxonomy
193
+ ),
194
+ )
195
+
196
+
197
+ def ask(
198
+ question: str,
199
+ document_text: str,
200
+ *,
201
+ document_name: Optional[str] = None,
202
+ has_text_layer: Optional[bool] = None,
203
+ top_k: Optional[int] = None,
204
+ ) -> RequestSpec:
205
+ return RequestSpec(
206
+ "POST",
207
+ "/api/v1/ask",
208
+ json=_compact(
209
+ question=question,
210
+ documentText=document_text,
211
+ documentName=document_name,
212
+ hasTextLayer=has_text_layer,
213
+ topK=top_k,
214
+ ),
215
+ )
216
+
217
+
218
+ def get_ask(job_id: str) -> RequestSpec:
219
+ return RequestSpec("GET", f"/api/v1/ask/{_seg(job_id)}")
220
+
221
+
222
+ def analyze_conflicts(
223
+ figures: Sequence[Mapping[str, Any]],
224
+ *,
225
+ fx_rates: Optional[Sequence[Mapping[str, Any]]] = None,
226
+ precedence_rules: Optional[Sequence[Mapping[str, Any]]] = None,
227
+ ) -> RequestSpec:
228
+ return RequestSpec(
229
+ "POST",
230
+ "/api/v1/analyze/conflicts",
231
+ json=_compact(
232
+ figures=[dict(f) for f in figures],
233
+ fxRates=[dict(r) for r in fx_rates] if fx_rates is not None else None,
234
+ precedenceRules=[dict(r) for r in precedence_rules]
235
+ if precedence_rules is not None
236
+ else None,
237
+ ),
238
+ )
239
+
240
+
241
+ def analyze_document(asset_id: str) -> RequestSpec:
242
+ return RequestSpec("POST", "/api/v1/analyze/document", json={"asset_id": asset_id})
243
+
244
+
245
+ def accuracy() -> RequestSpec:
246
+ return RequestSpec("GET", "/api/v1/accuracy")
247
+
248
+
249
+ def balance() -> RequestSpec:
250
+ # Account route used by the Webcite MCP server's get_credit_balance tool. It accepts an API
251
+ # key but is not in the public OpenAPI document; the contract test lists it as the one
252
+ # exception.
253
+ return RequestSpec("GET", "/api/v1/payment/credits/balance")
254
+
255
+
256
+ def register_source(asset_id: str, file: FileInput, filename: Optional[str] = None) -> RequestSpec:
257
+ name, content = read_file(file, filename)
258
+ return RequestSpec(
259
+ "POST", "/api/v2/sources", files={"file": (name, content)}, data={"assetId": asset_id}
260
+ )
261
+
262
+
263
+ def _rep(version_id: str, rest: str = "") -> str:
264
+ return f"/api/v2/sources/{_seg(version_id)}/representations{rest}"
265
+
266
+
267
+ def publish_text_representation(version_id: str) -> RequestSpec:
268
+ return RequestSpec("POST", _rep(version_id, "/text"))
269
+
270
+
271
+ def latest_representation(version_id: str) -> RequestSpec:
272
+ return RequestSpec("GET", _rep(version_id, "/latest"))
273
+
274
+
275
+ def source_unit(version_id: str, representation_id: str, unit_id: str) -> RequestSpec:
276
+ return RequestSpec("GET", _rep(version_id, f"/{_seg(representation_id)}/units/{_seg(unit_id)}"))
277
+
278
+
279
+ def prepare_ocr_rescue(version_id: str, representation_id: str) -> RequestSpec:
280
+ return RequestSpec("POST", _rep(version_id, f"/{_seg(representation_id)}/prepare-ocr-rescue"))
281
+
282
+
283
+ ASK_TERMINAL: List[str] = ["done", "failed"]
webcite/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
webcite/py.typed ADDED
File without changes
webcite/types.py ADDED
@@ -0,0 +1,182 @@
1
+ """Response types. Responses are plain dicts; these TypedDicts describe the documented fields.
2
+
3
+ Fields can be missing or null. A null value means the server did not know it, not zero, so
4
+ keep nulls as they are when you store a response.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Dict, List, Optional, TypedDict
10
+
11
+ JSONObject = Dict[str, Any]
12
+
13
+
14
+ class Usage(TypedDict, total=False):
15
+ credits: Optional[float]
16
+ pages: Optional[int]
17
+ page_charges: List[JSONObject]
18
+
19
+
20
+ class CreditUsage(TypedDict, total=False):
21
+ credits_used: Optional[float]
22
+ credits_remaining: Optional[float]
23
+ monthly_allocation: Optional[float]
24
+ overage_enabled: Optional[bool]
25
+ operation_id: Optional[str]
26
+
27
+
28
+ class StanceBreakdown(TypedDict, total=False):
29
+ supports: int
30
+ partially_supports: int
31
+ contradicts: int
32
+ neutral: int
33
+ inconclusive: int
34
+ irrelevant: int
35
+ unknown: int
36
+
37
+
38
+ class Verdict(TypedDict, total=False):
39
+ claim: str
40
+ result: str
41
+ confidence: Optional[float]
42
+ summary: str
43
+ stance_breakdown: StanceBreakdown
44
+ origin_count: int
45
+ document_count: int
46
+ insufficient_evidence: bool
47
+ key_findings: List[JSONObject]
48
+ corrections: List[JSONObject]
49
+ confidence_basis: str
50
+ confidence_available: bool
51
+ confidence_meaning: str
52
+
53
+
54
+ class Citation(TypedDict, total=False):
55
+ id: str
56
+ title: str
57
+ url: str
58
+ snippet: str
59
+ status: str
60
+ source_type: str
61
+ stance: str
62
+ stance_confidence: Optional[float]
63
+ stance_explanation: str
64
+ credibility_score: Optional[float]
65
+ rank: int
66
+ group_id: str
67
+ is_group_primary: bool
68
+ source_metadata: JSONObject
69
+
70
+
71
+ class DomainGroup(TypedDict, total=False):
72
+ group_id: str
73
+ domain: str
74
+ domain_category: str
75
+ group_stance: str
76
+ citation_ids: List[str]
77
+ primary_citation_id: str
78
+
79
+
80
+ class ClaimGroup(TypedDict, total=False):
81
+ claim_id: str
82
+ claim_index: int
83
+ claim: str
84
+ stance_summary: str
85
+ citation_count: int
86
+ citations: List[Citation]
87
+ domain_groups: List[DomainGroup]
88
+ verdict: Verdict
89
+
90
+
91
+ class VerifyResponse(TypedDict, total=False):
92
+ """Returned by verify() and search()."""
93
+
94
+ claim_groups: List[ClaimGroup]
95
+ citations: List[Citation]
96
+ domain_groups: List[DomainGroup]
97
+ verdict: Verdict
98
+ totalResults: int
99
+ thread_id: str
100
+ operation_id: str
101
+ search_metadata: JSONObject
102
+ usage: Usage
103
+ credit_usage: CreditUsage
104
+
105
+
106
+ class ExtractUnit(TypedDict, total=False):
107
+ kind: str
108
+ index: int
109
+ text: str
110
+ provenance: JSONObject
111
+ elements: List[JSONObject]
112
+ geometry: JSONObject
113
+ extraction_method: str
114
+ reader: JSONObject
115
+
116
+
117
+ class ExtractResponse(TypedDict, total=False):
118
+ format: str
119
+ markdown: str
120
+ units: List[ExtractUnit]
121
+ state: str
122
+ code: Optional[str]
123
+ reason: Optional[str]
124
+ complete: bool
125
+ lost: List[JSONObject]
126
+ extraction_method: str
127
+ operation_id: str
128
+ usage: Usage
129
+ credit_usage: CreditUsage
130
+
131
+
132
+ class UploadedAsset(TypedDict, total=False):
133
+ asset_id: str
134
+ asset_url: str
135
+ source_version_id: str
136
+ filename: str
137
+ size: int
138
+
139
+
140
+ class UploadResponse(TypedDict, total=False):
141
+ successCode: int
142
+ message: str
143
+ data: UploadedAsset
144
+ operation_id: str
145
+ usage: Usage
146
+ credit_usage: CreditUsage
147
+
148
+
149
+ class CitationList(TypedDict, total=False):
150
+ statusCode: int
151
+ message: str
152
+ data: List[JSONObject]
153
+ pagination: JSONObject
154
+
155
+
156
+ class AskJob(TypedDict, total=False):
157
+ id: str
158
+ status: str
159
+ operation_id: str
160
+ billing_status: str
161
+ billing: JSONObject
162
+ result: JSONObject
163
+ usage: Usage
164
+
165
+
166
+ class BalanceCredits(TypedDict, total=False):
167
+ used: float
168
+ remaining: float
169
+ total: float
170
+
171
+
172
+ class Balance(TypedDict, total=False):
173
+ credits: BalanceCredits
174
+ allow_overage: bool
175
+ monthly_allocation: str
176
+ billing_period_start: str
177
+ billing_period_end: str
178
+
179
+
180
+ class StreamEvent(TypedDict):
181
+ event: str
182
+ data: Any