nonecap 0.8.7__tar.gz → 0.9.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: nonecap
3
- Version: 0.8.7
3
+ Version: 0.9.0
4
4
  Summary: Official Python client for NoneCap, the hCaptcha solver API.
5
5
  Project-URL: Homepage, https://nonecap.com/
6
6
  Project-URL: Documentation, https://nonecap.com/api-reference
@@ -172,7 +172,7 @@ except RateLimitError as err:
172
172
  time.sleep(err.retry_after or 1)
173
173
  ```
174
174
 
175
- The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
175
+ The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `RecognitionFailedError` (422, `recognize()` found no answer; nothing was charged), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
176
176
 
177
177
  `SolveFailedError` carries the full `solve`. `solve.error.code` is a `SolveErrorCode`, `solve.error.reason` a typed sub-reason or `None` (`proxy_rejected`, `sitekey_rate_limited`, …), and `solve.error.retryable` says whether resubmitting the same request unchanged can succeed; `err.retryable`, `err.reason` and `err.solve_code` are shortcuts to those fields. Failed solves are never charged.
178
178
 
@@ -241,6 +241,47 @@ if batch.failed:
241
241
 
242
242
  Reporting the same solve again corrects the earlier verdict, so retries and late fixes are safe. You can report any of your own solved solves within ~30 days of the solve; corrections to something you already reported are never cut off by that window. On `AsyncNoneCap` both methods are coroutines.
243
243
 
244
+ ## Recognizing images
245
+
246
+ When you run your own browser or extension and only need the answer to a challenge, send its images and instruction to `recognize()`. The answer comes back in the same response: no token, no polling.
247
+
248
+ ```python
249
+ rec = nc.recognize(
250
+ type="hcaptcha",
251
+ task="Please click each image containing a bus",
252
+ image_data=tiles, # base64 strings, data: URIs or raw bytes; or image_urls=[...] for hCaptcha image URLs
253
+ )
254
+ print(rec.data) # [True, False, False, True, ...], one per tile
255
+ ```
256
+
257
+ `type="hcaptcha"` takes 1 to 27 tiles and answers one boolean per tile. `type="hcaptcha_area_select"` takes exactly one image and answers the first point to click as `rec.data` (`{"x", "y", "w": 0, "h": 0}`, in percent of the image), with every point in `rec.points` for wordings that need several clicks. Pass `image_examples` when the challenge shows example images, and `host` (the site's bare domain) when you know it.
258
+
259
+ You can also send the challenge's tasklist as hCaptcha served it, which covers drag-and-drop too:
260
+
261
+ ```python
262
+ rec = nc.recognize(data={
263
+ "request_type": "image_drag_drop",
264
+ "requester_question": {"en": "Drag the piece to complete the image"},
265
+ "tasklist": [{
266
+ "task_key": "...",
267
+ "datapoint_uri": image_b64,
268
+ "entities": [{"entity_id": "...", "entity_uri": piece_b64, "coords": [10, 20], "size": [40, 30]}],
269
+ }],
270
+ })
271
+ ```
272
+
273
+ Here `rec.data` holds pages of 9 booleans for `image_label_binary`, one box per task (or `None`) plus `rec.points` per task for `image_label_area_select`, and per task a list of `{"entity_id", "x", "y", "w", "h"}` drop boxes for `image_drag_drop`. The field names are NopeCHA's recognition shapes, so a NopeCHA recognition integration ports over as is.
274
+
275
+ When no answer is found, or the challenge type is not supported, `recognize()` raises `RecognitionFailedError` and nothing is charged. A call that returns an answer is charged, whether or not the answer works on the challenge.
276
+
277
+ You can tell us how the challenge ended. It is optional, it helps us track recognition accuracy, and it does not refund the call:
278
+
279
+ ```python
280
+ nc.report_recognition_outcome(rec.id, "solved") # or "failed"
281
+ ```
282
+
283
+ The first report for an id sticks. On `AsyncNoneCap` both methods are coroutines.
284
+
244
285
  ## Lower-level API
245
286
 
246
287
  `solve()` is the convenient path. When you want control over submission and polling, the resource methods map one to one to the REST API:
@@ -141,7 +141,7 @@ except RateLimitError as err:
141
141
  time.sleep(err.retry_after or 1)
142
142
  ```
143
143
 
144
- The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
144
+ The subclasses are `AuthenticationError` (401), `PermissionDeniedError` (403), `InsufficientCreditsError` (402, with `KeyCreditLimitError` when one API key hit its own cap), `ValidationError` (422/400, with a `param` naming the bad field; `PayloadTooLargeError` for 413 and `UnsupportedMediaTypeError` for 415), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `ConcurrencyLimitError`, `SitekeyRateLimitedError`, `ProxyUnavailableError` (your own proxy is refusing connections) and `RateCappedError` (your account reached its submit rate cap on this sitekey, or your own-proxy sessions for it are at their limit) telling them apart; `retry_after` is the seconds the API asked you to wait), `RecognitionFailedError` (422, `recognize()` found no answer; nothing was charged), `APIError` (5xx, with `ServiceUnavailableError` for a maintenance pause), `APIConnectionError` and `APITimeoutError` (the request never landed), and `SolveTimeoutError` (your `solve()` budget ran out). Every error from a response carries `request_id`, the id to quote to support.
145
145
 
146
146
  `SolveFailedError` carries the full `solve`. `solve.error.code` is a `SolveErrorCode`, `solve.error.reason` a typed sub-reason or `None` (`proxy_rejected`, `sitekey_rate_limited`, …), and `solve.error.retryable` says whether resubmitting the same request unchanged can succeed; `err.retryable`, `err.reason` and `err.solve_code` are shortcuts to those fields. Failed solves are never charged.
147
147
 
@@ -210,6 +210,47 @@ if batch.failed:
210
210
 
211
211
  Reporting the same solve again corrects the earlier verdict, so retries and late fixes are safe. You can report any of your own solved solves within ~30 days of the solve; corrections to something you already reported are never cut off by that window. On `AsyncNoneCap` both methods are coroutines.
212
212
 
213
+ ## Recognizing images
214
+
215
+ When you run your own browser or extension and only need the answer to a challenge, send its images and instruction to `recognize()`. The answer comes back in the same response: no token, no polling.
216
+
217
+ ```python
218
+ rec = nc.recognize(
219
+ type="hcaptcha",
220
+ task="Please click each image containing a bus",
221
+ image_data=tiles, # base64 strings, data: URIs or raw bytes; or image_urls=[...] for hCaptcha image URLs
222
+ )
223
+ print(rec.data) # [True, False, False, True, ...], one per tile
224
+ ```
225
+
226
+ `type="hcaptcha"` takes 1 to 27 tiles and answers one boolean per tile. `type="hcaptcha_area_select"` takes exactly one image and answers the first point to click as `rec.data` (`{"x", "y", "w": 0, "h": 0}`, in percent of the image), with every point in `rec.points` for wordings that need several clicks. Pass `image_examples` when the challenge shows example images, and `host` (the site's bare domain) when you know it.
227
+
228
+ You can also send the challenge's tasklist as hCaptcha served it, which covers drag-and-drop too:
229
+
230
+ ```python
231
+ rec = nc.recognize(data={
232
+ "request_type": "image_drag_drop",
233
+ "requester_question": {"en": "Drag the piece to complete the image"},
234
+ "tasklist": [{
235
+ "task_key": "...",
236
+ "datapoint_uri": image_b64,
237
+ "entities": [{"entity_id": "...", "entity_uri": piece_b64, "coords": [10, 20], "size": [40, 30]}],
238
+ }],
239
+ })
240
+ ```
241
+
242
+ Here `rec.data` holds pages of 9 booleans for `image_label_binary`, one box per task (or `None`) plus `rec.points` per task for `image_label_area_select`, and per task a list of `{"entity_id", "x", "y", "w", "h"}` drop boxes for `image_drag_drop`. The field names are NopeCHA's recognition shapes, so a NopeCHA recognition integration ports over as is.
243
+
244
+ When no answer is found, or the challenge type is not supported, `recognize()` raises `RecognitionFailedError` and nothing is charged. A call that returns an answer is charged, whether or not the answer works on the challenge.
245
+
246
+ You can tell us how the challenge ended. It is optional, it helps us track recognition accuracy, and it does not refund the call:
247
+
248
+ ```python
249
+ nc.report_recognition_outcome(rec.id, "solved") # or "failed"
250
+ ```
251
+
252
+ The first report for an id sticks. On `AsyncNoneCap` both methods are coroutines.
253
+
213
254
  ## Lower-level API
214
255
 
215
256
  `solve()` is the convenient path. When you want control over submission and polling, the resource methods map one to one to the REST API:
@@ -30,6 +30,7 @@ from ._errors import (
30
30
  ProxyUnavailableError,
31
31
  RateCappedError,
32
32
  RateLimitError,
33
+ RecognitionFailedError,
33
34
  ServiceUnavailableError,
34
35
  SitekeyRateLimitedError,
35
36
  SolveFailedError,
@@ -48,6 +49,20 @@ from ._types import (
48
49
  FeedbackResult,
49
50
  FeedbackStatus,
50
51
  Proxy,
52
+ Recognition,
53
+ RecognitionOutcome,
54
+ RecognitionOutcomeResult,
55
+ RecognitionTasklistData,
56
+ RecognizeBox,
57
+ RecognizeDrop,
58
+ RecognizeEntity,
59
+ RecognizeImage,
60
+ RecognizePoint,
61
+ RecognizeQuestion,
62
+ RecognizeRequestType,
63
+ RecognizeTask,
64
+ RecognizeTasklist,
65
+ RecognizeType,
51
66
  Solve,
52
67
  SolveError,
53
68
  SolveErrorCode,
@@ -87,6 +102,20 @@ __all__ = [
87
102
  "FeedbackOutcome",
88
103
  "FeedbackStatus",
89
104
  "FEEDBACK_BATCH_MAX",
105
+ "Recognition",
106
+ "RecognitionOutcome",
107
+ "RecognitionOutcomeResult",
108
+ "RecognitionTasklistData",
109
+ "RecognizeBox",
110
+ "RecognizeDrop",
111
+ "RecognizeEntity",
112
+ "RecognizeImage",
113
+ "RecognizePoint",
114
+ "RecognizeQuestion",
115
+ "RecognizeRequestType",
116
+ "RecognizeTask",
117
+ "RecognizeTasklist",
118
+ "RecognizeType",
90
119
  # errors
91
120
  "NoneCapError",
92
121
  "AuthenticationError",
@@ -103,6 +132,7 @@ __all__ = [
103
132
  "SitekeyRateLimitedError",
104
133
  "ProxyUnavailableError",
105
134
  "RateCappedError",
135
+ "RecognitionFailedError",
106
136
  "APIError",
107
137
  "ServiceUnavailableError",
108
138
  "APIConnectionError",
@@ -8,6 +8,8 @@ Both clients expose the same surface:
8
8
  resource methods, mapping one to one to the REST API.
9
9
  - ``client.feedback.report / report_many`` — tell us whether the tokens we
10
10
  minted were accepted downstream.
11
+ - ``client.recognize(...)`` / ``client.report_recognition_outcome(...)`` — the
12
+ answer to one challenge's images, for callers that run their own browser.
11
13
  - ``client.me()`` — account info and credit balance.
12
14
 
13
15
  ``rqdata`` is optional for both types: many enterprise sitekeys issue none.
@@ -17,13 +19,16 @@ When the site passes one to its widget, send it.
17
19
  from __future__ import annotations
18
20
 
19
21
  import asyncio
22
+ import base64
20
23
  import time
21
24
  from collections.abc import AsyncIterator, Iterator, Sequence
22
25
  from datetime import datetime
23
26
  from typing import (
24
27
  Any,
28
+ Literal,
25
29
  Optional,
26
30
  Union,
31
+ overload,
27
32
  )
28
33
 
29
34
  import httpx
@@ -44,6 +49,15 @@ from ._types import (
44
49
  FeedbackOutcome,
45
50
  FeedbackReport,
46
51
  Proxy,
52
+ Recognition,
53
+ RecognitionOutcome,
54
+ RecognitionOutcomeResult,
55
+ RecognitionTasklistData,
56
+ RecognizeBox,
57
+ RecognizeImage,
58
+ RecognizePoint,
59
+ RecognizeTasklist,
60
+ RecognizeType,
47
61
  Solve,
48
62
  SolvePage,
49
63
  SolveStatus,
@@ -173,6 +187,51 @@ def _merged_batch(parts: list[FeedbackBatch]) -> FeedbackBatch:
173
187
  )
174
188
 
175
189
 
190
+ def _encode_image(image: RecognizeImage) -> str:
191
+ if isinstance(image, (bytes, bytearray, memoryview)):
192
+ return base64.b64encode(image).decode("ascii")
193
+ return image
194
+
195
+
196
+ def _build_recognize_body(
197
+ *,
198
+ type: Optional[RecognizeType],
199
+ task: Optional[str],
200
+ image_data: Optional[Sequence[RecognizeImage]],
201
+ image_urls: Optional[Sequence[str]],
202
+ image_examples: Optional[Sequence[RecognizeImage]],
203
+ data: Optional[RecognizeTasklist],
204
+ host: Optional[str],
205
+ ) -> dict[str, Any]:
206
+ for name, images in (
207
+ ("image_data", image_data),
208
+ ("image_urls", image_urls),
209
+ ("image_examples", image_examples),
210
+ ):
211
+ if isinstance(images, (str, bytes)):
212
+ raise TypeError(f"{name} must be a list of images, not a single one.")
213
+ body: dict[str, Any]
214
+ if data is not None:
215
+ if any(v is not None for v in (type, task, image_data, image_urls, image_examples)):
216
+ raise ValueError("Pass either data= (the full tasklist) or type=/task=/images.")
217
+ body = {"data": data}
218
+ else:
219
+ if type is None or task is None:
220
+ raise ValueError("recognize() needs type= and task=, or the tasklist as data=.")
221
+ body = {"type": type, "task": task}
222
+ if image_data is not None and image_urls is None:
223
+ body["image_data"] = [_encode_image(image) for image in image_data]
224
+ elif image_urls is not None and image_data is None:
225
+ body["image_urls"] = list(image_urls)
226
+ else:
227
+ raise ValueError("Pass exactly one of image_data or image_urls.")
228
+ if image_examples is not None:
229
+ body["image_examples"] = [_encode_image(image) for image in image_examples]
230
+ if host is not None:
231
+ body["host"] = host
232
+ return body
233
+
234
+
176
235
  def _process_response(response: httpx.Response) -> Any:
177
236
  """Parse a response, mapping non-2xx envelopes to typed errors.
178
237
 
@@ -594,6 +653,94 @@ class NoneCap(_BaseClient):
594
653
  )
595
654
  return self.solves._start_from_body(body).result(timeout)
596
655
 
656
+ @overload
657
+ def recognize(
658
+ self,
659
+ *,
660
+ type: Literal["hcaptcha"],
661
+ task: str,
662
+ image_data: Optional[Sequence[RecognizeImage]] = None,
663
+ image_urls: Optional[Sequence[str]] = None,
664
+ image_examples: Optional[Sequence[RecognizeImage]] = None,
665
+ host: Optional[str] = None,
666
+ ) -> Recognition[list[bool], None]: ...
667
+
668
+ @overload
669
+ def recognize(
670
+ self,
671
+ *,
672
+ type: Literal["hcaptcha_area_select"],
673
+ task: str,
674
+ image_data: Optional[Sequence[RecognizeImage]] = None,
675
+ image_urls: Optional[Sequence[str]] = None,
676
+ image_examples: Optional[Sequence[RecognizeImage]] = None,
677
+ host: Optional[str] = None,
678
+ ) -> Recognition[RecognizeBox, list[RecognizePoint]]: ...
679
+
680
+ @overload
681
+ def recognize(
682
+ self,
683
+ *,
684
+ data: RecognizeTasklist,
685
+ host: Optional[str] = None,
686
+ ) -> Recognition[RecognitionTasklistData, Optional[list[list[RecognizePoint]]]]: ...
687
+
688
+ def recognize(
689
+ self,
690
+ *,
691
+ type: Optional[RecognizeType] = None,
692
+ task: Optional[str] = None,
693
+ image_data: Optional[Sequence[RecognizeImage]] = None,
694
+ image_urls: Optional[Sequence[str]] = None,
695
+ image_examples: Optional[Sequence[RecognizeImage]] = None,
696
+ data: Optional[RecognizeTasklist] = None,
697
+ host: Optional[str] = None,
698
+ ) -> Recognition[Any, Any]:
699
+ """Recognize one challenge's images and return the answer in the same response.
700
+
701
+ For callers that run their own browser or extension and want only the answer:
702
+ no token, no polling. Send either the simple form (``type``, ``task`` and exactly
703
+ one of ``image_data`` / ``image_urls``) or the challenge's full tasklist as
704
+ ``data``; :class:`Recognition` says which answer shape comes back. ``host`` is the
705
+ site's bare domain, when you know it.
706
+
707
+ Raises :class:`RecognitionFailedError` when no answer was found or the challenge
708
+ type is not supported; nothing is charged then. An answered call is charged in
709
+ full, whether or not the answer works on the challenge.
710
+
711
+ >>> rec = nc.recognize(
712
+ ... type="hcaptcha", task="Please click each image containing a bus",
713
+ ... image_data=tiles,
714
+ ... )
715
+ >>> rec.data
716
+ [True, False, False, True, False, False, False, True, False]
717
+ """
718
+ body = _build_recognize_body(
719
+ type=type,
720
+ task=task,
721
+ image_data=image_data,
722
+ image_urls=image_urls,
723
+ image_examples=image_examples,
724
+ data=data,
725
+ host=host,
726
+ )
727
+ return Recognition._from_dict(self._request("POST", "/v1/recognize", json=body))
728
+
729
+ def report_recognition_outcome(
730
+ self, recognition_id: str, result: RecognitionOutcome
731
+ ) -> RecognitionOutcomeResult:
732
+ """Report whether a recognition's answer worked on the challenge.
733
+
734
+ Optional, and it only records the result: it never refunds the call
735
+ (``refunded_credits`` is always 0). The first report for an id sticks; a repeat
736
+ returns the recorded outcome. Raises :class:`NotFoundError` for an id that is not
737
+ one of your recognitions.
738
+ """
739
+ payload = self._request(
740
+ "POST", "/v1/recognize/outcome", json={"id": recognition_id, "result": result}
741
+ )
742
+ return RecognitionOutcomeResult._from_dict(payload)
743
+
597
744
  def me(self) -> Account:
598
745
  """Fetch your account, including the current credit balance."""
599
746
  return Account._from_dict(self._request("GET", "/v1/me"))
@@ -1000,6 +1147,87 @@ class AsyncNoneCap(_BaseClient):
1000
1147
  handle = await self.solves._start_from_body(body)
1001
1148
  return await handle.result(timeout)
1002
1149
 
1150
+ @overload
1151
+ async def recognize(
1152
+ self,
1153
+ *,
1154
+ type: Literal["hcaptcha"],
1155
+ task: str,
1156
+ image_data: Optional[Sequence[RecognizeImage]] = None,
1157
+ image_urls: Optional[Sequence[str]] = None,
1158
+ image_examples: Optional[Sequence[RecognizeImage]] = None,
1159
+ host: Optional[str] = None,
1160
+ ) -> Recognition[list[bool], None]: ...
1161
+
1162
+ @overload
1163
+ async def recognize(
1164
+ self,
1165
+ *,
1166
+ type: Literal["hcaptcha_area_select"],
1167
+ task: str,
1168
+ image_data: Optional[Sequence[RecognizeImage]] = None,
1169
+ image_urls: Optional[Sequence[str]] = None,
1170
+ image_examples: Optional[Sequence[RecognizeImage]] = None,
1171
+ host: Optional[str] = None,
1172
+ ) -> Recognition[RecognizeBox, list[RecognizePoint]]: ...
1173
+
1174
+ @overload
1175
+ async def recognize(
1176
+ self,
1177
+ *,
1178
+ data: RecognizeTasklist,
1179
+ host: Optional[str] = None,
1180
+ ) -> Recognition[RecognitionTasklistData, Optional[list[list[RecognizePoint]]]]: ...
1181
+
1182
+ async def recognize(
1183
+ self,
1184
+ *,
1185
+ type: Optional[RecognizeType] = None,
1186
+ task: Optional[str] = None,
1187
+ image_data: Optional[Sequence[RecognizeImage]] = None,
1188
+ image_urls: Optional[Sequence[str]] = None,
1189
+ image_examples: Optional[Sequence[RecognizeImage]] = None,
1190
+ data: Optional[RecognizeTasklist] = None,
1191
+ host: Optional[str] = None,
1192
+ ) -> Recognition[Any, Any]:
1193
+ """Recognize one challenge's images and return the answer in the same response.
1194
+
1195
+ For callers that run their own browser or extension and want only the answer:
1196
+ no token, no polling. Send either the simple form (``type``, ``task`` and exactly
1197
+ one of ``image_data`` / ``image_urls``) or the challenge's full tasklist as
1198
+ ``data``; :class:`Recognition` says which answer shape comes back. ``host`` is the
1199
+ site's bare domain, when you know it.
1200
+
1201
+ Raises :class:`RecognitionFailedError` when no answer was found or the challenge
1202
+ type is not supported; nothing is charged then. An answered call is charged in
1203
+ full, whether or not the answer works on the challenge.
1204
+ """
1205
+ body = _build_recognize_body(
1206
+ type=type,
1207
+ task=task,
1208
+ image_data=image_data,
1209
+ image_urls=image_urls,
1210
+ image_examples=image_examples,
1211
+ data=data,
1212
+ host=host,
1213
+ )
1214
+ return Recognition._from_dict(await self._request("POST", "/v1/recognize", json=body))
1215
+
1216
+ async def report_recognition_outcome(
1217
+ self, recognition_id: str, result: RecognitionOutcome
1218
+ ) -> RecognitionOutcomeResult:
1219
+ """Report whether a recognition's answer worked on the challenge.
1220
+
1221
+ Optional, and it only records the result: it never refunds the call
1222
+ (``refunded_credits`` is always 0). The first report for an id sticks; a repeat
1223
+ returns the recorded outcome. Raises :class:`NotFoundError` for an id that is not
1224
+ one of your recognitions.
1225
+ """
1226
+ payload = await self._request(
1227
+ "POST", "/v1/recognize/outcome", json={"id": recognition_id, "result": result}
1228
+ )
1229
+ return RecognitionOutcomeResult._from_dict(payload)
1230
+
1003
1231
  async def me(self) -> Account:
1004
1232
  """Fetch your account, including the current credit balance."""
1005
1233
  return Account._from_dict(await self._request("GET", "/v1/me"))
@@ -97,6 +97,11 @@ class RateCappedError(RateLimitError):
97
97
  Nothing was charged; wait ``retry_after`` seconds."""
98
98
 
99
99
 
100
+ class RecognitionFailedError(NoneCapError):
101
+ """422 — ``recognize()`` found no answer for these images, or the challenge type is not
102
+ supported. Nothing was charged; load a fresh challenge and retry."""
103
+
104
+
100
105
  class APIError(NoneCapError):
101
106
  """5xx, or a response that was not the expected shape. ``request_id`` is the id to quote."""
102
107
 
@@ -202,6 +207,8 @@ def error_from_response(
202
207
  cls = RateCappedError
203
208
  elif code in ("rate_limited", "ext_daily_limit"):
204
209
  cls = RateLimitError
210
+ elif code == "recognition_failed":
211
+ cls = RecognitionFailedError
205
212
  elif code == "maintenance":
206
213
  cls = ServiceUnavailableError
207
214
  else:
@@ -7,9 +7,10 @@ ignore unknown ones, so new server-side fields never break old clients.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ from collections.abc import Sequence
10
11
  from dataclasses import dataclass, field
11
12
  from datetime import datetime
12
- from typing import Any, Literal, Optional, TypedDict, Union
13
+ from typing import Any, Generic, Literal, Optional, TypedDict, TypeVar, Union
13
14
 
14
15
  SolveType = Literal["hcaptcha", "hcaptcha_enterprise"]
15
16
  """Captcha type a solve targets."""
@@ -326,6 +327,151 @@ class FeedbackBatch:
326
327
  )
327
328
 
328
329
 
330
+ RecognizeType = Literal["hcaptcha", "hcaptcha_area_select"]
331
+ """The simple recognition form: ``hcaptcha`` is a grid of 1-27 tiles answered with one
332
+ boolean each, ``hcaptcha_area_select`` one image answered with the point(s) to click."""
333
+
334
+ RecognizeImage = Union[str, bytes]
335
+ """An image for ``recognize``: base64 (bare or a ``data:`` URI) or raw bytes, which the
336
+ client base64-encodes. PNG, JPEG, WebP or GIF, up to 1.5 MiB decoded."""
337
+
338
+ RecognizeRequestType = Literal[
339
+ "image_label_binary", "image_label_area_select", "image_drag_drop"
340
+ ]
341
+ """The ``request_type`` of a full tasklist, as hCaptcha serves it."""
342
+
343
+ RecognitionOutcome = Literal["solved", "failed"]
344
+ """Whether a recognition's answer worked on the challenge."""
345
+
346
+
347
+ class RecognizeQuestion(TypedDict):
348
+ en: str
349
+
350
+
351
+ class _RecognizeEntityRequired(TypedDict):
352
+ entity_id: str
353
+ coords: Sequence[float]
354
+ size: Sequence[float]
355
+
356
+
357
+ class RecognizeEntity(_RecognizeEntityRequired, total=False):
358
+ """A draggable piece of an ``image_drag_drop`` task. ``coords`` and ``size`` are
359
+ ``[x, y]`` and ``[w, h]`` in image pixels."""
360
+
361
+ entity_uri: str
362
+ """The piece's image, as base64 or an hCaptcha image URL."""
363
+
364
+
365
+ class _RecognizeTaskRequired(TypedDict):
366
+ task_key: str
367
+ datapoint_uri: str
368
+ """The task's image, as base64 (bare or a ``data:`` URI) or an hCaptcha image URL."""
369
+
370
+
371
+ class RecognizeTask(_RecognizeTaskRequired, total=False):
372
+ """One task of a :class:`RecognizeTasklist`."""
373
+
374
+ entities: list[RecognizeEntity]
375
+
376
+
377
+ class _RecognizeTasklistRequired(TypedDict):
378
+ request_type: RecognizeRequestType
379
+ requester_question: RecognizeQuestion
380
+ tasklist: list[RecognizeTask]
381
+
382
+
383
+ class RecognizeTasklist(_RecognizeTasklistRequired, total=False):
384
+ """The full recognition form: the challenge's tasklist as hCaptcha served it
385
+ (NopeCHA's v1 recognition body), passed as ``recognize(data=...)``."""
386
+
387
+ requester_question_example: list[str]
388
+ request_config: dict[str, Any]
389
+
390
+
391
+ class RecognizePoint(TypedDict):
392
+ """A point, in percent of the image's width and height."""
393
+
394
+ x: float
395
+ y: float
396
+
397
+
398
+ class RecognizeBox(TypedDict):
399
+ """A box (top-left and size), in percent of the image. Area-select answers are a
400
+ point, so ``w`` and ``h`` are 0."""
401
+
402
+ x: float
403
+ y: float
404
+ w: float
405
+ h: float
406
+
407
+
408
+ class RecognizeDrop(RecognizeBox):
409
+ """Where to drop one entity: a box centred on the drop point, sized by the
410
+ entity's ``size``."""
411
+
412
+ entity_id: str
413
+
414
+
415
+ RecognitionTasklistData = Union[
416
+ list[list[bool]], list[Optional[RecognizeBox]], list[list[RecognizeDrop]]
417
+ ]
418
+ """``data`` for the full form, by ``request_type``: ``image_label_binary`` pages of 9
419
+ booleans, ``image_label_area_select`` one box per task (None when it has no point),
420
+ ``image_drag_drop`` per task where to drop each entity."""
421
+
422
+ DataT = TypeVar("DataT")
423
+ PointsT = TypeVar("PointsT")
424
+
425
+
426
+ @dataclass(frozen=True)
427
+ class Recognition(Generic[DataT, PointsT]):
428
+ """The answer to ``client.recognize``. ``data`` takes the shape of the request:
429
+
430
+ - ``type="hcaptcha"``: ``list[bool]``, one per tile in request order; ``points``
431
+ is None.
432
+ - ``type="hcaptcha_area_select"``: the first point to click as a
433
+ :class:`RecognizeBox` (``w`` and ``h`` are 0); ``points`` lists every point,
434
+ for wordings that take several clicks.
435
+ - ``data=`` (full form): a :data:`RecognitionTasklistData`; ``points`` is one
436
+ list of points per task for ``image_label_area_select``, otherwise None.
437
+ """
438
+
439
+ id: str
440
+ """The recognition's id (``extsess_…``), for ``report_recognition_outcome``."""
441
+ data: DataT
442
+ points: PointsT
443
+ credits_charged: int
444
+
445
+ @classmethod
446
+ def _from_dict(cls, payload: dict[str, Any]) -> Recognition[Any, Any]:
447
+ points: Any = payload.get("points")
448
+ return cls(
449
+ id=payload["id"],
450
+ data=payload["data"],
451
+ points=points,
452
+ credits_charged=int(payload.get("credits_charged", 0)),
453
+ )
454
+
455
+
456
+ @dataclass(frozen=True)
457
+ class RecognitionOutcomeResult:
458
+ """The result of ``client.report_recognition_outcome``."""
459
+
460
+ id: str
461
+ result: RecognitionOutcome
462
+ """The recorded outcome. The first report sticks, so a repeat returns the first."""
463
+ refunded_credits: int
464
+ """Always 0: reporting an outcome never refunds the call."""
465
+
466
+ @classmethod
467
+ def _from_dict(cls, payload: dict[str, Any]) -> RecognitionOutcomeResult:
468
+ return cls(
469
+ id=payload["id"],
470
+ result=payload["result"],
471
+ refunded_credits=int(payload.get("refunded_credits", 0)),
472
+ )
473
+
474
+
329
475
  @dataclass(frozen=True)
330
476
  class Account:
331
477
  """Your account, including the current credit balance."""
@@ -0,0 +1 @@
1
+ __version__ = "0.9.0"
@@ -0,0 +1,278 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ from typing import Any
5
+
6
+ import httpx
7
+ import pytest
8
+
9
+ from nonecap import (
10
+ AsyncNoneCap,
11
+ ConcurrencyLimitError,
12
+ InsufficientCreditsError,
13
+ NoneCap,
14
+ NotFoundError,
15
+ PayloadTooLargeError,
16
+ RecognitionFailedError,
17
+ RecognizeTasklist,
18
+ ValidationError,
19
+ )
20
+
21
+ from .conftest import Script, error_payload
22
+
23
+ PNG = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
24
+ PNG_B64 = base64.b64encode(PNG).decode("ascii")
25
+ SESSION_ID = "extsess_01JABCDEFGHJKMNPQRSTVWXYZ0"
26
+
27
+
28
+ def client_for(script: Script) -> NoneCap:
29
+ return NoneCap(api_key="nc_test", http_client=httpx.Client(transport=script.transport))
30
+
31
+
32
+ def async_client_for(script: Script) -> AsyncNoneCap:
33
+ return AsyncNoneCap(
34
+ api_key="nc_test", http_client=httpx.AsyncClient(transport=script.transport)
35
+ )
36
+
37
+
38
+ def recognition_payload(**overrides: Any) -> dict[str, Any]:
39
+ base: dict[str, Any] = {
40
+ "id": SESSION_ID,
41
+ "data": [True, False, True],
42
+ "credits_charged": 5,
43
+ }
44
+ base.update(overrides)
45
+ return base
46
+
47
+
48
+ def drag_tasklist() -> RecognizeTasklist:
49
+ return {
50
+ "request_type": "image_drag_drop",
51
+ "requester_question": {"en": "Drag the piece to complete the image"},
52
+ "tasklist": [
53
+ {
54
+ "task_key": "k1",
55
+ "datapoint_uri": PNG_B64,
56
+ "entities": [
57
+ {
58
+ "entity_id": "e1",
59
+ "entity_uri": PNG_B64,
60
+ "coords": [10, 20],
61
+ "size": [40, 30],
62
+ }
63
+ ],
64
+ }
65
+ ],
66
+ }
67
+
68
+
69
+ class TestRecognize:
70
+ def test_posts_the_simple_form_with_bearer_auth(self) -> None:
71
+ script = Script((200, recognition_payload()))
72
+ rec = client_for(script).recognize(
73
+ type="hcaptcha",
74
+ task="Please click each image containing a bus",
75
+ image_data=[PNG_B64, PNG_B64, PNG_B64],
76
+ host="example.com",
77
+ )
78
+
79
+ request = script.requests[0]
80
+ assert request.method == "POST"
81
+ assert request.url.path == "/v1/recognize"
82
+ assert request.headers["Authorization"] == "Bearer nc_test"
83
+ assert script.body_of(0) == {
84
+ "type": "hcaptcha",
85
+ "task": "Please click each image containing a bus",
86
+ "image_data": [PNG_B64, PNG_B64, PNG_B64],
87
+ "host": "example.com",
88
+ }
89
+ assert rec.id == SESSION_ID
90
+ assert rec.data == [True, False, True]
91
+ assert rec.points is None
92
+ assert rec.credits_charged == 5
93
+
94
+ def test_base64_encodes_raw_image_bytes(self) -> None:
95
+ script = Script((200, recognition_payload()))
96
+ client_for(script).recognize(
97
+ type="hcaptcha",
98
+ task="t",
99
+ image_data=[PNG, "data:image/png;base64," + PNG_B64],
100
+ image_examples=[PNG],
101
+ )
102
+ body = script.body_of(0)
103
+ assert body["image_data"] == [PNG_B64, "data:image/png;base64," + PNG_B64]
104
+ assert body["image_examples"] == [PNG_B64]
105
+
106
+ def test_area_select_returns_the_box_and_every_point(self) -> None:
107
+ script = Script(
108
+ (
109
+ 200,
110
+ recognition_payload(
111
+ data={"x": 12.5, "y": 40.0, "w": 0, "h": 0},
112
+ points=[{"x": 12.5, "y": 40.0}, {"x": 70.0, "y": 22.25}],
113
+ ),
114
+ )
115
+ )
116
+ rec = client_for(script).recognize(
117
+ type="hcaptcha_area_select",
118
+ task="Please click on the head of the animal",
119
+ image_urls=["https://imgs.hcaptcha.com/abc"],
120
+ )
121
+ assert script.body_of(0) == {
122
+ "type": "hcaptcha_area_select",
123
+ "task": "Please click on the head of the animal",
124
+ "image_urls": ["https://imgs.hcaptcha.com/abc"],
125
+ }
126
+ assert rec.data["x"] == 12.5
127
+ assert [p["x"] for p in rec.points] == [12.5, 70.0]
128
+
129
+ def test_sends_the_full_tasklist_under_data(self) -> None:
130
+ placements = [[{"entity_id": "e1", "x": 30.0, "y": 50.0, "w": 8.33, "h": 9.38}]]
131
+ script = Script((200, recognition_payload(data=placements)))
132
+ tasklist = drag_tasklist()
133
+ rec = client_for(script).recognize(data=tasklist)
134
+
135
+ assert script.body_of(0) == {"data": tasklist}
136
+ assert rec.data == placements
137
+ assert rec.points is None
138
+
139
+ def test_refuses_both_forms_at_once(self) -> None:
140
+ script = Script((200, recognition_payload()))
141
+ with pytest.raises(ValueError):
142
+ client_for(script).recognize(data=drag_tasklist(), type="hcaptcha")
143
+ assert script.requests == []
144
+
145
+ @pytest.mark.parametrize(
146
+ "images",
147
+ [
148
+ {},
149
+ {"image_data": [PNG_B64], "image_urls": ["https://imgs.hcaptcha.com/abc"]},
150
+ ],
151
+ )
152
+ def test_refuses_anything_but_exactly_one_image_source(
153
+ self, images: dict[str, Any]
154
+ ) -> None:
155
+ script = Script((200, recognition_payload()))
156
+ with pytest.raises(ValueError):
157
+ client_for(script).recognize(type="hcaptcha", task="t", **images)
158
+ assert script.requests == []
159
+
160
+ def test_refuses_a_single_image_passed_as_the_list(self) -> None:
161
+ script = Script((200, recognition_payload()))
162
+ with pytest.raises(TypeError):
163
+ client_for(script).recognize(
164
+ type="hcaptcha_area_select",
165
+ task="t",
166
+ image_urls="https://imgs.hcaptcha.com/abc",
167
+ )
168
+ assert script.requests == []
169
+
170
+ def test_raises_recognition_failed_when_no_answer_came_back(self) -> None:
171
+ script = Script(
172
+ (
173
+ 422,
174
+ error_payload(
175
+ "recognition_failed", "No answer was found. Nothing was charged."
176
+ ),
177
+ )
178
+ )
179
+ with pytest.raises(RecognitionFailedError) as excinfo:
180
+ client_for(script).recognize(type="hcaptcha", task="t", image_data=[PNG_B64])
181
+ assert excinfo.value.status == 422
182
+ assert excinfo.value.code == "recognition_failed"
183
+
184
+ @pytest.mark.parametrize(
185
+ ("status", "code", "error"),
186
+ [
187
+ (422, "validation_error", ValidationError),
188
+ (413, "payload_too_large", PayloadTooLargeError),
189
+ (402, "insufficient_credits", InsufficientCreditsError),
190
+ ],
191
+ )
192
+ def test_maps_request_errors(self, status: int, code: str, error: type[Exception]) -> None:
193
+ script = Script((status, error_payload(code, param="image_data[0]")))
194
+ with pytest.raises(error):
195
+ client_for(script).recognize(type="hcaptcha", task="t", image_data=[PNG_B64])
196
+
197
+ def test_concurrency_limit_carries_retry_after(self) -> None:
198
+ script = Script(
199
+ lambda request: httpx.Response(
200
+ 429,
201
+ json=error_payload("concurrency_limit_exceeded", "too many in flight"),
202
+ headers={"Retry-After": "1"},
203
+ )
204
+ )
205
+ with pytest.raises(ConcurrencyLimitError) as excinfo:
206
+ client_for(script).recognize(type="hcaptcha", task="t", image_data=[PNG_B64])
207
+ assert excinfo.value.retry_after == 1
208
+
209
+
210
+ class TestReportRecognitionOutcome:
211
+ def test_posts_the_outcome(self) -> None:
212
+ script = Script((200, {"id": SESSION_ID, "result": "failed", "refunded_credits": 0}))
213
+ result = client_for(script).report_recognition_outcome(SESSION_ID, "failed")
214
+
215
+ assert script.requests[0].method == "POST"
216
+ assert script.requests[0].url.path == "/v1/recognize/outcome"
217
+ assert script.body_of(0) == {"id": SESSION_ID, "result": "failed"}
218
+ assert result.id == SESSION_ID
219
+ assert result.result == "failed"
220
+ assert result.refunded_credits == 0
221
+
222
+ def test_raises_not_found_for_an_unknown_id(self) -> None:
223
+ script = Script((404, error_payload("not_found")))
224
+ with pytest.raises(NotFoundError):
225
+ client_for(script).report_recognition_outcome(SESSION_ID, "solved")
226
+
227
+ def test_a_repeat_returns_the_first_report(self) -> None:
228
+ script = Script((200, {"id": SESSION_ID, "result": "solved", "refunded_credits": 0}))
229
+ result = client_for(script).report_recognition_outcome(SESSION_ID, "failed")
230
+ assert result.result == "solved"
231
+
232
+
233
+ class TestAsyncRecognize:
234
+ async def test_recognize(self) -> None:
235
+ script = Script((200, recognition_payload()))
236
+ async with async_client_for(script) as nc:
237
+ rec = await nc.recognize(type="hcaptcha", task="t", image_data=[PNG])
238
+ assert script.requests[0].url.path == "/v1/recognize"
239
+ assert script.body_of(0) == {"type": "hcaptcha", "task": "t", "image_data": [PNG_B64]}
240
+ assert rec.data == [True, False, True]
241
+
242
+ async def test_recognize_full_tasklist_area_select(self) -> None:
243
+ tasklist: RecognizeTasklist = {
244
+ "request_type": "image_label_area_select",
245
+ "requester_question": {"en": "Please click on the head of the animal"},
246
+ "tasklist": [
247
+ {"task_key": "k1", "datapoint_uri": PNG_B64},
248
+ {"task_key": "k2", "datapoint_uri": PNG_B64},
249
+ ],
250
+ }
251
+ script = Script(
252
+ (
253
+ 200,
254
+ recognition_payload(
255
+ data=[{"x": 10.0, "y": 20.0, "w": 0, "h": 0}, None],
256
+ points=[[{"x": 10.0, "y": 20.0}], []],
257
+ ),
258
+ )
259
+ )
260
+ async with async_client_for(script) as nc:
261
+ rec = await nc.recognize(data=tasklist, host="example.com")
262
+ assert script.body_of(0) == {"data": tasklist, "host": "example.com"}
263
+ assert rec.data[1] is None
264
+ assert rec.points == [[{"x": 10.0, "y": 20.0}], []]
265
+
266
+ async def test_recognize_failed(self) -> None:
267
+ script = Script((422, error_payload("recognition_failed")))
268
+ async with async_client_for(script) as nc:
269
+ with pytest.raises(RecognitionFailedError):
270
+ await nc.recognize(type="hcaptcha", task="t", image_data=[PNG_B64])
271
+
272
+ async def test_report_recognition_outcome(self) -> None:
273
+ script = Script((200, {"id": SESSION_ID, "result": "solved", "refunded_credits": 0}))
274
+ async with async_client_for(script) as nc:
275
+ result = await nc.report_recognition_outcome(SESSION_ID, "solved")
276
+ assert script.requests[0].url.path == "/v1/recognize/outcome"
277
+ assert script.body_of(0) == {"id": SESSION_ID, "result": "solved"}
278
+ assert result.refunded_credits == 0
@@ -18,6 +18,12 @@ from nonecap import (
18
18
  FeedbackBatch,
19
19
  FeedbackReport,
20
20
  NoneCap,
21
+ Recognition,
22
+ RecognitionOutcomeResult,
23
+ RecognitionTasklistData,
24
+ RecognizeBox,
25
+ RecognizePoint,
26
+ RecognizeTasklist,
21
27
  Solve,
22
28
  SolveErrorReason,
23
29
  SolveHandle,
@@ -78,6 +84,52 @@ async def feedback_cases_async() -> None:
78
84
  )
79
85
 
80
86
 
87
+ def recognize_cases() -> None:
88
+ grid: Recognition[list[bool], None] = nc.recognize(
89
+ type="hcaptcha", task="t", image_data=["b64", b"raw"]
90
+ )
91
+ _tiles: list[bool] = grid.data
92
+ area: Recognition[RecognizeBox, list[RecognizePoint]] = nc.recognize(
93
+ type="hcaptcha_area_select", task="t", image_urls=["https://imgs.hcaptcha.com/x"]
94
+ )
95
+ _x: float = area.data["x"]
96
+ _first: RecognizePoint = area.points[0]
97
+ tasklist: RecognizeTasklist = {
98
+ "request_type": "image_drag_drop",
99
+ "requester_question": {"en": "t"},
100
+ "tasklist": [
101
+ {
102
+ "task_key": "k",
103
+ "datapoint_uri": "b64",
104
+ "entities": [{"entity_id": "e", "coords": [1, 2], "size": [3.5, 4]}],
105
+ }
106
+ ],
107
+ }
108
+ full: Recognition[RecognitionTasklistData, Optional[list[list[RecognizePoint]]]] = (
109
+ nc.recognize(data=tasklist, host="example.com")
110
+ )
111
+ _id: str = full.id
112
+ _o: RecognitionOutcomeResult = nc.report_recognition_outcome(full.id, "failed")
113
+ # An unknown recognition type must not type-check.
114
+ nc.recognize(type="hcaptcha_multiple_choice", task="t", image_data=["b64"]) # type: ignore[call-overload]
115
+ # The simple form and the tasklist do not mix.
116
+ nc.recognize(data=tasklist, type="hcaptcha", task="t") # type: ignore[call-overload]
117
+ # An outcome other than solved/failed must not type-check.
118
+ nc.report_recognition_outcome("extsess_1", "accepted") # type: ignore[arg-type]
119
+ # A tasklist with an unknown request_type must not type-check.
120
+ _bad: RecognizeTasklist = {
121
+ "request_type": "image_label_multiple_choice", # type: ignore[typeddict-item]
122
+ "requester_question": {"en": "t"},
123
+ "tasklist": [],
124
+ }
125
+
126
+
127
+ async def recognize_cases_async() -> None:
128
+ grid = await anc.recognize(type="hcaptcha", task="t", image_data=[b"raw"])
129
+ _tiles: list[bool] = grid.data
130
+ _o: RecognitionOutcomeResult = await anc.report_recognition_outcome(grid.id, "solved")
131
+
132
+
81
133
  def negative_cases() -> None:
82
134
  # A non-string rqdata must not type-check.
83
135
  nc.solve(type="hcaptcha_enterprise", sitekey="s", url="u", rqdata=1) # type: ignore[arg-type]
@@ -1 +0,0 @@
1
- __version__ = "0.8.7"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes