diff --git a/README.md b/README.md index 3c61896..d9933d5 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,7 @@ on the target page. | Image to Text | ✅ | - | | Yandex SmartCaptcha | ✅ | ✅ | | Yandex SmartCaptcha Image | ✅ | - | +| Yandex SmartCaptcha Kaleidoscope | ✅ | - | | Coordinates (click captcha) | ✅ | - | | Tencent | ✅ | ✅ | @@ -213,8 +214,8 @@ solution -- wraps `create_task()` + `get_task_result()` so you don't poll by han | `language_pool` | `Optional[str]` | Worker pool selector, `"en"` or `"ru"`. | | `timeout` | `Optional[int]` | Overrides the client's default timeout for this call only, in seconds. Useful for captcha types that reliably take longer (e.g. classic reCAPTCHA v2, GeeTest, reCAPTCHA v3 with a high `minScore`). | -Returns the `solution` dict once `status` is `"ready"` -- its shape depends on -the task type (see [Captcha Types](#captcha-types)). +Returns the `solution` once `status` is `"ready"`. Most task types return a dict; +Yandex SmartCaptcha Kaleidoscope returns a string. Raises `ValidationError` before any request if `task` is not a task object or a required task parameter is missing or empty. Otherwise raises `ApiError`, `CaptchaTimeoutError`, or `NetworkError`. @@ -231,7 +232,7 @@ Raises `ValidationError` before any request if `task` is invalid (same rules as Fetches the current status of a task created with `create_task()`. Always returns a dict with a `status` key (`"processing"` or `"ready"`); when -`"ready"`, also has a `solution` dict. This is a single poll, not a wait -- +`"ready"`, also has a `solution` value. This is a single poll, not a wait -- call it repeatedly (as `solve()` does) until `status` is `"ready"`. Raises `ApiError`, `CaptchaTimeoutError`, or `NetworkError`. @@ -510,7 +511,8 @@ With proxy, use `GeeTestTask` (same proxy fields as reCAPTCHA v2). [API method description.](https://captcha-solver.com/en/docs/captcha-types#yandex-smartcaptcha) Use this method to solve the token-based Yandex SmartCaptcha and obtain a token -for the widget on the target page. Use the dedicated image method for image challenges. +for the widget on the target page. Use the dedicated image methods for visual +SmartCaptcha and Kaleidoscope challenges. `YandexSmartCaptchaTaskProxyless` / `YandexSmartCaptchaTask` -- token-based challenge. @@ -573,6 +575,40 @@ result = CaptchaClient("your_api_key").solve(task) print(result["coordinates"]) ``` +#### Kaleidoscope puzzle + +Use `YandexSmartCaptchaKaleidoscopeTask` for the image-based Kaleidoscope puzzle. +Encode the captcha image as base64 and pass the puzzle steps as a JSON array string. +The SDK sends API v2 type `PazlCaptchaTask`. + +| Parameter | Required | Description | +|---|---|---| +| `image` | yes | Main captcha image, base64-encoded. | +| `task` | yes | Puzzle steps serialized as a JSON array string, for example `"[15,24,4,13,10]"`. | + +**Response:** a string containing the number of slider-arrow clicks required to +solve the captcha. + +```python +import base64 +from captcha_solver_api import CaptchaClient +from captcha_solver_api.tasks import YandexSmartCaptchaKaleidoscopeTask + +with open("examples/assets/yandex-smartcaptcha-kaleidoscope.jpg", "rb") as f: + image = base64.b64encode(f.read()).decode("utf-8") + +task = YandexSmartCaptchaKaleidoscopeTask( + image=image, + task="[15,24,4,13,10]", +) +clicks = CaptchaClient("your_api_key").solve(task) +print(clicks) +``` + +Runnable examples: +[sync](examples/sync/yandex_smartcaptcha_kaleidoscope.py) and +[async](examples/async/yandex_smartcaptcha_kaleidoscope.py). + ### Coordinates (click captcha) [API method description.](https://captcha-solver.com/en/docs/captcha-types#coordinates) @@ -807,6 +843,7 @@ python examples/sync/balance.py python examples/sync/image_to_text.py python examples/sync/coordinates.py python examples/sync/yandex_smartcaptcha_image.py +python examples/sync/yandex_smartcaptcha_kaleidoscope.py ``` Live checks with real parameters have exercised all supported task types. diff --git a/captcha_solver_api/async_client.py b/captcha_solver_api/async_client.py index 45454cd..921d1ea 100644 --- a/captcha_solver_api/async_client.py +++ b/captcha_solver_api/async_client.py @@ -209,9 +209,8 @@ async def get_task_result(self, task_id: int) -> Dict[str, Any]: Returns: The raw API response with `status` (`"processing"` or `"ready"`). - Ready responses also contain a `solution` dict, e.g. - `{"gRecaptchaResponse": "..."}` for reCAPTCHA or `{"text": "..."}` - for `ImageToTextTask`. + Ready responses also contain a `solution` value whose shape depends + on the task type. Raises: ApiError: The API reports an error for the task. @@ -263,7 +262,7 @@ async def solve( task: Any, language_pool: Optional[str] = None, timeout: Optional[int] = None, - ) -> Dict[str, Any]: + ) -> Dict[str, Any] | str: """Submit a task and asynchronously poll until its solution is ready. This is the main entry point for the async client. It combines @@ -283,9 +282,8 @@ async def solve( not a strict deadline for the entire call. Returns: - The `solution` dict once `status` is `"ready"`. Its shape depends on - the task type -- see the per-type docstrings in `captcha_solver_api.tasks` - or the README's method reference. + The `solution` once `status` is `"ready"`. Most task types return a + dict; `YandexSmartCaptchaKaleidoscopeTask` returns a string. Raises: ValidationError: `task` is not a task object, or a required task @@ -334,9 +332,9 @@ async def solve( if result.get("status") == "ready": solution = result["solution"] - if not isinstance(solution, dict): + if not isinstance(solution, (dict, str)) or solution == "": raise NetworkError( - "API returned a ready task without a solution object", + "API returned a ready task without a valid solution", task_id=task_id, ) return solution diff --git a/captcha_solver_api/client.py b/captcha_solver_api/client.py index 5e42c8a..3b48ed2 100644 --- a/captcha_solver_api/client.py +++ b/captcha_solver_api/client.py @@ -194,9 +194,8 @@ def get_task_result(self, task_id: int) -> Dict[str, Any]: Returns: The raw API response. Always has a `status` key (`"processing"` or - `"ready"`); when `"ready"`, also has a `solution` dict whose shape - depends on the task type (e.g. `{"gRecaptchaResponse": "..."}` for - reCAPTCHA, `{"text": "..."}` for `ImageToTextTask`). + `"ready"`); when `"ready"`, also has a `solution` value whose shape + depends on the task type. Raises: ApiError: The API reports an error for this task (e.g. it expired). @@ -246,7 +245,7 @@ def solve( task: Any, language_pool: Optional[str] = None, timeout: Optional[int] = None, - ) -> Dict[str, Any]: + ) -> Dict[str, Any] | str: """Submits `task` and polls until it's solved. This is the main entry point -- it wraps `create_task()` and `get_task_result()` so you don't have to poll by hand. @@ -261,9 +260,8 @@ def solve( not a strict deadline for the entire call. Returns: - The `solution` dict once `status` is `"ready"`. Its shape depends on - the task type -- see the per-type docstrings in `captcha_solver_api.tasks` - or the README's method reference. + The `solution` once `status` is `"ready"`. Most task types return a + dict; `YandexSmartCaptchaKaleidoscopeTask` returns a string. Raises: ValidationError: `task` is not a task object, or a required task @@ -312,9 +310,9 @@ def solve( if result.get("status") == "ready": solution = result["solution"] - if not isinstance(solution, dict): + if not isinstance(solution, (dict, str)) or solution == "": raise NetworkError( - "API returned a ready task without a solution object", + "API returned a ready task without a valid solution", task_id=task_id, ) return solution diff --git a/captcha_solver_api/tasks.py b/captcha_solver_api/tasks.py index d4e6824..38142d9 100644 --- a/captcha_solver_api/tasks.py +++ b/captcha_solver_api/tasks.py @@ -13,6 +13,7 @@ from __future__ import annotations import inspect +import json from typing import Any, Dict, Optional from .exceptions import ValidationError @@ -927,6 +928,47 @@ def __init__( self.comment = comment +class YandexSmartCaptchaKaleidoscopeTask(BaseTask): + """Image-based Yandex SmartCaptcha Kaleidoscope puzzle, sent as API type + `PazlCaptchaTask`. No proxy variant exists because the image is submitted directly. + + Args: + image: Required. Main Kaleidoscope challenge image, base64-encoded + without a `data:image/...;base64,` prefix. + task: Required. Puzzle-step sequence captured from the same challenge, + as a JSON array string or a list of integers. Preserve the original + order; the sequence is challenge-specific. + + Returns (`solution` from `solve()`): + A string containing the number of slider-arrow clicks required to solve + the puzzle. + + Example: + from captcha_solver_api.tasks import YandexSmartCaptchaKaleidoscopeTask + + task = YandexSmartCaptchaKaleidoscopeTask( + image="BASE64_IMAGE", + task="[15,24,4,13,10]", + ) + clicks = client.solve(task) + """ + + type = "PazlCaptchaTask" + + def __init__(self, image: str, task: str | list[int]) -> None: + """Create a Kaleidoscope puzzle task. + + Args: + image: Main challenge image encoded as a pure Base64 string, without + a data-URL prefix. + task: Challenge-specific puzzle steps as a JSON array string or a list + of integers, for example `"[15,24,4,13,10]"` or + `[15, 24, 4, 13, 10]`. Keep the captured order unchanged. + """ + self.image = image + self.task = json.dumps(task, separators=(",", ":")) if isinstance(task, list) else task + + class TencentTaskProxyless(BaseTask): """Tencent captcha without proxy. diff --git a/examples/README.md b/examples/README.md index ef4b00b..aea0c90 100644 --- a/examples/README.md +++ b/examples/README.md @@ -67,6 +67,7 @@ script demonstrates exactly one task variant. | GeeTest v4 (proxyless / proxy) | [proxyless](sync/geetest_v4_proxyless.py) / [proxy](sync/geetest_v4_proxy.py) | [proxyless](async/geetest_v4_proxyless.py) / [proxy](async/geetest_v4_proxy.py) | `captcha_output` and related fields | | Yandex SmartCaptcha (proxyless / proxy) | [proxyless](sync/yandex_smartcaptcha_proxyless.py) / [proxy](sync/yandex_smartcaptcha_proxy.py) | [proxyless](async/yandex_smartcaptcha_proxyless.py) / [proxy](async/yandex_smartcaptcha_proxy.py) | `token` | | Yandex SmartCaptcha image | [yandex_smartcaptcha_image.py](sync/yandex_smartcaptcha_image.py) | [yandex_smartcaptcha_image.py](async/yandex_smartcaptcha_image.py) | `coordinates` | +| Yandex SmartCaptcha Kaleidoscope | [yandex_smartcaptcha_kaleidoscope.py](sync/yandex_smartcaptcha_kaleidoscope.py) | [yandex_smartcaptcha_kaleidoscope.py](async/yandex_smartcaptcha_kaleidoscope.py) | `str` slider-arrow click count | | Coordinates / click captcha | [coordinates.py](sync/coordinates.py) | [coordinates.py](async/coordinates.py) | `coordinates` | | Tencent (proxyless / proxy) | [proxyless](sync/tencent_proxyless.py) / [proxy](sync/tencent_proxy.py) | [proxyless](async/tencent_proxyless.py) / [proxy](async/tencent_proxy.py) | `appid`, `ret`, `ticket`, `randstr` | @@ -77,6 +78,7 @@ Run commands from the repository root so local imports and bundled assets resolv ```bash python examples/sync/balance.py python examples/sync/image_to_text.py +python examples/sync/yandex_smartcaptcha_kaleidoscope.py python examples/async/recaptcha_v2_proxyless.py ``` diff --git a/examples/assets/yandex-smartcaptcha-kaleidoscope.jpg b/examples/assets/yandex-smartcaptcha-kaleidoscope.jpg new file mode 100644 index 0000000..b266962 Binary files /dev/null and b/examples/assets/yandex-smartcaptcha-kaleidoscope.jpg differ diff --git a/examples/async/yandex_smartcaptcha_kaleidoscope.py b/examples/async/yandex_smartcaptcha_kaleidoscope.py new file mode 100644 index 0000000..e49a799 --- /dev/null +++ b/examples/async/yandex_smartcaptcha_kaleidoscope.py @@ -0,0 +1,73 @@ +"""Example: Solve an image-based Yandex SmartCaptcha Kaleidoscope asynchronously. + +This example reads the bundled Kaleidoscope challenge image, encodes it as +Base64, sends it together with the puzzle-step sequence without a proxy, and +prints how many times to click the slider arrow. It uses +YandexSmartCaptchaKaleidoscopeTask and AsyncCaptchaClient.solve(). + +How it works: +STEP-01 - Configure AsyncCaptchaClient and locate the bundled challenge image. +STEP-02 - Encode the image and create a task with the captured puzzle steps. +STEP-03 - Await solve(), which creates the task and polls for its solution. +STEP-04 - Print the slider-arrow click count, or report the error. + +Prerequisites: + Set the CAPTCHA_API_KEY environment variable. + The sample image is bundled in examples/assets/. +""" + +import asyncio +import os +import sys +from base64 import b64encode + +try: + from dotenv import load_dotenv +except ModuleNotFoundError as exc: + if exc.name != "dotenv": + raise + load_dotenv = None + +repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +sys.path.append(repo_root) +if load_dotenv is not None: + load_dotenv(os.path.join(repo_root, ".env")) + +from captcha_solver_api import AsyncCaptchaClient +from captcha_solver_api.tasks import YandexSmartCaptchaKaleidoscopeTask + + +def encode_image(filename: str) -> str: + """Return an image from examples/assets as a Base64 string.""" + path = os.path.join(repo_root, "examples", "assets", filename) + with open(path, "rb") as image_file: + return b64encode(image_file.read()).decode("utf-8") + + +async def main() -> None: + # STEP-01: Configure AsyncCaptchaClient and locate the bundled challenge image. + api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") + async with AsyncCaptchaClient(api_key) as solver: + # STEP-02: Encode the image and create a task with the captured puzzle steps. + # STEP-03: Await solve(), which creates the task and polls for its solution. + clicks = await solver.solve( + YandexSmartCaptchaKaleidoscopeTask( + # Base64-encoded Kaleidoscope image (required). + image=encode_image("yandex-smartcaptcha-kaleidoscope.jpg"), + # JSON array string captured from this challenge (required). + # Preserve the original order; the sequence is challenge-specific. + task="[7,15,14,0,11,6,6,0,11,15,6,10,1,14,3,12,9,0,15,1,5,1,8,11,12,11,0,12,1,10,1,4,14,6,10,6,10,8,3,0,5,9,7,8,0,3,8,0,9,12,12,11,3,0,8,10]", + ) + ) + # STEP-04: Print the slider-arrow click count, or report the error. + # Unlike most SDK tasks, this task returns a plain string rather than a dict. + # Click the Kaleidoscope slider arrow this many times to complete the puzzle. + # Example: "8" + print("Slider arrow clicks: " + str(clicks)) + + +if __name__ == "__main__": + try: + asyncio.run(main()) + except Exception as exc: + sys.exit(exc) diff --git a/examples/sync/yandex_smartcaptcha_kaleidoscope.py b/examples/sync/yandex_smartcaptcha_kaleidoscope.py new file mode 100644 index 0000000..694e2f9 --- /dev/null +++ b/examples/sync/yandex_smartcaptcha_kaleidoscope.py @@ -0,0 +1,68 @@ +"""Example: Solve an image-based Yandex SmartCaptcha Kaleidoscope puzzle. + +This example reads the bundled Kaleidoscope challenge image, encodes it as +Base64, sends it together with the puzzle-step sequence without a proxy, and +prints how many times to click the slider arrow. It uses +YandexSmartCaptchaKaleidoscopeTask and CaptchaClient.solve(). + +How it works: +STEP-01 - Configure CaptchaClient and locate the bundled challenge image. +STEP-02 - Encode the image and create a task with the captured puzzle steps. +STEP-03 - Call solve(), which creates the task and polls for its solution. +STEP-04 - Print the slider-arrow click count, or report the error. + +Prerequisites: + Set the CAPTCHA_API_KEY environment variable. + The sample image is bundled in examples/assets/. +""" + +import os +import sys +from base64 import b64encode + +try: + from dotenv import load_dotenv +except ModuleNotFoundError as exc: + if exc.name != "dotenv": + raise + load_dotenv = None + +repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +sys.path.append(repo_root) +if load_dotenv is not None: + load_dotenv(os.path.join(repo_root, ".env")) + +from captcha_solver_api import CaptchaClient +from captcha_solver_api.tasks import YandexSmartCaptchaKaleidoscopeTask + + +def encode_image(filename: str) -> str: + """Return an image from examples/assets as a Base64 string.""" + path = os.path.join(repo_root, "examples", "assets", filename) + with open(path, "rb") as image_file: + return b64encode(image_file.read()).decode("utf-8") + + +# STEP-01: Configure CaptchaClient and locate the bundled challenge image. +api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY") +solver = CaptchaClient(api_key) + +try: + # STEP-02: Encode the image and create a task with the captured puzzle steps. + # STEP-03: Call solve(), which creates the task and polls for its solution. + clicks = solver.solve( + YandexSmartCaptchaKaleidoscopeTask( + # Base64-encoded Kaleidoscope image (required). + image=encode_image("yandex-smartcaptcha-kaleidoscope.jpg"), + # JSON array string captured from this challenge (required). + # Preserve the original order; the sequence is challenge-specific. + task="[7,15,14,0,11,6,6,0,11,15,6,10,1,14,3,12,9,0,15,1,5,1,8,11,12,11,0,12,1,10,1,4,14,6,10,6,10,8,3,0,5,9,7,8,0,3,8,0,9,12,12,11,3,0,8,10]", + ) + ) + # STEP-04: Print the slider-arrow click count, or report the error. + # Unlike most SDK tasks, this task returns a plain string rather than a dict. + # Click the Kaleidoscope slider arrow this many times to complete the puzzle. + # Example: "8" + print("Slider arrow clicks: " + str(clicks)) +except Exception as exc: + sys.exit(exc) diff --git a/tests/async/test_async_error_task_id.py b/tests/async/test_async_error_task_id.py index 8d2a599..926978e 100644 --- a/tests/async/test_async_error_task_id.py +++ b/tests/async/test_async_error_task_id.py @@ -71,11 +71,22 @@ async def test_network_error_after_retries_has_task_id(): assert exc_info.value.task_id == 100 -async def test_ready_task_without_solution_object_has_task_id(): +async def test_ready_task_with_invalid_solution_has_task_id(): client = make_client() with patch.object(client, "_request", new_callable=AsyncMock) as mock_request: - mock_request.side_effect = [CREATED, {"errorId": 0, "status": "ready", "solution": "x"}] + mock_request.side_effect = [CREATED, {"errorId": 0, "status": "ready", "solution": 42}] + with pytest.raises(NetworkError) as exc_info: + await client.solve(TASK) + + assert exc_info.value.task_id == 100 + + +async def test_ready_task_with_empty_string_solution_has_task_id(): + client = make_client() + + with patch.object(client, "_request", new_callable=AsyncMock) as mock_request: + mock_request.side_effect = [CREATED, {"errorId": 0, "status": "ready", "solution": ""}] with pytest.raises(NetworkError) as exc_info: await client.solve(TASK) diff --git a/tests/sync/test_error_task_id.py b/tests/sync/test_error_task_id.py index b28acaf..90c9136 100644 --- a/tests/sync/test_error_task_id.py +++ b/tests/sync/test_error_task_id.py @@ -70,11 +70,22 @@ def test_network_error_after_retries_has_task_id(): assert exc_info.value.task_id == 100 -def test_ready_task_without_solution_object_has_task_id(): +def test_ready_task_with_invalid_solution_has_task_id(): client = make_client() with patch.object(client, "_request") as mock_request: - mock_request.side_effect = [CREATED, {"errorId": 0, "status": "ready", "solution": "x"}] + mock_request.side_effect = [CREATED, {"errorId": 0, "status": "ready", "solution": 42}] + with pytest.raises(NetworkError) as exc_info: + client.solve(TASK) + + assert exc_info.value.task_id == 100 + + +def test_ready_task_with_empty_string_solution_has_task_id(): + client = make_client() + + with patch.object(client, "_request") as mock_request: + mock_request.side_effect = [CREATED, {"errorId": 0, "status": "ready", "solution": ""}] with pytest.raises(NetworkError) as exc_info: client.solve(TASK) diff --git a/tests/sync/test_yandex_smartcaptcha_kaleidoscope.py b/tests/sync/test_yandex_smartcaptcha_kaleidoscope.py new file mode 100644 index 0000000..cb9bbb7 --- /dev/null +++ b/tests/sync/test_yandex_smartcaptcha_kaleidoscope.py @@ -0,0 +1,38 @@ +"""Tests for YandexSmartCaptchaKaleidoscopeTask.""" + +import pytest + +from captcha_solver_api import ValidationError +from captcha_solver_api.tasks import YandexSmartCaptchaKaleidoscopeTask + + +class TestYandexSmartCaptchaKaleidoscope: + def test_to_dict_uses_api_v2_task_type(self): + task = YandexSmartCaptchaKaleidoscopeTask( + image="captcha-image", + task="[7,15,14,0]", + ) + + assert task.to_dict() == { + "type": "PazlCaptchaTask", + "image": "captcha-image", + "task": "[7,15,14,0]", + } + + def test_list_task_is_serialized_as_json_string(self): + task = YandexSmartCaptchaKaleidoscopeTask( + image="captcha-image", + task=[7, 15, 14, 0], + ) + + assert task.to_dict()["task"] == "[7,15,14,0]" + + @pytest.mark.parametrize( + "image,task,missing", + [("", "[7,15,14,0]", "image"), ("captcha-image", " ", "task")], + ) + def test_required_fields_are_validated(self, image, task, missing): + captcha = YandexSmartCaptchaKaleidoscopeTask(image=image, task=task) + + with pytest.raises(ValidationError, match=missing): + captcha.to_dict() diff --git a/tests/test_polling.py b/tests/test_polling.py index fdf1b37..9db9074 100644 --- a/tests/test_polling.py +++ b/tests/test_polling.py @@ -8,7 +8,10 @@ import captcha_solver_api.async_client as async_module import captcha_solver_api.client as sync_module from captcha_solver_api import AsyncCaptchaClient, CaptchaClient, CaptchaTimeoutError -from captcha_solver_api.tasks import RecaptchaV2TaskProxyless +from captcha_solver_api.tasks import ( + RecaptchaV2TaskProxyless, + YandexSmartCaptchaKaleidoscopeTask, +) class Clock: @@ -89,3 +92,42 @@ async def request(endpoint, payload): else: assert await client.solve(task, timeout=timeout) == {"token": "done"} assert polls == expected_polls + + +def test_sync_solve_returns_kaleidoscope_string(monkeypatch): + clock = Clock() + monkeypatch.setattr(sync_module, "time", clock) + + responses = iter( + [ + {"errorId": 0, "taskId": 100}, + {"errorId": 0, "status": "ready", "solution": "8"}, + ] + ) + with CaptchaClient("test-key", polling_interval=1) as client: + monkeypatch.setattr(client, "_request", lambda endpoint, payload: next(responses)) + task = YandexSmartCaptchaKaleidoscopeTask("image", "[7,15,14,0]") + assert client.solve(task, timeout=2) == "8" + + +async def test_async_solve_returns_kaleidoscope_string(monkeypatch): + clock = Clock() + monkeypatch.setattr(async_module, "time", clock) + monkeypatch.setattr( + async_module, "asyncio", SimpleNamespace(sleep=AsyncMock(side_effect=clock.sleep)) + ) + + responses = iter( + [ + {"errorId": 0, "taskId": 100}, + {"errorId": 0, "status": "ready", "solution": "8"}, + ] + ) + + async def request(endpoint, payload): + return next(responses) + + async with AsyncCaptchaClient("test-key", polling_interval=1) as client: + monkeypatch.setattr(client, "_request", request) + task = YandexSmartCaptchaKaleidoscopeTask("image", "[7,15,14,0]") + assert await client.solve(task, timeout=2) == "8"