|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# Author: @Scottcjn (Elyan Labs) |
| 3 | +""" |
| 4 | +BoTTube Studio — pay RTC to generate a video. Technical demo of the pay-to-generate |
| 5 | +flow on RustChain's own RTC token (no external gatekeeper, ships today). The GENERATION |
| 6 | +layer is pluggable: today it uses the existing /api/generate-video cascade |
| 7 | +(LTX -> Ken Burns -> ffmpeg); when the Alibaba Cloud video API + SDK arrive, Alibaba |
| 8 | +slots into that cascade (video_providers.py) with NO change to this Studio code — the |
| 9 | +currency + UI here stay identical. |
| 10 | +
|
| 11 | +Endpoints: |
| 12 | + GET /studio -> the Studio storefront page |
| 13 | + GET /api/studio/info -> tiers + caller's RTC balance |
| 14 | + POST /api/studio/generate -> {prompt, tier} : atomic RTC debit + start generation |
| 15 | +
|
| 16 | +RTC debit is atomic (conditional UPDATE ... WHERE rtc_balance >= cost) and refunds if |
| 17 | +the generation fails to start. |
| 18 | +""" |
| 19 | +import os |
| 20 | +import sqlite3 |
| 21 | +import threading |
| 22 | +import time |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +from flask import Blueprint, jsonify, render_template, request, session |
| 26 | + |
| 27 | +studio_bp = Blueprint("studio", __name__) |
| 28 | + |
| 29 | +# RTC price per tier (env-overridable). Demo defaults; tune freely. |
| 30 | +STUDIO_TIERS = { |
| 31 | + "text_card": {"rtc": float(os.environ.get("STUDIO_RTC_TEXT", "1")), |
| 32 | + "name": "Text Card", "desc": "Instant title-card video", "badge": "CHEAPEST", "duration": 5}, |
| 33 | + "ken_burns": {"rtc": float(os.environ.get("STUDIO_RTC_KENBURNS", "3")), |
| 34 | + "name": "Ken Burns", "desc": "Cinematic pan & zoom over images", "badge": "POPULAR", "duration": 8}, |
| 35 | + "full_ai": {"rtc": float(os.environ.get("STUDIO_RTC_FULLAI", "5")), |
| 36 | + "name": "Full AI Video", "desc": "LTX-2 generated, with audio", "badge": "PREMIUM", "duration": 8}, |
| 37 | +} |
| 38 | +PROMPT_MAX = 500 |
| 39 | +_rate = {} |
| 40 | +_COOLDOWN = float(os.environ.get("STUDIO_COOLDOWN", "30")) # per-caller, protects the GPU |
| 41 | + |
| 42 | + |
| 43 | +def _db_path() -> str: |
| 44 | + base = os.environ.get("BOTTUBE_BASE_DIR", str(Path(__file__).resolve().parent)) |
| 45 | + return os.environ.get("BOTTUBE_DB_PATH", str(Path(base) / "bottube.db")) |
| 46 | + |
| 47 | + |
| 48 | +def _conn(): |
| 49 | + c = sqlite3.connect(_db_path(), timeout=30) |
| 50 | + c.row_factory = sqlite3.Row |
| 51 | + c.execute("PRAGMA busy_timeout=30000") |
| 52 | + return c |
| 53 | + |
| 54 | + |
| 55 | +def _resolve_caller(conn): |
| 56 | + """(id, agent_name, rtc_balance) for an API agent (X-API-Key/agent_api_key) or a |
| 57 | + logged-in human (session), else None.""" |
| 58 | + api_key = request.headers.get("X-API-Key", "") |
| 59 | + if not api_key: |
| 60 | + api_key = ((request.get_json(silent=True) or {}).get("agent_api_key") or "").strip() |
| 61 | + if api_key: |
| 62 | + row = conn.execute( |
| 63 | + "SELECT id, agent_name, rtc_balance FROM agents WHERE api_key=? AND COALESCE(is_banned,0)=0", |
| 64 | + (api_key,)).fetchone() |
| 65 | + if row: |
| 66 | + return row |
| 67 | + uid = session.get("user_id") |
| 68 | + if uid: |
| 69 | + row = conn.execute( |
| 70 | + "SELECT id, agent_name, rtc_balance FROM agents WHERE id=? AND COALESCE(is_banned,0)=0", |
| 71 | + (uid,)).fetchone() |
| 72 | + if row: |
| 73 | + return row |
| 74 | + return None |
| 75 | + |
| 76 | + |
| 77 | +@studio_bp.route("/studio") |
| 78 | +def studio_home(): |
| 79 | + tiers = [{"key": k, **v} for k, v in STUDIO_TIERS.items()] |
| 80 | + return render_template("studio.html", studio_tiers=tiers) |
| 81 | + |
| 82 | + |
| 83 | +@studio_bp.route("/api/studio/info", methods=["GET"]) |
| 84 | +def studio_info(): |
| 85 | + conn = _conn() |
| 86 | + try: |
| 87 | + caller = _resolve_caller(conn) |
| 88 | + bal = round(caller["rtc_balance"], 6) if caller else None |
| 89 | + signed_in = caller is not None |
| 90 | + finally: |
| 91 | + conn.close() |
| 92 | + return jsonify({ |
| 93 | + "ok": True, |
| 94 | + "signed_in": signed_in, |
| 95 | + "rtc_balance": bal, |
| 96 | + "tiers": {k: v["rtc"] for k, v in STUDIO_TIERS.items()}, |
| 97 | + }) |
| 98 | + |
| 99 | + |
| 100 | +@studio_bp.route("/api/studio/generate", methods=["POST"]) |
| 101 | +def studio_generate(): |
| 102 | + body = request.get_json(silent=True) or {} |
| 103 | + prompt = (body.get("prompt") or "").strip() |
| 104 | + tier = (body.get("tier") or "").strip() |
| 105 | + if not prompt: |
| 106 | + return jsonify({"error": "prompt required"}), 400 |
| 107 | + if len(prompt) > PROMPT_MAX: |
| 108 | + return jsonify({"error": f"prompt exceeds {PROMPT_MAX} characters"}), 400 |
| 109 | + if tier not in STUDIO_TIERS: |
| 110 | + return jsonify({"error": "unknown tier"}), 400 |
| 111 | + cost = STUDIO_TIERS[tier]["rtc"] |
| 112 | + |
| 113 | + conn = _conn() |
| 114 | + try: |
| 115 | + caller = _resolve_caller(conn) |
| 116 | + if not caller: |
| 117 | + return jsonify({"error": "sign in (or use an API key) to generate"}), 401 |
| 118 | + agent_id = caller["id"] |
| 119 | + |
| 120 | + # Per-caller cooldown (protect the single GPU). |
| 121 | + now = time.time() |
| 122 | + last = _rate.get(agent_id, 0) |
| 123 | + if now - last < _COOLDOWN: |
| 124 | + return jsonify({"error": "slow down a moment", |
| 125 | + "retry_after": round(_COOLDOWN - (now - last), 1)}), 429 |
| 126 | + |
| 127 | + # ATOMIC debit: only succeeds if balance covers the cost (prevents races/overspend). |
| 128 | + cur = conn.execute( |
| 129 | + "UPDATE agents SET rtc_balance = rtc_balance - ? WHERE id = ? AND rtc_balance >= ?", |
| 130 | + (cost, agent_id, cost)) |
| 131 | + conn.commit() |
| 132 | + if cur.rowcount == 0: |
| 133 | + bal = conn.execute("SELECT rtc_balance FROM agents WHERE id=?", (agent_id,)).fetchone() |
| 134 | + return jsonify({"error": "insufficient RTC balance", "needed": cost, |
| 135 | + "balance": round(bal["rtc_balance"], 6) if bal else 0}), 402 |
| 136 | + _rate[agent_id] = now |
| 137 | + new_balance = conn.execute("SELECT rtc_balance FROM agents WHERE id=?", (agent_id,)).fetchone()["rtc_balance"] |
| 138 | + finally: |
| 139 | + conn.close() |
| 140 | + |
| 141 | + # Start generation by reusing the existing cascade (Alibaba slots in here later). |
| 142 | + try: |
| 143 | + from video_gen_blueprint import _create_job, _generation_worker |
| 144 | + job_id = _create_job(agent_id, prompt) |
| 145 | + threading.Thread( |
| 146 | + target=_generation_worker, |
| 147 | + args=(job_id, agent_id, prompt, STUDIO_TIERS[tier]["duration"], "ai-art", prompt[:200]), |
| 148 | + daemon=True, |
| 149 | + ).start() |
| 150 | + except Exception as e: |
| 151 | + # Refund on failure to start — never charge for a job we couldn't launch. |
| 152 | + try: |
| 153 | + rc = _conn() |
| 154 | + rc.execute("UPDATE agents SET rtc_balance = rtc_balance + ? WHERE id = ?", (cost, agent_id)) |
| 155 | + rc.commit(); rc.close() |
| 156 | + except sqlite3.Error: |
| 157 | + pass |
| 158 | + print(f"[studio] generation start failed (refunded {cost} RTC): {e}", flush=True) |
| 159 | + return jsonify({"error": "couldn't start generation; your RTC was refunded"}), 502 |
| 160 | + |
| 161 | + return jsonify({ |
| 162 | + "ok": True, |
| 163 | + "job_id": job_id, |
| 164 | + "tier": tier, |
| 165 | + "charged_rtc": cost, |
| 166 | + "new_balance": round(new_balance, 6), |
| 167 | + "status_url": f"/api/generate-video/status/{job_id}", |
| 168 | + "message": "Generation started. Poll status_url for the video.", |
| 169 | + }), 202 |
0 commit comments