238 lines
9.8 KiB
Python
238 lines
9.8 KiB
Python
#!/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=<wav>, name=<str>, 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() |