{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "colab": {
      "name": "character-performance.ipynb"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Crucible Character Performance\n",
        "\n",
        "Animate **people, animals, or illustrated characters** with your recording. Choose lip sync, natural gestures, or rap performance. Use a clear image of one subject with a visible mouth. Include the upper body and hands/paws if you want gestures.\n",
        "\n",
        "This notebook uses **Kling AI Avatar v2 through Hedra**, a paid API. A normal **CPU runtime** is enough; Google GPU credits do not pay for these renders. Create a [Hedra API key](https://www.hedra.com/develop/api-keys) and fund its separate [API wallet](https://www.hedra.com/develop/billing). Enter the key only in the hidden prompt below, never in notebook code or chat. Your selected image and audio clip are uploaded to Hedra.\n",
        "\n",
        "Run the cells in order. Start with a **10-second test**. The live API estimate appears before a separate confirmation to render. Rerunning the render cell resumes the same saved job in this runtime instead of purchasing another render. Save the printed job ID to recover after a runtime reset.\n",
        "\n",
        "**Limits:** this is a new integration, awaiting a real paid render test. Animal and character support is documented by the provider; exact mouth shapes and gestures still need visual review. Objects with drawn mouths are experimental. There is no universal mouth detector or guarantee that every visible mouth will animate. If the renderer cannot use the subject, choose a clearer single-subject image. Gesture prompts guide the model; they are not exact motion capture or instrument fingering.\n"
      ],
      "id": "character-00"
    },
    {
      "cell_type": "code",
      "metadata": {
        "tags": [
          "settings"
        ],
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": [],
      "source": [
        "#@title 1 \u00b7 Choose your character and movement\n",
        "subject = \"Animal\" #@param [\"Human\", \"Animal\", \"Illustrated character\", \"Object with a mouth (experimental)\"]\n",
        "movement = \"Natural gestures\" #@param [\"Lip sync focus\", \"Natural gestures\", \"Rap performance\"]\n",
        "intensity = \"Subtle\" #@param [\"Subtle\", \"Medium\", \"Energetic\"]\n",
        "direction = \"\" #@param {type:\"string\"}\n",
        "aspect_ratio = \"9:16\" #@param [\"9:16\", \"16:9\", \"1:1\"]\n",
        "quality = \"standard\" #@param [\"standard\", \"pro\"]\n",
        "start_seconds = 0 #@param {type:\"number\"}\n",
        "clip_seconds = 10 #@param {type:\"number\"}\n",
        "# A previous job ID retrieves that existing render without submitting another.\n",
        "resume_job_id = \"\" #@param {type:\"string\"}\n",
        "print(\"Choose 2\u201360 seconds. Include visible hands or paws for gesture prompts.\")\n",
        "print(\"After changing settings, rerun this cell and the preparation cell.\")\n"
      ],
      "id": "character-01"
    },
    {
      "cell_type": "code",
      "metadata": {
        "tags": [
          "dependencies"
        ],
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": [],
      "source": [
        "#@title 2 \u00b7 Load the renderer\n",
        "import sys, subprocess\n",
        "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"requests\", \"Pillow\", \"jsonschema\"], check=True)\n"
      ],
      "id": "character-02"
    },
    {
      "cell_type": "code",
      "metadata": {
        "tags": [
          "renderer"
        ],
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": [],
      "source": [
        "#@title 2b \u00b7 Set up the character renderer\n",
        "import hashlib, json, math, mimetypes, os, time\n",
        "from pathlib import Path\n",
        "from urllib.parse import quote, urlparse\n",
        "import requests\n",
        "\n",
        "API = \"https://api.hedra.com/v3\"\n",
        "MODEL = \"kling-ai-avatar-v2\"\n",
        "SUBJECTS = {\n",
        "    \"Human\": \"Keep the same human identity, facial structure and body proportions.\",\n",
        "    \"Animal\": \"Keep the animal's species, muzzle, fur, ears, paws and anatomy. Do not add human hands, teeth or a human face.\",\n",
        "    \"Illustrated character\": \"Keep the original illustration style, facial design and drawn anatomy.\",\n",
        "    \"Object with a mouth (experimental)\": \"Animate only the existing drawn mouth. Preserve the object's material and silhouette. Do not add a human face or extra limbs.\",\n",
        "}\n",
        "MOVEMENTS = {\n",
        "    \"Lip sync focus\": \"Prioritize mouth motion synchronized to the supplied audio. Keep the body still with only small natural blinks and head movement.\",\n",
        "    \"Natural gestures\": \"Use relaxed, coherent body language and natural head movement with the delivery. When visible and anatomically appropriate, use occasional hand or paw gestures.\",\n",
        "    \"Rap performance\": \"Perform the supplied rap with rhythmic head nods and expressive upper-body movement following the delivery. When visible and anatomically appropriate, use purposeful hand or paw gestures on emphatic phrases.\",\n",
        "}\n",
        "\n",
        "def performance_input(subject, movement, intensity, direction, aspect_ratio, quality):\n",
        "    if subject not in SUBJECTS or movement not in MOVEMENTS:\n",
        "        raise ValueError(\"Choose a supported subject and movement option.\")\n",
        "    if intensity not in (\"Subtle\", \"Medium\", \"Energetic\"):\n",
        "        raise ValueError(\"Choose Subtle, Medium or Energetic movement.\")\n",
        "    if aspect_ratio not in (\"9:16\", \"16:9\", \"1:1\") or quality not in (\"standard\", \"pro\"):\n",
        "        raise ValueError(\"Choose a listed aspect ratio and quality.\")\n",
        "    prompt = \" \".join([\n",
        "        \"One continuous shot of the single subject in the image performing the supplied audio with synchronized mouth movement.\",\n",
        "        SUBJECTS[subject], MOVEMENTS[movement],\n",
        "        f\"Movement intensity: {intensity.lower()}.\",\n",
        "        \"Preserve identity, existing limbs and background. Keep the camera steady. Do not invent instruments or unseen hands.\",\n",
        "        direction.strip(),\n",
        "    ])\n",
        "    if len(prompt) > 2500:\n",
        "        raise ValueError(\"Shorten the extra direction; the complete prompt must fit 2,500 characters.\")\n",
        "    return {\"prompt\": prompt, \"aspect_ratio\": aspect_ratio, \"quality\": quality, \"resolution\": \"720p\", \"num_outputs\": 1}\n",
        "\n",
        "def check_clip(start, length):\n",
        "    if not math.isfinite(start) or start < 0 or not math.isfinite(length) or not 2 <= length <= 60:\n",
        "        raise ValueError(\"Start must be zero or later; clip length must be 2\u201360 seconds.\")\n",
        "\n",
        "def save_state(path, state):\n",
        "    temporary = path.with_suffix(\".tmp\")\n",
        "    temporary.write_text(json.dumps(state), encoding=\"utf-8\")\n",
        "    temporary.chmod(0o600)\n",
        "    temporary.replace(path)\n",
        "\n",
        "def api_json(session, method, path, **kwargs):\n",
        "    try:\n",
        "        response = session.request(method, API + path, timeout=60, allow_redirects=False, **kwargs)\n",
        "    except requests.RequestException:\n",
        "        raise RuntimeError(\"Connection interrupted. Rerun this cell to resume; do not start a fresh job.\") from None\n",
        "    if not 200 <= response.status_code < 300:\n",
        "        hints = {401: \"Check your Hedra v3 API key.\", 402: \"The Hedra API wallet needs funds; Studio credits are separate.\",\n",
        "                 403: \"Check key permissions for file uploads, job submission and reading jobs.\",\n",
        "                 429: \"Rate limited. Wait for the provider's Retry-After interval before resuming.\"}\n",
        "        retry = response.headers.get(\"Retry-After\", \"\")\n",
        "        raise RuntimeError(f\"Hedra HTTP {response.status_code}. \" + hints.get(response.status_code, \"Inspect this job in the Hedra console before retrying.\") + (f\" Retry-After: {retry} seconds.\" if retry.isdigit() else \"\"))\n",
        "    return response.json()\n",
        "\n",
        "def upload_media(session, path):\n",
        "    with path.open(\"rb\") as stream:\n",
        "        result = api_json(session, \"POST\", \"/files\", files={\"file\": (path.name, stream, mimetypes.guess_type(path.name)[0] or \"application/octet-stream\")})\n",
        "    if not isinstance(result.get(\"url\"), str) or urlparse(result[\"url\"]).scheme != \"https\":\n",
        "        raise RuntimeError(\"Hedra did not return a valid upload handle.\")\n",
        "    return {\"source\": \"url\", \"url\": result[\"url\"]}\n",
        "\n",
        "def estimate_price(estimate):\n",
        "    cost = estimate.get(\"cost\")\n",
        "    if estimate.get(\"model\") != MODEL or estimate.get(\"currency\") != \"USD\" or isinstance(cost, bool) or not isinstance(cost, (int, float)) or not math.isfinite(cost) or cost < 0:\n",
        "        raise RuntimeError(\"No valid USD estimate was returned. No render was submitted.\")\n",
        "    return cost\n",
        "\n",
        "def submit_once(session, state_path, model_input):\n",
        "    # Persist the exact payload and idempotency key BEFORE the first POST.\n",
        "    # A lost acknowledgement must replay this same request, not new uploads.\n",
        "    state = json.loads(state_path.read_text())\n",
        "    if state.get(\"job_id\"):\n",
        "        return state[\"job_id\"]\n",
        "    if \"payload\" not in state:\n",
        "        if model_input is None:\n",
        "            raise RuntimeError(\"Prepare and approve this render first.\")\n",
        "        state[\"payload\"] = {\"input\": model_input, \"idempotency_key\": \"crucible-\" + state[\"fingerprint\"]}\n",
        "        save_state(state_path, state)\n",
        "    ack = api_json(session, \"POST\", \"/models/\" + MODEL, json=state[\"payload\"])\n",
        "    if not isinstance(ack.get(\"job_id\"), str) or not ack[\"job_id\"]:\n",
        "        raise RuntimeError(\"No job ID returned. Keep this runtime and resume the same request.\")\n",
        "    state[\"job_id\"] = ack[\"job_id\"]\n",
        "    save_state(state_path, state)\n",
        "    return state[\"job_id\"]\n",
        "\n",
        "def completed_video(result):\n",
        "    if result.get(\"status\") == \"FAILED\":\n",
        "        raise RuntimeError(\"The render failed. Review the job in Hedra; no automatic replacement render was purchased.\")\n",
        "    if result.get(\"status\") != \"COMPLETED\":\n",
        "        raise RuntimeError(\"The video is not complete yet. Resume this job.\")\n",
        "    outputs = result.get(\"outputs\") or []\n",
        "    videos = [x for x in outputs if x.get(\"status\") == \"COMPLETED\" and str(x.get(\"content_type\", \"\")).startswith(\"video/\") and x.get(\"url\")]\n",
        "    if len(videos) != 1 or urlparse(videos[0][\"url\"]).scheme != \"https\":\n",
        "        raise RuntimeError(\"No completed downloadable video. The output may have failed or expired; inspect the existing job.\")\n",
        "    return videos[0][\"url\"]\n",
        "\n",
        "def wait_for_video(session, job_id, seconds=1800):\n",
        "    path = \"/jobs/\" + quote(job_id, safe=\"\")\n",
        "    deadline, last = time.monotonic() + seconds, None\n",
        "    while time.monotonic() < deadline:\n",
        "        status = api_json(session, \"GET\", path + \"/status\")\n",
        "        current = status.get(\"status\")\n",
        "        if current != last:\n",
        "            print(\"Video:\", current, flush=True)\n",
        "            last = current\n",
        "        if current in (\"COMPLETED\", \"FAILED\"):\n",
        "            return completed_video(api_json(session, \"GET\", path))\n",
        "        if current not in (\"IN_QUEUE\", \"IN_PROGRESS\"):\n",
        "            raise RuntimeError(\"Unknown job status. Inspect the existing job; do not create a replacement.\")\n",
        "        time.sleep(10)\n",
        "    raise TimeoutError(\"Still rendering. Rerun this cell to resume the same job. A local timeout does not cancel it.\")\n",
        "\n",
        "def download_video(url, path):\n",
        "    # Never send the Hedra Authorization header to the output storage host.\n",
        "    with requests.get(url, stream=True, timeout=120) as response:\n",
        "        response.raise_for_status()\n",
        "        temporary = path.with_suffix(\".part\")\n",
        "        with temporary.open(\"wb\") as stream:\n",
        "            for chunk in response.iter_content(1024 * 1024):\n",
        "                stream.write(chunk)\n",
        "    temporary.replace(path)\n"
      ],
      "id": "character-03"
    },
    {
      "cell_type": "code",
      "metadata": {
        "tags": [
          "prepare"
        ],
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": [],
      "source": [
        "#@title 3 \u00b7 Upload and prepare your clip\n",
        "from google.colab import files\n",
        "from PIL import Image, ImageOps\n",
        "from IPython.display import display, Video\n",
        "from tempfile import mkdtemp\n",
        "\n",
        "settings = performance_input(subject, movement, intensity, direction, aspect_ratio, quality)\n",
        "check_clip(float(start_seconds), float(clip_seconds))\n",
        "if resume_job_id.strip():\n",
        "    print(\"Recovery mode: the next cell will retrieve job\", resume_job_id.strip())\n",
        "else:\n",
        "    prepared = None  # Changing settings or a failed upload must not reuse old media.\n",
        "    folder = Path(mkdtemp(prefix=\"crucible-character-\"))\n",
        "    def choose_one(label, extensions):\n",
        "        print(label, flush=True)\n",
        "        selected = files.upload()\n",
        "        if len(selected) != 1:\n",
        "            raise ValueError(\"Select exactly one file. Rerun only this preparation cell.\")\n",
        "        name, data = next(iter(selected.items()))\n",
        "        suffix = Path(name).suffix.lower()\n",
        "        if suffix not in extensions:\n",
        "            raise ValueError(\"Choose one of: \" + \", \".join(extensions))\n",
        "        path = folder / (\"image\" if label.startswith(\"Image\") else \"audio\")\n",
        "        path = path.with_suffix(suffix)\n",
        "        path.write_bytes(data)\n",
        "        return path\n",
        "    source_image = choose_one(\"Image: one visible mouth\", [\".png\", \".jpg\", \".jpeg\", \".webp\"])\n",
        "    original_audio = choose_one(\"Audio recording\", [\".mp3\", \".m4a\", \".wav\", \".flac\", \".aac\"])\n",
        "    photo = folder / \"start.png\"\n",
        "    with Image.open(source_image) as source:\n",
        "        normalized = ImageOps.exif_transpose(source).convert(\"RGB\")\n",
        "        normalized.save(photo)\n",
        "    if photo.stat().st_size > 10485760:\n",
        "        raise ValueError(\"The prepared image exceeds 10 MB. Use a smaller image.\")\n",
        "    clip = folder / \"clip.mp3\"\n",
        "    subprocess.run([\"ffmpeg\", \"-y\", \"-loglevel\", \"error\", \"-ss\", str(start_seconds), \"-i\", str(original_audio), \"-t\", str(clip_seconds), \"-vn\", \"-ar\", \"44100\", \"-ac\", \"2\", \"-b:a\", \"192k\", str(clip)], check=True)\n",
        "    duration = float(subprocess.check_output([\"ffprobe\", \"-v\", \"error\", \"-show_entries\", \"format=duration\", \"-of\", \"default=noprint_wrappers=1:nokey=1\", str(clip)], text=True).strip())\n",
        "    if not math.isfinite(duration) or not 2 <= duration <= 60.15 or clip.stat().st_size > 5000000:\n",
        "        raise ValueError(\"The prepared audio must be 2\u201360.15 seconds and at most 5 MB. Adjust the clip range.\")\n",
        "    prepared = {\"photo\": photo, \"clip\": clip, \"settings\": dict(settings), \"start\": start_seconds, \"length\": clip_seconds}\n",
        "    display(Image.open(photo).copy())\n",
        "    print(f\"Prepared {duration:.2f} seconds starting at {start_seconds}s. Subject: {subject}; movement: {movement}.\")\n",
        "    print(\"Review the image. Only the selected audio clip will be rendered.\")\n"
      ],
      "id": "character-04"
    },
    {
      "cell_type": "code",
      "metadata": {
        "tags": [
          "run"
        ],
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": [],
      "source": [
        "#@title 4 \u00b7 Get price, render or resume, and download\n",
        "from getpass import getpass\n",
        "from google.colab import files\n",
        "from IPython.display import display, Video\n",
        "\n",
        "def render_character():\n",
        "    recovery = resume_job_id.strip()\n",
        "    if not recovery:\n",
        "        current = performance_input(subject, movement, intensity, direction, aspect_ratio, quality)\n",
        "        if not globals().get(\"prepared\") or prepared[\"settings\"] != current or prepared[\"start\"] != start_seconds or prepared[\"length\"] != clip_seconds:\n",
        "            raise ValueError(\"Run the preparation cell with your current settings first.\")\n",
        "    key = getpass(\"Hedra v3 API key (hidden): \").strip()\n",
        "    if not key:\n",
        "        raise ValueError(\"Enter your Hedra API key in the hidden field, not in the code.\")\n",
        "    session = requests.Session()\n",
        "    session.headers[\"Authorization\"] = \"Key \" + key\n",
        "    account = hashlib.sha256(key.encode()).hexdigest()\n",
        "    key = None\n",
        "    try:\n",
        "        destination = Path(\"/content/crucible-character-jobs\")\n",
        "        destination.mkdir(parents=True, exist_ok=True)\n",
        "        if recovery:\n",
        "            job_id = recovery\n",
        "            job_folder = destination / hashlib.sha256((account + recovery).encode()).hexdigest()\n",
        "            job_folder.mkdir(exist_ok=True)\n",
        "        else:\n",
        "            digest = hashlib.sha256((account + MODEL + json.dumps(current, sort_keys=True)).encode())\n",
        "            digest.update(prepared[\"photo\"].read_bytes())\n",
        "            digest.update(prepared[\"clip\"].read_bytes())\n",
        "            fingerprint = digest.hexdigest()\n",
        "            job_folder = destination / fingerprint\n",
        "            job_folder.mkdir(exist_ok=True)\n",
        "            state_path = job_folder / \"job.json\"\n",
        "            if not state_path.exists():\n",
        "                save_state(state_path, {\"fingerprint\": fingerprint})\n",
        "            state = json.loads(state_path.read_text())\n",
        "            if state.get(\"job_id\") or state.get(\"payload\"):\n",
        "                print(\"Resuming the saved render request; no fresh request will be created.\", flush=True)\n",
        "                job_id = submit_once(session, state_path, None)\n",
        "            else:\n",
        "                from jsonschema import validate\n",
        "                print(\"Uploading the selected image and audio to Hedra\u2026\", flush=True)\n",
        "                model_input = dict(current, start_image=upload_media(session, prepared[\"photo\"]), audio=upload_media(session, prepared[\"clip\"]))\n",
        "                catalog = api_json(session, \"GET\", \"/models/\" + MODEL)\n",
        "                validate(model_input, catalog[\"input_schema\"])\n",
        "                estimate = api_json(session, \"POST\", \"/models/\" + MODEL + \"/estimate\", json={\"input\": model_input})\n",
        "                cost = estimate_price(estimate)\n",
        "                print(f\"Estimated Hedra charge: ${cost:.4f} USD for this clip ({quality}).\", flush=True)\n",
        "                if input(\"Type RENDER to submit this paid video, or press Enter to stop: \").strip() != \"RENDER\":\n",
        "                    print(\"Stopped. No render submitted.\")\n",
        "                    return\n",
        "                job_id = submit_once(session, state_path, model_input)\n",
        "        print(\"Save this job ID:\", job_id, flush=True)\n",
        "        print(\"If your runtime resets, enter it in Resume job ID to recover without another render.\", flush=True)\n",
        "        url = wait_for_video(session, job_id)\n",
        "        output = job_folder / \"Crucible-Character-Performance.mp4\"\n",
        "        download_video(url, output)\n",
        "        print(\"Video saved. Preview it below; check the mouth timing and gestures.\", flush=True)\n",
        "        display(Video(str(output), embed=True))\n",
        "        files.download(str(output))\n",
        "    finally:\n",
        "        session.headers.pop(\"Authorization\", None)\n",
        "        session.close()\n",
        "\n",
        "try:\n",
        "    render_character()\n",
        "except (RuntimeError, ValueError, TimeoutError) as error:\n",
        "    print(str(error))\n"
      ],
      "id": "character-05"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Recovery\n",
        "If the iPhone download does not appear, rerun only cell 4. In the same runtime it resumes the saved job. After a runtime reset, paste the printed **job ID** into cell 1, run cells 1\u20132 and the renderer definitions, and run cell 4. You can also find the existing job in [Hedra Jobs](https://www.hedra.com/develop/jobs). Do not create a new render just to download the same video.\n",
        "\n",
        "### Provider references\n",
        "- [Model capabilities and limits](https://www.hedra.com/develop/models/video/kling-ai-avatar-v2)\n",
        "- [Live input schema](https://api.hedra.com/v3/models/kling-ai-avatar-v2)\n",
        "- [Uploads](https://www.hedra.com/docs/pages/developer/v3/files)\n",
        "- [Jobs and idempotent retries](https://www.hedra.com/docs/pages/developer/v3/errors-and-retries)\n",
        "- [Live cost estimates](https://www.hedra.com/docs/pages/developer/v3/billing)\n"
      ],
      "id": "character-06"
    }
  ]
}
