decodo-register — авторег Decodo (free DC proxies)
Decodo (ex-Smartproxy) даёт 1 GB datacenter-прокси трафика в месяц бесплатно на аккаунт: без карты, только подтверждение почты. Реггер делает аккаунты пачками и складывает в банк рабочие username:password к dc.decodo.com:10000.
# -*- coding: utf-8 -*-"""Vision-капча и аудио-капча как шаги флоу, а не разовые скрипты.
Два независимых солвера, оба необязательные — включаются конфигом:
from . import vision
# сетка «выбери все светофоры» / «нажми на фигуру»
cells = vision.solve_grid_captcha(page, prompt="Select all traffic lights")
# → [3, 9] (индексы ячеек в сетке 3×3)
# аудио-капча reCAPTCHA: скачать mp3 → STT → текст
text = vision.solve_audio_captcha(audio_url)
Провайдеры — OpenAI-совместимый VLM и любой Whisper-совместимый STT.
Ключи берутся из config.json (`vlm_*`, `stt_*`) или env `VLM_API_BASE` /
`VLM_API_KEY` / `VLM_MODEL` / `STT_API_BASE` / `STT_API_KEY` / `STT_MODEL`.
Зачем отдельный модуль. У нас VLM уже дважды писался точечно под слайдер
(`zai/slider_solver.py`). Повторять это в каждом реггере не нужно: сетка
ячеек — общая задача, различается только текст промпта.
"""import base64
import json
import os
import re
import urllib.error
import urllib.request
from.import config
GRID_PROMPT =("This is a captcha grid. {question}\n""Number the cells left-to-right, top-to-bottom starting at 0. ""Answer ONLY JSON: {{\"cells\": [<indices>], \"confidence\": <0-1>}}")def_cfg(name, env, default=None):return os.environ.get(env)or config.get(name) default
_cfg
_cfg
_cfg
base key model _vlm_cfg
base key model
path_or_bytes
path_or_bytes
base64b64encodepath_or_bytesdecode
path_or_bytes f
base64b64encodefreaddecode
image prompt max_tokens stream
jsondumps
_vlm_cfg
prompt
_img_b64image
max_tokens
stream
encode
resp
out
raw resp
line rawdecode strip
linestartswith
chunk linestrip
chunk
data jsonloadschunk
ValueError
choice dataget
delta choiceget choiceget
field
deltagetfield
outappenddeltafield
joinout
image prompt max_tokens timeout stream
base key model _vlm_cfg
base key model
RuntimeError
url baserstrip
headers
key
with_stream
req urllibrequestRequest
url data_payloadimage prompt max_tokens with_stream headersheaders
urllibrequesturlopenreq timeouttimeout r
with_stream
_read_sser
data jsonloadr
msg dataget get
msgget msgget
stream
call
urlliberrorHTTPError exc
body excread
exccode
RuntimeError exc
call
urlliberrorHTTPError exc
RuntimeError exc
_CELL_KEYS
text
start ch text
ch
depth
end start text
textend
depth
textend
depth
depth
jsonloadstextstartend
ValueError
value
value
value k k v valueitems v
out
item value value value
item
item
outappenditem
item
found refindall item
found
outappendfound
out
text
text
obj _json_objectstext
key _CELL_KEYS
key obj
nums _intsobjkey
nums
conf objget
TypeError ValueError
conf
nums conf
m research join_CELL_KEYS text
m
nums n n refindall mgroup
nums
nums
m refinditer text
nums n n refindall mgroup
nums
nums
page question
cells out_path
osmakedirsospathdirnameout_path exist_ok
pagescreenshotpathout_path full_page
prompt GRID_PROMPTquestionquestion
text ask_vlmout_path prompt
idx conf _parse_cellstext
idx
clean i i idx i cells
clean conf
page question options out_path
osmakedirsospathdirnameout_path exist_ok
pagescreenshotpathout_path full_page
prompt
text ask_vlmout_path prompt
idx conf _parse_cellstext
i i idx i options conf
_cfg
_cfg
_cfg
audio_path language timeout
base key model _stt_cfg
base key
RuntimeError
audio_path f
audio fread
boundary base64urlsafe_b64encodeosurandomdecoderstrip
parts
name value
partsappend
encode
field model
language
field language
partsappend
encode
audio
partsappendencode
body joinparts
req urllibrequestRequest
baserstrip databody
headers
key
urllibrequesturlopenreq timeouttimeout r
data jsonloadr
urlliberrorHTTPError exc
RuntimeError exc
dataget strip
page download_to
language
osmakedirsospathdirnamedownload_to exist_ok
sel
el pagelocatorselfirst
elcount elis_visible
elclicktimeout
pagewait_for_timeout
Exception
url
sel
el pagelocatorselfirst
elcount
url elget_attribute elget_attribute
url
url elevaluate
Exception
url
Exception
url
RuntimeError
urllibrequesturlopenurl timeout r download_to f
fwriterread
text transcribedownload_to languagelanguage
text
RuntimeError
text
page cfg
kind cfgget lower
kind
solve_audio_captchapage languagecfgget
kind
idx conf solve_image_choicepage cfgget
optionscfgget
idx conf
idx conf solve_grid_captchapage cfgget
cellscfgget
idx conf
"""Склеить дельты SSE в текст. reasoning_content тоже берём.
Нужно потому, что не-стриминговый ответ на CPU-VLM идёт 10–20 с, а
приватный порт Instabox обрывает молчащий запрос примерно на 20-й
секунде (502). Стрим отдаёт заголовки сразу и живёт сколько нужно.
"""
=
[
]
for
in
:
=
.
(
"utf-8"
,
"replace"
)
.
(
)
if
not
.
(
"data:"
)
:
continue
=
[
5
:
]
.
(
)
if
==
"[DONE]"
:
break
try
:
=
.
(
)
except
:
continue
for
in
.
(
"choices"
)
or
[
]
:
=
.
(
"delta"
)
or
.
(
"message"
)
or
{
}
for
in
(
"content"
,
"reasoning_content"
)
:
if
.
(
)
:
.
(
[
]
)
return
""
.
(
)
def
ask_vlm
(
,
,
=
600
,
=
180
,
=
True
)
:
"""Один запрос к VLM. Возвращает текст ответа или бросает RuntimeError."""
,
,
=
(
)
if
not
(
and
and
)
:
raise
(
"VLM не настроен: config.vlm_api_base/vlm_api_key/vlm_model"
)
=
.
(
"/"
)
+
"/chat/completions"
=
{
"Content-Type"
:
"application/json"
,
"Authorization"
:
"Bearer "
+
}
def
call
(
)
:
=
.
.
(
,
=
(
,
,
,
)
,
=
)
with
.
.
(
,
=
)
as
:
if
:
return
(
)
=
.
(
)
=
(
.
(
"choices"
)
or
[
{
}
]
)
[
0
]
.
(
"message"
)
or
{
}
return
(
.
(
"content"
)
or
""
)
+
"\n"
+
(
.
(
"reasoning_content"
)
or
""
)
if
:
try
:
return
(
True
)
except
.
.
as
:
=
.
(
)
[
:
200
]
# провайдер без SSE — дожимаем обычным запросом
if
.
not
in
(
400
,
404
,
405
,
501
)
:
raise
(
f"VLM HTTP {exc.code}: {body!r}"
)
from
try
:
return
(
False
)
except
.
.
as
:
raise
(
f"VLM HTTP {exc.code}: {exc.read()[:200]!r}"
)
from
=
(
"cells"
,
"answer"
,
"tiles"
,
"selected"
,
"indices"
)
def
_json_objects
(
)
:
"""Все сбалансированные {...} из текста, которые парсятся как JSON."""
for
,
in
enumerate
(
)
:
if
!=
"{"
:
continue
=
0
for
in
range
(
,
len
(
)
)
:
if
[
]
==
"{"
:
+=
1
elif
[
]
==
"}"
:
-=
1
if
==
0
:
try
:
yield
.
(
[
:
+
1
]
)
except
:
pass
break
def
_ints
(
)
:
"""Привести что угодно к списку индексов: [0,4,6], "0,4,6", {"1": true}."""
if
isinstance
(
,
dict
)
:
=
[
for
,
in
.
(
)
if
]
=
[
]
for
in
(
if
isinstance
(
,
(
list
,
tuple
)
)
else
[
]
)
:
if
isinstance
(
,
bool
)
:
continue
if
isinstance
(
,
(
int
,
float
)
)
:
.
(
int
(
)
)
elif
isinstance
(
,
str
)
:
=
.
(
r"\d+"
,
)
if
:
.
(
int
(
[
0
]
)
)
return
def
_parse_cells
(
)
:
"""Достать список индексов из вольного ответа модели.
Форматы отличаются: `{"cells": [...]}`, `{"answer": [...]}`, голая
строка `answer: [0,4,6]` или просто `[0,4,6]`. Модель, которая
ответила правильно, но не тем ключом, не должна давать пустой клик.
"""
if
not
:
return
None
,
0.0
for
in
(
)
:
for
in
:
if
in
:
=
(
[
]
)
if
:
try
:
=
float
(
.
(
"confidence"
)
or
0.6
)
except
(
,
)
:
=
0.6
return
,
# ключ без валидного JSON вокруг: "cells": [0, 4, 6]
=
.
(
r'"?(?:%s)"?\s*:\s*\[([^\]]*)\]'
%
"|"
.
(
)
,
)
if
:
=
[
int
(
)
for
in
.
(
r"\d+"
,
.
(
1
)
)
]
if
:
return
,
0.5
# совсем без ключа — единственный JSON-массив чисел в ответе
for
in
.
(
r"\[([\d\s,]+)\]"
,
)
:
=
[
int
(
)
for
in
.
(
r"\d+"
,
.
(
1
)
)
]
if
:
return
,
0.4
return
None
,
0.0
def
solve_grid_captcha
(
,
=
"Select all images matching the prompt."
,
=
9
,
=
"data/captcha-grid.png"
)
:
"""Снять сетку со страницы и вернуть индексы ячеек для клика.
`cells` — ожидаемое число ячеек (3×3 = 9, 4×4 = 16). Модель может
вернуть индексы вне диапазона — они отбрасываются.
"""
.
(
.
.
(
)
or
"."
,
=
True
)
.
(
=
,
=
False
)
=
.
format
(
=
)
=
(
,
)
,
=
(
)
if
not
:
return
[
]
,
0.0
=
sorted
(
{
for
in
if
0
<=
<
}
)
return
,
def
solve_image_choice
(
,
,
=
4
,
=
"data/captcha-choice.png"
)
:
"""Капча-выбор из N картинок: вернуть индексы картинок, которые просят."""
.
(
.
.
(
)
or
"."
,
=
True
)
.
(
=
,
=
False
)
=
(
f"{question}\nThere are {options} image options, numbered left-to-right "
f"from 0. Answer ONLY JSON: {{\"cells\": [<indices>], \"confidence\": <0-1>}}"
"""Нажать кнопку аудио-капчи, скачать mp3, распознать.
Возвращает распознанный текст. Ошибка — если кнопки/URL нет или STT
не настроен: молча возвращать пустую строку нельзя, иначе реггер
отправит пустое поле и получит невнятный отказ.
"""
.
(
.
.
(
)
or
"."
,
=
True
)
# reCAPTCHA: кнопка переключения на аудио, затем ссылка на mp3
for
in
(
'#recaptcha-audio-button'
,
'button[title*="audio" i]'
,
'[aria-label*="audio" i]'
)
:
try
:
=
.
(
)
.
if
.
(
)
and
.
(
)
:
.
(
=
5000
)
.
(
1500
)
break
except
:
continue
=
None
for
in
(
'audio#audio-source'
,
'audio source'
,
'a[href$=".mp3"]'
)
:
try
:
=
.
(
)
.
if
.
(
)
:
=
.
(
"src"
)
or
.
(
"href"
)
if
:
break
try
:
=
.
(
"e => e.src || e.currentSrc"
)
except
:
pass
if
:
break
except
:
continue
if
not
:
raise
(
"аудио-капча: не нашёл ссылку на mp3"
)
with
.
.
(
,
=
60
)
as
,
open
(
,
"wb"
)
as
:
.
(
.
(
)
)
=
(
,
=
)
if
not
:
raise
(
"аудио-капча: STT вернул пустой текст"
)
return
def
step
(
,
)
:
"""Шаг флоу: единая точка для vision-капчи в реггере.
cfg = {"kind": "grid"|"choice"|"audio", "question": ..., "cells": 9,
"selector": "..."} — что нашлось в recon.
Возвращает dict с результатом, чтобы реггер сам решил, как применить.
"""