Files
camb-autoreg/camb_shim.py
T

201 lines
6.6 KiB
Python

#!/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():
"""[RR 1101] round-robin over live keys.
CAMB throttles a single account when many requests hit it back to back, and one
slow key used to add its full timeout to every call. Start each request at a
different offset so load spreads across the pool.
"""
global _idx
now = time.time()
live = [k for k in _keys if k not in _dead and _cool.get(k, 0) <= now]
if not live:
live = [k for k in _keys if k not in _dead]
if not live:
return []
with _lock:
start = _idx % len(live)
_idx += 1
return live[start:] + live[:start]
def call_upstream(key, body, timeout=75):
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()