From f0bc949182382ad2d26d5a94302d61c5f9f0e901 Mon Sep 17 00:00:00 2001 From: reform Date: Sun, 1 Nov 2026 18:47:41 +0300 Subject: [PATCH] init --- .gitignore | 4 + POST.md | 19 +++ README.md | 49 ++++++ camb_shim.py | 193 ++++++++++++++++++++++ chr.py | 38 +++++ farm.py | 441 +++++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 744 insertions(+) create mode 100644 .gitignore create mode 100644 POST.md create mode 100644 README.md create mode 100644 camb_shim.py create mode 100644 chr.py create mode 100644 farm.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7850ee9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.jsonl +*_keys.json +*.log +__pycache__/ diff --git a/POST.md b/POST.md new file mode 100644 index 0000000..8b7da60 --- /dev/null +++ b/POST.md @@ -0,0 +1,19 @@ +# CAMB.AI — 5000 кредитов на аккаунт + +CAMB делает дубляж видео и озвучку на 100+ языков. Free-план даёт **5000 кредитов** и они **возобновляются каждый месяц** — это не разовый триал. + +Проверить баланс можно прямо из API: `/payments/credits/team/` → `{"credits_left":5000,"is_free_plan":true}`. + +Что это в работе: дубляж стоит 550 кредитов — около **9 дубляжей видео** с аккаунта. Одна фраза озвучки — ~3 кредита, то есть полторы тысячи озвучек. Пакет на 100 000 кредитов у них $50, значит free-аккаунт это **~$2.5** их же денег. + +Регистрация живёт по одному адресу — `studio.camb.ai/public/onboarding`, остальные пути отдают пустой шелл. Форма: имя, почта, пароль, галочка. Дальше обязательный Turnstile, и только с его токеном уходит `POST /uservault/auth/signup` — токен рабочий сразу, до подтверждения почты. + +Главная ловушка — код из письма. Он **шесть алфанумерических символов** (`LSQX01`), а не цифры: парсеры с `\d{6}` вытаскивают мусор и сервер отвечает `Invalid Code`. Подтверждение: `PATCH /uservault/users/verification/mail/verify?verification_code=`. + +Ключ: `refresh-token` → `GET /v1/teams/` → `team_id` → `/workspace//api-keys` → Create New API Key. + +Рабочий вызов — только `POST https://client.camb.ai/apis/tts-stream` с `x-api-key` (тело: text, language, voice_id, speech_model `mars-flash`). `/v1/tts/` и `api.camb.ai` мёртвые. + +Барьер: Vercel Security Checkpoint на studio-домене — curl получает 429-заглушку, проходит только реальный Chrome по CDP. Логин тоже Turnstile-gated, HTTP-only авторег не строится. + +Итог: 18 аккаунтов, **90 000 кредитов** — это ~29 000 озвучек или 160 дубляжей. Отдаётся одним OpenAI-совместимым `/v1/audio/speech`. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0ed514e --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +# camb-autoreg + +Autoreg for [studio.camb.ai](https://studio.camb.ai) — dubbing / TTS service with a refillable free plan. + +## Economics (verified on live accounts, 2026-11-01) + +* Free product: **5000 credits**, `is_refill_based: true` (monthly refill). +* Balance: `GET https://client.camb.ai/payments/credits/team/` -> `{"credits_left":5000.0,"is_free_plan":true}`. +* Dub job (job_type 1) = 550 credits -> ~9 dubs per account. TTS phrase ~3 credits. +* 100k credits pack = $50 -> 1 credit ~= $0.0005 -> free account ~= $2.5 of API value. + +## Flow + +1. `https://studio.camb.ai/public/onboarding` is the only signup entry (`/signup`, `/register` return 404 shells). +2. Form: `input[name=name]`, `input[type=email]`, `input[type=password]` (10+ chars, upper+lower+digit+symbol), consent checkbox (Radix `button[role=checkbox]` — click by bbox). +3. Turnstile sitekey `0x4AAAAAAB7HkZD89uSr-6VZ`, token lands in `input[name=cf-turnstile-response]` (~752 chars). Wait for it before submit. +4. `POST https://client.camb.ai/uservault/auth/signup` -> `200 {"payload":{"access_token":"..."}}`; token works before email verification. +5. Mail from `help@camb.ai`, subject `Email Verification`. **Code is 6 alphanumeric chars** (`LSQX01`), not digits. +6. `PATCH /uservault/users/verification/mail/verify?verification_code=` -> `{"verified": true}`. +7. Onboarding "Who are you?" -> Skip -> `/workspace//home`. +8. team_id: `POST /uservault/auth/refresh-token` (credentials include) -> `payload.access_token` -> `GET /v1/teams/` with bearer -> `payload.teams[0].id`. +9. Key: `/workspace//api-keys` -> Create New API Key -> `input[name=api-key-name]` -> Create Secret Key -> read 30+ char value. +10. Working call: `POST https://client.camb.ai/apis/tts-stream` with header `x-api-key` and body + `{"text","language":"en-us","voice_id":147320,"speech_model":"mars-flash","output_configuration":{"format":"wav"}}`. + Credits spent come back in `x-credits-required`. + +## Pitfalls + +* No Turnstile token -> `400 "Turnstile token not found"` on both signup and login. Browser farm only. +* Verification mail quota: `GET /uservault/users/verification/mail/quota-status` -> `can_send:false`, `block_type:"soft_block"`, ~2 min window. Do not hammer Resend. +* Match the submit button by exact text `create account`; a loose "sign up" match hits the Google button. +* Clear cookies AND localStorage before signup, otherwise the onboarding form may not render. +* `pg.close()` on the last tab kills CDP Chrome; reattach with `ensure_chrome(port, prof)`. +* Vercel Security Checkpoint: curl/curl_cffi get `429` + HTML stub; only real Chrome over CDP passes. The API host `client.camb.ai` is reachable directly — do recon there. + +## Files + +* `farm.py` — worker: signup -> code via VPS mailbox -> verify -> team_id -> api key -> TTS check -> bank row. +* `chr.py` — `ensure_chrome(port=9242)` CDP helper. +* `camb_shim.py` — OpenAI-compatible `/v1/audio/speech` shim over the key pool (round-robin, dead-key blacklist, 429 cooldown). + +## Env + +``` +CAMB_VPS=root@your-vps # ssh host able to read the mailbox +CAMB_MAIL_READER=/root/camb_code.py +CAMB_KEYS=/opt/camb-shim/camb_keys.json +CAMB_SHIM_PORT=8822 +``` diff --git a/camb_shim.py b/camb_shim.py new file mode 100644 index 0000000..f0cb288 --- /dev/null +++ b/camb_shim.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""CAMBI.AI -> OpenAI-compatible TTS shim (stdlib only). + +Endpoints: + POST /v1/audio/speech {model, input|text, voice, language, format} + GET /v1/models + GET /health + +Upstream: POST https://client.camb.ai/apis/tts-stream (header x-api-key) +Key pool: camb_keys.json [{"api_key": "...", "email": "..."}] +401/403 -> blacklist key, 429/5xx -> cooldown, retry with next key. +""" +import json +import os +import threading +import time +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +HERE = os.path.dirname(os.path.abspath(__file__)) +KEYS_FILE = os.environ.get("CAMB_KEYS", os.path.join(HERE, "camb_keys.json")) +DEAD_FILE = os.path.join(HERE, "camb_dead.json") +PORT = int(os.environ.get("CAMB_SHIM_PORT", "8822")) +UPSTREAM = "https://client.camb.ai/apis/tts-stream" + +MODELS = { + "camb-tts": "mars-flash", + "camb-tts-pro": "mars", +} +DEFAULT_VOICE = 147320 +VOICES = { + "alloy": 147320, "echo": 147320, "fable": 147320, + "onyx": 147320, "nova": 147320, "shimmer": 147320, + "sarah": 147320, "george": 147320, +} + +_lock = threading.Lock() +_keys = [] +_idx = 0 +_dead = set() +_cool = {} + + +def load_keys(): + global _keys + try: + raw = json.load(open(KEYS_FILE, encoding="utf-8")) + except (OSError, ValueError): + return [] + data = raw if isinstance(raw, list) else raw.get("keys", []) + out = [] + for item in data: + if isinstance(item, str): + out.append(item) + elif isinstance(item, dict) and item.get("api_key"): + out.append(item["api_key"]) + return out + + +def reload_if_changed(): + global _keys + keys = load_keys() + if keys and len(keys) != len(_keys): + with _lock: + _keys = keys + print("camb-shim keys loaded: %d" % len(_keys), flush=True) + + +def alive_keys(): + now = time.time() + out = [] + for k in _keys: + if k in _dead: + continue + if _cool.get(k, 0) > now: + continue + out.append(k) + return out or [k for k in _keys if k not in _dead] + + +def call_upstream(key, body, timeout=180): + req = urllib.request.Request( + UPSTREAM, + data=json.dumps(body).encode(), + headers={ + "x-api-key": key, + "Content-Type": "application/json", + "Accept": "*/*", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/141.0", + }, + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, r.read(), r.headers.get("x-credits-required") + + +class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *a): + print("%s %s" % (time.strftime("%H:%M:%S"), fmt % a), flush=True) + + def _json(self, code, obj): + b = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + if self.path.startswith("/health"): + reload_if_changed() + return self._json(200, {"status": "ok", "live_keys": len(alive_keys()), + "total": len(_keys), "dead": len(_dead)}) + if self.path.startswith("/v1/models"): + return self._json(200, {"object": "list", "data": [ + {"id": m, "object": "model", "owned_by": "camb"} for m in MODELS]}) + return self._json(404, {"error": "not found"}) + + def do_POST(self): + if not self.path.startswith("/v1/audio/speech"): + return self._json(404, {"error": "not found"}) + try: + n = int(self.headers.get("Content-Length") or 0) + req = json.loads(self.rfile.read(n) or b"{}") + except ValueError: + return self._json(400, {"error": "bad json"}) + text = (req.get("input") or req.get("text") or "").strip() + if not text: + return self._json(400, {"error": "input is required"}) + model = MODELS.get(req.get("model") or "camb-tts", "mars-flash") + vname = str(req.get("voice") or "alloy").lower() + voice_id = VOICES.get(vname, DEFAULT_VOICE) + body = { + "text": text, + "language": req.get("language") or "en-us", + "voice_id": voice_id, + "speech_model": model, + "output_configuration": {"format": req.get("format") or "wav"}, + } + reload_if_changed() + last = None + for key in alive_keys(): + try: + status, data, credits = call_upstream(key, body) + except urllib.error.HTTPError as e: + code = e.code + msg = e.read(300).decode("utf-8", "replace") + last = (code, msg) + if code in (401, 403): + _dead.add(key) + json.dump(sorted(_dead), open(DEAD_FILE, "w")) + continue + if code == 429: + _cool[key] = time.time() + 60 + continue + if code == 400: + return self._json(400, {"error": msg[:300]}) + continue + except Exception as e: # noqa: BLE001 + last = (None, str(e)[:120]) + continue + if status == 200 and len(data) > 500: + self.send_response(200) + ctype = "audio/wav" if body["output_configuration"]["format"] == "wav" else "audio/mpeg" + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + if credits: + self.send_header("x-credits-required", str(credits)) + self.end_headers() + self.wfile.write(data) + return + last = (status, "short body %d" % len(data)) + return self._json(502, {"error": "all keys failed", "last": last}) + + +def main(): + keys = load_keys() + with _lock: + _keys.extend(keys) + try: + for k in json.load(open(DEAD_FILE)): + _dead.add(k) + except (OSError, ValueError): + pass + print("camb-shim on :%d, keys=%d" % (PORT, len(_keys)), flush=True) + ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/chr.py b/chr.py new file mode 100644 index 0000000..43cff4a --- /dev/null +++ b/chr.py @@ -0,0 +1,38 @@ +"""chrome helper: ensure chrome with CDP is running.""" +import json +import os +import subprocess +import time +import urllib.request + +CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe" + + +def _up(port): + try: + with urllib.request.urlopen("http://127.0.0.1:%d/json/version" % port, timeout=2) as r: + return json.loads(r.read().decode()) + except Exception: + return None + + +def ensure(port=9242, prof=r"C:\Users\User\tmp\camb\prof2", extra=None): + v = _up(port) + if v: + return v + os.makedirs(prof, exist_ok=True) + args = [CHROME, "--remote-debugging-port=%d" % port, "--user-data-dir=" + prof, + "--no-first-run", "--no-default-browser-check", + "--disable-blink-features=AutomationControlled", + "--window-size=1280,1000"] + if extra: + args += extra + args.append("about:blank") + subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True) + for _ in range(30): + time.sleep(1) + v = _up(port) + if v: + return v + raise RuntimeError("chrome failed to start on %d" % port) \ No newline at end of file diff --git a/farm.py b/farm.py new file mode 100644 index 0000000..1f1f318 --- /dev/null +++ b/farm.py @@ -0,0 +1,441 @@ +"""Camb.ai autoreg farm: signup -> mail verify -> skip onboarding -> create API key -> bank. + +Usage: python farm.py [start_idx] +One playwright session, fresh incognito context per account (Chrome dies between runs). +""" +import json +import random +import re +import string +import subprocess +import sys +import time + +import requests +from playwright.sync_api import sync_playwright + +import chr + +MPOOL = r"C:\Users\User\Desktop\avtoreg\working_mails.txt" +BANK = "camb_bank.jsonl" +VPS = os.environ.get("CAMB_VPS", "") # ssh target that can read the mailbox code + +N = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 1 +START = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 30 + + +def gen_pass(n=16): + parts = [random.choice(string.ascii_uppercase), random.choice(string.ascii_lowercase), + random.choice(string.digits), random.choice("*#!")] + parts += [random.choice(string.ascii_letters + string.digits + "*#!") for _ in range(n - 4)] + random.shuffle(parts) + return "".join(parts) + + +def mail_code(email, password, timeout=150, tag=""): + """fetch 6-char verification code (camb letter: 'code is XXXXXX').""" + deadline = time.time() + timeout + while time.time() < deadline: + try: + r = subprocess.run( + ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=15", VPS, + "python3", os.environ.get("CAMB_MAIL_READER", "/root/camb_code.py"), email, password], + capture_output=True, text=True, timeout=90) + out = (r.stdout or "") + (r.stderr or "") + m = re.search(r"CCODE\s+([A-Z0-9]{6})\b", out) + if m: + return m.group(1) + except Exception as e: + print(f" [{tag}] ssh err", e) + time.sleep(10) + return None + + +def one(ctx, email, password, tag): + events = [] + + def on_resp(r): + try: + if "client.camb.ai" in r.url: + b = "" + try: + if "json" in (r.headers.get("content-type") or ""): + b = r.text()[:600] + except Exception: + pass + events.append((r.status, r.request.method, r.url, b)) + except Exception: + pass + + pg = ctx.new_page() + pg.on("response", on_resp) + # wipe any previous session (cookies + localStorage) before signup + try: + pg.goto("https://studio.camb.ai/public/onboarding", wait_until="domcontentloaded", timeout=60000) + time.sleep(6) + pg.evaluate("()=>{try{localStorage.clear();sessionStorage.clear()}catch(e){}}") + ctx.clear_cookies() + time.sleep(2) + except Exception: + pass + # --- signup form + ok_form = False + for attempt in range(6): + try: + pg.goto("https://studio.camb.ai/public/onboarding", wait_until="domcontentloaded", timeout=60000) + pg.wait_for_selector("input[name=name]", timeout=30000) + ok_form = True + break + except Exception as e: + print(f"[{tag}] form attempt {attempt}:", str(e)[:80]) + time.sleep(5) + if not ok_form: + print(f"[{tag}] form never appeared"); pg.close(); return None + pg.fill("input[name=name]", "Nik Reform") + pg.fill("input[type=email]", email) + pw = gen_pass() + pg.fill("input[type=password]", pw) + cb = pg.query_selector("#consent") + if cb: + bb = cb.bounding_box() + if bb: + pg.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2) + time.sleep(0.5) + checked = cb.get_attribute("aria-checked") or cb.get_attribute("data-state") + print(f"[{tag}] consent state: {checked}") + else: + print(f"[{tag}] no consent checkbox") + time.sleep(2) + for el in pg.query_selector_all("button"): + try: + t = (el.inner_text() or "").strip()[:25] + d = el.get_attribute("disabled") + print(f"[{tag}] btn: {t!r} disabled={d}") + except Exception: + pass + # wait for turnstile token + for _ in range(24): + t = pg.evaluate("()=>{const i=document.querySelector('input[name=cf-turnstile-response]');return i?i.value:''}") + if t and len(t) > 50: + break + time.sleep(1.5) + clicked = False + for el in pg.query_selector_all("button"): + try: + t = (el.inner_text() or "").lower() + if "create account" in t: + el.click() + clicked = True + print(f"[{tag}] clicked btn: {t.strip()[:30]}") + break + except Exception: + pass + if not clicked: + for el in pg.query_selector_all("button"): + try: + tp = (el.get_attribute("type") or "").lower() + if tp == "submit": + el.click() + clicked = True + break + except Exception: + pass + if not clicked: + pg.keyboard.press("Enter") + print(f"[{tag}] pressed Enter") + time.sleep(8) + signed = any("auth/signup" in u and s == 200 for s, m, u, b in events) + print(f"[{tag}] signup events:", [(s, u.split('camb.ai')[-1][:60]) for s, m, u, b in events if 'uservault' in u]) + if not signed: + # maybe verify-code screen appeared anyway + pass + # --- verify code + code = mail_code(email, password, tag=tag) + print(f"[{tag}] code: {code}") + if not code: + return {"email": email, "password": pw, "error": "no_code"} + box = None + try: + pg.wait_for_selector("input[autocomplete='one-time-code'], input[maxlength='6']", timeout=30000) + box = pg.query_selector("input[autocomplete='one-time-code']") or pg.query_selector("input[maxlength='6']") + except Exception: + box = None + if not box: + return {"email": email, "password": pw, "error": "no_code_field"} + # --- verify code via direct PATCH (React OTP form sends empty value) + try: + vres = pg.evaluate("""async (code) => { + try { + const r = await fetch('https://client.camb.ai/uservault/auth/refresh-token', + {method:'POST', credentials:'include', headers:{'Content-Type':'application/json'}, body:'{}'}); + const j = await r.json(); + const jwt = (j.payload||{}).access_token || ''; + if (!jwt) return 'NOJWT:'+r.status; + const rv = await fetch('https://client.camb.ai/uservault/users/verification/mail/verify?verification_code='+encodeURIComponent(code), + {method:'PATCH', credentials:'include', headers:{'Authorization':'Bearer '+jwt,'Content-Type':'application/json'}}); + const jv = await rv.json(); + return 'PATCH '+rv.status+' '+JSON.stringify(jv.payload||jv).slice(0,120); + } catch(e){ return 'ERR:'+e.message; } + }""", code) + print(f"[{tag}] verify: {vres}") + except Exception as e: + print(f"[{tag}] verify call failed: {str(e)[:80]}") + try: + vstat = pg.evaluate("""async () => { + try { + const r = await fetch('https://client.camb.ai/uservault/auth/refresh-token', + {method:'POST', credentials:'include', headers:{'Content-Type':'application/json'}, body:'{}'}); + const j = await r.json(); + const jwt = (j.payload||{}).access_token || ''; + if (!jwt) return 'NOJWT:'+r.status; + const r2 = await fetch('https://client.camb.ai/uservault/users/me', + {credentials:'include', headers:{'Authorization':'Bearer '+jwt}}); + const j2 = await r2.json(); + const u = (j2.payload||{}).user || j2.payload || {}; + return 'verified='+String(u.email_verified ?? u.is_email_verified ?? '?'); + } catch(e){ return 'ERR:'+e.message; } + }""") + print(f"[{tag}] verify status: {vstat}") + for st, meth, url, body in events: + if "verification" in url or "verify" in url: + print(f"[{tag}] VER {st} {meth} {url.split('camb.ai')[-1][:60]} {body[:180]}") + except Exception as e: + print(f"[{tag}] verify probe failed: {str(e)[:60]}") + # --- skip onboarding questions + for _ in range(4): + el = pg.query_selector("text=Skip") + if not el: + break + el.click() + time.sleep(5) + # --- team id (URL after onboarding redirect, then fetch fallback) + try: + pg.goto("https://studio.camb.ai/workspace", wait_until="domcontentloaded", timeout=60000) + time.sleep(10) + except Exception: + pass + team_id = None + m = re.search(r"/workspace/(\d+)", pg.url) + if m: + team_id = int(m.group(1)) + if not team_id: + team_id = pg.evaluate("""async () => { + try { + const r = await fetch('https://client.camb.ai/uservault/auth/refresh-token', + {method:'POST', credentials:'include', headers:{'Content-Type':'application/json'}, body:'{}'}); + const j = await r.json(); + const jwt = (j.payload||{}).access_token || ''; + if (!jwt) return 'NOJWT:'+r.status; + const r2 = await fetch('https://client.camb.ai/v1/teams/', + {credentials:'include', headers:{'Authorization':'Bearer '+jwt}}); + const j2 = await r2.json(); + const teams = (j2.payload||{}).teams || j2.payload || []; + const t = teams[0] || {}; + return t.id || t.team_id || ('NOTEAM:'+JSON.stringify(j2).slice(0,120)); + } catch(e){ return 'ERR:'+e.message; } + }""") + print(f"[{tag}] team_id:", team_id, "url:", pg.url[:90]) + if isinstance(team_id, str): + print(f"[{tag}] team debug: {team_id}") + team_id = None + if not team_id: + return {"email": email, "password": pw, "error": "no_team"} + rec = {"email": email, "password": pw, "team_id": team_id, "credits": 5000, "ts": int(time.time())} + return rec + + +def create_key(p, team_id, tag, attempts=3): + """Fresh browser session (profile keeps cookies), open api-keys, create key.""" + key = None + for att in range(attempts): + try: + chr.ensure(9242, r"C:\Users\User\tmp\camb\prof_farm") + time.sleep(4) + b = p.chromium.connect_over_cdp("http://127.0.0.1:9242") + ctx = b.contexts[0] + pg = ctx.new_page() + pg.goto(f"https://studio.camb.ai/workspace/{team_id}/api-keys", wait_until="domcontentloaded", timeout=60000) + time.sleep(14) + if "/public/onboarding" in pg.url: + print(f"[{tag}] create_key: not verified, at {pg.url}") + try: + pg.close() + except Exception: + pass + return None + tt = "" + got = [] + def on_r(r): + try: + if "camb.ai" in r.url and ("api" in r.url.lower() or "key" in r.url.lower()): + body = "" + try: + if "json" in (r.headers.get("content-type") or ""): + body = r.text()[:800] + except Exception: + pass + got.append((r.status, r.request.method, r.url, body)) + except Exception: + pass + pg.on("response", on_r) + for el in pg.query_selector_all("button"): + try: + if "create new api key" in (el.inner_text() or "").lower(): + bb = el.bounding_box() + if bb: + pg.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2) + tt = "clicked create" + break + except Exception: + pass + print(f"[{tag}] create_key att{att}: url={pg.url[:70]} {tt}") + time.sleep(6) + # name input: React controlled -> real keyboard events + nmv = "farm" + str(int(time.time()))[-4:] + inp = pg.query_selector("input[name=api-key-name]") + if inp: + bb = inp.bounding_box() + pg.mouse.click(bb["x"] + 20, bb["y"] + bb["height"] / 2) + time.sleep(0.4) + pg.keyboard.type(nmv, delay=80) + time.sleep(1.2) + print(f"[{tag}] name typed: {inp.input_value()}") + else: + print(f"[{tag}] name input missing") + time.sleep(1.5) + for el in pg.query_selector_all("button"): + try: + if "create secret key" in (el.inner_text() or "").lower(): + bb = el.bounding_box() + if bb: + pg.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2) + print(f"[{tag}] clicked create secret key dis={el.get_attribute('disabled')}") + break + except Exception: + pass + time.sleep(10) + for st, meth, url, body in got: + print(f"[{tag}] KEYEV {st} {meth} {url.split('camb.ai')[-1][:70]} {body[:220]}") + if not key: + for pat in (r'"api_key"\s*:\s*"([^"]{20,})"', r'"key"\s*:\s*"([^"]{20,})"', + r'"secret"\s*:\s*"([^"]{20,})"'): + m2 = re.search(pat, body) + if m2 and not m2.group(1).startswith("eyJ"): + key = m2.group(1) + break + if not key: + for el in pg.query_selector_all("input"): + try: + v = el.input_value() + if v and len(v) >= 30 and " " not in v.strip() and re.fullmatch(r"[A-Za-z0-9\-]+", v.strip()): + key = v.strip() + break + except Exception: + pass + if not key: + cands = pg.evaluate("""() => { + const out = []; + for (const el of document.querySelectorAll('input,textarea,code,pre,div,span,p')) { + let v = (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') ? (el.value || '') : (el.innerText || ''); + v = (v || '').trim(); + if (v.length >= 24 && v.length <= 120 && !v.includes(' ')) out.push(v); + } + return [...new Set(out)].slice(0, 30); + }""") + print(f"[{tag}] DOM cands:", cands[:6]) + for c in cands: + if c.startswith("eyJ") or c.count(".") >= 2: + continue + if re.fullmatch(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", c): + key = c + break + if re.fullmatch(r"[0-9a-fA-F]{32,48}", c): + key = c + break + try: + pg.close() + except Exception: + pass + if key: + break + except Exception as e: + print(f"[{tag}] create_key err att{att}", type(e).__name__, str(e)[:100]) + kill_chrome(9242) + time.sleep(3) + print(f"[{tag}] api_key:", key) + return key + + +def kill_chrome(port): + import psutil + for pr in psutil.process_iter(["pid", "name", "cmdline"]): + try: + if pr.info["name"] and "chrome" in pr.info["name"].lower(): + cl = " ".join(pr.info["cmdline"] or []) + if f"--remote-debugging-port={port}" in cl: + psutil.Process(pr.info["pid"]).kill() + except Exception: + pass + time.sleep(3) + + +def main(): + mails = [] + for line in open(MPOOL, encoding="utf-8", errors="ignore"): + line = line.strip() + if ":" in line and "@" in line: + e, p = line.split(":", 1) + mails.append((e.strip(), p.strip())) + print(f"pool: {len(mails)}") + kill_chrome(9242) + time.sleep(3) + with sync_playwright() as p: + for i in range(N): + email, mpass = mails[START + i] + tag = f"A{i}" + print(f"=== {tag} {email}") + try: + chr.ensure(9242, r"C:\Users\User\tmp\camb\prof_farm") + b = p.chromium.connect_over_cdp("http://127.0.0.1:9242") + main_ctx = b.contexts[0] + except Exception as e: + print(f"[{tag}] browser dead: {str(e)[:80]}") + rec = {"email": email, "error": f"browser:{str(e)[:80]}"} + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(rec) + "\n") + time.sleep(20) + continue + try: + rec = one(main_ctx, email, mpass, tag) + except Exception as e: + print(f"[{tag}] FATAL", type(e).__name__, str(e)[:120]) + rec = {"email": email, "error": f"fatal:{str(e)[:100]}"} + if rec and rec.get("team_id") and not rec.get("error"): + key = create_key(p, rec["team_id"], tag) + rec["api_key"] = key + if not key: + rec["error"] = "no_key" + else: + try: + r = requests.post("https://client.camb.ai/apis/tts-stream", + json={"text": "Test.", "language": "en-us", "voice_id": 147320, + "speech_model": "mars-flash", "output_configuration": {"format": "wav"}}, + headers={"x-api-key": key}, stream=True, timeout=90) + rec["tts_check"] = r.status_code + rec["tts_credits"] = r.headers.get("x-credits-required") + print(f"[{tag}] tts check: {r.status_code} credits={rec['tts_credits']}") + r.close() + if r.status_code != 200: + rec["api_key"] = None + rec["error"] = f"bad_key:{r.status_code}" + except Exception as e: + rec["tts_check"] = f"err:{str(e)[:60]}" + if rec: + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(rec) + "\n") + time.sleep(random.randint(20, 40)) + print("DONE") + + +if __name__ == "__main__": + main() \ No newline at end of file