Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ on the target page.
| Image to Text | ✅ | - |
| Yandex SmartCaptcha | ✅ | ✅ |
| Yandex SmartCaptcha Image | ✅ | - |
| Yandex SmartCaptcha Kaleidoscope | ✅ | - |
| Coordinates (click captcha) | ✅ | - |
| Tencent | ✅ | ✅ |

Expand Down Expand Up @@ -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`.
Expand All @@ -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`.

Expand Down Expand Up @@ -510,7 +511,8 @@ With proxy, use `GeeTestTask` (same proxy fields as reCAPTCHA v2).
<sup>[API method description.](https://captcha-solver.com/en/docs/captcha-types#yandex-smartcaptcha)</sup>

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.

Expand Down Expand Up @@ -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)

<sup>[API method description.](https://captcha-solver.com/en/docs/captcha-types#coordinates)</sup>
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 7 additions & 9 deletions captcha_solver_api/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
16 changes: 7 additions & 9 deletions captcha_solver_api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions captcha_solver_api/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from __future__ import annotations

import inspect
import json
from typing import Any, Dict, Optional

from .exceptions import ValidationError
Expand Down Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |

Expand All @@ -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
```

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
73 changes: 73 additions & 0 deletions examples/async/yandex_smartcaptcha_kaleidoscope.py
Original file line number Diff line number Diff line change
@@ -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)
68 changes: 68 additions & 0 deletions examples/sync/yandex_smartcaptcha_kaleidoscope.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading