decodo-register — авторег Decodo (free DC proxies)
Decodo (ex-Smartproxy) даёт 1 GB datacenter-прокси трафика в месяц бесплатно на аккаунт: без карты, только подтверждение почты. Реггер делает аккаунты пачками и складывает в банк рабочие username:password к dc.decodo.com:10000.
# -*- coding: utf-8 -*-"""reCAPTCHA v2: свой браузер + свой vision-стек($0), 2captcha как fallback.
Типовая задача: сервис ставит reCAPTCHA v2 на форму (поле вида
`captchaToken`). Токен привязан к домену сайта, поэтому минтим его НА САМОЙ
странице: рендерим виджет в отдельный div, жмём чекбокс, а если выпал
картинка-челлендж («Select all images with crosswalks») — решаем сетку и
кликаем по ячейкам.
Два солвера сетки, порядок задаётся `grid_solver`:
classifier ONNX YOLO11x-cls на 57k тайлов, 14 классов — ~0.2 с, дёшево
vlm OpenAI-совместимая VLM (`vlm_api_base/_key/_model`) — ~15 с,
«понимает» любую инструкцию, нужна для 4×4 и «none left»
auto классификатор → VLM, если классификатор не нашёл ничего
both объединение ответов (медленнее, полнее)
Аудио-челлендж — в `vision.solve_audio_captcha` (Whisper-совместимый STT).
Оба своих пути стоят $0; verify идёт fetch'ем из той же страницы, так что
origin/TLS-контекст совпадает по построению.
Готовый стек под это (без GPU, 4 vCPU): `провайдеры/sandboxes-vm/instabox-vision.md`
— ONNX-классификатор, LFM3-VL-2B-recaptcha на llama.cpp и faster-whisper.
"""import base64
import json
import os
import re
import time
import requests
from.import config
TWOCAPTCHA_CREATE ="https://api.2captcha.com/createTask"
TWOCAPTCHA_RESULT ="https://api.2captcha.com/getTaskResult"# recaptcha.net — зеркало для регионов, где google.com недоступен.# Важно: через наши прокси www.google.com отдаёт ProxyError, а# www.recaptcha.net — 200; токен тот же, sitekey тот же.
_LOAD_JS ="""() => new Promise((resolve) => {
if (window.grecaptcha && window.grecaptcha.render) return resolve(true);
window.__mcap_onload = () => resolve(true);
const srcs = [
'https://www.recaptcha.net/recaptcha/api.js?render=explicit&onload=__mcap_onload',
'https://www.google.com/recaptcha/api.js?render=explicit&onload=__mcap_onload'
];
let i = 0;
const next = () => {
if (i >= srcs.length) return resolve(false);
const s = document.createElement('script');
s.src = srcs[i++];
s.onerror = () => { s.remove(); next(); };
document.head.appendChild(s);
};
next();
setTimeout(() => resolve(!!(window.grecaptcha && window.grecaptcha.render)), 15000);
})"""
_RENDER_JS
_TOKEN_JS
_BFRAME
_TABLE
_INSTR
_TILES
GRID_PROMPT
msg
flush
base osenvironget configget rstrip
key osenvironget configget
model osenvironget configget
base key model
image_path prompt timeout
base key model vlm_cfg
base key model
_log
image_path f
b64 base64b64encodefreaddecode
OSError exc
_log
body
model
prompt
b64
r requestspostbase jsonbody timeouttimeout
stream
headers key
rstatus_code
_log
out
line riter_linesdecode_unicode
line linestartswith
chunk linestrip
chunk
d jsonloadschunk
ValueError
ch dget
delta chget chget
field
deltagetfield
outappenddeltafield
joinoutstrip
Exception exc
_log
base osenvironget configget rstrip
key osenvironget configget
base key
paths question timeout
base key grid_cfg
base key
tiles
path paths
path
path f
tilesappendbase64b64encodefreaddecode
OSError
r requestspostbase
json question tiles
timeouttimeout
headers key
rstatus_code
_log
d rjson
dget dget
dget
Exception exc
_log
text limit
text
cells conf
m refinditer text
j jsonloadsmgroup
ValueError TypeError
j
got jget jget jget jget
got
cells got
conf jget
TypeError ValueError
conf
cells
nums refindall text
cells n n nums
cells
cells k k v cellsitems v
out c c cells
c refullmatch cstrip
c c out c limit conf
img_path rows cols out_path
PIL Image ImageDraw
ImportError
img_path
img Imageimg_pathconvert
w h imgsize
d ImageDrawDrawimg
cw ch w cols h rows
r rows
c cols
idx r cols c
x y c cw r ch
drectanglex y x cw y ch
outline width
tx ty x y
drectangletx ty tx ty fill
dtexttx ty idx fill
imgsaveout_path
out_path
Exception
img_path
page timeout
bf pageframe_locator_BFRAME
deadline timetime timeout
timetime deadline
ready bflocator_TILESevaluate_all
Exception
ready
ready
timesleep
timesleep
page
bf pageframe_locator_BFRAME
el bflocator
elcount elfirstis_visible
elfirstinner_texttimeoutstrip
Exception
page
pageframe_locator_BFRAMElocator
count
Exception
page
pageframe_locator_BFRAMElocator_TILESevaluate_all
Exception
srcs proxy out_dir tag
paths
i src srcs
path ospathjoinout_dir
r requestsgetsrc timeout
proxies proxy proxy proxy
headers configUA
rstatus_code rcontent
path f
fwritercontent
pathsappendpath
Exception
pathsappend
paths
paths rows cols out_path size
PIL Image ImageDraw
ImportError
canvas Imagenew cols size rows size
d ImageDrawDrawcanvas
idx path pathsrows cols
r c idx cols
path
im Imagepathconvertresizesize size ImageLANCZOS
Exception
im Imagenew size size
im Imagenew size size
canvaspasteim c size r size
drectanglec size r size
c size r size
outline width
drectanglec size r size
c size r size fill
dtextc size r size idx fill
canvassaveout_path quality
out_path
page
pageframe_locator_BFRAMElocator_TABLEevaluate
page rounds proxy
bf pageframe_locator_BFRAME
bflocator_TABLEwait_forstate timeout
Exception exc
_log
out_dir ospathjoinconfigDATA_DIR
osmakedirsout_dir exist_ok
rnd rounds
question bflocator_INSTRinner_texttimeoutstrip
Exception
question
question resub question
rows cols _grid_shapepage
Exception
rows cols
total rows cols
_wait_tiles_loadedpage
tag
shot ospathjoinout_dir tag
bflocator_TABLEscreenshotpathshot timeout
Exception exc
_log
srcs _tile_srcspage
paths _fetch_tilessrcs proxy out_dir tag
mode configget lower
cells conf src
mode paths paths
got cconf label classify_tilespaths question
got
cells conf src got cconf
asked_vlm
mode mode cells
labeled _compose_montagepaths rows cols
ospathjoinout_dir tag
labeled
labeled _label_gridshot rows cols ospathjoinout_dir tag
prompt GRID_PROMPTrowsrows colscols questionquestion
text ask_vlmlabeled prompt
asked_vlm
vcells vconf parse_cellstext total
mode cells
cells cells vcells
conf conf vconf
src
vcells
cells conf src vcells vconf
cells
src
_log
cells
tds bflocator_TILES
idx cells
tdsnthidxclicktimeout
timesleep
Exception exc
_log
sel _selected_countpage
sel
_log
dynamic questionlower total
dynamic
timesleep
bflocatorclicktimeout
timesleep
err _challenge_errorpage
_log err
Exception exc
_log
page sitekey timeout challenge_rounds proxy
sitekey
pageevaluate_LOAD_JS
Exception exc
_log
pageevaluate_RENDER_JS sitekeystartswith
fl pageframe_locator
anchor fllocator
anchorwait_forstate timeout
timesleep
anchorclicktimeout
Exception exc
_log
deadline timetime timeout
solved_rounds
timetime deadline
tok pageevaluate_TOKEN_JS
Exception
tok
tok
_log
tok
challenge pageframe_locator_BFRAMElocator_TABLEcount
Exception
challenge
challenge solved_rounds challenge_rounds
solved_rounds
_log
solve_grid_challengepage proxyproxy
timesleep
timesleep
sitekey pageurl timeout
key configget strip
key sitekey
siteurl pageurl configget
r requestspostTWOCAPTCHA_CREATE json
key
siteurl sitekey
timeoutjson
Exception exc
_log
rget
_log
tid rget
deadline timetime timeout
timetime deadline
timesleep
g requestspostTWOCAPTCHA_RESULT json key tid
timeoutjson
Exception
gget
tok gget get
_log
tok
gget
_log
page sitekey pageurl proxy
mode configget lower
mode
tok solve_in_pagepage sitekey proxyproxy
tok
tok
mode
solve_2captchasitekey pageurlpageurl
mode configget lower
base key model vlm_cfg
gbase gkey grid_cfg
has_2c configget strip
label
getmode mode
label model base key model
configget
gbase gkey
configget has_2c
"""Картинка + текст → ответ VLM (текст). Ошибка → пустая строка.
Обязательно стримом: CPU-VLM думает 10–20 с, а приватный порт Instabox
обрывает молчащий запрос на ~20-й секунде (502 Bad Gateway). SSE отдаёт
заголовки сразу, и соединение живёт сколько нужно.
"""
,
,
=
(
)
if
not
(
and
and
)
:
(
"VLM не настроен (vlm_api_base/vlm_api_key/vlm_model)"
"""Оригиналы тайлов → (cells, confidence, label). Без классификатора — None.
В отличие от VLM, эта штука не «рассуждает», а классифицирует каждый
тайл по 14 классам reCAPTCHA: ~0.2 с на сетку вместо ~15 с. Зато видит
только те объекты, на которых обучена (светофор, зебра, автобус, …),
поэтому в solve_grid_challenge она идёт первой, а VLM добирает, если
классификатор не нашёл ничего.
"""
"""Ответ VLM → индексы ячеек. Терпимо к ```json, лишнему тексту.
Модели отвечают по-разному: {"cells": [...]}, {"answer": [...]} (так
делает LFM3-VL), просто списком. Любой из вариантов — валиден.
"""
if
not
:
return
[
]
,
0.0
,
=
[
]
,
0.0
for
in
.
(
r"\{[\s\S]*?\}"
,
)
:
try
:
=
.
(
.
(
0
)
)
except
(
,
)
:
continue
if
not
isinstance
(
,
dict
)
:
continue
=
.
(
"cells"
)
or
.
(
"answer"
)
or
.
(
"indices"
)
or
.
(
"tiles"
)
if
:
=
try
:
=
float
(
.
(
"confidence"
)
or
0
)
except
(
,
)
:
=
0.0
break
if
not
:
=
.
(
r"\b(\d{1,2})\b"
,
)
=
[
int
(
)
for
in
]
if
isinstance
(
,
dict
)
:
=
[
for
,
in
.
(
)
if
]
=
sorted
(
{
int
(
)
for
in
if
isinstance
(
,
(
int
,
str
)
)
and
.
(
r"\d+"
,
str
(
)
.
(
)
)
}
)
return
[
for
in
if
0
<=
<
]
,
def
_label_grid
(
,
,
,
)
:
"""Нарисовать номера ячеек на скриншоте сетки (VLM так точнее)."""
try
:
from
import
,
except
:
return
try
:
=
.
open
(
)
.
(
"RGB"
)
,
=
.
=
.
(
,
"RGBA"
)
,
=
/
,
/
for
in
range
(
)
:
for
in
range
(
)
:
=
*
+
,
=
int
(
*
)
,
int
(
*
)
.
(
[
+
1
,
+
1
,
+
-
2
,
+
-
2
]
,
=
(
0
,
200
,
0
,
255
)
,
=
2
)
,
=
+
4
,
+
3
.
(
[
-
2
,
-
1
,
+
20
,
+
13
]
,
=
(
0
,
0
,
0
,
190
)
)
.
(
(
,
)
,
str
(
)
,
=
(
255
,
255
,
0
,
255
)
)
.
(
)
return
except
:
return
def
_wait_tiles_loaded
(
,
=
15
)
:
"""Дождаться полной загрузки картинок сетки.
reCAPTCHA отдаёт прогрессивный JPEG: если снять скриншот сразу, VLM видит
полузагруженную «дизерингую» картинку и гадает. Ждём img.complete и
naturalWidth>0 у всех ячеек.
"""
=
.
(
)
=
.
(
)
+
while
.
(
)
<
:
try
:
=
.
(
)
.
(
"els => els.every(td => { const i = td.querySelector('img');"
" return i && i.complete && i.naturalWidth > 0; })"
)
except
:
=
False
if
:
.
(
0.6
)
return
True
.
(
0.4
)
return
False
def
_challenge_error
(
)
:
"""Текст ошибки под сеткой («Please try again» и т.п.), если есть."""
"els => els.map(td => { const i = td.querySelector('img'); return i ? i.src : ''; }).filter(Boolean)"
)
except
:
return
[
]
def
_fetch_tiles
(
,
,
,
)
:
"""Скачать оригиналы ячеек через тот же прокси → список путей."""
=
[
]
for
,
in
enumerate
(
)
:
=
.
.
(
,
f"{tag}-tile{i}.jpg"
)
try
:
=
.
(
,
=
30
,
=
{
"http"
:
,
"https"
:
}
if
else
None
,
=
{
"User-Agent"
:
.
,
"Referer"
:
"https://www.recaptcha.net/"
}
)
if
.
==
200
and
.
:
with
open
(
,
"wb"
)
as
:
.
(
.
)
.
(
)
continue
except
:
pass
.
(
""
)
return
def
_compose_montage
(
,
,
,
,
=
300
)
:
"""Склеить оригиналы в одну сетку с номерами (VLM видит качество 1:1).
Скриншот bframe даёт 378px из 300px исходника (апскейл + сглаживание),
из-за чего картинки «шумят». Оригиналы payload — 300×300, их и показываем.
"""
try
:
from
import
,
except
:
return
None
=
.
(
"RGB"
,
(
*
,
*
)
,
(
255
,
255
,
255
)
)
=
.
(
)
for
,
in
enumerate
(
[
:
*
]
)
:
,
=
divmod
(
,
)
if
:
try
:
=
.
open
(
)
.
(
"RGB"
)
.
(
(
,
)
,
.
)
except
:
=
.
(
"RGB"
,
(
,
)
,
(
220
,
220
,
220
)
)
else
:
=
.
(
"RGB"
,
(
,
)
,
(
220
,
220
,
220
)
)
.
(
,
(
*
,
*
)
)
.
(
[
*
+
1
,
*
+
1
,
(
+
1
)
*
-
2
,
(
+
1
)
*
-
2
]
,
=
(
0
,
200
,
0
)
,
=
3
)
.
(
[
*
+
4
,
*
+
4
,
*
+
34
,
*
+
28
]
,
=
(
0
,
0
,
0
)
)
.
(
(
*
+
10
,
*
+
8
)
,
str
(
)
,
=
(
255
,
255
,
0
)
)
.
(
,
=
90
)
return
def
_grid_shape
(
)
:
"""Число строк/столбцов видимой сетки (3x3 или 4x4) из bframe."""
f"(conf {conf:.2f}, {src or'пусто'}{' , vlm'if asked_vlm and mode =='both'else''})"
)
if
not
:
break
=
.
(
)
for
in
:
try
:
.
(
)
.
(
=
8000
)
.
(
0.25
)
except
as
:
(
f"клик {idx}: {str(exc)[:60]}"
)
=
(
)
if
>=
0
:
(
f"отмечено ячеек: {sel} (кликали {len(cells)})"
)
# Динамическая сетка (в инструкции «Click verify once there are none
# left») заменяет нажатые ячейки новыми — надо продолжать, пока VLM не
# скажет «больше нет». Классическая 3x3 без замены — сразу VERIFY.
=
"none left"
in
.
(
)
or
>
9
if
not
:
break
.
(
2.5
)
# дождаться подмены ячеек
try
:
.
(
"#recaptcha-verify-button"
)
.
(
=
8000
)
.
(
1.5
)
=
(
)
(
"VERIFY нажат"
+
(
f", ответ: {err[:80]}"
if
else
""
)
)
return
True
except
as
:
(
f"VERIFY: {str(exc)[:80]}"
)
return
False
def
solve_in_page
(
,
,
=
240
,
=
8
,
=
None
)
:
"""Минт reCAPTCHA v2 в контексте страницы. Токен или None.
page — playwright/camoufox Page уже на домене сервиса (иначе sitekey не
примется: Google сверяет домен). Каждый челлендж решается VLM-солвером;
при провале рекапча даёт новый челлендж — пробуем `challenge_rounds` раз.
"""
if
not
:
return
None
try
:
.
(
)
except
as
:
(
f"api.js не поднялся: {str(exc)[:100]}"
)
return
None
if
str
(
.
(
,
)
)
.
(
"ERR"
)
:
# повторная отрисовка того же виджета — ок, ошибку мог дать первый вызов
pass
try
:
=
.
(
'iframe[src*="api2/anchor"]'
)
=
.
(
"#recaptcha-anchor"
)
.
(
=
"visible"
,
=
20000
)
.
(
0.8
)
.
(
=
8000
)
except
as
:
(
f"клик по чекбоксу: {str(exc)[:80]}"
)
=
.
(
)
+
=
0
while
.
(
)
<
:
try
:
=
.
(
)
except
:
=
""
if
:
(
f"токен получен ({len(tok)} симв.)"
)
return
# есть ли челлендж, который надо решать
try
:
=
.
(
)
.
(
)
.
(
)
>
0
except
:
=
False
if
and
<
:
+=
1
(
f"челлендж {solved_rounds}/{challenge_rounds}"
)
(
,
=
)
.
(
3
)
continue
.
(
2
)
return
None
def
solve_2captcha
(
,
=
None
,
=
180
)
:
"""Fallback: RecaptchaV2TaskProxyless (так работал чужой фарм)."""