{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "L4", "toc_visible": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 手持ちの動画を 4K・60fps に仕上げる(Real-ESRGAN + RIFE)\n", "\n", "- 動画「Colab の GPU で AI 動画を4K・60fps に」(ずんだもんのAI教室)と、記事 [https://media.proplyd-ai.com/articles/colab-4k60/](https://media.proplyd-ai.com/articles/colab-4k60/) の配布用です。\n", "- 上から順に ▶ を押すだけで動きます。Hugging Face のトークンや有料の API キーは要りません。\n", "- **最初に**「ランタイム」→「ランタイムのタイプを変更」で GPU(T4・L4・A100 のどれか)を選んでください。記事の実測では、5秒・720p の動画が T4 で約36分・L4 で約18分・A100 で約5分でした。\n", "- 有料プランや Google AI プランの単位が残っている人は、つないでいるあいだ単位が減ります。終わったら最後のセルで切断してください。\n", "- 使ってよいこと・いけないことは [Colab のよくある質問](https://research.google.com/colaboratory/faq.html) に従ってください(ディープフェイクの作成などは禁止)。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## しくみ\n", "1. **60fps 化(RIFE)**:24コマ/秒の動画の、コマとコマのあいだの絵を AI が推測して描き足し、60コマ/秒にします。\n", "2. **4K 化(Real-ESRGAN x4plus)**:1コマずつ4倍に拡大し、3840 ピクセル幅に縮めて保存します。ぼやけた輪郭をくっきりさせますが、**元の映像にない細かい模様は推測で描かれます**。最初から 4K で撮った映像と同じにはなりません。\n", "3. **FFmpeg** で MP4 にまとめます。音はつきません(元の音を戻すセルが最後にあります)。\n", "\n", "使う重み:Real-ESRGAN(BSD-3-Clause、xinntao さんの公開)、RIFE v4.26(MIT、hzwer さんの公開)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# GPU の名前と VRAM(GPU のメモリ)を確かめる\n", "!nvidia-smi --query-gpu=name,memory.total --format=csv" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 道具と重みを用意する(1分ほど)\n", "!pip -q install spandrel\n", "!mkdir -p /content/w\n", "!wget -q -nc -O /content/w/RealESRGAN_x4plus.pth https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth\n", "!test -d /content/Practical-RIFE || git clone -q https://github.com/hzwer/Practical-RIFE /content/Practical-RIFE\n", "!cd /content/w && wget -q -nc https://huggingface.co/hzwer/RIFE/resolve/main/RIFEv4.26_0921.zip && unzip -q -o RIFEv4.26_0921.zip && rm -rf train_log && cp -r RIFEv4.26_0921 train_log && cp -r /content/Practical-RIFE/model /content/w/model\n", "print(\"ok\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 動画を選ぶ\n", "`USE_SAMPLE = True` のままなら、記事の作例(Gemini Omni で作った5秒・720p・24コマ/秒の動画)を使います。自分の動画を使うときは `False` にして実行し、出てきたボタンからファイルを選んでください(15秒・720p くらいまでがおすすめ。長いほど時間と単位がかかります)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "USE_SAMPLE = True\n", "import os\n", "os.makedirs(\"/content/out\", exist_ok=True)\n", "if USE_SAMPLE:\n", " !wget -q -O /content/out/input.mp4 https://media.proplyd-ai.com/media/colab-4k60/notebooks/sample_720p24.mp4\n", " SRC = \"/content/out/input.mp4\"\n", "else:\n", " from google.colab import files\n", " up = files.upload()\n", " name = list(up.keys())[0]\n", " SRC = \"/content/out/\" + name\n", " os.replace(name, SRC)\n", "print(SRC)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 60fps 化 → 4K 化(時間がかかるセル)\n", "下のセルの最後に、かかった秒数が出ます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os; os.chdir('/content/w')\n", "# 60fps 化(RIFE)→ 4K 化(Real-ESRGAN)。SRC の動画から *_4k60.mp4 を作る\n", "import cv2, torch, numpy as np, subprocess, time, json, os, sys, math, glob\n", "import spandrel\n", "dev = \"cuda\"\n", "half = True\n", "def read(path):\n", " c = cv2.VideoCapture(path); fps = c.get(5); fr = []\n", " while True:\n", " ok, f = c.read()\n", " if not ok: break\n", " fr.append(f)\n", " return fr, fps\n", "def writer(path, w, h, fps):\n", " return subprocess.Popen([\"ffmpeg\",\"-y\",\"-loglevel\",\"error\",\"-f\",\"rawvideo\",\"-pix_fmt\",\"bgr24\",\"-s\",f\"{w}x{h}\",\"-r\",str(fps),\"-i\",\"-\",\n", " \"-c:v\",\"libx264\",\"-preset\",\"medium\",\"-crf\",\"16\",\"-pix_fmt\",\"yuv420p\",path], stdin=subprocess.PIPE)\n", "# --- Real-ESRGAN\n", "if \"SR\" not in globals():\n", " SR = spandrel.ModelLoader().load_from_file(\"/content/w/RealESRGAN_x4plus.pth\").model.eval().to(dev)\n", " if half: SR = SR.half()\n", "def upscale(f, out_w, out_h):\n", " x = torch.from_numpy(f[:, :, ::-1].copy()).permute(2,0,1).float().div(255).unsqueeze(0).to(dev)\n", " if half: x = x.half()\n", " with torch.no_grad(): y = SR(x)\n", " y = (y.clamp(0,1)*255).round().byte()[0].permute(1,2,0).cpu().numpy()[:, :, ::-1]\n", " return cv2.resize(y, (out_w, out_h), interpolation=cv2.INTER_AREA)\n", "# --- RIFE\n", "if \"RIFE\" not in globals():\n", " sys.path.insert(0, \"/content/w\")\n", " from train_log.RIFE_HDv3 import Model\n", " RIFE = Model(); RIFE.load_model(\"/content/w/train_log\", -1); RIFE.eval(); RIFE.device()\n", "def to_t(f):\n", " t = torch.from_numpy(f.transpose(2,0,1).copy()).to(dev).unsqueeze(0).float()/255.\n", " h, w = f.shape[:2]; ph = ((h-1)//64+1)*64; pw = ((w-1)//64+1)*64\n", " return torch.nn.functional.pad(t, (0, pw-w, 0, ph-h)), h, w\n", "def interp(frames, src_fps, dst_fps=60):\n", " n_out = int(round((len(frames)-1) / src_fps * dst_fps)) + 1\n", " out = []\n", " for k in range(n_out):\n", " p = k * src_fps / dst_fps; i = int(math.floor(p + 1e-6)); a = p - i\n", " if a < 1e-3 or i >= len(frames)-1:\n", " out.append(frames[min(i, len(frames)-1)]); continue\n", " I0, h, w = to_t(frames[i]); I1, _, _ = to_t(frames[i+1])\n", " with torch.no_grad(): m = RIFE.inference(I0, I1, timestep=a, scale=1.0)\n", " out.append((m[0]*255).byte().cpu().numpy().transpose(1,2,0)[:h, :w].copy())\n", " return out\n", "fr, fps = read(SRC)\n", "h, w = fr[0].shape[:2]\n", "OW, OH = (3840, int(round(h*3840/w/2))*2)\n", "base = SRC.rsplit(\".\",1)[0]\n", "log = dict(src=SRC, in_w=w, in_h=h, in_fps=fps, frames=len(fr), out_w=OW, out_h=OH, gpu=torch.cuda.get_device_name(0), mode=\"final\")\n", "t0 = time.time(); fr60 = interp(fr, fps, 60); torch.cuda.synchronize(); log[\"rife_sec\"] = round(time.time()-t0,1); log[\"frames60\"] = len(fr60)\n", "t0 = time.time()\n", "p = writer(base+\"_4k60.mp4\", OW, OH, 60)\n", "for f in fr60: p.stdin.write(upscale(f, OW, OH).tobytes())\n", "p.stdin.close(); p.wait(); torch.cuda.synchronize(); log[\"sr_sec\"] = round(time.time()-t0,1)\n", "print(json.dumps(log))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## できた動画を保存する" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 元の動画に音があれば戻して、ダウンロードする\n", "import subprocess\n", "out = SRC.rsplit(\".\", 1)[0] + \"_4k60.mp4\"\n", "final = SRC.rsplit(\".\", 1)[0] + \"_4k60_audio.mp4\"\n", "r = subprocess.run([\"ffmpeg\", \"-y\", \"-loglevel\", \"error\", \"-i\", out, \"-i\", SRC, \"-map\", \"0:v\", \"-map\", \"1:a?\", \"-c:v\", \"copy\", \"-c:a\", \"aac\", \"-shortest\", final])\n", "from google.colab import files\n", "files.download(final if r.returncode == 0 else out)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 終わったら切断する(つないだままだと単位が減り続けます)\n", "from google.colab import runtime\n", "runtime.unassign()" ] } ] }