init
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
*.jsonl
|
||||
*.txt
|
||||
__pycache__/
|
||||
.2cap_key
|
||||
fbkey.txt
|
||||
@@ -0,0 +1,38 @@
|
||||
# bria-autoreg
|
||||
|
||||
Autoreg for [Bria AI](https://bria.ai) media API (Fibo 2 / Fibo Lite image generation).
|
||||
Zero captcha, zero email verification: Firebase `signUp` -> session -> `create_organization` -> API key.
|
||||
|
||||
## What you get per account
|
||||
* **100 free API calls** (`lite` counts the same as `full`), no card required.
|
||||
* Hard stop after the quota: `403 free_limit_reached`. Rate limit 10 req/min.
|
||||
* Key is a 32-hex `api_token`, sent as the `api_token:` header (not Bearer).
|
||||
|
||||
## Verified flow (2026-11-01)
|
||||
1. `POST https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=<FB_KEY>` `{email,password,returnSecureToken:true}`
|
||||
* `FB_KEY` = Firebase web key from the `platform` JS bundle (see `fbkey.txt`).
|
||||
* Too many signups from one IP -> `400 TOO_MANY_ATTEMPTS_TRY_LATER` -> rotate egress (IPv6 `/64` boxes or mobile).
|
||||
2. `POST https://platform-api.bria.ai/session/login` -> id token
|
||||
3. `POST https://platform-api.bria.ai/.../create_organization`
|
||||
4. `POST https://api.bria.ai/v2/organizations/api-keys/create` `{key_type:"production"}` with `Org-Id`
|
||||
5. Probe: `POST https://engine.prod.bria-api.com/v2/image/generate/lite` with `api_token` header + `sync:true`
|
||||
|
||||
Measured: ~10s per account, 121/150 (80%) success per wave with egress rotation, generation latency 4.8-6s.
|
||||
|
||||
## Files
|
||||
* `bria_farm.py` - worker: `python bria_farm.py --n 150 --workers 6 --proxy round`
|
||||
* `bria_shim.py` - OpenAI-compatible shim (`/v1/models`, `/v1/images/generations`) with round-robin key pool,
|
||||
dead-key blacklist, 60s cooldown on 429.
|
||||
|
||||
## Env
|
||||
```
|
||||
BRIA_PROXIES=http://user:pass@host:port,... # rotation pool (IPv6 CONNECT proxies work best)
|
||||
BRIA_DIRECT=1 # append direct connection as last resort
|
||||
BRIA_SHIM_PORT=8820
|
||||
BRIA_BANK=/path/bank.jsonl
|
||||
```
|
||||
|
||||
## Bank row
|
||||
```json
|
||||
{"email":"...","password":"...","api_token":"<32hex>","status":"ok","note":"gen=200","proxy":"..."}
|
||||
```
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Bria AI autoreg (platform.bria.ai) -> api_token
|
||||
|
||||
Flow (verified 31.10.2026):
|
||||
1) Firebase signUp POST identitytoolkit.googleapis.com/v1/accounts:signUp?key=<FB_KEY>
|
||||
2) session login POST https://platform-api.bria.ai/session/login {idToken}
|
||||
-> cookie session_production (Domain=.bria.ai)
|
||||
3) create org POST https://platform-api.bria.ai/create_organization/
|
||||
{name, display_name, org_type:"personal"} -> uid
|
||||
4) create api key POST https://api.bria.ai/v2/organizations/api-keys/create
|
||||
headers: Cookie, Org-Id: <uid>, App-Name: platform
|
||||
{name, display_name, key_type:"production"} -> api_token (32 hex)
|
||||
|
||||
No email verification needed: token works immediately after signup.
|
||||
|
||||
Usage:
|
||||
python bria_farm.py --n 5 # 5 accounts
|
||||
python bria_farm.py --n 20 --workers 4 --proxy round
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import secrets
|
||||
import string
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import requests
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BANK = os.path.join(HERE, "bank.jsonl")
|
||||
DONE = os.path.join(HERE, "done_emails.txt")
|
||||
FB_KEY_FILE = os.path.join(HERE, "fbkey.txt")
|
||||
|
||||
FB_KEY = open(FB_KEY_FILE).read().strip() if os.path.exists(FB_KEY_FILE) else ""
|
||||
FB_SIGNUP = "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key="
|
||||
PLAT = "https://platform-api.bria.ai"
|
||||
API = "https://api.bria.ai/v2"
|
||||
ENGINE = "https://engine.prod.bria-api.com"
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
|
||||
|
||||
PROXIES = [p.strip() for p in os.environ.get("BRIA_PROXIES", "").split(",") if p.strip()]
|
||||
if os.environ.get("BRIA_DIRECT", "1") == "1":
|
||||
PROXIES.append(None) # direct last: Firebase IP quota burns fast without rotation
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def log(*a):
|
||||
with _lock:
|
||||
print(time.strftime("%H:%M:%S"), *a, flush=True)
|
||||
|
||||
|
||||
def rand_email():
|
||||
dom = random.choice(["t-online.de", "gmail.com", "web.de", "gmx.de", "mail.ru"])
|
||||
tag = "bria" + "".join(random.choices(string.ascii_lowercase + string.digits, k=12))
|
||||
return f"{tag}@{dom}"
|
||||
|
||||
|
||||
def rand_pw():
|
||||
return "".join(random.choices(string.ascii_letters + string.digits, k=10)) + "!A9"
|
||||
|
||||
|
||||
def px(proxy):
|
||||
if not proxy:
|
||||
return None
|
||||
return {"http": proxy, "https": proxy}
|
||||
|
||||
|
||||
class Account:
|
||||
def __init__(self, proxy=None):
|
||||
self.proxy = proxy
|
||||
self.s = requests.Session()
|
||||
self.s.headers.update({"User-Agent": UA, "App-Name": "platform",
|
||||
"Origin": "https://platform.bria.ai",
|
||||
"Referer": "https://platform.bria.ai/"})
|
||||
if proxy:
|
||||
self.s.proxies.update(px(proxy))
|
||||
self.email = None
|
||||
self.password = None
|
||||
self.id_token = None
|
||||
self.org_uid = None
|
||||
self.api_token = None
|
||||
|
||||
def signup(self):
|
||||
self.email = rand_email()
|
||||
self.password = rand_pw()
|
||||
r = self.s.post(FB_SIGNUP + FB_KEY, json={
|
||||
"email": self.email, "password": self.password, "returnSecureToken": True
|
||||
}, timeout=40)
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"fb_signup {r.status_code} {r.text[:160]}")
|
||||
self.id_token = r.json()["idToken"]
|
||||
|
||||
def drain_email_verify(self):
|
||||
"""Firebase verification mail is optional; ignore failures."""
|
||||
try:
|
||||
self.s.post("https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=" + FB_KEY,
|
||||
json={"requestType": "VERIFY_EMAIL", "idToken": self.id_token}, timeout=30)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def login(self):
|
||||
r = self.s.post(PLAT + "/session/login", json={"idToken": self.id_token}, timeout=40)
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"session_login {r.status_code} {r.text[:160]}")
|
||||
|
||||
def create_org(self):
|
||||
name = "ws" + secrets.token_hex(6)
|
||||
r = self.s.post(PLAT + "/create_organization/", json={
|
||||
"name": name, "display_name": "Bria Workspace", "org_type": "personal"
|
||||
}, timeout=45)
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"create_org {r.status_code} {r.text[:160]}")
|
||||
j = r.json()
|
||||
if not j.get("uid"):
|
||||
raise RuntimeError(f"create_org_nouid {j}")
|
||||
self.org_uid = j["uid"]
|
||||
|
||||
def create_key(self):
|
||||
r = self.s.post(API + "/organizations/api-keys/create",
|
||||
headers={"Org-Id": self.org_uid},
|
||||
json={"name": "default", "display_name": "Default",
|
||||
"key_type": "production"}, timeout=45)
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"create_key {r.status_code} {r.text[:160]}")
|
||||
self.api_token = r.json()["result"]["api_key"]["api_token"]
|
||||
|
||||
def verify_key(self, timeout=90):
|
||||
r = self.s.post(ENGINE + "/v2/image/generate/lite",
|
||||
headers={"api_token": self.api_token},
|
||||
json={"prompt": "a small red cube on white", "sync": True},
|
||||
timeout=timeout)
|
||||
ok = r.status_code == 200 and "image_url" in r.text
|
||||
return ok, r.status_code
|
||||
|
||||
def run(self):
|
||||
self.signup()
|
||||
self.login()
|
||||
self.create_org()
|
||||
self.create_key()
|
||||
return self.api_token
|
||||
|
||||
|
||||
def load_done():
|
||||
if not os.path.exists(DONE):
|
||||
return set()
|
||||
with open(DONE, encoding="utf-8") as f:
|
||||
return {l.strip() for l in f if l.strip()}
|
||||
|
||||
|
||||
def record(acc, status, note=""):
|
||||
row = {"email": acc.email, "password": acc.password, "api_token": acc.api_token,
|
||||
"org_uid": acc.org_uid, "status": status, "note": note,
|
||||
"proxy": acc.proxy or "direct", "ts": int(time.time())}
|
||||
with _lock:
|
||||
with open(BANK, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
with open(DONE, "a", encoding="utf-8") as f:
|
||||
f.write(acc.email + "\n")
|
||||
|
||||
|
||||
def worker(idx, mode):
|
||||
proxies_try = [None]
|
||||
if mode == "round":
|
||||
proxies_try = [PROXIES[idx % len(PROXIES)], None, None]
|
||||
elif mode == "direct":
|
||||
proxies_try = [None, None, None]
|
||||
elif mode.startswith("http"):
|
||||
proxies_try = [mode, None, None]
|
||||
|
||||
last = None
|
||||
for attempt, proxy in enumerate(proxies_try):
|
||||
acc = Account(proxy)
|
||||
try:
|
||||
acc.run()
|
||||
ok, code = acc.verify_key()
|
||||
record(acc, "ok" if ok else "key_nogen", f"gen={code}")
|
||||
log(f"[+] {acc.email} -> {acc.api_token} gen={code} try={attempt}")
|
||||
return True
|
||||
except Exception as e:
|
||||
last = e
|
||||
log(f"[-] {acc.email or '?'} try{attempt} fail: {str(e)[:110]}")
|
||||
time.sleep(2)
|
||||
if last is not None:
|
||||
acc2 = Account(None)
|
||||
acc2.email = getattr(locals().get('acc'), 'email', None) or rand_email()
|
||||
record(acc2, "fail", str(last)[:200])
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--n", type=int, default=5)
|
||||
ap.add_argument("--workers", type=int, default=3)
|
||||
ap.add_argument("--proxy", default="round", help="round | direct | URL")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not FB_KEY:
|
||||
print("no fbkey.txt", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
t0 = time.time()
|
||||
ok = 0
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as ex:
|
||||
futs = [ex.submit(worker, i, args.proxy) for i in range(args.n)]
|
||||
for f in futs:
|
||||
try:
|
||||
ok += 1 if f.result() else 0
|
||||
except Exception:
|
||||
pass
|
||||
log(f"DONE ok={ok}/{args.n} in {int(time.time()-t0)}s bank={BANK}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Bria -> OpenAI-compatible shim (stdlib only, no fastapi).
|
||||
|
||||
Endpoints:
|
||||
GET /v1/models
|
||||
POST /v1/images/generations {prompt, n, size, model, seed, response_format}
|
||||
GET /health
|
||||
|
||||
Models:
|
||||
bria-fibo-2 -> /v2/image/generate (full Fibo 2, ~20s)
|
||||
bria-fibo-lite -> /v2/image/generate/lite (Fibo Lite, ~7s)
|
||||
bria-edit -> /v2/image/edit (needs input image; via /v1/images/edits)
|
||||
|
||||
Key pool: bank.jsonl (status=ok) round-robin.
|
||||
Key death: 401/402/403 -> blacklist; 429 -> cooldown 60s.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BANK = os.environ.get("BRIA_BANK", os.path.join(HERE, "bank.jsonl"))
|
||||
DEAD = os.path.join(HERE, "shim_dead.json")
|
||||
PORT = int(os.environ.get("BRIA_SHIM_PORT", "8805"))
|
||||
ENGINE = "https://engine.prod.bria-api.com"
|
||||
|
||||
MODELS = {
|
||||
"bria-fibo-2": "/v2/image/generate",
|
||||
"bria-fibo-lite": "/v2/image/generate/lite",
|
||||
}
|
||||
_lock = threading.Lock()
|
||||
_dead = set()
|
||||
_cooldown = {}
|
||||
|
||||
|
||||
def load_keys():
|
||||
keys = []
|
||||
if not os.path.exists(BANK):
|
||||
return keys
|
||||
with open(BANK, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
if r.get("status") == "ok" and r.get("api_token"):
|
||||
keys.append(r["api_token"])
|
||||
if os.path.exists(DEAD):
|
||||
try:
|
||||
_dead.update(json.load(open(DEAD)))
|
||||
except Exception:
|
||||
pass
|
||||
return [k for k in keys if k not in _dead]
|
||||
|
||||
|
||||
def save_dead():
|
||||
try:
|
||||
json.dump(sorted(_dead), open(DEAD, "w"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def pick_key():
|
||||
keys = load_keys()
|
||||
now = time.time()
|
||||
for _ in range(len(keys)):
|
||||
k = random.choice(keys)
|
||||
if _cooldown.get(k, 0) <= now:
|
||||
return k
|
||||
return keys[0] if keys else None
|
||||
|
||||
|
||||
def size_to_ratio(size):
|
||||
try:
|
||||
w, h = [int(x) for x in str(size).lower().replace("*", "x").split("x")]
|
||||
except Exception:
|
||||
return "1:1"
|
||||
from math import gcd
|
||||
g = gcd(w, h)
|
||||
return f"{w//g}:{h//g}"
|
||||
|
||||
|
||||
def bria_generate(prompt, model="bria-fibo-2", size="1024x1024", seed=None, timeout=120):
|
||||
path = MODELS.get(model, MODELS["bria-fibo-2"])
|
||||
body = {"prompt": prompt, "aspect_ratio": size_to_ratio(size), "sync": True}
|
||||
if seed:
|
||||
body["seed"] = int(seed)
|
||||
last = None
|
||||
for _ in range(4):
|
||||
key = pick_key()
|
||||
if not key:
|
||||
raise RuntimeError("no live keys in bank")
|
||||
req = urllib.request.Request(
|
||||
ENGINE + path, data=json.dumps(body).encode(),
|
||||
headers={"api_token": key, "Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
d = json.loads(r.read().decode())
|
||||
res = d.get("result") or {}
|
||||
url = res.get("image_url")
|
||||
if not url:
|
||||
raise RuntimeError("no image_url in response")
|
||||
return {"url": url, "seed": res.get("seed"), "raw": res}
|
||||
except urllib.error.HTTPError as e:
|
||||
code = e.code
|
||||
last = f"upstream {code}: {e.read()[:200]}"
|
||||
with _lock:
|
||||
if code in (401, 402, 403):
|
||||
_dead.add(key)
|
||||
save_dead()
|
||||
elif code == 429:
|
||||
_cooldown[key] = time.time() + 60
|
||||
continue
|
||||
except Exception as e:
|
||||
last = str(e)
|
||||
continue
|
||||
raise RuntimeError(last or "bria failed")
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
sys.stderr.write("%s %s\n" % (time.strftime("%H:%M:%S"), fmt % args))
|
||||
|
||||
def _send(self, code, obj):
|
||||
data = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/health"):
|
||||
keys = load_keys()
|
||||
return self._send(200, {"status": "ok", "live_keys": len(keys),
|
||||
"dead": len(_dead), "models": list(MODELS)})
|
||||
if self.path.startswith("/v1/models"):
|
||||
now = int(time.time())
|
||||
return self._send(200, {"object": "list", "data": [
|
||||
{"id": m, "object": "model", "created": now, "owned_by": "bria"}
|
||||
for m in MODELS]})
|
||||
return self._send(404, {"error": {"message": "not found"}})
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
try:
|
||||
body = json.loads(self.rfile.read(n) or b"{}")
|
||||
except Exception:
|
||||
return self._send(400, {"error": {"message": "bad json"}})
|
||||
if self.path.startswith("/v1/chat/completions"):
|
||||
return self._chat(body)
|
||||
if self.path.startswith("/v1/images/generations"):
|
||||
prompt = body.get("prompt") or ""
|
||||
if not prompt:
|
||||
return self._send(400, {"error": {"message": "prompt required"}})
|
||||
model = body.get("model") or "bria-fibo-2"
|
||||
count = max(1, min(int(body.get("n") or 1), 4))
|
||||
out = []
|
||||
try:
|
||||
for _ in range(count):
|
||||
g = bria_generate(prompt, model, body.get("size") or "1024x1024",
|
||||
body.get("seed"))
|
||||
out.append({"url": g["url"], "revised_prompt": prompt})
|
||||
return self._send(200, {"created": int(time.time()), "data": out})
|
||||
except Exception as e:
|
||||
return self._send(502, {"error": {"message": str(e)[:400]}})
|
||||
return self._send(404, {"error": {"message": "not found"}})
|
||||
|
||||
def _chat(self, body):
|
||||
model = body.get("model") or "bria-fibo-lite"
|
||||
msgs = body.get("messages") or []
|
||||
prompt = ""
|
||||
for m in msgs:
|
||||
c = m.get("content")
|
||||
if isinstance(c, list):
|
||||
c = " ".join(x.get("text", "") for x in c if isinstance(x, dict))
|
||||
if m.get("role") == "user":
|
||||
prompt = c or prompt
|
||||
elif not prompt and c:
|
||||
prompt = c
|
||||
if not prompt:
|
||||
return self._send(400, {"error": {"message": "empty prompt"}})
|
||||
try:
|
||||
g = bria_generate(prompt, model, body.get("size") or "1024x1024", body.get("seed"))
|
||||
except Exception as e:
|
||||
return self._send(502, {"error": {"message": str(e)[:400]}})
|
||||
content = "\n%s" % (g["url"], json.dumps(
|
||||
{"image_url": g["url"], "seed": g.get("seed"), "model": model}, ensure_ascii=False))
|
||||
return self._send(200, {
|
||||
"id": "chatcmpl-bria-%d" % int(time.time() * 1000),
|
||||
"object": "chat.completion",
|
||||
"created": int(time.time()),
|
||||
"model": model,
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": content},
|
||||
"finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": len(prompt) // 4, "completion_tokens": 1,
|
||||
"total_tokens": len(prompt) // 4 + 1},
|
||||
})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", PORT), H)
|
||||
print(f"bria-shim on :{PORT}, keys={len(load_keys())}", flush=True)
|
||||
srv.serve_forever()
|
||||
Reference in New Issue
Block a user