From c234e452f7ac65020276cd46696081cf1474e5c9 Mon Sep 17 00:00:00 2001 From: ENI Date: Sun, 1 Nov 2026 03:09:27 +0300 Subject: [PATCH] smallest.ai autoreg + Waves cookie-pool shim --- .gitignore | 5 + README.md | 99 +++++++++++++++ deploy/patch_gates.py | 48 +++++++ deploy/pg_inject.sh | 13 ++ deploy/smallest-shim.service | 14 +++ reg.py | 222 ++++++++++++++++++++++++++++++++ shim.py | 238 +++++++++++++++++++++++++++++++++++ waves.py | 108 ++++++++++++++++ 8 files changed, 747 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 deploy/patch_gates.py create mode 100644 deploy/pg_inject.sh create mode 100644 deploy/smallest-shim.service create mode 100644 reg.py create mode 100644 shim.py create mode 100644 waves.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..535f9cd --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +bank.jsonl +used_mails.txt +*.wav +*.log +cookies.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..52ad8e2 --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# smallest.ai autoreg + Waves pool + +Автоматическая регистрация аккаунтов [smallest.ai](https://app.smallest.ai) (Waves TTS / instant voice cloning), банк сессий и локальный OpenAI-совместимый шим для раздачи TTS через свой new-api. + +Регистрация **без капчи, без SMS, без телефона** — только email OTP. Один аккаунт = 10 бесплатных кредитов (`plan_standard`). + +## Что внутри + +| Файл | Назначение | +|------|-----------| +| `reg.py` | авторег: send-otp → чтение кода из IMAP (через VPS) → verify → онбординг → банк | +| `waves.py` | клиент Waves на cookie-сессиях: TTS, список голосов, instant voice cloning | +| `shim.py` | HTTP-шим `127.0.0.1:48014`: `/v1/audio/speech`, `/v1/voices`, `/v1/voices/clone`, ротация аккаунтов | +| `deploy/smallest-shim.service` | systemd-юнит | +| `deploy/pg_inject.sh` | создание канала `smallest-tts` + abilities + тестового токена в new-api (PostgreSQL) | +| `deploy/patch_gates.py` | снятие трёх гейтов iishko (rank_models, toolgate, sso_limits) | + +## Auth-стек (reverse) + +Фронт `app.smallest.ai` (Next.js) ходит в четыре бэкенда: + +``` +https://api.smallest.ai/atoms/v1 # профиль, организации, онбординг +https://api.smallest.ai/console/v1 # OTP-логин, API-ключи, платежи +https://api.smallest.ai/waves/v1 # TTS, voice cloning, голоса +https://api.smallest.ai/payment/v1 # баланс кредитов +``` + +Поток регистрации: + +1. `GET /console/v1/csrf-token` → cookie + токен, дальше заголовок `x-csrf-token` +2. `POST /console/v1/auth/send-otp` `{"userEmail": "..."}` +3. письмо `noreply@smallest.ai`, тема `Your verification code`, код 6 цифр в тексте `Here is the code to verify and sign into account. 123456` +4. `POST /console/v1/auth/verify-otp` **form-urlencoded**: `userEmail`, `otp`, `origin=console` + → `302 /dashboard/settings/subscription`, ставятся cookies `accessToken` / `refreshToken`, организация создаётся автоматически +5. `POST /atoms/v1/onboarding/create` `{"data": {name, nameType:"workspace", firstName, lastName, helpOption:"voice-cloning", platform:"Atoms"}}` + (тело **обязательно** завёрнуто в `data`, иначе `400 {"error":{"_errors":[],"data":{"_errors":["Required"]}}}`) +6. `GET /payment/v1/credits/balance` → `{"creditBalance":10,"planId":"plan_standard"}` + +Особенности: +- `origin` в verify-otp принимает только `console | waves | atoms | universe` — URL отбивается `error=Origin must be one of: ...` +- org-scoped ручки (`/apikeys/*`, `/credits/*`) требуют заголовок `X-Organization-Id: ` +- у `console/v1` и `atoms/v1` **свои** csrf-эндпоинты, токен нужен на каждую базу +- `POST /console/v1/apikeys/create-api-key` возвращает ключ **только маской** (`sk_b35...17aa`), полное значение сервер не отдаёт → работаем на cookie-сессиях + +## Waves API + +``` +GET /waves/v1/lightning-v3.1/get_voices # список голосов +POST /waves/v1/lightning-v3.1/get_speech # {"text","voice_id","sample_rate","output_format"} +GET /waves/v1/voice-cloning/models # lightning-v3.1 / lightning-v3.1-pro (32 языка) +POST /waves/v1/voice-cloning/upload-audio # multipart file + model + language, аудио <= 15 сек +POST /waves/v1/voice-cloning/create # {"voiceId","displayName","description","accent","tags","language"} +GET /waves/v1/voice-cloning # мои клоны +``` + +Цена: **0.0175 кредита / 1000 символов** TTS → 10 кредитов ≈ **572 000 символов** озвучки с аккаунта. Клонирование голоса кредитов практически не тратит (0.002 за цикл TTS+upload+clone). + +## Быстрый старт + +```bash +# 1) авторег 10 аккаунтов, 4 воркера +python reg.py wave 10 4 # -> bank.jsonl, used_mails.txt + +# 2) проверить аккаунт: баланс, голоса, клоны +python waves.py probe + +# 3) озвучка / клонирование +python waves.py tts "текст" lakshya +python waves.py clone sample.wav "Мой голос" +``` + +Почта: пул `working_mails.txt` в формате `addr:pass` (t-online), коды читаются по SSH с VPS (`SM_VPS`), локальный IMAP t-online рвёт соединение после ~30 логинов с одного IP. + +## Шим на прод + +```bash +scp shim.py root@HOST:/opt/smallest-shim/shim.py +scp bank.jsonl root@HOST:/opt/smallest-shim/bank.jsonl +scp deploy/smallest-shim.service root@HOST:/etc/systemd/system/ +ssh root@HOST 'systemctl daemon-reload && systemctl enable --now smallest-shim' +curl -s 127.0.0.1:48014/status +``` + +Дальше канал в new-api: + +```bash +bash deploy/pg_inject.sh # channels + abilities + токен sm-test +python3 deploy/patch_gates.py # rank_models / toolgate / sso_limits +``` + +Проверка: `POST /v1/audio/speech {"model":"smallest-tts","input":"...","voice":"lakshya"}` → 200, WAV. + +## Ограничения + +- Сессия живёт на cookies `accessToken/refreshToken` (~месяц); после протухания нужен повторный OTP-логин на тот же email +- Клонирование принимает аудио **≤ 15 секунд** (27.3 с отбивается `400 Audio is 27.3 s long; voice clone audio must be at most 15 seconds`) +- Один аккаунт = один workspace (`nameType: workspace`), переименование через `PUT /account/update-org-name` +- Ключи API панель не отдаёт в открытом виде → пул работает на сессиях, а не на ключах \ No newline at end of file diff --git a/deploy/patch_gates.py b/deploy/patch_gates.py new file mode 100644 index 0000000..513551d --- /dev/null +++ b/deploy/patch_gates.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Add smallest-tts models to the three iishko gates (idempotent, backed up).""" +import shutil, sys, time + +STAMP = time.strftime("%Y%m%d-%H%M%S") +NEW = ["smallest-tts", "smallest-tts-pro"] + + +def patch(path, old, new, label): + try: + src = open(path, encoding="utf-8").read() + except FileNotFoundError: + print("MISS %s %s" % (label, path)) + return + if new.strip() in src and all(('"%s"' % m) in src for m in NEW): + print("SKIP %s already patched" % label) + return + if old not in src: + print("WARN %s anchor not found in %s" % (label, path)) + return + shutil.copy2(path, path + ".bak-sm-" + STAMP) + open(path, "w", encoding="utf-8").write(src.replace(old, new, 1)) + print("OK %s patched" % label) + + +def main(): + # 1) bot rank_models: model disappears from token limits on every user activity + patch("/opt/grok-bot/iishko/legacy.py", + 'models += [m for m in ("eleven-tts", "qwen3-tts-flash") if m not in models]', + 'models += [m for m in ("eleven-tts", "qwen3-tts-flash", "smallest-tts", "smallest-tts-pro") if m not in models]', + "legacy.rank_models") + + # 2) toolgate allow-list + patch("/root/toolgate.py", + 'ALLOW.append("eleven-tts")', + 'ALLOW.append("eleven-tts")\nfor _m in ("smallest-tts", "smallest-tts-pro"):\n ALLOW.append(_m)', + "toolgate") + + # 3) sso_limits MODELS (tokens.model_limits source) + patch("/root/sso_limits.py", + 'MODELS += [m for m in ["eleven-tts","qwen3-tts-flash"] if m not in MODELS]', + 'MODELS += [m for m in ["eleven-tts","qwen3-tts-flash","smallest-tts","smallest-tts-pro"] if m not in MODELS]', + "sso_limits") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/deploy/pg_inject.sh b/deploy/pg_inject.sh new file mode 100644 index 0000000..5bdb342 --- /dev/null +++ b/deploy/pg_inject.sh @@ -0,0 +1,13 @@ +#!/bin/bash +CID=115991 +for M in smallest-tts smallest-tts-pro; do + for G in default premium t1 t2 t3 t4; do + sudo -u postgres psql -d newapi -q -c "insert into abilities (\"group\",model,channel_id,enabled,priority,weight,tag) values ('$G','$M',$CID,true,700,1,'sm');" >/dev/null 2>&1 + done +done +echo "abilities=$(sudo -u postgres psql -d newapi -tAc "select count(*) from abilities where channel_id=$CID;" 2>/dev/null | tr -d ' ')" +KEY=$(cat /root/_sm_key) +systemctl restart new-api; sleep 10 +curl -s -m 120 -o /tmp/gw.wav -w "gateway:%{http_code} size:%{size_download}\n" -X POST http://127.0.0.1:48000/v1/audio/speech -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"model":"smallest-tts","input":"gateway routing check one two three","voice":"lakshya"}' +file /tmp/gw.wav +head -c 120 /tmp/gw.wav diff --git a/deploy/smallest-shim.service b/deploy/smallest-shim.service new file mode 100644 index 0000000..df362d8 --- /dev/null +++ b/deploy/smallest-shim.service @@ -0,0 +1,14 @@ +[Unit] +Description=smallest.ai Waves shim (cookie pool) +After=network-online.target + +[Service] +Type=simple +Environment=SS_BANK=/opt/smallest-shim/bank.jsonl +Environment=SS_PORT=48014 +ExecStart=/usr/bin/python3 /opt/smallest-shim/shim.py +Restart=always +RestartSec=3 + +[Install] +WantedBy=multi-user.target diff --git a/reg.py b/reg.py new file mode 100644 index 0000000..798b526 --- /dev/null +++ b/reg.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python +"""smallest.ai (smallest.ai / Waves) autoreg pipeline. + +Flow (no captcha, no SMS, email OTP only): + 1) GET /console/v1/csrf-token -> x-csrf-token cookie + token + 2) POST /console/v1/auth/send-otp {userEmail} -> OTP mail from noreply@smallest.ai + 3) POST /console/v1/auth/verify-otp (form-urlencoded: userEmail, otp, origin=console) + -> 302 to /dashboard/settings/subscription, sets accessToken/refreshToken cookies + 4) GET /atoms/v1/account/get-account-details -> userId + orgId (auto-created) + 5) POST /atoms/v1/onboarding/create {"data":{...}} -> hasOnboarded=true + 6) GET /payment/v1/credits/balance -> 10.0 free credits (plan_standard) + 7) POST /console/v1/apikeys/create-api-key -> key record (value masked server-side) + +Every write to waves/console needs X-Organization-Id for org-scoped routes. +""" +import json, os, random, re, subprocess, sys, threading, time +import requests + +BASE = "https://api.smallest.ai" +CONSOLE = BASE + "/console/v1" +ATOMS = BASE + "/atoms/v1" +PAYMENT = BASE + "/payment/v1" +WAVES = BASE + "/waves/v1" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36") + +HERE = os.path.dirname(os.path.abspath(__file__)) +MAIL_POOL = r"C:\Users\User\Desktop\avtoreg\working_mails.txt" +USED_FILE = os.path.join(HERE, "used_mails.txt") +BANK = os.path.join(HERE, "bank.jsonl") +VPS = os.environ.get("SM_VPS", "root@144.31.34.147") +IMAP_HOST = "secureimap.t-online.de" + +_lock = threading.Lock() + + +# ---------------------------------------------------------------- mail reader +def _ssh(cmd, timeout=180): + p = subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", VPS, cmd], + capture_output=True, text=True, timeout=timeout) + return (p.stdout or "") + (p.stderr or "") + + +def fetch_code(email, pw, timeout=150): + """Poll the mailbox (on VPS, t-online IMAP is throttled from home) for the + smallest.ai OTP. Returns 6-digit code or None.""" + remote = ( + 'python3 - "%s" "%s" %d <<\'PYEOF\'\n' + "import imaplib,email,re,sys,time,html\n" + "addr,pw,tmo=sys.argv[1],sys.argv[2],int(sys.argv[3])\n" + "t0=time.time()\n" + "while time.time()-t0]+>',' ',b)); t=re.sub(r'\\s+',' ',t)\n" + " mm=re.search(r'account\\.\\s*(\\d{6})',t) or re.search(r'\\b(\\d{6})\\b',t)\n" + " if mm:\n" + " print('CODE',mm.group(1)); m.logout(); sys.exit(0)\n" + " m.logout()\n" + " except Exception as e:\n" + " print('ERR',type(e).__name__)\n" + " time.sleep(5)\n" + "print('NONE')\n" + "PYEOF\n" % (email, pw, timeout) + ) + out = _ssh(remote, timeout=timeout + 60) + m = re.search(r"CODE (\d{6})", out) + return m.group(1) if m else None + + +# ------------------------------------------------------------------- http ops +def new_session(referer="/login"): + s = requests.Session() + s.headers.update({"User-Agent": UA, "Origin": "https://app.smallest.ai", + "Referer": "https://app.smallest.ai" + referer, + "Accept": "application/json, text/plain, */*"}) + return s + + +def csrf(s, base=CONSOLE): + tok = json.loads(s.get(base + "/csrf-token", timeout=25).text)["csrfToken"] + s.headers["x-csrf-token"] = tok + return tok + + +def register(email, pw, otp_timeout=150, verbose=True): + """Returns dict with session cookies + org/user ids, or {'error': ...}.""" + s = new_session() + csrf(s) + r = s.post(CONSOLE + "/auth/send-otp", json={"userEmail": email}, timeout=30) + if r.status_code != 200 or "success" not in r.text.lower(): + return {"error": "send-otp %s %s" % (r.status_code, r.text[:120])} + code = fetch_code(email, pw, timeout=otp_timeout) + if not code: + return {"error": "no-otp"} + r = s.post(CONSOLE + "/auth/verify-otp", + data={"userEmail": email, "otp": code, "origin": "console"}, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + timeout=30, allow_redirects=False) + loc = r.headers.get("location", "") + if "error=" in loc: + return {"error": "verify %s" % loc.split("error=")[-1][:80]} + if "accessToken" not in s.cookies: + return {"error": "no-token %s" % loc[:80]} + acc = s.get(ATOMS + "/account/get-account-details", timeout=25).json() + org = acc["organizations"][0]["orgId"] + uid = acc["userId"] + s.headers["X-Organization-Id"] = org + csrf(s, ATOMS) + body = {"data": {"name": "Wave Labs", "nameType": "workspace", + "firstName": "Alex", "lastName": "M", + "helpOption": "voice-cloning", "platform": "Atoms"}} + onb = s.post(ATOMS + "/onboarding/create", json=body, timeout=30) + bal = s.get(PAYMENT + "/credits/balance", timeout=25) + credits = None + try: + credits = bal.json()["data"]["creditBalance"] + except Exception: + pass + rec = {"email": email, "pw": pw, "userId": uid, "orgId": org, + "credits": credits, "onboarded": onb.status_code == 201, + "cookies": s.cookies.get_dict(), "ts": int(time.time())} + if verbose: + print("OK %s org=%s credits=%s onb=%s" % (email, org, credits, onb.status_code), flush=True) + return rec + + +def make_key(rec, name="auto"): + s = session_from(rec) + csrf(s) + s.headers["X-Organization-Id"] = rec["orgId"] + r = s.post(CONSOLE + "/apikeys/create-api-key", + json={"userId": rec["userId"], "apiKeyName": name}, timeout=30) + return r.status_code, r.text[:200] + + +def session_from(rec, referer="/dashboard"): + s = new_session(referer) + for k, v in rec["cookies"].items(): + s.cookies.set(k, v, domain="api.smallest.ai") + s.headers["X-Organization-Id"] = rec["orgId"] + return s + + +# ------------------------------------------------------------------- wave run +def load_pool(): + used = set() + if os.path.exists(USED_FILE): + used = {l.strip() for l in open(USED_FILE, encoding="utf-8", errors="ignore")} + out = [] + for l in open(MAIL_POOL, encoding="utf-8", errors="ignore"): + l = l.strip() + if not l or l.startswith("#") or ":" not in l: + continue + em, pw = l.split(":", 1) + if "@t-online.de" not in em or em in used: + continue + out.append((em, pw)) + random.shuffle(out) + return out + + +def wave(n=5, workers=3): + pool = load_pool() + print("pool free:", len(pool), flush=True) + todo = pool[: max(n * 2, n)] + q = list(todo) + got = 0 + res = [] + + def worker(): + nonlocal got + while True: + with _lock: + if not q or got >= n: + return + em, pw = q.pop(0) + try: + rec = register(em, pw) + except Exception as e: + rec = {"error": "%s: %s" % (type(e).__name__, e), "email": em, "pw": pw} + if rec.get("error"): + print("FAIL", em, rec["error"][:90], flush=True) + continue + with _lock: + got += 1 + res.append(rec) + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(rec, ensure_ascii=False) + "\n") + with open(USED_FILE, "a", encoding="utf-8") as f: + f.write(em + "\n") + + ths = [threading.Thread(target=worker) for _ in range(workers)] + for t in ths: + t.start() + for t in ths: + t.join() + print("WAVE DONE ok=%d" % len(res), flush=True) + return res + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] == "wave": + n = int(sys.argv[2]) if len(sys.argv) > 2 else 5 + w = int(sys.argv[3]) if len(sys.argv) > 3 else 3 + wave(n, w) + elif len(sys.argv) > 2 and sys.argv[1] == "one": + em, pw = sys.argv[2], sys.argv[3] + rec = register(em, pw) + print(json.dumps({k: v for k, v in rec.items() if k != "cookies"}, indent=1)) + elif len(sys.argv) > 2 and sys.argv[1] == "key": + recs = [json.loads(l) for l in open(BANK, encoding="utf-8")] + for i, rec in enumerate(recs[: int(sys.argv[2])]): + print(rec["email"], make_key(rec, "auto%d" % i)) \ No newline at end of file diff --git a/shim.py b/shim.py new file mode 100644 index 0000000..f16b8ea --- /dev/null +++ b/shim.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""smallest-shim: OpenAI-compatible TTS/clone front-end over a pool of +smallest.ai dashboards (cookie sessions, no API keys needed). + +Listens on 127.0.0.1:48014, rotates accounts round-robin by remaining credits, +retries the next account on 401/402/429/5xx. + +Endpoints + GET /status pool + balances + GET /v1/models model list + GET /v1/voices premade + cloned voices of the active account + POST /v1/audio/speech {model,input,voice,response_format,speed} -> audio + POST /v1/voices/clone multipart: file=, name=, language=en +""" +import json, os, threading, time, urllib.request, urllib.error, uuid, base64 + +BANK = os.environ.get("SS_BANK", "/opt/smallest-shim/bank.jsonl") +PORT = int(os.environ.get("SS_PORT", "48014")) +BASE = "https://api.smallest.ai" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36") +MODELS = ["smallest-tts", "smallest-tts-pro"] + +_lock = threading.Lock() +_state = {"i": 0} + + +def load_bank(): + recs = [] + try: + for line in open(BANK, encoding="utf-8"): + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + if r.get("cookies"): + recs.append(r) + except FileNotFoundError: + pass + return recs + + +def http(method, url, body=None, headers=None, timeout=180, raw=False): + req = urllib.request.Request(url, data=body, method=method) + for k, v in (headers or {}).items(): + req.add_header(k, v) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + data = r.read() + return r.status, (data if raw else data.decode("utf-8", "replace")) + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace") + except Exception as e: + return 0, "%s: %s" % (type(e).__name__, e) + + +def cookies_of(rec): + return "; ".join("%s=%s" % (k, v) for k, v in rec["cookies"].items()) + + +def hdrs(rec, extra=None): + h = {"User-Agent": UA, "Cookie": cookies_of(rec), + "X-Organization-Id": rec["orgId"], "Origin": "https://app.smallest.ai", + "Referer": "https://app.smallest.ai/dashboard"} + h.update(extra or {}) + return h + + +def speak(rec, text, voice, model, speed, fmt): + mm = "lightning-v3.1-pro" if model == "smallest-tts-pro" else "lightning-v3.1" + payload = json.dumps({"text": text, "voice_id": voice, "sample_rate": 24000, + "speed": speed or 1.0, "output_format": fmt or "wav"}).encode() + return http("POST", "%s/waves/v1/%s/get_speech" % (BASE, mm), payload, + hdrs(rec, {"Content-Type": "application/json"}), raw=True) + + +def pick(): + bank = load_bank() + if not bank: + return None + with _lock: + idx = _state["i"] + _state["i"] = (idx + 1) % len(bank) + return bank[idx] + + +def do_speech(text, voice="lakshya", model="smallest-tts", speed=1.0, fmt="wav"): + bank = load_bank() + if not bank: + return 503, b"no accounts in pool" + start = _state["i"] + last = (500, "no attempt") + for n in range(min(len(bank), 8)): + rec = bank[(start + n) % len(bank)] + st, data = speak(rec, text, voice, model, speed, fmt) + if st == 200 and isinstance(data, bytes) and len(data) > 1000: + with _lock: + _state["i"] = (start + n + 1) % len(bank) + return 200, data + last = (st, data[:200] if isinstance(data, bytes) else data[:200]) + if st in (200,): + continue + return (last[0] or 502), (last[1] if isinstance(last[1], bytes) else str(last[1]).encode()) + + +def do_clone(fields, file_bytes, filename): + rec = pick() + if not rec: + return 503, {"error": "no accounts"} + boundary = "----ss" + uuid.uuid4().hex + parts = [] + for k in ("model", "language"): + if k in fields: + parts.append(("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n" + % (boundary, k, fields[k])).encode()) + parts.append(("--%s\r\nContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\n" + "Content-Type: audio/wav\r\n\r\n" % (boundary, filename)).encode()) + parts.append(file_bytes) + parts.append(("\r\n--%s--\r\n" % boundary).encode()) + body = b"".join(parts) + st, txt = http("POST", BASE + "/waves/v1/voice-cloning/upload-audio", body, + hdrs(rec, {"Content-Type": "multipart/form-data; boundary=" + boundary})) + if st != 200: + return st, {"error": txt[:300]} + up = json.loads(txt)["data"] + body2 = json.dumps({"voiceId": up["voiceId"], + "displayName": fields.get("name", "clone"), + "description": fields.get("description", "shim clone"), + "accent": fields.get("accent", "American"), + "tags": [], "language": fields.get("language", "en")}).encode() + st2, txt2 = http("POST", BASE + "/waves/v1/voice-cloning/create", body2, + hdrs(rec, {"Content-Type": "application/json"})) + if st2 != 200: + return st2, {"error": txt2[:300]} + d = json.loads(txt2)["data"] + return 200, {"id": d.get("_id"), "voice": up["voiceId"], "status": d.get("status")} + + +# ------------------------------------------------------------------ HTTP layer +def make_handler(): + from http.server import BaseHTTPRequestHandler + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + 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 _bin(self, code, data, ctype="audio/wav"): + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + p = self.path.split("?")[0] + if p == "/status": + bank = load_bank() + return self._json(200, {"accounts": len(bank), + "emails": [r["email"] for r in bank[:50]], + "models": MODELS}) + if p in ("/v1/models", "/models"): + return self._json(200, {"object": "list", + "data": [{"id": m, "object": "model"} for m in MODELS]}) + if p in ("/v1/voices", "/voices"): + rec = pick() + if not rec: + return self._json(503, {"error": "no accounts"}) + st, txt = http("GET", BASE + "/waves/v1/lightning-v3.1/get_voices", None, hdrs(rec)) + if st != 200: + return self._json(st, {"error": txt[:200]}) + return self._json(200, json.loads(txt)) + return self._json(404, {"error": "not found"}) + + def do_POST(self): + p = self.path.split("?")[0] + n = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(n) if n else b"" + if p in ("/v1/audio/speech", "/audio/speech"): + try: + j = json.loads(body or b"{}") + except Exception: + return self._json(400, {"error": "bad json"}) + st, data = do_speech(j.get("input") or j.get("text") or "", + j.get("voice") or "lakshya", + j.get("model") or "smallest-tts", + j.get("speed") or 1.0, + j.get("response_format") or "wav") + if st != 200: + return self._json(st, {"error": str(data)[:300]}) + ctype = "audio/mpeg" if (j.get("response_format") == "mp3") else "audio/wav" + return self._bin(200, data, ctype) + if p in ("/v1/voices/clone", "/voices/clone"): + ctype = self.headers.get("Content-Type", "") + fields, fbytes, fname = {}, b"", "sample.wav" + if "multipart/form-data" in ctype: + boundary = ctype.split("boundary=")[-1].strip().strip('"') + for chunk in body.split(b"--" + boundary.encode()): + if b"Content-Disposition" not in chunk: + continue + head, _, val = chunk.partition(b"\r\n\r\n") + head_s = head.decode("utf-8", "replace") + val = val.rstrip(b"\r\n-") + if "filename=" in head_s: + fbytes = val + fname = head_s.split("filename=")[1].split('"')[1] + else: + name = head_s.split('name="')[1].split('"')[0] + fields[name] = val.decode("utf-8", "replace") + else: + fields = json.loads(body or b"{}") + fbytes = base64.b64decode(fields.pop("file_b64", "")) + if not fbytes: + return self._json(400, {"error": "no audio"}) + st, out = do_clone(fields, fbytes, fname) + return self._json(st, out) + return self._json(404, {"error": "not found"}) + + return H + + +if __name__ == "__main__": + from http.server import ThreadingHTTPServer + srv = ThreadingHTTPServer(("127.0.0.1", PORT), make_handler()) + print("smallest-shim on :%d bank=%s accounts=%d" % (PORT, BANK, len(load_bank())), flush=True) + srv.serve_forever() \ No newline at end of file diff --git a/waves.py b/waves.py new file mode 100644 index 0000000..48ec088 --- /dev/null +++ b/waves.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +"""Cookie-session client for smallest.ai Waves (TTS + instant voice cloning). + +Auth: accessToken/refreshToken cookies obtained by reg.py. No API key needed - +the dashboard itself calls /waves/v1/* with cookies + X-Organization-Id. +""" +import json, os, sys +import requests + +BASE = "https://api.smallest.ai" +WAVES = BASE + "/waves/v1" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36") +HERE = os.path.dirname(os.path.abspath(__file__)) + + +class Waves: + def __init__(self, rec): + self.rec = rec + s = requests.Session() + s.headers.update({"User-Agent": UA, "Origin": "https://app.smallest.ai", + "Referer": "https://app.smallest.ai/dashboard", + "X-Organization-Id": rec["orgId"], + "Accept": "application/json, text/plain, */*"}) + for k, v in rec["cookies"].items(): + s.cookies.set(k, v, domain="api.smallest.ai") + self.s = s + + # ---- voices + def voices(self, model="lightning-v3.1"): + return self.s.get(WAVES + "/%s/get_voices" % model, timeout=30).json().get("voices", []) + + def clone_models(self): + return self.s.get(WAVES + "/voice-cloning/models", timeout=30).json()["data"] + + def clones(self): + return self.s.get(WAVES + "/voice-cloning", timeout=30).json().get("data", []) + + # ---- tts + def tts(self, text, voice_id="lakshya", model="lightning-v3.1", + sample_rate=24000, fmt="wav", speed=1.0): + r = self.s.post(WAVES + "/%s/get_speech" % model, + json={"text": text, "voice_id": voice_id, + "sample_rate": sample_rate, "speed": speed, + "output_format": fmt}, timeout=180) + if r.status_code != 200: + raise RuntimeError("tts %s %s" % (r.status_code, r.text[:200])) + return r.content + + # ---- cloning + def upload(self, path, model="lightning-v3.1-pro", language="en"): + with open(path, "rb") as fh: + files = {"file": (os.path.basename(path), fh, "audio/wav")} + r = self.s.post(WAVES + "/voice-cloning/upload-audio", + files=files, data={"model": model, "language": language}, + timeout=240) + if r.status_code != 200: + raise RuntimeError("upload %s %s" % (r.status_code, r.text[:300])) + return r.json()["data"] + + def create_clone(self, voice_id, display_name, description="", accent="American", + tags=None, language="en"): + body = {"voiceId": voice_id, "displayName": display_name, + "description": description, "accent": accent, + "tags": tags or [], "language": language} + r = self.s.post(WAVES + "/voice-cloning/create", json=body, timeout=180) + if r.status_code != 200: + raise RuntimeError("clone %s %s" % (r.status_code, r.text[:300])) + return r.json()["data"] + + def delete_clone(self, clone_id): + return self.s.post(WAVES + "/voice-cloning/delete", json={"id": clone_id}, timeout=60). status_code + + def credits(self): + return self.s.get(BASE + "/payment/v1/credits/balance", timeout=30).json()["data"] + + +def load_bank(): + p = os.path.join(HERE, "bank.jsonl") + return [json.loads(l) for l in open(p, encoding="utf-8")] + + +if __name__ == "__main__": + cmd = sys.argv[1] if len(sys.argv) > 1 else "probe" + bank = load_bank() + rec = bank[0] + w = Waves(rec) + if cmd == "probe": + print("account", rec["email"], "credits", w.credits()) + print("clone models", [m["model"] for m in w.clone_models()]) + print("voices", [v["voiceId"] for v in w.voices()][:10]) + print("clones", [(c["voiceId"], c["displayName"], c["status"]) for c in w.clones()]) + elif cmd == "tts": + audio = w.tts(sys.argv[2], voice_id=sys.argv[3] if len(sys.argv) > 3 else "lakshya") + out = "out.wav" + open(out, "wb").write(audio) + print("wrote", out, len(audio), "bytes") + elif cmd == "clone": + sample = sys.argv[2] + name = sys.argv[3] if len(sys.argv) > 3 else "Clone 1" + up = w.upload(sample) + vid = up["voiceId"] + print("uploaded", vid) + c = w.create_clone(vid, name) + print("clone", c["_id"], c["status"]) + print("credits", w.credits()) + else: + print("usage: waves.py probe|tts [voice]|clone [name]") \ No newline at end of file