AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Automating Bulk Video Generation with DeepBrain AI Studios REST API and Webhooks

Sergio García Encina · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

When technical teams need to generate hundreds or thousands of personalized videos—such as customized student onboarding messages, dynamic monthly financial statement summaries, or localized programmatic marketing campaigns—relying on the AI Studios web interface is an operational dead end. Manually pasting scripts, repositioning avatar frames, selecting voice timbres, and queuing individual browser exports consumes hundreds of engineering and design hours while introducing unacceptable human error.

At 365Finds, our institutional stance is unambiguous: for any workload exceeding 20 personalized videos per batch, engineering teams should bypass the graphical UI entirely and deploy an event-driven rendering pipeline using the DeepBrain AI Studios V3 REST API and Webhooks. This guide details how to construct an automated bulk generation architecture: configuring App ID and UserKey authentication, generating 24-hour JSON Web Tokens (JWTs), parameterizing multi-layer JSON templates, and establishing an asynchronous webhook callback receiver to pull finalized MP4 assets into production storage.

flowchart LR
    A["Customer Data / CRM"] --> B["Template Compiler / Worker"]
    B --> C["DeepBrain AI V3 API<br>(POST /editor/project)"]
    C --> D["DeepBrain Rendering Queue"]
    D -->|Async Completion| E["Developer Webhook Receiver<br>(POST /webhooks/deepbrain)"]
    E --> F["Asset Ingestion & S3/R2 Storage"]
    E --> G["CRM / User Notification"]

Architecture Overview and Core Workflow

DeepBrain AI Studios V3 structures video synthesis into a declarative JSON document model. Rather than rendering videos synchronously over a long-lived HTTP connection (which would inevitably trigger gateway timeouts, as avatar rendering requires 1 to 10 minutes depending on duration and server load), the API operates on an asynchronous event-driven model:

  1. Token Acquisition: Exchange static account credentials (appId and userKey) for a time-limited Bearer token (valid for 24 hours).
  2. Payload Compilation: Inject dynamic customer variables (recipient names, financial figures, localized audio scripts, background images) into a pre-structured JSON scene graph.
  3. Synthesis Dispatch: Send a single HTTP POST request to /api/odin/v3/editor/project containing the scene data, export flags, and your dedicated webhookUrl.
  4. Asynchronous Webhook Ingestion: DeepBrain AI notifies your HTTP callback URL when rendering completes, transmitting the final download_url, compute task metadata, and credit consumption metrics.
  5. Storage Pipeline: Your receiver verifies the callback payload, downloads the raw MP4 stream, stores it in enterprise cloud storage (Amazon S3, Cloudflare R2, or Google Cloud Storage), and flags the job as complete.

Step 1: Authentication and Token Lifecycle Management

DeepBrain AI Studios V3 utilizes a two-tier authentication architecture. You do not pass your raw API keys directly in high-frequency rendering requests; instead, you issue an ephemeral JWT access token.

Generating Credentials

  1. Sign in to your AI Studios account (requires an active Pro or Enterprise plan with API access enabled).
  2. Navigate to your profile in the top-right corner, select Profile, and scroll to Issue API Key.
  3. Generate and record both your App ID (appId) and UserKey (userKey). Note that userKey is revealed only once upon creation; store it immediately in an enterprise secrets manager (such as AWS Secrets Manager or HashiCorp Vault).

Domain Selection Caution

DeepBrain maintains isolated infrastructure environments:

Ensure all endpoint configurations target the appropriate jurisdiction.

Token Exchange Implementation

The access token returned by DeepBrain AI is valid for 24 hours (86,400 seconds). In a production bulk generation environment, creating a new token per video request will throttle your authentication limits. Cache the token in memory or Redis with a 23-hour time-to-live (TTL).

Python Authentication Client

import time
import requests

class DeepBrainAuth:
    def __init__(self, app_id: str, user_key: str, base_url: str = "https://app.aistudios.com"):
        self.app_id = app_id
        self.user_key = user_key
        self.base_url = base_url
        self._cached_token = None
        self._token_expires_at = 0

    def get_token(self) -> str:
        # Re-authenticate 10 minutes before actual expiration
        if self._cached_token and time.time() < (self._token_expires_at - 600):
            return self._cached_token

        url = f"{self.base_url}/api/odin/v3/auth/token"
        payload = {
            "appId": self.app_id,
            "userKey": self.user_key
        }
        headers = {"Content-Type": "application/json"}

        response = requests.post(url, json=payload, headers=headers, timeout=10)
        response.raise_for_status()
        data = response.json()

        if not data.get("token"):
            raise ValueError(f"Failed to retrieve token: {data}")

        self._cached_token = data["token"]
        self._token_expires_at = time.time() + 86400
        return self._cached_token

Step 2: Designing Parameterized JSON Video Templates

The core of DeepBrain AI bulk rendering is the declarative scene document. A project consists of global properties (name, orientation, resolution) and a sequence of scenes. Each scene contains background definitions, text/image overlay clips, and the synthetic avatar (aiModel).

The Critical ID Synchronization Constraint

A frequent stumbling block for developers integrating DeepBrain AI V3 is the strict property binding between the audio speech script and the avatar clip. DeepBrain decouples the script array (scenes[].scripts[]) from the visual clip layout (scenes[].clips[]). However:

If these identifiers diverge, the rendering engine fails silently or reverts to a default avatar, corrupting bulk output.

Standard Parameterized Template Payload

Below is a production-grade JSON template structure configured for a 1080p landscape personalized welcome video:

{
  "name": "Personalized_Onboarding_{{USER_ID}}",
  "orientation": "landscape",
  "resolution": "1080",
  "isExport": true,
  "webhookUrl": "https://api.yourdomain.com/webhooks/deepbrain",
  "scenes": [
    {
      "sceneIdx": 0,
      "watermark": false,
      "background": {
        "id": "background",
        "type": "background",
        "source_type": "image",
        "source_url": "https://assets.yourdomain.com/backgrounds/modern_office.jpg",
        "source_color": "rgb(255,255,255)"
      },
      "scripts": [
        {
          "org": "Hello {{USER_NAME}}, welcome to the platform. Your account balance is {{ACCOUNT_BALANCE}} dollars.",
          "isTTS": false,
          "tts": null,
          "modelId": "M000045058",
          "clothId": "BG00002320"
        }
      ],
      "clips": [
        {
          "id": "avatar-main",
          "type": "aiModel",
          "layer": 1,
          "top": 146.74,
          "left": 630.25,
          "width": 679,
          "height": 2229,
          "scaleX": 1,
          "scaleY": 1,
          "effects": [
            {
              "type": "head-only"
            }
          ],
          "model": {
            "ai_name": "M000045058",
            "emotion": "BG00002320",
            "language": "en"
          }
        },
        {
          "id": "text-title",
          "type": "textImage",
          "layer": 2,
          "top": 120.0,
          "left": 100.0,
          "width": 500,
          "height": 100,
          "text": "Welcome, {{USER_NAME}}!",
          "fill": "rgb(33,33,33)",
          "fontSize": 48,
          "fontFamily": "Noto Sans CJK",
          "align": "left"
        }
      ]
    }
  ]
}

Exploring Models and Custom Voices

To programmatically discover available avatar models and outfits, invoke:

curl https://app.aistudios.com/api/odin/v3/dropdown/models \
  -H "Authorization: ${BEARER_TOKEN}" \
  -H "Content-Type: application/json"

If your campaign demands a third-party synthetic voice (e.g., ElevenLabs or Google Cloud TTS) rather than the avatar's native actor voice:

  1. Set scripts[].isTTS to true.
  2. Populate scripts[].tts with the voice configuration payload or pre-generate an audio track via POST /api/odin/v3/tools/voice-generator and bind it as an audio clip.

Step 3: Triggering Generation with Webhook Bindings

When dispatching bulk jobs, pass isExport: true and specify your public webhookUrl directly in the project creation payload. This ensures the rendering engine immediately initiates synthesis upon project instantiation without requiring a secondary export API call.

Node.js Bulk Dispatch Worker

import axios from 'axios';

async function dispatchVideoGeneration(projectPayload, token) {
  const url = 'https://app.aistudios.com/api/odin/v3/editor/project';
  
  try {
    const response = await axios.post(url, projectPayload, {
      headers: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      timeout: 15000
    });

    if (response.data && response.data.success) {
      const projectId = response.data.data.projectId;
      console.log(`[DeepBrain] Successfully queued video synthesis. Project ID: ${projectId}`);
      return projectId;
    } else {
      throw new Error(`API returned failure: ${JSON.stringify(response.data)}`);
    }
  } catch (error) {
    console.error('[DeepBrain] Dispatch error:', error.response?.data || error.message);
    throw error;
  }
}

Step 4: Building the Webhook Callback Receiver

The webhook receiver is the critical event ingestion point. Video synthesis takes several minutes. When the export concludes, DeepBrain sends an HTTP POST request to your specified webhookUrl.

DeepBrain Webhook Payload Structure

When rendering reaches completion, DeepBrain delivers the following JSON body:

{
  "progress": 100,
  "credit": 5,
  "backendTaskId": "65fa6b07dca2e367461a2925",
  "download_url": "https://cdn-studio.aistudios.com/videos/export/65fa6b07dca2e367461a2925.mp4"
}

Express.js Webhook Receiver Implementation

The receiver must respond with an HTTP 200 OK promptly to prevent DeepBrain from registering a delivery failure, while offloading media downloading and ingestion to an asynchronous worker queue.

import express from 'express';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import axios from 'axios';

const app = express();
app.use(express.json());

const s3 = new S3Client({ region: 'us-east-1' });

app.post('/webhooks/deepbrain', async (req, res) => {
  const { progress, credit, backendTaskId, download_url } = req.body;

  console.log(`[Webhook] Event received for Task ${backendTaskId}. Progress: ${progress}%`);

  // Acknowledge receipt immediately to avoid upstream timeout
  res.status(200).json({ received: true });

  if (progress === 100 && download_url) {
    try {
      console.log(`[Storage] Fetching generated MP4 from ${download_url}`);
      
      // Stream directly from DeepBrain CDN to internal S3 bucket
      const videoStream = await axios.get(download_url, { responseType: 'stream' });
      
      const uploadParams = {
        Bucket: 'production-video-assets',
        Key: `personalized/${backendTaskId}.mp4`,
        Body: videoStream.data,
        ContentType: 'video/mp4'
      };

      await s3.send(new PutObjectCommand(uploadParams));
      console.log(`[Storage] Successfully archived video for task ${backendTaskId}. Used ${credit} credits.`);

      // Trigger downstream CRM notification or email delivery
      // await notifyCustomer(backendTaskId);
    } catch (err) {
      console.error(`[Storage] Failed to archive video for task ${backendTaskId}:`, err);
    }
  }
});

app.listen(3000, () => console.log('DeepBrain webhook listener active on port 3000'));

Step 5: Enterprise Production Hardening and Best Practices

Scaling an automated pipeline to handle tens of thousands of video renders per month introduces operational edge cases that simple scripts cannot withstand. 365Finds recommends adhering to the following structural conventions:

1. Concurrency Management and Throttling

Do not fire 500 parallel HTTP requests simultaneously. While DeepBrain operates server-side queuing, dumping massive request spikes can trigger rate limiting (HTTP 429) or gateway drops.

2. Implement the "Missing Webhook" Polling Reconciliation Worker

While webhooks provide 99% reliability, network transient drops, corporate firewalls, or receiver restarts can cause dropped callback events.

3. Public Asset Hosting Cleanliness

All image and video assets injected into scenes (company logos, personalized product cards, custom backgrounds) must be publicly accessible over HTTPS without basic auth or IP whitelisting. DeepBrain's cloud render workers fetch these URLs during frame compositing. Ensure your storage bucket serves these assets with high availability and low latency.

4. Text and Script Sanitization

Avoid embedding unescaped angle brackets or complex HTML in scripts[].org. While <p> tags are tolerated, nested tags or unexpected punctuation can cause phoneme parsing failures in the speech synthesizer. Validate customer inputs with a sanitization pass before compiling the scene payload.


Decision Matrix: Web UI vs. REST API vs. Custom SDK

CriteriaAI Studios Web UIREST API (V3) + WebhooksAI Human SDK (Interactive)
Primary Use CaseOne-off marketing clips, executive messages, manual PPT conversionsProgrammatic personalized video, high-volume transactional summaries, CRM-triggered outreachReal-time conversational kiosks, interactive web customer support
Output FormatRendered MP4 video fileRendered MP4 video fileReal-time WebRTC audio/video stream
Volume Capability1 to 10 videos/dayHundreds to thousands/dayConcurrent real-time sessions
Developer OverheadZero (visual editor)Moderate (JSON formatting, webhook setup, asset pipeline)High (client SDK integration, WebSocket/WebRTC management)
LatencyManual rendering queue (minutes)Asynchronous batch (1–10 minutes/job)Real-time (<1 second conversational response)

Institutional Judgment

365Finds considers the DeepBrain AI Studios REST API (V3) a robust, enterprise-capable engine for asynchronous video synthesis. However, developers must recognize that its JSON template specification is low-level and unforgiving: rigid bounding-box geometries and strict ID matching between clips and speech tracks require thorough schema validation before dispatch.

Teams adopting this pipeline should not write raw JSON strings in business code. Instead, construct a typed builder pattern or internal template compiler that abstracts DeepBrain's pixel-coordinate layer model. Combining this abstraction with a resilient webhook ingestion worker and a 24-hour token caching strategy delivers an automated, cost-efficient video manufacturing machine capable of powering high-impact personalized communication at scale.


References