Skip to main content

SDK Python: Camoufox + asistencia Turnstile (DOM o YOLO con polling) para Playwright async.

Project description

camoufox-turnstile

imagen

SDK en Python para integrar Cloudflare Turnstile en scrapers o automatizaciones que usen Camoufox y Playwright (async API).

  • Modo YOLO (extra [yolo]): bucle de captura + inferencia con polling, distinción de success_mark / target_checkbox / widget_container, y espera del token en input[name="cf-turnstile-response"].
  • Modo solo DOM: heurística de clics sobre el iframe, sin modelo.

Alcance: sitios que usan el campo oculto estándar cf-turnstile-response. No sustituye otros captchas (reCAPTCHA, hCaptcha, etc.).

Para probar el SDK puedes usar el Turnstile Lab público: https://turnstile-lab.builker.com/ (es la URL por defecto del ejemplo examples/minimal.py).

Guía paso a paso para integrarlo en cualquier proyecto Python: INTEGRACION.md (enlace absoluto para lectura desde PyPI).

pip install camoufox-turnstile

Visión YOLO: instala el extra [yolo] (Ultralytics + OpenCV para inferencia). El archivo .pt no se descarga a mano: la primera vez que uses solve_on_page(..., use_yolo=True) sin TURNSTILE_YOLO_WEIGHTS, el SDK baja solo turnstile-yolo-latest.pt desde Builker Open Models y lo guarda en caché; después reutiliza ese archivo.

pip install "camoufox-turnstile[yolo]"
# bucket S3 privado opcional:
pip install "camoufox-turnstile[yolo,s3]"

Instala también Camoufox y ejecuta (una vez por máquina):

camoufox fetch

Torch: instala la variante CPU/GPU que corresponda a tu entorno (no viene forzado en el extra [yolo] para no imponer CUDA).

Pesos .pt (descarga automática por defecto)

El wheel no incluye el modelo en PyPI, pero no tienes que bajarlo tú: salvo que fijes una ruta local, el SDK lo obtiene de red la primera vez y lo deja en caché.

Prioridad (ensure_yolo_weights / SolveOptions.yolo_weights):

  1. Ruta local explícita (yolo_weights en SolveOptions o variable TURNSTILE_YOLO_WEIGHTS).

  2. Archivo en caché (platformdirs, nombre por defecto turnstile-yolo-latest.pt).

  3. Descarga: TURNSTILE_YOLO_WEIGHTS_URL o TURNSTILE_YOLO_S3_URI si las defines; si no, el SDK usa por defecto la última versión pública en Builker Open Models:

    https://builker-open-models.s3.us-east-2.amazonaws.com/camoufox-turnstile-sdk/turnstile-yolo-latest.pt

    (constante DEFAULT_YOLO_WEIGHTS_URL en el paquete).

Para un bucket privado (s3://bucket/key) usa TURNSTILE_YOLO_S3_URI e instala pip install 'camoufox-turnstile[s3]' (boto3 + credenciales en el entorno).

Opcional: TURNSTILE_YOLO_WEIGHTS_SHA256 para verificar integridad tras descarga.
Opcional: TURNSTILE_YOLO_FORCE_DOWNLOAD (1 / true / yes / on): ignora caché y vuelve a bajar el .pt (misma URL en S3).
Opcional: TURNSTILE_YOLO_CACHE_BASENAME para otro nombre de archivo en caché (p. ej. varias variantes del modelo).

Sustituiste el .pt en S3 con el mismo nombre (turnstile-yolo-latest.pt)

Los usuarios que ya tengan caché no descargan de nuevo solos. Opciones:

  • Variable de entorno TURNSTILE_YOLO_FORCE_DOWNLOAD=1 (o true / yes / on) antes de ejecutar, o
  • En código: SolveOptions(refresh_yolo_weights=True), o
  • ensure_yolo_weights(force_download=True), o
  • Borrar el archivo en la caché de usuario (directorio camoufox_turnstile / weights de platformdirs).

Publicas un modelo con otra clave o otra URL

  • Puedes fijar TURNSTILE_YOLO_WEIGHTS_URL (o TURNSTILE_YOLO_CACHE_BASENAME) sin subir versión del paquete pip.
  • Si quieres que todos los installs por defecto apunten a un archivo nuevo, cambia DEFAULT_YOLO_WEIGHTS_URL en el código del SDK y publica una nueva versión en PyPI (0.1.1, 0.2.0, …). El número de versión pip es para cambios del SDK Python, no para cada reentrenamiento del modelo si sigues usando env/URL propia.

Uso rápido

import asyncio
from camoufox.async_api import AsyncCamoufox
from camoufox_turnstile import (
    SolveOptions,
    camoufox_context_options,
    solve_on_page,
    DEFAULT_VIEWPORT,
)

async def main():
    async with AsyncCamoufox(headless=True) as browser:
        ctx = await browser.new_context(
            **camoufox_context_options(viewport=DEFAULT_VIEWPORT, use_yolo=True)
        )
        page = await ctx.new_page()
        await page.goto("https://turnstile-lab.builker.com/", wait_until="load")
        result = await solve_on_page(page, SolveOptions())
        print(result.visual_ok_via, len(result.token))
        await ctx.close()

asyncio.run(main())

Modo solo DOM:

result = await solve_on_page(page, SolveOptions(use_yolo=False))

API relevante: read_turnstile_token, wait_turnstile_token, assist_turnstile_clicks, assist_turnstile_vision_clicks, load_yolo_detector, ensure_yolo_weights.

Ejemplo en línea de comandos

Desde la raíz del repo del SDK (con entorno editable):

pip install -e ".[yolo]"
python examples/minimal.py --headless
# URL explícita (por defecto ya es el lab público):
python examples/minimal.py "https://turnstile-lab.builker.com/" --headless
# o sin YOLO:
python examples/minimal.py --dom-only

Pruebas recomendadas contra el Turnstile Lab público: https://turnstile-lab.builker.com/

Construir el paquete (mantenedor)

pip install build
python -m build

Comprueba el wheel en un venv limpio con pip install dist/camoufox_turnstile-*.whl.

Publicar en PyPI

  1. Comprueba en pypi.org que el nombre del proyecto (camoufox-turnstile) esté libre y crea el proyecto en tu cuenta.
  2. Trusted Publishing (recomendado): en la configuración del proyecto en PyPI, añade un Trusted Publisher que apunte a este repositorio y al workflow .github/workflows/publish-pypi.yml antes del primer envío por CI. Documentación: PyPI Trusted Publishers y Publishing with a trusted publisher.
  3. Sube la versión en pyproject.toml y crea un tag semántico en Git, p. ej. git tag v0.1.0 && git push origin v0.1.0. El workflow construye el paquete y lo publica con OIDC (sin contraseña en el repo).
  4. Alternativa manual: tras python -m build, sube con twine upload dist/* y un API token de PyPI (no commitear secretos). Guía PyPA: Packaging Python Projects.

Tras publicar, verifica en un venv limpio: pip install camoufox-turnstile y python -c "import camoufox_turnstile; print(camoufox_turnstile.__version__)".

Legal y responsabilidad

Respeta los términos de uso del sitio objetivo y la legislación aplicable. Este SDK es una herramienta técnica; el uso indebido es responsabilidad del integrador.

Enlace al laboratorio

Proyecto de referencia (experimento): repositorio turnstile-security-lab (experiments/camoufox_yolo_turnstile).

Repositorio del SDK: https://github.com/builker-col/turnstile-camoufox-sdk

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

camoufox_turnstile-0.1.0.tar.gz (22.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

camoufox_turnstile-0.1.0-py3-none-any.whl (18.7 kB view details)

Uploaded Python 3

File details

Details for the file camoufox_turnstile-0.1.0.tar.gz.

File metadata

  • Download URL: camoufox_turnstile-0.1.0.tar.gz
  • Upload date:
  • Size: 22.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for camoufox_turnstile-0.1.0.tar.gz
Algorithm Hash digest
SHA256 20eb0e5bafbf33ee342f84cff6d7e15284b3bcad298d3f42872035888d55b2ee
MD5 fd4544a04b307bc2dc95ba3b0a5d0a3a
BLAKE2b-256 3b959e83f9b0e0539132e78ea901344111428bc7842020ba9de36bcb9795081c

See more details on using hashes here.

Provenance

The following attestation bundles were made for camoufox_turnstile-0.1.0.tar.gz:

Publisher: publish-pypi.yml on builker-col/turnstile-camoufox-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file camoufox_turnstile-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for camoufox_turnstile-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7b53171e87b36188dcb1088fecfe332c89d132fe82443c21058c3a7a4a279c75
MD5 19eccd1f727458ea12f3715da5eaea82
BLAKE2b-256 3d7b75bdd3c3cef51b2cb4a1c92ef09871adecf66226fa602e5bbe45ef37bd4f

See more details on using hashes here.

Provenance

The following attestation bundles were made for camoufox_turnstile-0.1.0-py3-none-any.whl:

Publisher: publish-pypi.yml on builker-col/turnstile-camoufox-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page