{
 "nbformat": 4,
 "nbformat_minor": 0,
 "metadata": {
  "colab": {
   "provenance": [],
   "name": "Hermes Asset Pipeline"
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU"
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hermes Asset Pipeline — for Joe",
    "",
    "**Run order:** Runtime ▸ Run all. The first run installs packages (about 5 minutes); later runs are quicker.",
    "",
    "**Sign in as `gomesy61@gmail.com`** — that is the account with the AI Pro plan, and it needs to be the one whose Drive holds your manifest and receives the assets.",
    "",
    "---",
    "",
    "## What it does",
    "",
    "| Stage | What | Reliable? |",
    "|---|---|---|",
    "| **A** | Images from a manifest — FLUX.1-schnell, transparent background option, tidy filenames | ✅ yes |",
    "| **B** | Optional short video loops (LTX-Video) for skyboxes, water, sprite sheets | ⚠️ 2–5 s clips, may need retries |",
    "| **C** | Processing only — video upscale, frame extraction, sprite sheets | ✅ yes, no model download |",
    "",
    "⚠️ **Colab is not a server.** Never leave this running as a service — Google terminates runtimes that are used that way."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 1 · Check the machine",
    "import subprocess, sys, torch",
    "print(\"GPU:\", torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"NONE — go to Runtime > Change runtime type\")",
    "if torch.cuda.is_available():",
    "    free, total = torch.cuda.mem_get_info()",
    "    print(f\"VRAM: {total/1e9:.1f} GB total, {free/1e9:.1f} GB free\")",
    "print(subprocess.run([\"nvidia-smi\", \"--query-gpu=name,memory.total\", \"--format=csv\"], capture_output=True, text=True).stdout)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 2 · Mount Drive and set the folders",
    "from google.colab import drive",
    "drive.mount('/content/drive')",
    "",
    "BASE  = '/content/drive/MyDrive/Hermes/colab'      # <- manifest lives here",
    "OUT   = f'{BASE}/out'                              # <- assets come out here",
    "VID   = f'{BASE}/video'",
    "import os",
    "for d in (BASE, OUT, VID): os.makedirs(d, exist_ok=True)",
    "print(\"working folders ready:\", BASE)",
    "print(\"contents:\", os.listdir(BASE)[:20])"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 3 · Install (5 minutes the first time)",
    "%pip -q install \"diffusers>=0.31\" transformers accelerate safetensors sentencepiece ftfy \"peft>=0.13\" rembg onnxruntime pillow imageio imageio-ffmpeg",
    "print(\"done — if Colab asks you to restart the runtime, do it and run cell 2 again\")"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 4 · Get the manifest (installs itself — no file copying)",
    "#@markdown Hermes publishes the manifest at a fixed address. This cell copies the current version into your Drive,",
    "#@markdown so there is nothing to upload, paste or copy by hand.",
    "MANIFEST_URL = 'https://joe-colab.pages.dev/manifest.json'",
    "MANIFEST     = '/content/drive/MyDrive/Hermes/colab/manifest.json'",
    "import json, os, urllib.request",
    "",
    "def fetch(url):",
    "    req = urllib.request.Request(url, headers={'Cache-Control': 'no-cache'})",
    "    with urllib.request.urlopen(req, timeout=30) as r:",
    "        return json.loads(r.read().decode('utf-8'))",
    "",
    "try:",
    "    live = fetch(MANIFEST_URL)",
    "    have = json.load(open(MANIFEST)) if os.path.exists(MANIFEST) else None",
    "    if have is None or have.get('version', 0) < live.get('version', 0):",
    "        json.dump(live, open(MANIFEST, 'w'), indent=2)",
    "        print('installed version', live.get('version'), 'from the web')",
    "    else:",
    "        print('Drive copy already current (version', have.get('version'), ')')",
    "except Exception as e:",
    "    print('could not reach the manifest URL (', e, ')')",
    "    if os.path.exists(MANIFEST):",
    "        print('using the copy already in Drive')",
    "    else:",
    "        json.dump({\"version\": 0,",
    "                   \"style\": \"cute Pixar-style 3D render, plain white background\",",
    "                   \"seed\": 7, \"size\": 1024, \"transparent\": True,",
    "                   \"jobs\": [{\"category\": \"test\", \"slug\": \"test_subject\",",
    "                             \"prompt\": \"a friendly cartoon dinosaur\"}]},",
    "                  open(MANIFEST, 'w'), indent=2)",
    "        print('wrote a one-image test manifest instead')",
    "",
    "m = json.load(open(MANIFEST))",
    "print('job count:', len(m['jobs']), '| categories:', sorted({j['category'] for j in m['jobs']}))",
    "for job in m['jobs'][:4]:",
    "    print('  ', job['category'], '/', job['slug'], '->', job['prompt'][:70])"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 5 · STAGE A — images (the dependable one)",
    "import json, os, re, torch",
    "from diffusers import FluxPipeline",
    "from PIL import Image",
    "",
    "MANIFEST = '/content/drive/MyDrive/Hermes/colab/manifest.json'",
    "OUT      = '/content/drive/MyDrive/Hermes/colab/out'",
    "m = json.load(open(MANIFEST))",
    "style, neg = m.get(\"style\", \"\"), m.get(\"negative\", \"\")",
    "base_seed  = int(m.get(\"seed\", 7))",
    "default_sz = int(m.get(\"size\", 1024))",
    "transparent = bool(m.get(\"transparent\", True))",
    "",
    "pipe = FluxPipeline.from_pretrained(\"black-forest-labs/FLUX.1-schnell\", torch_dtype=torch.bfloat16)",
    "pipe.enable_model_cpu_offload()            # keeps VRAM low so a bigger batch fits",
    "pipe.set_progress_bar_config(disable=True)",
    "",
    "def safe(s):                                # Joe's library rule: lowercase, underscores, no spaces",
    "    return re.sub(r'[^a-z0-9_]+', '_', s.lower()).strip('_')",
    "",
    "made, failed = [], []",
    "for i, job in enumerate(m[\"jobs\"], 1):",
    "    folder = os.path.join(OUT, safe(job.get(\"category\", \"misc\")))",
    "    os.makedirs(folder, exist_ok=True)",
    "    name = f'{safe(job[\"slug\"])}_{i:03d}.png'",
    "    dest = os.path.join(folder, name)",
    "    if os.path.exists(dest):",
    "        print(f'[{i}/{len(m[\"jobs\"])}] skip (exists) {name}'); made.append(dest); continue",
    "    prompt = (job[\"prompt\"] + \", \" + style).strip(\", \")",
    "    size = int(job.get(\"size\", default_sz))",
    "    try:",
    "        img = pipe(prompt=prompt, negative_prompt=neg, width=size, height=size,",
    "                   num_inference_steps=4, guidance_scale=0.0,",
    "                   generator=torch.Generator(\"cuda\").manual_seed(base_seed + i)).images[0]",
    "        if job.get(\"transparent\", transparent):",
    "            try:",
    "                from rembg import remove",
    "                img = remove(img)",
    "            except Exception as e:",
    "                print(\"   (transparency skipped:\", e, \")\")",
    "        img.save(dest)",
    "        made.append(dest); print(f'[{i}/{len(m[\"jobs\"])}] {name}')",
    "    except Exception as e:",
    "        failed.append((name, str(e)[:120])); print(f'[{i}/{len(m[\"jobs\"])}] FAILED {name}: {e}')",
    "",
    "print()",
    "print(f\"made {len(made)} images, {len(failed)} failed\")",
    "for n, e in failed: print(\"  failed:\", n, e)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 6 · STAGE B (optional) — short video loop",
    "# 2-5 second clips only. For character shots with audio, Veo in Flow is better; this is for LOOPS and SPRITES",
    "# you want to iterate on twenty times without spending credits.",
    "RUN_VIDEO = False      #@param {type:\"boolean\"}",
    "VIDEO_PROMPT = \"seamless looping animated sky, soft purple clouds drifting, slow, no camera movement\" #@param {type:\"string\"}",
    "VIDEO_SECONDS = 2.5    #@param {type:\"number\"}",
    "VIDEO_W, VIDEO_H = 512, 288",
    "",
    "if RUN_VIDEO:",
    "    import torch, imageio, numpy as np, os",
    "    from diffusers import LTXPipeline",
    "    from diffusers.utils import export_to_video",
    "    ltx = LTXPipeline.from_pretrained(\"Lightricks/LTX-Video\", torch_dtype=torch.bfloat16)",
    "    ltx.enable_model_cpu_offload()",
    "    frames = int(VIDEO_SECONDS * 24)",
    "    out = ltx(prompt=VIDEO_PROMPT, width=VIDEO_W, height=VIDEO_H,",
    "              num_frames=frames, num_inference_steps=30,",
    "              generator=torch.Generator(\"cuda\").manual_seed(7)).frames[0]",
    "    dest = '/content/drive/MyDrive/Hermes/colab/video/loop_test.mp4'",
    "    export_to_video(out, dest, fps=24)",
    "    print(\"wrote\", dest)",
    "else:",
    "    print(\"Stage B skipped — tick RUN_VIDEO to try it\")"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 7 · STAGE C — processing (no model downloads, very reliable)",
    "#@markdown Use these for family video and for turning a clip into a sprite sheet.",
    "import os, subprocess, glob",
    "from PIL import Image",
    "",
    "VIDEO_IN   = '/content/drive/MyDrive/Hermes/colab/video/loop_test.mp4'   #@param {type:\"string\"}",
    "UPSCALE_TO = 1024                                                          #@param {type:\"integer\"}",
    "SPRITE_SHEET = False                                                      #@param {type:\"boolean\"}",
    "FRAME_STEP  = 6                                                          #@param {type:\"integer\"}",
    "",
    "if os.path.exists(VIDEO_IN):",
    "    base = os.path.splitext(os.path.basename(VIDEO_IN))[0]",
    "    big = f'/content/drive/MyDrive/Hermes/colab/video/{base}_up{UPSCALE_TO}.mp4'",
    "    subprocess.run(['ffmpeg', '-y', '-i', VIDEO_IN, '-vf', f'scale={UPSCALE_TO}:-2:flags=lanczos',",
    "                    '-c:v', 'libx264', '-crf', '18', '-pix_fmt', 'yuv420p', big],",
    "                   check=False, capture_output=True)",
    "    print(\"upscaled ->\", big if os.path.exists(big) else \"failed\")",
    "",
    "    if SPRITE_SHEET:",
    "        tmp = '/content/frames'; os.makedirs(tmp, exist_ok=True)",
    "        subprocess.run(['ffmpeg', '-y', '-i', VIDEO_IN, '-vf', f'select=not(mod(n\\\\,{FRAME_STEP}))',",
    "                        '-vsync', 'vfr', f'{tmp}/f_%03d.png'], check=False, capture_output=True)",
    "        files = sorted(glob.glob(f'{tmp}/f_*.png'))",
    "        if files:",
    "            ims = [Image.open(f).convert('RGB') for f in files]",
    "            w, h = ims[0].size",
    "            cols = min(8, len(ims)); rows = (len(ims) + cols - 1) // cols",
    "            sheet = Image.new('RGB', (cols * w, rows * h), 'white')",
    "            for k, im in enumerate(ims):",
    "                sheet.paste(im, ((k % cols) * w, (k // cols) * h))",
    "            sp = f'/content/drive/MyDrive/Hermes/colab/video/{base}_sheet.png'",
    "            sheet.save(sp); print(f\"sprite sheet: {len(ims)} frames -> {sp}\")",
    "else:",
    "    print(\"no video found at\", VIDEO_IN)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title 8 · What came out",
    "import os",
    "for root, dirs, files in os.walk('/content/drive/MyDrive/Hermes/colab/out'):",
    "    imgs = [f for f in files if f.lower().endswith(('.png', '.jpg'))]",
    "    if imgs:",
    "        print(f\"{os.path.basename(root)}/  ({len(imgs)} files)\")",
    "        for f in sorted(imgs)[:12]:",
    "            print(\"   \", f)",
    "print()",
    "print(\"Everything is already saved in Drive — nothing to download.\")"
   ]
  }
 ]
}