decodo-register — авторег Decodo (free DC proxies)
Decodo (ex-Smartproxy) даёт 1 GB datacenter-прокси трафика в месяц бесплатно на аккаунт: без карты, только подтверждение почты. Реггер делает аккаунты пачками и складывает в банк рабочие username:password к dc.decodo.com:10000.
# -*- coding: utf-8 -*-"""limits — квоты и расход по аккаунтам (ОБРАЗЕЦ под сервис с free-tier).
Это пример под конкретный тип сервиса (эндпоинты `/api/me/free-tier`,
`/api/keys` — из образца register.py). Под свой сервис правь эндпоинты и поля,
но принцип сохраняй:
Что сервис обычно отдаёт (проверяй на своём):
* `/api/me/free-tier` (только с сессией, т.е. после login):
req_used, reset_at, exhausted, used_pct, model_ids[], rpm_limit, plan…
Числового лимита токенов в ответе часто НЕТ — только «сколько уже сделано»
и дата сброса периода.
* `/api/keys`: дневные/недельные/месячные лимиты по ключу.
Поэтому «сколько осталось» считаем из двух источников:
1) серверные поля (req_used, exhausted, reset_at) — авторитетно для статуса;
2) локальный леджер моста data/usage.jsonl — реальные токены/запросы на аккаунт.
Модуль кэширует результат в data/limits.json, чтобы панель не логинилась
по всем аккаунтам на каждый запрос.
"""import json
import os
import threading
import time
from.import config
from.register import ServiceClient, list_models
LIMITS_FILE = os.path.join(config.DATA_DIR,"limits.json")
_lock = threading.Lock()# сколько секунд кэш считается свежим
CACHE_TTL =int(getattr(config,"LIMITS_CACHE_TTL",600))
LIMITS_FILE encoding f
jsonloadf
OSError ValueError
data
tmp
tmp encoding f
jsondumpdata f ensure_ascii indent
osreplacetmp LIMITS_FILE
email password proxy attempts backoff
last
att attempts
c ServiceClientproxyproxy
res cloginemail password
Exception exc
last
timesleepbackoff att
resget
last
last
resget resget lower
timesleepbackoff att
last
email last timetime
out email timetime
ft csessionget timeoutjson
outupdate
ftget
ftget
ftget
ftget
ftget
ftget
ftget
ftget
ftget
ftget
ftget
ftget
Exception exc
out
keys csessionget timeoutjsonget
keys
out keysget
out keysget
Exception
out
agg
path ospathjoinconfigDATA_DIR
ospathexistspath
agg
path encoding f
line f
line linestrip
line
r jsonloadsline
ValueError
p rget
a aggsetdefaultp
a
a rget
a rget
rget
a r
a r a
a r
agg
PRICE_FILE ospathjoinconfigDATA_DIR
api_key force
force ospathexistsPRICE_FILE
PRICE_FILE encoding f
cached jsonloadf
cachedget
cached
OSError ValueError
prices
requests
r requestsget
headers
configUA timeout
m rjsonget
mid mget
p mget
pricesmid pget
pget
Exception
prices
tmp
tmp encoding f
jsondump prices timetime f ensure_ascii indent
osreplacetmp PRICE_FILE
prices
prices model prompt_tokens completion_tokens
mid model
p
midendswith
p pricesgetmid
p
p pricesgetmid
p
prompt_tokens pget \
completion_tokens pget
agg
path ospathjoinconfigDATA_DIR
ospathexistspath
agg
path encoding f
line f
line linestrip
line
r jsonloadsline
ValueError
p rget
a aggsetdefaultp
a
a rget
a rget
a rget
m rget
am agetm
rget
a r
a r a
a r
agg
accounts proxy only_missing max_workers
on_progress pause
concurrentfutures ThreadPoolExecutor
cache _load_cache
accs cacheget
now timetime
todo
a accounts
email aget
email aget
prev accsgetemail
only_missing prev now prevget CACHE_TTL
todoappenda
done
a
q account_quotaa a proxyproxy
timesleeppause
done
on_progress
on_progressdone todo
Exception
a q
todo
ThreadPoolExecutormax_workersmax_workers ex
email q exwork todo
accsemail q
cache accs
cache now
_lock
_save_cachecache
cache
accounts
results load_accounts
accounts accounts accounts load_accounts
key aget a accounts aget
prices price_tablekey key
agg
path ospathjoinconfigDATA_DIR
ospathexistspath
path encoding f
line f
line linestrip
line
r jsonloadsline
ValueError
m rget
a aggsetdefaultm
a
a rget
a rget
a rget
rows
mid a aggitems
base mid midendswith mid
p pricesgetbase pricesgetmid
toks a a
rowsappend
mid
a
a
a
toks
a
pget
pget
config
pget pget
pget pget
rowssortkey r r
rows rows
accounts
results load_accounts
accounts accounts accounts load_accounts
cache _load_cache
quotas cacheget
usage usage_detailed
rows
total_requests total_prompt total_completion
total_usd
free_accounts exhausted_accounts
model_ok
a accounts
email aget
key aget
prefix key
q quotasgetemail
u usagegetprefix
aget qget
free_accounts
req uget
pt uget
ct uget
usd uget
total_requests req
total_prompt pt
total_completion ct
total_usd usd
m qget
model_okm model_okgetm
pct qget
est_total_usd
pct pct
est_total_usd usd pct
_allow config
local_left_usd _allow usd _allow
local_exhausted qget
_allow usd _allow
local_exhausted
exhausted_accounts
reset_at qget
reset_at local_exhausted uget
datetime _dt
t0 _dtdatetimestrptimeu
reset_at t0 _dttimedeltadaysstrftime
Exception
reset_at
rowsappend
email
prefix
aget
local_left_usd
local_exhausted
reset_at
local_exhausted
qget
pct
est_total_usd
qget
qget
qget
qget
req
pt
ct
pt ct
usd
uget
qget
qget
est_allowances r r rows rget
avg_usd_per_token total_usd total_prompt total_completion \
total_prompt total_completion
cfg_allow config
allow_per_acc cfg_allow est_allowances est_allowances
est_allowances
alive_n rows exhausted_accounts
spent_usd total_usd
remaining_usd
remaining_tokens
allow_per_acc
remaining_usd allow_per_acc alive_n spent_usd
avg_usd_per_token
remaining_tokens remaining_usd avg_usd_per_token
spent_out r rows
allow_per_acc rget allow_per_acc
rows
rows
free_accounts
exhausted_accounts
alive_n
total_requests
total_prompt
total_completion
total_prompt total_completion
spent_usd
allow_per_acc
remaining_usd
remaining_tokens
avg_usd_per_token avg_usd_per_token
spent_out
model_ok
cacheget
cfg_allow
est_allowances
api_key proxy
out
m list_modelsapi_key proxy
mendswith
outappend m
out
api_key models proxy
register test_key
models models m m list_modelsapi_key proxy mendswith
res
m models
ok _ detail test_keyapi_key modelm proxyproxy
resappend m ok detail
res
# ── своя тарификация ────────────────────────────────────────────────────
# У части сервисов лимит измеряется НЕ в токенах и НЕ в запросах, а в долларовой
# стоимости по прайсу («list-price value of the work»), период — скользящие
# 7×24ч от ПЕРВОГО запроса (не календарная неделя). Тогда, чтобы знать «сколько
# осталось», надо считать $: токены × цена платного аналога модели.
# У своего сервиса проверь, в чём именно измеряется лимит, и правь под него.
=
.
.
(
.
,
"prices.json"
)
def
price_table
(
,
=
False
)
:
"""{model_id: {in, out}} — цены за 1M токенов. Кэш в data/prices.json."""
if
not
and
.
.
(
)
:
try
:
with
open
(
,
=
"utf-8"
)
as
:
=
.
(
)
if
.
(
"prices"
)
:
return
[
"prices"
]
except
(
,
)
:
pass
=
{
}
try
:
import
=
.
(
f"{config.BASE_URL}/v1/models"
,
=
{
"Authorization"
:
f"Bearer {api_key}"
,
"User-Agent"
:
.
}
,
=
20
)
for
in
(
.
(
)
.
(
"data"
)
or
[
]
)
:
=
.
(
"id"
,
""
)
=
.
(
"pricing"
)
or
{
}
[
]
=
{
"in"
:
.
(
"input_usd_per_1m"
,
0
)
or
0
,
"out"
:
.
(
"output_usd_per_1m"
,
0
)
or
0
}
except
:
return
{
}
if
:
=
f"{PRICE_FILE}.tmp"
with
open
(
,
"w"
,
=
"utf-8"
)
as
:
.
(
{
"prices"
:
,
"ts"
:
.
(
)
}
,
,
=
False
,
=
2
)
.
(
,
)
return
def
usd_for
(
,
,
,
)
:
"""Стоимость запроса по прайсу.
ВАЖНО: у free-роутов pricing = 0 (они бесплатны), но лимит сервиса
считается по list-price — поэтому для `*:free` всегда берём цену ПЛАТНОГО
аналога, а не нулевую запись самой free-модели.
"""
=
or
""
=
None
if
.
(
":free"
)
:
=
.
(
[
:
-
5
]
)
if
is
None
:
=
.
(
)
if
not
:
return
0.0
return
(
or
0
)
/
1e6
*
(
.
(
"in"
)
or
0
)
+
(
or
0
)
/
1e6
*
(
.
(
"out"
)
or
0
)
def
usage_detailed
(
)
:
"""Леджер с $: по каждому префиксу ключа — токены, запросы, usd, разбивка по моделям."""
=
{
}
=
.
.
(
.
,
"usage.jsonl"
)
if
not
.
.
(
)
:
return
with
open
(
,
=
"utf-8"
)
as
:
for
in
:
=
.
(
)
if
not
:
continue
try
:
=
.
(
)
except
:
continue
=
(
.
(
"key_prefix"
)
or
""
)
[
:
24
]
=
.
(
,
{
"requests"
:
0
,
"prompt_tokens"
:
0
,
"completion_tokens"
:
0
,
"usd"
:
0.0
,
"models"
:
{
}
,
"last_ts"
:
None
,
"first_ts"
:
None
}
)
[
"requests"
]
+=
1
[
"prompt_tokens"
]
+=
.
(
"prompt_tokens"
)
or
0
[
"completion_tokens"
]
+=
.
(
"completion_tokens"
)
or
0
[
"usd"
]
+=
.
(
"usd"
)
or
0.0
=
.
(
"model"
)
or
"?"
[
"models"
]
[
]
=
[
"models"
]
.
(
,
0
)
+
1
if
.
(
"ts"
)
:
[
"last_ts"
]
=
[
"ts"
]
if
[
"first_ts"
]
is
None
or
[
"ts"
]
<
[
"first_ts"
]
:
[
"first_ts"
]
=
[
"ts"
]
# начало rolling-окна аккаунта
return
def
collect
(
,
=
None
,
=
False
,
=
3
,
=
None
,
=
1.0
)
:
"""Собрать квоты по списку аккаунтов, кэш в data/limits.json.
Логин рейт-лимитится, поэтому:
* параллельность низкая (по умолчанию 3);
* пауза `pause` секунд после каждого логина;
* на 429 внутри account_quota — ретрай с бэкоффом.
only_missing=True — не трогать тех, у кого свежий кэш (инкрементальный обход).
"""
from
.
import
=
(
)
=
.
(
"accounts"
,
{
}
)
=
.
(
)
=
[
]
for
in
:
=
.
(
"email"
)
if
not
or
not
.
(
"password"
)
:
continue
=
.
(
)
if
and
and
(
-
(
.
(
"checked_at"
)
or
0
)
)
<
:
continue
.
(
)
=
[
0
]
def
work
(
)
:
=
(
[
"email"
]
,
[
"password"
]
,
=
)
.
(
)
[
0
]
+=
1
if
:
try
:
(
[
0
]
,
len
(
)
)
except
:
pass
return
[
"email"
]
,
if
:
with
(
=
)
as
:
for
,
in
.
map
(
,
)
:
[
]
=
[
"accounts"
]
=
[
"checked_at"
]
=
with
:
(
)
return
def
model_costs
(
=
None
)
:
"""Расход по КАЖДОЙ модели: запросы, токены, $ (наш учёт) + прайс.
Считается из леджера моста (data/usage.jsonl, поле model) — то есть
показывает, во что реально обходится каждая модель и сколько она «съела»
из лимита. Прайс — из /v1/models (цена платного аналога для *:free).
"""
from
.
import
=
if
is
not
None
else
(
)
=
next
(
(
.
(
"api_key"
)
for
in
if
.
(
"api_key"
)
)
,
None
)
=
(
)
if
else
{
}
=
{
}
=
.
.
(
.
,
"usage.jsonl"
)
if
.
.
(
)
:
with
open
(
,
=
"utf-8"
)
as
:
for
in
:
=
.
(
)
if
not
:
continue
try
:
=
.
(
)
except
:
continue
=
.
(
"model"
)
or
"?"
=
.
(
,
{
"requests"
:
0
,
"prompt_tokens"
:
0
,
"completion_tokens"
:
0
,
"usd"
:
0.0
}
)
[
"requests"
]
+=
1
[
"prompt_tokens"
]
+=
.
(
"prompt_tokens"
)
or
0
[
"completion_tokens"
]
+=
.
(
"completion_tokens"
)
or
0
[
"usd"
]
+=
.
(
"usd"
)
or
0.0
=
[
]
for
,
in
.
(
)
:
=
[
:
-
5
]
if
.
(
":free"
)
else
=
.
(
)
or
.
(
)
or
{
}
=
[
"prompt_tokens"
]
+
[
"completion_tokens"
]
.
(
{
"model"
:
,
"requests"
:
[
"requests"
]
,
"prompt_tokens"
:
[
"prompt_tokens"
]
,
"completion_tokens"
:
[
"completion_tokens"
]
,
"total_tokens"
:
,
"usd"
:
round
(
[
"usd"
]
,
6
)
,
"usd_per_1m_in"
:
.
(
"in"
)
,
"usd_per_1m_out"
:
.
(
"out"
)
,
# сколько токенов влезет в один лимит аккаунта по этой модели
"tokens_per_allowance"
:
(
int
(
getattr
(
,
"FREE_ALLOWANCE_USD_PER_ACCOUNT"
,
0
)
/
(
.
(
"in"
)
or
.
(
"out"
)
or
1
)
*
1e6
)
if
(
.
(
"in"
)
or
.
(
"out"
)
)
else
None
)
,
}
)
.
(
=
lambda
:
-
[
"usd"
]
)
return
{
"models"
:
,
"count"
:
len
(
)
}
def
summary
(
=
None
)
:
"""Сводка для панели: по аккаунтам + суммарно + реально доступные модели."""
from
.
import
=
if
is
not
None
else
(
)
=
(
)
=
.
(
"accounts"
,
{
}
)
=
(
)
=
[
]
=
=
=
0
=
0.0
=
=
0
=
{
}
for
in
:
=
.
(
"email"
)
=
.
(
"api_key"
)
or
""
=
[
:
24
]
=
.
(
)
or
{
}
=
.
(
)
or
{
}
# free-аккаунт определяем ЛОКАЛЬНО (по своему accounts.jsonl), а не по
# серверному кэшу: кэш мог быть собран раньше, когда аккаунтов было меньше
if
.
(
"free_tier_enabled"
)
or
.
(
"model_ids"
)
:
+=
1
=
.
(
"requests"
,
0
)
=
.
(
"prompt_tokens"
,
0
)
=
.
(
"completion_tokens"
,
0
)
=
.
(
"usd"
,
0.0
)
+=
+=
+=
+=
for
in
(
.
(
"model_ids"
)
or
[
]
)
:
[
]
=
.
(
,
0
)
+
1
# оценка полного лимита в $: если сервер дал used_pct, достраиваем пропорцию
=
.
(
"used_pct"
)
=
None
if
and
>
0
:
=
round
(
/
(
/
100.0
)
,
6
)
# ЛОКАЛЬНЫЙ остаток: лимит аккаунта минус наш учёт расхода.
# Считается из своего леджера, без похода на сервер.
=
getattr
(
,
"FREE_ALLOWANCE_USD_PER_ACCOUNT"
,
None
)
=
round
(
max
(
0.0
,
-
)
,
6
)
if
else
None
# Исчерпан: сервер сказал exhausted ИЛИ наш учёт выбрал лимит.
=
bool
(
.
(
"exhausted"
)
)
or
(
bool
(
)
and
>=
)
# Когда лимит вернётся: серверный reset_at, иначе первое использование
# + 7×24ч (личное скользящее окно сервиса от первого запроса).
if
:
+=
1
=
.
(
"reset_at"
)
if
not
and
and
.
(
"first_ts"
)
:
try
:
import
as
=
.
.
(
[
"first_ts"
]
[
:
19
]
,
"%Y-%m-%dT%H:%M:%S"
)
=
(
+
.
(
=
7
)
)
.
(
"%Y-%m-%dT%H:%M:%SZ"
)
except
:
=
None
.
(
{
"email"
:
,
"api_key_prefix"
:
,
"free"
:
.
(
"free_tier_enabled"
)
,
"local_remaining_usd"
:
,
"local_exhausted"
:
,
"reset_at_est"
:
,
"exhausted"
:
,
"req_used"
:
.
(
"req_used"
)
,
"used_pct"
:
,
"est_total_usd"
:
,
"reset_at"
:
.
(
"reset_at"
)
,
"period_started_at"
:
.
(
"period_started_at"
)
,
"plan"
:
.
(
"plan"
)
,
"models"
:
.
(
"model_ids"
)
or
[
]
,
"local_requests"
:
,
"prompt_tokens"
:
,
"completion_tokens"
:
,
"total_tokens"
:
+
,
"usd"
:
round
(
,
6
)
,
"last_ts"
:
.
(
"last_ts"
)
,
"error"
:
.
(
"error"
)
,
"checked_at"
:
.
(
"checked_at"
)
,
}
)
=
[
[
"est_total_usd"
]
for
in
if
.
(
"est_total_usd"
)
]
# средняя цена токена по нашему леджеру (микс моделей) — для пересчёта $ ⇄ токены
=
(
/
(
+
)
)
if
(
+
)
else
None
# оценка лимита на аккаунт в $: 1) из конфига, 2) из серверного used_pct
=
getattr
(
,
"FREE_ALLOWANCE_USD_PER_ACCOUNT"
,
None
)
=
or
(
round
(
sum
(
)
/
len
(
)
,
4
)
if
else
None
)
=
len
(
)
-
=
round
(
,
6
)
=
None
=
None
if
:
=
round
(
max
(
0.0
,
*
-
)
,
6
)
if
:
=
int
(
/
)
# сколько аккаунтов уже на нуле по нашему учёту
=
sum
(
1
for
in
if
and
(
.
(
"usd"
)
or
0
)
>=
)
return
{
"accounts"
:
,
"totals"
:
{
"accounts"
:
len
(
)
,
"free_accounts"
:
,
"exhausted"
:
,
"alive"
:
,
"requests"
:
,
"prompt_tokens"
:
,
"completion_tokens"
:
,
"total_tokens"
:
+
,
"usd"
:
,
"usd_per_account_est"
:
,
"usd_remaining_est"
:
,
"tokens_remaining_est"
:
,
"avg_usd_per_1k_tokens"
:
round
(
*
1000
,
6
)
if
else
None
,
"spent_out_local"
:
,
"local_ledger"
:
True
,
# расход считается локально (usage.jsonl), не с сервера
}
,
"models_available"
:
,
"checked_at"
:
.
(
"checked_at"
)
,
"billing"
:
{
"unit"
:
"USD list-price value"
,
"period"
:
"rolling 7×24h от ПЕРВОГО free-запроса (не календарная неделя)"
,
"on_exhausted"
:
"free-роут отдаёт rate-limit ошибку (429); баланс не тратится"
,
"allowance_source"
:
(
"config.FREE_ALLOWANCE_USD_PER_ACCOUNT"
if
else
(
"оценка из серверного used_pct"
if
else
"неизвестно — нужно измерить"
)
)
,
"note"
:
"сервис считает лимит в $ по прайсу, не в токенах/запросах. "
"Расход считаем САМИ из своего леджера моста (usage.jsonl) в реальном "
"exhausted, reset_at) — только по кнопке, для сверки."
,
}
,
}
def
check_models
(
,
=
None
)
:
"""Какие модели РЕАЛЬНО отвечают (не просто числятся в /v1/models).
Возвращает [{id, ok, detail}]. Голый ':free' у апстрима битый — пометится ok=false.
"""
=
[
]
for
in
(
,
)
:
if
not
.
(
":free"
)
:
continue
.
(
{
"id"
:
}
)
return
def
probe_models
(
,
=
None
,
=
None
)
:
"""Живая проверка: по каждой модели один короткий запрос."""