decodo-register · VibeGit
decodo-register decodo-register — авторег Decodo (free DC proxies)
Decodo (ex-Smartproxy) даёт 1 GB datacenter-прокси трафика в месяц бесплатно на аккаунт: без карты, только подтверждение почты. Реггер делает аккаунты пачками и складывает в банк рабочие username:password к dc.decodo.com:10000.
decodo-register / panel / server.py 1068 строк · изменён 14 нояб., 06:52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
"""Панель реггера — PANEL-SPEC (stdlib http.server + threading).
Запуск: bash start.sh (порт и имя сервиса — свои; реестр autoreg/docs/PANEL-PORTS.md)
→ http://127.0.0.1:<порт>
Эндпоинты (все JSON, слушаем только 127.0.0.1):
GET / index.html
GET /api/summary сводка: counts, капча, последний прогон, мост <порт>
GET /api/accounts аккаунты (results.load_accounts) + статус ключа из
data/keys_state.json (alive→ok, cooldown→unknown,
dead→failed, нет записи→unknown)
POST /api/accounts/check перепроверка ключей (test_key; ≤5 синхронно, иначе фон)
POST /api/register {count} → фоновый прогон {job_id}
GET /api/job прогресс прогона + хвост лога
POST /api/job/stop мягкий стоп прогона
GET /api/captcha провайдер/статус капчи
GET /api/models живой /v1/models по первому ключу; fallback — из конфига
GET /api/pool data/keys_state.json моста + counts
GET /api/logs?tail=200 хвост data/panel.log
"""
import argparse
import json
import os
import re
import sys
import threading
import time
import uuid
from http. server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib. parse import parse_qs, urlparse
ROOT = os. path. dirname( os. path. dirname( os. path. abspath( __file__) ) )
sys. path. insert ROOT
requests
core config
core results
core register register_one test_key list_models
DATA_DIR config DATA_DIR
JOB_FILE os path join DATA_DIR
LOG_FILE os path join DATA_DIR
KEYS_STATE_FILE os path join DATA_DIR
INDEX_FILE os path join ROOT
VERSION
SERVICE_NAME config get
config get replace replace rstrip
BRIDGE_PORT config get
BRIDGE_START config get
PANEL_PORT config get
_log_lock threading Lock
msg
line
line flush
line
lines
LOG_FILE encoding errors f
data f readlines
OSError
ln rstrip ln data lines
path lines
path encoding errors f
data f readlines
OSError
ln rstrip ln data lines
path default
path encoding f
json load f
ValueError OSError
default
_write_lock threading Lock
path obj
tmp
tmp encoding f
json dump obj f ensure_ascii indent
f flush
_write_lock
os replace tmp path
path
path
path
path os path isabs path os path normpath os path join ROOT path
r requests get timeout
r status_code
Exception
os path exists KEYS_STATE_FILE
raw read_json KEYS_STATE_FILE
raw
raw
src raw get raw get raw
out
k v src items
k
v
out k v
v
out k v
out raw
api_key keys_state
api_key
entry keys_state get api_key
entry
k v keys_state items
api_key startswith k k startswith api_key
entry v
entry
st entry get lower
get st
row keys_state
row get
key_status row get keys_state
row get
row get
row get
Exception
IDLE
self
self lock threading Lock
self stop_event threading Event
self state self IDLE
saved read_json JOB_FILE
saved saved get
self state self IDLE saved
self thread
self
self lock
self state
self
self lock
self state
self kw
self lock
self state update kw
snap self state
os makedirs DATA_DIR exist_ok
write_json_atomic JOB_FILE snap
OSError
self count workers
self lock
self state
job_id uuid uuid4
self state self IDLE job_id
time time count
workers
snap self state
self stop_event clear
write_json_atomic JOB_FILE snap
self thread threading Thread target self _run args count workers
name daemon
self thread start
job_id
self
self is_running
self stop_event
log
self
core proxy proxy_mod
rot proxy_mod make_rotator
rot
rot __name__
log
log
rot
log
Exception exc
log
self rot on_step
proxy_try
acc register_one proxy rot rot
on_step on_step
StopRequested
Exception exc
acc
log
err_low acc get lower
acc get proxy_try
acc
w err_low w
log
acc
self acc ok fails_in_row last_error
self lock
acc get
last_error acc
status
fails_in_row
results save_account acc
ok
fails_in_row
status
self state
self state ok
self state self state
acc get status
snap self state
write_json_atomic JOB_FILE snap
OSError
acc get
log
log
ok fails_in_row last_error
self stopped ok last_error
snap self snapshot
stopped self stop_event is_set
status
ok snap
status
status
self _update status status ok ok finished_at time time
last_error last_error current currents
log
last_error
self count workers
workers
self _run_parallel count workers
log
rot self _setup_proxies
ok fails_in_row last_error stopped
i count
self stop_event is_set
stopped
log
self _update current i
msg idx i
m re msg
m
self _update current idx m group
m group
m group
log msg
self stop_event is_set
StopRequested
acc self _register_once rot on_step
acc
stopped
ok fails_in_row last_error self _account_result
acc ok fails_in_row last_error
fails_in_row config
last_error
log
i count self stop_event is_set
has_proxies rot rot
delay has_proxies config BATCH_INTERVAL_SEC
log
self stop_event wait delay
stopped
Exception exc
last_error
log
self _update status last_error last_error
finished_at time time current currents
self _finish stopped ok last_error
self count workers
concurrent futures ThreadPoolExecutor
log
rot self _setup_proxies
rot rot __name__ rot workers
workers rot
log
tasks count
queue_lock threading Lock
shared
CB config
slot kw
self lock
cur self state get workers
row cur slot
row update kw
cur slot row
self state cur
snap self state
write_json_atomic JOB_FILE snap
OSError
slot
shared self stop_event is_set
queue_lock
tasks
idx tasks pop
log
slot_update slot index idx step steps_total label
msg s slot i idx
m re msg
m
slot_update s index i step m group
steps_total m group
label m group
log
self stop_event is_set
StopRequested
acc self _register_once rot on_step
pause_sec
queue_lock
shared acc
shared shared shared \
self _account_result acc acc
shared shared
shared
slot_update slot done
shared CB
shared CB
shared
shared
log
shared
pause_sec
pause_sec self stop_event is_set
self stop_event wait pause_sec
shared
time sleep
ThreadPoolExecutor max_workers workers ex
ex worker workers
Exception exc
shared
log
self _update status last_error shared
finished_at time time currents
self _finish shared shared shared
JOB JobRunner
LIMITS_STATE
_limits_lock threading Lock
_bg_stop threading Event
v os environ get
v
v
ValueError
v config get
TypeError ValueError
v
v v
core limits
accounts results load_accounts
LIMITS_STATE accounts
log
done total
LIMITS_STATE done
LIMITS_STATE total
limits collect accounts only_missing max_workers on_progress prog
LIMITS_STATE LIMITS_STATE
log
Exception exc
LIMITS_STATE
log
LIMITS_STATE
LIMITS_STATE time time
_limits_lock
LIMITS_STATE
LIMITS_STATE update running done total error
started_at time time finished_at
threading Thread target _limits_job name daemon start
interval _limits_bg_interval
LIMITS_STATE interval
interval
LIMITS_STATE
log
first interval
log
_bg_stop wait first
_bg_stop is_set
LIMITS_STATE
LIMITS_STATE
JOB is_running
LIMITS_STATE
log
LIMITS_STATE
limits_start
LIMITS_STATE time time interval
_bg_stop wait interval
_check_lock threading Lock
_check_state
_key_checks
_key_checks_lock threading Lock
acc
acc get
ok _m detail test_key acc
Exception exc
acc get exc
acc get ok detail
key acc get
key
acc get
model config FALLBACK_FREE_MODELS
ok model detail test_key key model model
Exception exc
acc get exc
acc get ok
email status note
_key_checks_lock
_key_checks email status note time time
mark status
log
count_hint
accs results load_accounts
total accs
accs
total
log
checked ok
acc accs
email status note _check_one acc
_apply_check email status note
checked
ok status
log
checked ok
_check_lock
_check_state
_check_state
_check_state update running checked total total ok
started_at time time finished_at
threading Thread target _check_worker args accs name
daemon start
total
accs
log
ok
acc accs
email status note _check_one acc
_apply_check email status note
ok status
_check_lock
_check_state
_check_state ok
_check_lock
_check_state update running finished_at time time
log
camoufox _resolve config CAMOUFOX_PYTHON
core engines engines_mod
engines engines_mod available
Exception
engines
vlm_base config get
vlm_model config get
has_vlm vlm_base config get vlm_model
has_cls config get config get
has_stt config get config get
camoufox os path exists camoufox
config CAPSOLVER_API_KEY
camoufox
engines
config get
config get
vlm_model
vlm_base
has_vlm
has_cls
config get has_stt
has_stt
config get strip
accs results load_accounts
key a get a accs a get
ids live err
key
ids list_models key
live ids
Exception exc
err exc
err
free_set
core limits limits_mod
cache limits_mod _load_cache get
q cache values
m q get
free_set add m
free_set add m
Exception
now time strftime time gmtime
models
live
mid ids
is_free_id mid endswith
base mid is_free_id mid
on_free_tier mid free_set base free_set is_free_id
on_free_tier
status note
status note
models append mid base status
note now
source
mid config FALLBACK_FREE_MODELS
models append
mid mid mid endswith mid
err
source err
free_models m m models m
models source live
free_models models
m m free_models
BaseHTTPRequestHandler
server_version VERSION
self args
self code body ctype
raw body body json dumps body ensure_ascii encode
self send_response code
self send_header ctype ctype
self send_header raw
self send_header
self end_headers
self wfile write raw
BrokenPipeError
self code msg
self _send code msg
self
n self headers get
ValueError
n
n
data json loads self rfile read n decode
ValueError UnicodeDecodeError
data data
self
url urlparse self path
path query url path parse_qs url query
path
INDEX_FILE f
self _send f read
OSError
self _err
path
self _send self _summary
path
keys_state _ load_keys_state
_key_checks_lock
checks _key_checks
core limits limits_mod
usage limits_mod usage_detailed
Exception
usage
lim limits_mod summary
lim_by_email r get r r lim get
Exception
lim_by_email
out
row results load_accounts
pub public_account row keys_state
u usage get pub get
pub u get
pub u get \
u get
pub u get
lr lim_by_email get pub get
pub lr get pub
pub lr get lr get
pub lr get
chk checks get pub
chk pub
pub chk
chk
pub chk
pub chk
out append pub
self _send out
path
snap JOB snapshot
snap log_tail
self _send snap
path
self _send captcha_info
path
self _send models_payload
path
core limits
self _send limits summary
path
core limits
self _send limits model_costs
path
self _send LIMITS_STATE
path
self _send self _pool
path
tail query get
ValueError
tail
self _send self _bridge_requests tail
path
tail query get
ValueError
tail
self _send _tail_file
os path join config DATA_DIR tail
path
tail query get
ValueError
tail
lines log_tail tail
self _send lines lines
self _err
self
keys_state _ load_keys_state
accs results load_accounts
counts accs
row accs
row get row get
chk _key_checks get row get
chk
st chk
row get
st
row get
st
st
st key_status row get keys_state
counts st counts get st
job JOB snapshot
SERVICE_NAME
VERSION
job
self server server_port
counts
config CAPSOLVER_API_KEY
config get
config get
config get
config get config get
config get
config get
config get
config get config get
job job
job job
BRIDGE_PORT bridge_alive
BRIDGE_START
self tail
path os path join config DATA_DIR
rows
path encoding errors f
lines f readlines tail
OSError
lines
lat
errs
ln lines
r json loads ln
ValueError
st r get
st st
r get
lat append r
errs
rows append
r get
r get
r get
st
r get
r get r get
r get
rows reverse
lat sort
stats
rows
errs
lat lat lat
lat lat lat
lat lat
rows stats
BRIDGE_PORT bridge_alive
BRIDGE_START
self
keys raw load_keys_state
raw
BRIDGE_PORT bridge_alive
BRIDGE_START
counts keys
v keys values
st v get lower
counts st st
keys counts
raw get raw
BRIDGE_PORT bridge_alive
BRIDGE_START
self
path urlparse self path path
body self _body_json
body
self _err
path
limits_start
self _err
self _send
path
count body get
count count
TypeError ValueError
self _err
count
self _err
workers body get
TypeError ValueError
self _err
workers
self _err
job_id JOB start count workers workers
job_id
self _err
self _send job_id count workers
path
JOB stop
self _err
self _send
path
self _send accounts_check
self _err
ap argparse ArgumentParser description
ap add_argument default PANEL_PORT
ap add_argument default
args ap parse_args
os makedirs DATA_DIR exist_ok
args host
args host
srv ThreadingHTTPServer args host args port Handler
srv daemon_threads
threading Thread target limits_bg_loop name daemon start
log
srv serve_forever
KeyboardInterrupt
_bg_stop
srv server_close
__name__
main
(
0
,
)
import
from
import
from
import
from
.
import
,
,
=
.
=
.
.
(
,
"job.json"
)
=
.
.
(
,
"panel.log"
)
=
.
.
(
,
"keys_state.json"
)
=
.
.
(
,
"panel"
,
"static"
,
"index.html"
)
=
"1.0.0"
=
(
.
(
"service_name"
)
or
(
.
(
"base_url"
)
or
""
)
.
(
"https://"
,
""
)
.
(
"http://"
,
""
)
.
(
"/"
)
or
"<сервис>"
)
=
int
(
.
(
"bridge_port"
)
or
0
)
=
.
(
"bridge_start"
)
or
f"bash <путь-к-мосту>/start.sh"
=
int
(
.
(
"panel_port"
)
or
9900
)
=
.
(
)
def
log
(
)
:
"""Строка в stdout; start.sh ловит его tee'ом в data/panel.log.
(Прямая запись в файл убрана: иначе каждая строка дублируется.)"""
=
f" { time. strftime( '%Y-%m-%d %H:%M:%S' ) } { msg} "
print
(
,
=
True
)
return
def
log_tail
(
=
200
)
:
try
:
with
open
(
,
=
"utf-8"
,
=
"replace"
)
as
:
=
.
(
)
except
:
return
[
]
return
[
.
(
"\n"
)
for
in
[
-
max
(
1
,
)
:
]
]
def
_tail_file
(
,
=
200
)
:
"""Хвост произвольного файла (для логов моста)."""
try
:
with
open
(
,
=
"utf-8"
,
=
"replace"
)
as
:
=
.
(
)
except
:
return
[
]
return
[
.
(
"\n"
)
for
in
[
-
max
(
1
,
)
:
]
]
def
read_json
(
,
)
:
try
:
with
open
(
,
=
"utf-8"
)
as
:
return
.
(
)
except
(
,
)
:
return
=
.
(
)
def
write_json_atomic
(
,
)
:
"""Атомарно, потокобезопасно: уникальный tmp на вызов + лок на replace."""
=
f" { path} . { os. getpid( ) } . { threading. get_ident( ) } .tmp"
with
open
(
,
"w"
,
=
"utf-8"
)
as
:
.
(
,
,
=
False
,
=
2
)
.
(
)
with
:
.
(
,
)
def
_resolve
(
)
:
"""Путь из конфига может быть относительным — резолвим от корня реггера."""
if
not
:
return
return
if
.
.
(
)
else
.
.
(
.
.
(
,
)
)
def
bridge_alive
(
)
:
"""Быстрый GET /health моста (таймаут 2с); мост выключен — не падаем."""
try
:
=
.
(
f"http://127.0.0.1: { BRIDGE_PORT} /health"
,
=
2
)
return
.
==
200
except
:
return
False
def
load_keys_state
(
)
:
"""data/keys_state.json → dict key → state (толерантно к форме файла).
Ожидаемые формы (мост ещё в разработке, принимаем любую):
{"keys": {"thk_...": {"status": "alive", ...}}, ...}
{"thk_...": {"status": "cooldown"}, ...}
{"thk_...": "dead", ...}
Возвращает (keys_dict, raw_payload или None если файла нет).
"""
if
not
.
.
(
)
:
return
{
}
,
None
=
(
,
None
)
if
not
isinstance
(
,
dict
)
:
return
{
}
,
=
.
(
"keys"
)
if
isinstance
(
.
(
"keys"
)
,
dict
)
else
=
{
}
for
,
in
.
(
)
:
if
not
isinstance
(
,
str
)
:
continue
if
isinstance
(
,
dict
)
:
[
]
=
elif
isinstance
(
,
str
)
:
[
]
=
{
"status"
:
}
return
,
def
key_status
(
,
)
:
"""Статус ключа аккаунта по keys_state: alive→ok, cooldown→unknown,
dead→failed, нет записи→unknown. Матчинг: точный или по префиксу."""
if
not
:
return
"unknown"
=
.
(
)
if
is
None
:
for
,
in
.
(
)
:
if
.
(
)
or
.
(
[
:
20
]
)
:
=
break
if
is
None
:
return
"unknown"
=
str
(
.
(
"status"
)
or
""
)
.
(
)
return
{
"alive"
:
"ok"
,
"dead"
:
"failed"
,
"cooldown"
:
"unknown"
,
"exhausted"
:
"exhausted"
}
.
(
,
"unknown"
)
def
public_account
(
,
)
:
return
{
"email"
:
.
(
"email"
)
or
"?"
,
"status"
:
(
.
(
"api_key"
)
,
)
,
"api_key"
:
.
(
"api_key"
)
,
"free_tier_enabled"
:
bool
(
.
(
"free_tier_enabled"
)
)
,
"created_at"
:
.
(
"created_at"
)
,
}
class
StopRequested
(
)
:
pass
class
JobRunner
:
"""Один фон-прогон за раз: прогресс в data/job.json, лог — в panel.log."""
=
{
"job_id"
:
None
,
"status"
:
"idle"
,
"started_at"
:
None
,
"finished_at"
:
None
,
"done"
:
0
,
"total"
:
0
,
"ok"
:
0
,
"last_error"
:
None
,
"results"
:
[
]
,
"current"
:
None
,
"workers"
:
1
,
"currents"
:
[
]
}
def
__init__
(
)
:
.
=
.
(
)
.
=
.
(
)
.
=
dict
(
.
)
=
(
,
None
)
if
isinstance
(
,
dict
)
and
.
(
"status"
)
!=
"running"
:
.
=
{
**
.
,
**
}
.
=
None
def
snapshot
(
)
:
with
.
:
return
dict
(
.
)
def
is_running
(
)
:
with
.
:
return
.
[
"status"
]
==
"running"
def
_update
(
,
**
)
:
with
.
:
.
.
(
)
=
dict
(
.
)
try
:
.
(
,
=
True
)
(
,
)
except
:
pass
def
start
(
,
,
=
1
)
:
with
.
:
if
.
[
"status"
]
==
"running"
:
return
None
=
"job-"
+
.
(
)
.
hex
[
:
8
]
.
=
{
**
.
,
"job_id"
:
,
"status"
:
"running"
,
"started_at"
:
.
(
)
,
"total"
:
,
"workers"
:
,
"currents"
:
[
]
}
=
dict
(
.
)
.
.
(
)
(
,
)
.
=
.
(
=
.
,
=
(
,
)
,
=
"reg-job"
,
=
True
)
.
.
(
)
return
def
stop
(
)
:
if
not
.
(
)
:
return
False
.
.
set
(
)
(
" ⏹ запрошен стоп прогона"
)
return
True
def
_setup_proxies
(
)
:
"""Ротатор прокси: сессионные BRD-зоны (свежий IP на акк) либо статический
список. None → напрямую."""
try
:
from
import
as
=
.
(
)
if
len
(
)
>
0
:
if
type
(
)
.
==
"SessionRotator"
:
(
f"прокси: BRD session-ротация, зон { len ( rot) } "
f"(свежий IP на каждый аккаунт)"
)
else
:
(
f"прокси: статический пул, { len ( rot) } шт"
)
return
(
"прокси не заданы — прямые подключения"
)
except
as
:
(
f"прокси: ошибка ( { exc} ) — прямые подключения"
)
return
None
def
_register_once
(
,
,
)
:
"""Один аккаунт с одним ретраем на следующем прокси (капча/сеть).
Возвращает acc-словарь (с error при фейле) или None при стопе."""
for
in
range
(
2
)
:
try
:
=
(
=
.
next
(
)
if
else
None
,
=
)
except
:
return
None
except
as
:
=
{
"email"
:
"?"
,
"error"
:
f" { type ( exc) . __name__} : { exc} "
}
(
f" ❌ { type ( exc) . __name__} : { exc} "
)
=
str
(
.
(
"error"
,
""
)
)
.
(
)
if
not
.
(
"error"
)
or
==
1
:
return
if
any
(
in
for
in
(
"turnstile"
,
"timed out"
,
"connection"
,
"fast"
,
"human check"
,
"too many"
)
)
:
(
" ↻ повтор на следующем прокси (капча/сеть/лимит)"
)
continue
return
return
{
"email"
:
"?"
,
"error"
:
"unknown"
}
def
_account_result
(
,
,
,
,
)
:
"""Учесть результат аккаунта (потокобезопасно). Возвращает (ok, fails, last_error)."""
with
.
:
if
.
(
"error"
)
:
=
str
(
[
"error"
]
)
=
"failed"
+=
1
else
:
.
(
)
+=
1
=
0
=
"ok"
.
[
"done"
]
+=
1
.
[
"ok"
]
=
.
[
"results"
]
=
list
(
.
[
"results"
]
)
+
[
{
"email"
:
.
(
"email"
)
,
"status"
:
}
]
=
dict
(
.
)
try
:
(
,
)
except
:
pass
if
.
(
"error"
)
:
(
f" ✗ { last_error} "
)
else
:
(
f" ✓ { acc. get( 'email' ) } (key … { str ( acc. get( 'api_key' ) ) [ - 8 : ] } )"
)
return
,
,
def
_finish
(
,
,
,
)
:
=
.
(
)
if
or
.
.
(
)
:
=
"stopped"
elif
==
0
and
[
"total"
]
>
0
:
=
"failed"
else
:
=
"done"
.
(
=
,
=
,
=
.
(
)
,
=
,
=
None
,
=
[
]
)
(
f"■ прогон { snap[ 'job_id' ] } : { status} , ok= { ok} / { snap[ 'total' ] } "
+
(
f", ошибка: { last_error} "
if
else
""
)
)
def
_run
(
,
,
=
1
)
:
if
>
1
:
return
.
(
,
)
(
f"▶ прогон { self. snapshot( ) [ 'job_id' ] } : { count} акк "
f"(последовательно, интервал { config. BATCH_INTERVAL_SEC} s)"
)
=
.
(
)
,
,
,
=
0
,
0
,
None
,
False
try
:
for
in
range
(
)
:
if
.
.
(
)
:
=
True
break
(
f"── аккаунт { i + 1 } / { count} "
)
.
(
=
{
"index"
:
+
1
,
"step"
:
0
,
"steps_total"
:
6
,
"label"
:
"старт"
}
)
def
on_step
(
,
=
+
1
)
:
=
.
match
(
r"step (\d+)/(\d+):\s*(.*)"
,
str
(
)
)
if
:
.
(
=
{
"index"
:
,
"step"
:
int
(
.
(
1
)
)
,
"steps_total"
:
int
(
.
(
2
)
)
,
"label"
:
.
(
3
)
[
:
140
]
}
)
(
" "
+
str
(
)
)
if
.
.
(
)
:
raise
(
)
=
.
(
,
)
if
is
None
:
=
True
break
,
,
=
.
(
,
,
,
)
if
>=
getattr
(
,
"CIRCUIT_BREAKER_FAILS"
,
5
)
:
=
(
f"circuit breaker: { fails_in_row} фейлов подряд "
f"(последняя: { last_error} ) — вероятно, IP в часовом "
f"бане; подождите час или дайте residential-прокси"
)
(
f"⛔ { last_error} "
)
break
if
<
-
1
and
not
.
.
(
)
:
=
bool
(
)
and
len
(
)
>
0
=
3
if
else
.
(
f" пауза { delay} s..."
)
if
.
.
(
)
:
=
True
break
except
as
:
=
f" { type ( exc) . __name__} : { exc} "
(
f"✖ прогон упал: { last_error} "
)
.
(
=
"failed"
,
=
,
=
.
(
)
,
=
None
,
=
[
]
)
return
.
(
,
,
)
def
_run_parallel
(
,
,
)
:
from
.
import
(
f"▶ прогон { self. snapshot( ) [ 'job_id' ] } : { count} акк "
f"ПАРАЛЛЕЛЬНО × { workers} воркеров"
)
=
.
(
)
if
and
type
(
)
.
!=
"SessionRotator"
and
len
(
)
<
:
=
max
(
1
,
len
(
)
)
(
f"воркеров урезано до живых прокси: { workers} "
)
=
list
(
range
(
1
,
+
1
)
)
=
.
(
)
=
{
"ok"
:
0
,
"fails"
:
0
,
"last_error"
:
None
,
"stopped"
:
False
}
=
getattr
(
,
"CIRCUIT_BREAKER_FAILS"
,
5
)
def
slot_update
(
,
**
)
:
with
.
:
=
list
(
.
.
(
"currents"
)
or
[
None
]
*
)
=
dict
(
[
]
or
{
}
)
.
(
)
[
]
=
.
[
"currents"
]
=
=
dict
(
.
)
try
:
(
,
)
except
:
pass
def
worker
(
)
:
while
not
[
"stopped"
]
and
not
.
.
(
)
:
with
:
if
not
:
return
=
.
(
0
)
(
f"[w { slot + 1 } ] ── аккаунт { idx} / { count} "
)
(
,
=
,
=
0
,
=
6
,
=
"старт"
)
def
on_step
(
,
=
,
=
)
:
=
.
match
(
r"step (\d+)/(\d+):\s*(.*)"
,
str
(
)
)
if
:
(
,
=
,
=
int
(
.
(
1
)
)
,
=
int
(
.
(
2
)
)
,
=
.
(
3
)
[
:
140
]
)
(
f" [w { s + 1 } # { i} ] { msg} "
)
if
.
.
(
)
:
raise
(
)
=
.
(
,
)
=
0
with
:
if
[
"stopped"
]
or
is
None
:
return
[
"ok"
]
,
[
"fails"
]
,
[
"last_error"
]
=
.
(
if
is
not
None
else
{
}
,
[
"ok"
]
,
[
"fails"
]
,
[
"last_error"
]
)
(
,
=
True
)
if
[
"fails"
]
>=
:
if
[
"fails"
]
>=
3
*
:
[
"last_error"
]
=
(
f"circuit breaker: { shared[ 'fails' ] } "
f"фейлов подряд — стоп"
)
[
"stopped"
]
=
True
else
:
(
f"⏸ { shared[ 'fails' ] } фейлов подряд — пауза 60с, продолжаю"
)
[
"fails"
]
=
0
=
60
if
and
not
.
.
(
)
:
if
.
.
(
)
:
return
if
not
[
"stopped"
]
:
.
(
3
)
try
:
with
(
=
)
as
:
list
(
.
map
(
,
range
(
)
)
)
except
as
:
[
"last_error"
]
=
f" { type ( exc) . __name__} : { exc} "
(
f"✖ прогон упал: { shared[ 'last_error' ] } "
)
.
(
=
"failed"
,
=
[
"last_error"
]
,
=
.
(
)
,
=
[
]
)
return
.
(
[
"stopped"
]
,
[
"ok"
]
,
[
"last_error"
]
)
=
(
)
=
{
"running"
:
False
,
"done"
:
0
,
"total"
:
0
,
"started_at"
:
None
,
"finished_at"
:
None
,
"error"
:
None
,
"next_run_at"
:
None
,
"interval_sec"
:
None
,
"skipped"
:
None
}
=
.
(
)
=
.
(
)
def
_limits_bg_interval
(
)
:
"""Интервал фонового опроса СЕРВЕРА за квотами, сек.
ПО УМОЛЧАНИЮ ВЫКЛЮЧЕН (0): расход считаем сами из своего леджера
(data/usage.jsonl) в реальном времени, а к серверу ходить незачем —
это логины по всем аккаунтам (медленно, рейт-лимит 429).
Включается явно: config.json → `limits_bg_interval_sec` (>0, секунды)
или env `REG_LIMITS_BG_MIN` (минуты). Нужен только для сверки
серверного `used_pct`/`exhausted`/`reset_at`."""
try
:
=
int
(
.
.
(
"REG_LIMITS_BG_MIN"
)
or
0
)
if
>
0
:
return
*
60
except
:
pass
try
:
=
int
(
.
(
"limits_bg_interval_sec"
,
0
)
or
0
)
except
(
,
)
:
=
0
return
if
>
0
else
0
def
_limits_job
(
)
:
"""Один проход сбора квот. running уже выставлен вызывающим (limits_start)."""
from
import
try
:
=
.
(
)
[
"total"
]
=
len
(
)
(
f"▶ сбор лимитов по { len ( accounts) } аккаунтам…"
)
def
prog
(
,
)
:
[
"done"
]
=
[
"total"
]
=
.
(
,
=
True
,
=
3
,
=
)
[
"done"
]
=
[
"total"
]
(
f"■ лимиты собраны ( { LIMITS_STATE[ 'total' ] } акк)"
)
except
as
:
[
"error"
]
=
f" { type ( exc) . __name__} : { exc} "
(
f"✖ сбор лимитов упал: { LIMITS_STATE[ 'error' ] } "
)
finally
:
[
"running"
]
=
False
[
"finished_at"
]
=
.
(
)
def
limits_start
(
)
:
"""Атомарно стартует фоновый сбор квот. False — сбор уже идёт."""
with
:
if
[
"running"
]
:
return
False
.
(
=
True
,
=
0
,
=
0
,
=
None
,
=
.
(
)
,
=
None
)
.
(
=
,
=
"limits-job"
,
=
True
)
.
(
)
return
True
def
limits_bg_loop
(
)
:
"""Демон: раз в интервал добирает протухшие квоты, если не идёт другой сбор
или прогон регистрации (иначе 429 и лишняя нагрузка). Первый сбор — через
~60с после старта панели."""
=
(
)
[
"interval_sec"
]
=
if
<=
0
:
[
"skipped"
]
=
"выключен (расход считаем локально)"
(
"фон-опрос квот выключен: расход считаем локально из usage.jsonl; "
"сверка с сервером — кнопкой «Обновить квоты»"
)
return
=
min
(
60
,
)
(
f"фон-опрос квот сервера: интервал { interval} s, первый через { first} s"
)
if
.
(
)
:
return
while
not
.
(
)
:
if
[
"running"
]
:
[
"skipped"
]
=
"сбор уже идёт"
elif
.
(
)
:
[
"skipped"
]
=
"идёт прогон регистрации"
(
"фон-сбор квот: пропуск — идёт прогон регистрации"
)
else
:
[
"skipped"
]
=
None
(
)
[
"next_run_at"
]
=
.
(
)
+
if
.
(
)
:
return
=
.
(
)
=
{
"running"
:
False
,
"checked"
:
0
,
"total"
:
0
,
"ok"
:
0
,
"started_at"
:
None
,
"finished_at"
:
None
}
=
{
}
=
.
(
)
def
_check_one
(
)
:
if
.
(
"proxy_username"
)
:
try
:
,
,
=
(
)
except
as
:
return
.
(
"email"
)
,
"failed"
,
str
(
)
[
:
120
]
return
.
(
"email"
)
,
"ok"
if
else
"failed"
,
str
(
)
[
:
100
]
=
.
(
"api_key"
)
if
not
:
return
.
(
"email"
)
,
"unknown"
,
"нет api_key"
=
(
.
or
[
None
]
)
[
0
]
try
:
,
,
=
(
,
=
)
except
as
:
return
.
(
"email"
)
,
"failed"
,
str
(
)
[
:
120
]
return
.
(
"email"
)
,
"ok"
if
else
"failed"
,
f" { model} : { str ( detail) [ : 80] } "
def
_apply_check
(
,
,
)
:
with
:
[
]
=
{
"status"
:
,
"note"
:
,
"ts"
:
.
(
)
}
=
"✓"
if
==
"ok"
else
"✗"
(
f" { mark} { email} : { note} "
)
def
accounts_check
(
=
None
)
:
"""Перепроверка ключей: ≤5 — синхронно, иначе фоном. → dict для ответа."""
=
.
(
)
=
len
(
)
if
not
:
return
{
"checked"
:
0
}
if
<=
5
:
(
f"▶ перепроверка ключей: { total} акк (синхронно)"
)
=
=
0
for
in
:
,
,
=
(
)
(
,
,
)
+=
1
+=
==
"ok"
(
f"■ перепроверка: { checked} проверено, ok= { ok} "
)
return
{
"checked"
:
,
"ok"
:
}
with
:
if
[
"running"
]
:
return
{
"checked"
:
0
,
"background"
:
True
,
"note"
:
"перепроверка уже идёт"
,
**
}
.
(
=
True
,
=
0
,
=
,
=
0
,
=
.
(
)
,
=
None
)
.
(
=
,
=
(
,
)
,
=
"reg-check"
,
=
True
)
.
(
)
return
{
"checked"
:
0
,
"background"
:
True
,
"total"
:
}
def
_check_worker
(
)
:
(
f"▶ перепроверка ключей: { len ( accs) } акк (фон)"
)
=
0
try
:
for
in
:
,
,
=
(
)
(
,
,
)
+=
==
"ok"
with
:
[
"checked"
]
+=
1
[
"ok"
]
=
finally
:
with
:
.
(
=
False
,
=
.
(
)
)
(
f"■ перепроверка: { _check_state[ 'checked' ] } проверено, ok= { ok} "
)
def
captcha_info
(
)
:
=
(
.
)
try
:
from
import
as
=
.
(
)
except
:
=
[
]
=
.
(
"vlm_api_base"
)
or
""
=
.
(
"vlm_model"
)
or
""
=
bool
(
and
.
(
"vlm_api_key"
)
and
)
=
bool
(
.
(
"grid_api_base"
)
and
.
(
"grid_api_key"
)
)
=
bool
(
.
(
"stt_api_base"
)
and
.
(
"stt_api_key"
)
)
return
{
"provider"
:
"auto (camoufox → capsolver)"
,
"configured"
:
bool
(
and
.
.
(
)
)
,
"capsolver_configured"
:
bool
(
.
)
,
"camoufox_python"
:
,
"balance"
:
None
,
"engines"
:
,
"recaptcha"
:
{
"solver"
:
.
(
"captcha_solver"
)
or
"auto"
,
"grid_solver"
:
.
(
"grid_solver"
)
or
"auto"
,
"vlm"
:
,
"vlm_base"
:
,
"vlm_ready"
:
,
"classifier_ready"
:
,
"stt"
:
(
.
(
"stt_model"
)
or
""
)
if
else
""
,
"stt_ready"
:
,
"twocaptcha"
:
bool
(
(
.
(
"twocaptcha_key"
)
or
""
)
.
(
)
)
,
}
,
"note"
:
"Решалка подключается только если сервер реально потребовал капчу "
"(не превентивно). Сетку reCAPTCHA v2 решает grid_solver: "
"classifier (ONNX, ~0.2 с) → vlm (~15 с); аудио — STT. "
"Тип капчи и решалку под свой сервис настрой "
"в core/register.py (см. docs/СТАНДАРТ.md §4)."
,
}
def
models_payload
(
)
:
"""Живой /v1/models по первому ключу + пометка, что реально доступно.
/v1/models перечисляет ВСЕ модели сервиса, но free-аккаунту доступны только
те, что в free-tier (см. кэш лимитов) — остальные требуют баланс.
"""
=
.
(
)
=
next
(
(
.
(
"api_key"
)
for
in
if
.
(
"api_key"
)
)
,
None
)
,
,
=
[
]
,
False
,
None
if
:
try
:
=
(
)
=
bool
(
)
except
as
:
=
str
(
)
[
:
120
]
else
:
=
"нет аккаунтов с api_key"
=
set
(
)
try
:
from
import
as
=
.
(
)
.
(
"accounts"
,
{
}
)
for
in
.
(
)
:
for
in
(
.
(
"model_ids"
)
or
[
]
)
:
.
(
)
.
(
+
":free"
)
except
:
pass
=
.
(
"%Y-%m-%dT%H:%M:%SZ"
,
.
(
)
)
=
[
]
if
:
for
in
:
=
.
(
":free"
)
=
[
:
-
5
]
if
else
=
in
or
in
or
if
:
,
=
"available"
,
"free tier — доступна без баланса"
else
:
,
=
"paid"
,
"требует баланс (в free-tier нет)"
.
(
{
"id"
:
,
"name"
:
,
"status"
:
,
"note"
:
,
"last_checked"
:
}
)
=
f"живой /v1/models (ключ … { key[ - 8 : ] } )"
else
:
for
in
.
:
.
(
{
"id"
:
,
"name"
:
[
:
-
5
]
if
.
(
":free"
)
else
,
"status"
:
"unknown"
,
"note"
:
(
"free tier; fallback — живой список недоступен"
+
(
f": { err} "
if
else
""
)
)
,
"last_checked"
:
None
,
}
)
=
"fallback из config.json"
+
(
f" ( { err} )"
if
else
""
)
=
[
for
in
if
[
"status"
]
==
"available"
]
return
{
"models"
:
,
"source"
:
,
"live"
:
,
"free_count"
:
len
(
)
,
"total_count"
:
len
(
)
,
"free_ids"
:
[
[
"id"
]
for
in
]
}
class
Handler
(
)
:
=
"reg-panel/"
+
def
log_message
(
,
*
)
:
pass
def
_send
(
,
,
,
=
"application/json"
)
:
=
if
isinstance
(
,
bytes
)
else
.
(
,
=
False
)
.
(
)
.
(
)
.
(
"Content-Type"
,
+
(
"; charset=utf-8"
if
"text"
in
else
""
)
)
.
(
"Content-Length"
,
str
(
len
(
)
)
)
.
(
"Cache-Control"
,
"no-store"
)
.
(
)
try
:
.
.
(
)
except
:
pass
def
_err
(
,
,
)
:
.
(
,
{
"error"
:
}
)
def
_body_json
(
)
:
try
:
=
int
(
.
.
(
"Content-Length"
)
or
0
)
except
:
=
0
if
<=
0
:
return
{
}
try
:
=
.
(
.
.
(
)
.
(
"utf-8"
)
or
"{}"
)
except
(
,
)
:
return
None
return
if
isinstance
(
,
dict
)
else
None
def
do_GET
(
)
:
=
(
.
)
,
=
.
,
(
.
)
if
in
(
"/"
,
"/index.html"
)
:
try
:
with
open
(
,
"rb"
)
as
:
return
.
(
200
,
.
(
)
,
"text/html"
)
except
:
return
.
(
500
,
"index.html не найден"
)
if
==
"/api/summary"
:
return
.
(
200
,
.
(
)
)
if
==
"/api/accounts"
:
,
=
(
)
with
:
=
dict
(
)
try
:
from
import
as
=
.
(
)
except
:
=
{
}
try
:
=
.
(
)
=
{
.
(
"email"
)
:
for
in
(
.
(
"accounts"
)
or
[
]
)
}
except
:
=
{
}
=
[
]
for
in
.
(
)
:
=
(
,
)
=
.
(
(
.
(
"api_key"
)
or
""
)
[
:
24
]
)
or
{
}
[
"requests"
]
=
.
(
"requests"
,
0
)
[
"total_tokens"
]
=
(
.
(
"prompt_tokens"
)
or
0
)
+
(
.
(
"completion_tokens"
)
or
0
)
[
"usd"
]
=
round
(
.
(
"usd"
)
or
0.0
,
6
)
=
.
(
.
(
"email"
)
)
or
{
}
[
"exhausted"
]
=
bool
(
.
(
"exhausted"
)
)
or
[
"status"
]
==
"exhausted"
[
"reset_at"
]
=
.
(
"reset_at_est"
)
or
.
(
"reset_at"
)
[
"remaining_usd"
]
=
.
(
"local_remaining_usd"
)
=
.
(
[
"email"
]
)
if
and
[
"status"
]
==
"unknown"
:
[
"status"
]
=
[
"status"
]
if
:
[
"note"
]
=
[
"note"
]
[
"last_check"
]
=
[
"ts"
]
.
(
)
return
.
(
200
,
)
if
==
"/api/job"
:
=
.
(
)
[
"log_tail"
]
=
(
40
)
return
.
(
200
,
)
if
==
"/api/captcha"
:
return
.
(
200
,
(
)
)
if
==
"/api/models"
:
return
.
(
200
,
(
)
)
if
==
"/api/limits"
:
from
import
return
.
(
200
,
.
(
)
)
if
==
"/api/limits/models"
:
from
import
return
.
(
200
,
.
(
)
)
if
==
"/api/limits/status"
:
return
.
(
200
,
dict
(
)
)
if
==
"/api/pool"
:
return
.
(
200
,
.
(
)
)
if
==
"/api/bridge/requests"
:
try
:
=
int
(
(
.
(
"tail"
)
or
[
"50"
]
)
[
0
]
)
except
:
=
50
return
.
(
200
,
.
(
)
)
if
==
"/api/bridge/logs"
:
try
:
=
int
(
(
.
(
"tail"
)
or
[
"200"
]
)
[
0
]
)
except
:
=
200
return
.
(
200
,
{
"lines"
:
(
.
.
(
.
,
"bridge.log"
)
,
)
}
)
if
==
"/api/logs"
:
try
:
=
int
(
(
.
(
"tail"
)
or
[
"200"
]
)
[
0
]
)
except
:
=
200
=
(
min
(
max
(
,
1
)
,
2000
)
)
return
.
(
200
,
{
"count"
:
len
(
)
,
"lines"
:
}
)
.
(
404
,
f"нет такого пути: { path} "
)
def
_summary
(
)
:
,
=
(
)
=
.
(
)
=
{
"total"
:
len
(
)
,
"ok"
:
0
,
"failed"
:
0
,
"unknown"
:
0
}
for
in
:
if
not
.
(
"api_key"
)
and
.
(
"proxy_username"
)
:
=
.
(
.
(
"email"
)
)
if
:
=
[
"status"
]
elif
.
(
"proxy_ok"
)
is
True
:
=
"ok"
elif
.
(
"proxy_ok"
)
is
False
:
=
"failed"
else
:
=
"unknown"
else
:
=
(
.
(
"api_key"
)
,
)
[
]
=
.
(
,
0
)
+
1
=
.
(
)
return
{
"service"
:
,
"version"
:
,
"running"
:
True
,
"job_running"
:
[
"status"
]
==
"running"
,
"port"
:
.
.
,
"counts"
:
,
"captcha"
:
{
"provider"
:
"auto (camoufox→capsolver)"
,
"configured"
:
bool
(
.
)
,
"balance"
:
None
,
"solver"
:
.
(
"captcha_solver"
)
or
"auto"
,
"grid_solver"
:
.
(
"grid_solver"
)
or
"auto"
,
"vlm"
:
.
(
"vlm_model"
)
or
""
,
"vlm_ready"
:
bool
(
.
(
"vlm_api_base"
)
and
.
(
"vlm_api_key"
)
and
.
(
"vlm_model"
)
)
,
"classifier_ready"
:
bool
(
.
(
"grid_api_base"
)
and
.
(
"grid_api_key"
)
)
,
"stt_ready"
:
bool
(
.
(
"stt_api_base"
)
and
.
(
"stt_api_key"
)
)
,
}
,
"last_run"
:
{
"started_at"
:
[
"started_at"
]
,
"ok"
:
[
"ok"
]
,
"total"
:
[
"total"
]
,
"status"
:
[
"status"
]
}
,
"bridge"
:
{
"port"
:
,
"alive"
:
(
)
,
"start"
:
}
,
}
def
_bridge_requests
(
,
=
50
)
:
"""Живой фид запросов моста к апстриму (из data/usage.jsonl) + сводка.
Показывает то, что важно при проблемах: статус, латентность, ошибку.
"""
=
.
.
(
.
,
"usage.jsonl"
)
=
[
]
try
:
with
open
(
,
=
"utf-8"
,
=
"replace"
)
as
:
=
.
(
)
[
-
max
(
1
,
)
:
]
except
:
=
[
]
=
[
]
=
0
for
in
:
try
:
=
.
(
)
except
:
continue
=
.
(
"status"
)
if
isinstance
(
,
int
)
and
200
<=
<
300
:
if
.
(
"latency_ms"
)
:
.
(
[
"latency_ms"
]
)
else
:
+=
1
.
(
{
"ts"
:
.
(
"ts"
)
,
"model"
:
.
(
"model"
)
,
"key"
:
(
.
(
"key_prefix"
)
or
""
)
[
:
16
]
,
"status"
:
,
"latency_ms"
:
.
(
"latency_ms"
)
,
"tokens"
:
(
.
(
"prompt_tokens"
)
or
0
)
+
(
.
(
"completion_tokens"
)
or
0
)
,
"usd"
:
.
(
"usd"
)
,
}
)
.
(
)
.
(
)
=
{
"shown"
:
len
(
)
,
"errors"
:
,
"avg_ms"
:
int
(
sum
(
)
/
len
(
)
)
if
else
None
,
"p95_ms"
:
[
int
(
len
(
)
*
0.95
)
]
if
else
None
,
"slowest_ms"
:
[
-
1
]
if
else
None
,
}
return
{
"requests"
:
,
"stats"
:
,
"bridge"
:
{
"port"
:
,
"alive"
:
(
)
,
"start"
:
}
}
def
_pool
(
)
:
,
=
(
)
if
is
None
:
return
{
"keys"
:
{
}
,
"counts"
:
None
,
"note"
:
"мост не запущен"
,
"bridge"
:
{
"port"
:
,
"alive"
:
(
)
,
"start"
:
}
}
=
{
"alive"
:
0
,
"cooldown"
:
0
,
"dead"
:
0
,
"other"
:
0
,
"total"
:
len
(
)
}
for
in
.
(
)
:
=
str
(
.
(
"status"
)
or
""
)
.
(
)
[
if
in
(
"alive"
,
"cooldown"
,
"dead"
)
else
"other"
]
+=
1
return
{
"keys"
:
,
"counts"
:
,
"refill"
:
.
(
"refill"
)
if
isinstance
(
,
dict
)
else
None
,
"note"
:
None
,
"bridge"
:
{
"port"
:
,
"alive"
:
(
)
,
"start"
:
}
}
def
do_POST
(
)
:
=
(
.
)
.
=
.
(
)
if
is
None
:
return
.
(
400
,
"тело должно быть JSON-объектом"
)
if
==
"/api/limits/check"
:
if
not
(
)
:
return
.
(
409
,
"сбор уже идёт"
)
return
.
(
200
,
{
"started"
:
True
}
)
if
==
"/api/register"
:
=
.
(
"count"
,
1
)
try
:
=
int
(
)
except
(
,
)
:
return
.
(
400
,
"count должен быть числом"
)
if
not
1
<=
<=
500
:
return
.
(
400
,
"count вне диапазона 1..500"
)
try
:
=
int
(
.
(
"workers"
,
1
)
)
except
(
,
)
:
return
.
(
400
,
"workers должен быть числом"
)
if
not
1
<=
<=
12
:
return
.
(
400
,
"workers вне диапазона 1..12"
)
=
.
(
,
=
)
if
is
None
:
return
.
(
409
,
"прогон уже идёт — сначала Стоп"
)
return
.
(
200
,
{
"job_id"
:
,
"count"
:
,
"workers"
:
}
)
if
==
"/api/job/stop"
:
if
not
.
(
)
:
return
.
(
409
,
"нечего останавливать: прогон не идёт"
)
return
.
(
200
,
{
"ok"
:
True
,
"stopped"
:
True
}
)
if
==
"/api/accounts/check"
:
return
.
(
200
,
(
)
)
.
(
404
,
f"нет такого пути: { path} "
)
def
main
(
)
:
=
.
(
=
"Панель реггера (PANEL-SPEC)"
)
.
(
"--port"
,
type
=
int
,
=
,
help
=
f"порт (по умолчанию { PANEL_PORT} , зарезервирован за реггером)"
)
.
(
"--host"
,
=
"127.0.0.1"
,
help
=
"адрес (только локальный)"
)
=
.
(
)
.
(
,
=
True
)
if
.
not
in
(
"127.0.0.1"
,
"localhost"
)
:
print
(
"[!] панель слушает только 127.0.0.1 — host принудительно локальный"
)
.
=
"127.0.0.1"
=
(
(
.
,
.
)
,
)
.
=
True
.
(
=
,
=
"limits-bg"
,
=
True
)
.
(
)
(
f"панель запущена: http:// { args. host} : { args. port} (данные: { DATA_DIR} )"
)
print
(
f"панель { SERVICE_NAME} : http:// { args. host} : { args. port} (Ctrl+C — стоп)"
)
try
:
.
(
)
except
:
print
(
"\nостановлено"
)
finally
:
.
set
(
)
.
(
)
if
==
"__main__"
:
(
)