{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "colab": {
      "name": "FlowUpscale_Colab_4K.ipynb",
      "provenance": [],
      "gpuType": "L4",
      "machine_shape": "hm"
    },
    "accelerator": "GPU",
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "flow_header_md"
      },
      "source": [
        "# 🚀 FlowUpscale — Cloud GPU Turbo (`v2.4.1`)\n",
        "**ขยายความละเอียดภาพนิ่ง AI (`JPG / PNG+Alpha / WEBP`) และวิดีโอ `4K UHD (.mp4)` ด้วย Tensor Core Multi-Frame Batch**\n",
        "\n",
        "### วิธีใช้งาน 3 ขั้นตอนสั้นๆ:\n",
        "1. *(ตรวจสอบการ์ดจอก่อนเริ่ม)* ไปที่เมนูด้านบน **`Runtime` ➔ `Change runtime type`** เลือก GPU:\n",
        "   - **`T4 GPU`** *(ฟรี — สำหรับบัญชีทั่วไป)* • **`L4 GPU`** *(ประหยัดโควตา มี NVENC + 22.5GB VRAM)* • **`G4` / `A100`** *(แรงสูงสุด 4–8 เท่าสำหรับงานด่วน)*\n",
        "2. กดปุ่ม **`▶`** หน้าหัวข้อ **`1. เชื่อมต่อ Google Drive & เตรียมเอนจิน Turbo AI`** ระบบจะสร้างโฟลเดอร์ `My Drive / FlowUpscale_AI / 01_Input` และ `02_Output_4K` ใน Drive ของคุณให้อัตโนมัติ\n",
        "3. นำไฟล์ภาพหรือวิดีโอไปวางในโฟลเดอร์ **`01_Input`** บน Google Drive ของคุณ แล้วกดปุ่ม **`▶`** หน้าหัวข้อ **`2. เริ่มขยายไฟล์ทั้งหมดใน 01_Input`** ได้ทันที *(เมื่อทำครบทุกไฟล์ ระบบจะซิงก์ Drive จนครบ 100% และตัดการเชื่อมต่อคืน GPU ให้อัตโนมัติเพื่อประหยัดโควตา)*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "flow_setup_cell",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "#@title 1. เชื่อมต่อ Google Drive & เตรียมเอนจิน Turbo AI { display-mode: \"form\" }\n",
        "โฟลเดอร์หลักใน_Google_Drive = \"FlowUpscale_AI\" #@param {type:\"string\"}\n",
        "\n",
        "import os\n",
        "import sys\n",
        "import math\n",
        "import json\n",
        "import time\n",
        "import queue\n",
        "import shutil\n",
        "import threading\n",
        "import urllib.request\n",
        "import subprocess\n",
        "import numpy as np\n",
        "from PIL import Image\n",
        "\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "\n",
        "print(\"=\" * 68)\n",
        "print(\"  FlowUpscale Cloud Turbo (v2.4) — กำลังตั้งค่า Tensor Core & ระบบท่อขนาน...\")\n",
        "print(\"=\" * 68)\n",
        "\n",
        "if torch.cuda.is_available():\n",
        "    FLOW_DEVICE = torch.device(\"cuda\")\n",
        "    torch.backends.cudnn.benchmark = True\n",
        "    torch.backends.cuda.matmul.allow_tf32 = True\n",
        "    torch.backends.cudnn.allow_tf32 = True\n",
        "    GPU_NAME = torch.cuda.get_device_name(0)\n",
        "    VRAM_GB = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)\n",
        "    if VRAM_GB >= 45:\n",
        "        AUTO_TILE_SIZE = 1536\n",
        "    elif VRAM_GB >= 28:\n",
        "        AUTO_TILE_SIZE = 1280\n",
        "    elif VRAM_GB >= 20:\n",
        "        AUTO_TILE_SIZE = 1024\n",
        "    else:\n",
        "        AUTO_TILE_SIZE = 640\n",
        "    print(f\"[GPU] การ์ดจอ: {GPU_NAME} ({VRAM_GB:.1f} GB VRAM) • Tensor Core FP16 + NHWC พร้อมทำงาน\")\n",
        "else:\n",
        "    FLOW_DEVICE = torch.device(\"cpu\")\n",
        "    GPU_NAME = \"CPU\"\n",
        "    VRAM_GB = 0.0\n",
        "    AUTO_TILE_SIZE = 256\n",
        "    print(\"[คำเตือน] ขณะนี้รันอยู่บน CPU! แนะนำไปที่เมนู Runtime -> Change runtime type -> เลือก GPU (T4 / L4 / G4 / A100)\")\n",
        "\n",
        "def _detect_nvenc():\n",
        "    if FLOW_DEVICE.type != \"cuda\":\n",
        "        return False\n",
        "    try:\n",
        "        cmd = [\n",
        "            \"ffmpeg\", \"-v\", \"error\", \"-f\", \"lavfi\", \"-i\", \"color=c=black:s=256x256:d=0.1\",\n",
        "            \"-c:v\", \"h264_nvenc\", \"-f\", \"null\", \"-\"\n",
        "        ]\n",
        "        return subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0\n",
        "    except Exception:\n",
        "        return False\n",
        "\n",
        "def _detect_nvdec():\n",
        "    if FLOW_DEVICE.type != \"cuda\":\n",
        "        return False\n",
        "    try:\n",
        "        out = subprocess.check_output([\"ffmpeg\", \"-hide_banner\", \"-hwaccels\"], stderr=subprocess.DEVNULL).decode(\"utf-8\", errors=\"ignore\")\n",
        "        return \"cuda\" in out.lower()\n",
        "    except Exception:\n",
        "        return False\n",
        "\n",
        "HAS_NVENC = _detect_nvenc()\n",
        "HAS_NVDEC = _detect_nvdec()\n",
        "print(f\"[Video HW] ถอดรหัสขาเข้า: {'CUDA NVDEC' if HAS_NVDEC else 'CPU'} • เข้ารหัสขาออก: {'NVIDIA H.264 NVENC (p3 Fast HQ)' if HAS_NVENC else 'H.264 libx264'}\")\n",
        "\n",
        "# Mount the current browser user's own Google Drive\n",
        "IN_COLAB = \"google.colab\" in sys.modules\n",
        "if IN_COLAB:\n",
        "    from google.colab import drive\n",
        "    drive.mount(\"/content/drive\", force_remount=False)\n",
        "    my_drive_base = \"/content/drive/MyDrive\" if os.path.exists(\"/content/drive/MyDrive\") else \"/content/drive/My Drive\"\n",
        "    DRIVE_ROOT = os.path.join(my_drive_base, โฟลเดอร์หลักใน_Google_Drive.strip() or \"FlowUpscale_AI\")\n",
        "else:\n",
        "    DRIVE_ROOT = os.path.abspath(โฟลเดอร์หลักใน_Google_Drive.strip() or \"FlowUpscale_AI\")\n",
        "\n",
        "INPUT_DIR  = os.path.join(DRIVE_ROOT, \"01_Input\")\n",
        "OUTPUT_DIR = os.path.join(DRIVE_ROOT, \"02_Output_4K\")\n",
        "DONE_DIR   = os.path.join(DRIVE_ROOT, \"03_Done_Originals\")\n",
        "WEIGHT_DIR = \"/content/flowupscale_weights\" if IN_COLAB else os.path.join(DRIVE_ROOT, \"_weights\")\n",
        "STAGE_DIR  = \"/content/flowupscale_stage\" if IN_COLAB else os.path.join(DRIVE_ROOT, \"_stage\")\n",
        "\n",
        "for d in (INPUT_DIR, OUTPUT_DIR, DONE_DIR, WEIGHT_DIR, STAGE_DIR):\n",
        "    os.makedirs(d, exist_ok=True)\n",
        "\n",
        "# -------------------------------------------------------------------------\n",
        "# Pure PyTorch Real-ESRGAN Architectures (Supports Native 2x & 4x + NHWC!)\n",
        "# -------------------------------------------------------------------------\n",
        "class ResidualDenseBlock(nn.Module):\n",
        "    def __init__(self, num_feat=64, num_grow_ch=32):\n",
        "        super().__init__()\n",
        "        self.conv1 = nn.Conv2d(num_feat, num_grow_ch, 3, 1, 1)\n",
        "        self.conv2 = nn.Conv2d(num_feat + num_grow_ch, num_grow_ch, 3, 1, 1)\n",
        "        self.conv3 = nn.Conv2d(num_feat + 2 * num_grow_ch, num_grow_ch, 3, 1, 1)\n",
        "        self.conv4 = nn.Conv2d(num_feat + 3 * num_grow_ch, num_grow_ch, 3, 1, 1)\n",
        "        self.conv5 = nn.Conv2d(num_feat + 4 * num_grow_ch, num_feat, 3, 1, 1)\n",
        "        self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n",
        "\n",
        "    def forward(self, x):\n",
        "        x1 = self.lrelu(self.conv1(x))\n",
        "        x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))\n",
        "        x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))\n",
        "        x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))\n",
        "        x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))\n",
        "        return x5 * 0.2 + x\n",
        "\n",
        "\n",
        "class RRDB(nn.Module):\n",
        "    def __init__(self, num_feat, num_grow_ch=32):\n",
        "        super().__init__()\n",
        "        self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch)\n",
        "        self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch)\n",
        "        self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch)\n",
        "\n",
        "    def forward(self, x):\n",
        "        out = self.rdb1(x)\n",
        "        out = self.rdb2(out)\n",
        "        out = self.rdb3(out)\n",
        "        return out * 0.2 + x\n",
        "\n",
        "\n",
        "class RRDBNet(nn.Module):\n",
        "    def __init__(self, num_in_ch=3, num_out_ch=3, scale=4, num_feat=64, num_block=23, num_grow_ch=32):\n",
        "        super().__init__()\n",
        "        self.scale = scale\n",
        "        if scale == 2:\n",
        "            num_in_ch = num_in_ch * 4\n",
        "        elif scale == 1:\n",
        "            num_in_ch = num_in_ch * 16\n",
        "        self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)\n",
        "        self.body = nn.Sequential(*[RRDB(num_feat=num_feat, num_grow_ch=num_grow_ch) for _ in range(num_block)])\n",
        "        self.conv_body = nn.Conv2d(num_feat, num_feat, 3, 1, 1)\n",
        "        self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)\n",
        "        self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)\n",
        "        self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)\n",
        "        self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)\n",
        "        self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n",
        "\n",
        "    def forward(self, x):\n",
        "        orig_h, orig_w = x.shape[2], x.shape[3]\n",
        "        pad_h, pad_w = 0, 0\n",
        "        if self.scale == 2:\n",
        "            pad_h = orig_h % 2\n",
        "            pad_w = orig_w % 2\n",
        "            if pad_h or pad_w:\n",
        "                x = F.pad(x, (0, pad_w, 0, pad_h), mode=\"replicate\")\n",
        "            feat = F.pixel_unshuffle(x, downscale_factor=2)\n",
        "        else:\n",
        "            feat = x\n",
        "        feat = self.conv_first(feat)\n",
        "        body_feat = self.conv_body(self.body(feat))\n",
        "        feat = feat + body_feat\n",
        "        feat = self.lrelu(self.conv_up1(F.interpolate(feat, scale_factor=2, mode=\"nearest\")))\n",
        "        feat = self.lrelu(self.conv_up2(F.interpolate(feat, scale_factor=2, mode=\"nearest\")))\n",
        "        out = self.conv_last(self.lrelu(self.conv_hr(feat)))\n",
        "        if pad_h or pad_w:\n",
        "            out = out[:, :, : orig_h * self.scale, : orig_w * self.scale]\n",
        "        return out\n",
        "\n",
        "\n",
        "class SRVGGNetCompact(nn.Module):\n",
        "    def __init__(self, num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4):\n",
        "        super().__init__()\n",
        "        self.upscale = upscale\n",
        "        self.body = nn.ModuleList()\n",
        "        self.body.append(nn.Conv2d(num_in_ch, num_feat, 3, 1, 1))\n",
        "        self.body.append(nn.PReLU(num_parameters=num_feat))\n",
        "        for _ in range(num_conv):\n",
        "            self.body.append(nn.Conv2d(num_feat, num_feat, 3, 1, 1))\n",
        "            self.body.append(nn.PReLU(num_parameters=num_feat))\n",
        "        self.body.append(nn.Conv2d(num_feat, num_out_ch * upscale * upscale, 3, 1, 1))\n",
        "\n",
        "    def forward(self, x):\n",
        "        out = x\n",
        "        for layer in self.body:\n",
        "            out = layer(out)\n",
        "        out = F.pixel_shuffle(out, self.upscale)\n",
        "        base = F.interpolate(x, scale_factor=self.upscale, mode=\"nearest\")\n",
        "        return out + base\n",
        "\n",
        "\n",
        "WEIGHT_SPECS = {\n",
        "    \"srvgg_x4\": {\n",
        "        \"url\": \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth\",\n",
        "        \"file\": \"realesr-animevideov3.pth\",\n",
        "        \"scale\": 4,\n",
        "        \"kind\": \"srvgg\",\n",
        "        \"build\": lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4),\n",
        "    },\n",
        "    \"plus_x2\": {\n",
        "        \"url\": \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth\",\n",
        "        \"file\": \"RealESRGAN_x2plus.pth\",\n",
        "        \"scale\": 2,\n",
        "        \"kind\": \"plus_x2\",\n",
        "        \"build\": lambda: RRDBNet(num_in_ch=3, num_out_ch=3, scale=2, num_feat=64, num_block=23, num_grow_ch=32),\n",
        "    },\n",
        "    \"plus_x4\": {\n",
        "        \"url\": \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth\",\n",
        "        \"file\": \"RealESRGAN_x4plus.pth\",\n",
        "        \"scale\": 4,\n",
        "        \"kind\": \"plus_x4\",\n",
        "        \"build\": lambda: RRDBNet(num_in_ch=3, num_out_ch=3, scale=4, num_feat=64, num_block=23, num_grow_ch=32),\n",
        "    },\n",
        "    \"anime_x4\": {\n",
        "        \"url\": \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth\",\n",
        "        \"file\": \"RealESRGAN_x4plus_anime_6B.pth\",\n",
        "        \"scale\": 4,\n",
        "        \"kind\": \"anime_x4\",\n",
        "        \"build\": lambda: RRDBNet(num_in_ch=3, num_out_ch=3, scale=4, num_feat=64, num_block=6, num_grow_ch=32),\n",
        "    },\n",
        "}\n",
        "\n",
        "_MODEL_POOL = {}\n",
        "\n",
        "def resolve_weight_key(model_label, in_w, in_h, out_w, out_h):\n",
        "    ratio = max(out_w / max(1, in_w), out_h / max(1, in_h))\n",
        "    if model_label == \"Real-ESRGAN Plus\":\n",
        "        # Native RealESRGAN_x2plus uses PixelUnshuffle (4x faster FLOPs!) when target scale <= 2.05x (e.g. 1080p -> 4K UHD)\n",
        "        return \"plus_x2\" if ratio <= 2.05 else \"plus_x4\"\n",
        "    if model_label == \"Real-ESRGAN Anime\":\n",
        "        return \"anime_x4\"\n",
        "    return \"srvgg_x4\"\n",
        "\n",
        "def get_turbo_model(weight_key, use_compile=False):\n",
        "    cache_id = f\"{weight_key}_c{int(use_compile)}\"\n",
        "    if cache_id in _MODEL_POOL:\n",
        "        return _MODEL_POOL[cache_id]\n",
        "\n",
        "    base_id = f\"{weight_key}_c0\"\n",
        "    if base_id in _MODEL_POOL:\n",
        "        net, scale, kind = _MODEL_POOL[base_id]\n",
        "    else:\n",
        "        spec = WEIGHT_SPECS[weight_key]\n",
        "        w_path = os.path.join(WEIGHT_DIR, spec[\"file\"])\n",
        "        if not os.path.exists(w_path):\n",
        "            print(f\"[Model] กำลังดาวน์โหลดน้ำหนัก {spec['file']} ...\")\n",
        "            urllib.request.urlretrieve(spec[\"url\"], w_path)\n",
        "        ckpt = torch.load(w_path, map_location=\"cpu\", weights_only=False)\n",
        "        state = ckpt.get(\"params_ema\") or ckpt.get(\"params\") or ckpt\n",
        "        net = spec[\"build\"]()\n",
        "        net.load_state_dict(state, strict=True)\n",
        "        net.eval().to(FLOW_DEVICE)\n",
        "        if FLOW_DEVICE.type == \"cuda\":\n",
        "            net = net.half().to(memory_format=torch.channels_last)\n",
        "        scale, kind = spec[\"scale\"], spec[\"kind\"]\n",
        "        _MODEL_POOL[base_id] = (net, scale, kind)\n",
        "\n",
        "    if use_compile and FLOW_DEVICE.type == \"cuda\" and hasattr(torch, \"compile\"):\n",
        "        try:\n",
        "            compiled = torch.compile(net, dynamic=False)\n",
        "            _MODEL_POOL[cache_id] = (compiled, scale, kind)\n",
        "            return compiled, scale, kind\n",
        "        except Exception:\n",
        "            pass\n",
        "\n",
        "    _MODEL_POOL[cache_id] = (net, scale, kind)\n",
        "    return net, scale, kind\n",
        "\n",
        "def compute_target_dims(in_w, in_h, scale_mode, force_even=False):\n",
        "    if scale_mode == \"4K UHD\":\n",
        "        if in_w >= in_h:\n",
        "            aspect = in_w / max(1, in_h)\n",
        "            if abs(aspect - 16.0 / 9.0) < 0.035:\n",
        "                tw, th = 3840, 2160\n",
        "            elif aspect >= 16.0 / 9.0:\n",
        "                tw, th = 3840, round(3840 / aspect)\n",
        "            else:\n",
        "                th, tw = 2160, round(2160 * aspect)\n",
        "        else:\n",
        "            aspect = in_h / max(1, in_w)\n",
        "            if abs(aspect - 16.0 / 9.0) < 0.035:\n",
        "                tw, th = 2160, 3840\n",
        "            elif aspect >= 16.0 / 9.0:\n",
        "                th, tw = 3840, round(3840 / aspect)\n",
        "            else:\n",
        "                tw, th = 2160, round(2160 * aspect)\n",
        "    else:\n",
        "        factor = 4 if scale_mode == \"4x\" else (3 if scale_mode == \"3x\" else 2)\n",
        "        tw, th = in_w * factor, in_h * factor\n",
        "    if force_even or scale_mode == \"4K UHD\":\n",
        "        tw = max(2, tw + (tw % 2))\n",
        "        th = max(2, th + (th % 2))\n",
        "    return int(tw), int(th)\n",
        "\n",
        "def choose_video_batch_size(in_w, in_h, kind):\n",
        "    if FLOW_DEVICE.type != \"cuda\":\n",
        "        return 1\n",
        "    mpix = (in_w * in_h) / 1_000_000.0\n",
        "    # Estimate safe per-frame peak VRAM (GB) for full untiled frame in FP16\n",
        "    if kind == \"srvgg\":\n",
        "        per_frame_gb = 0.24 * mpix\n",
        "    elif kind == \"plus_x2\":\n",
        "        per_frame_gb = 0.85 * mpix\n",
        "    elif kind == \"anime_x4\":\n",
        "        per_frame_gb = 2.15 * mpix\n",
        "    else:\n",
        "        per_frame_gb = 2.60 * mpix\n",
        "\n",
        "    usable_gb = max(2.0, VRAM_GB * 0.62)\n",
        "    if per_frame_gb > usable_gb:\n",
        "        return 0  # Signal to use tiled fallback for ultra-large input frames (e.g. 4K -> 8K)\n",
        "    batch = max(1, min(16, int(usable_gb // max(0.15, per_frame_gb))))\n",
        "    return batch\n",
        "\n",
        "@torch.inference_mode()\n",
        "def upscale_frames_batch_gpu(frames_uint8, net, net_scale, out_w, out_h):\n",
        "    \"\"\"\n",
        "    Fast Multi-Frame Tensor Core Batch Path:\n",
        "    frames_uint8: np.ndarray [B, H, W, 3] uint8 -> returns np.ndarray [B, out_h, out_w, 3] uint8\n",
        "    Performs neural upscale + GPU anti-aliased resize BEFORE transferring compact uint8 back to CPU!\n",
        "    \"\"\"\n",
        "    b, h, w, _ = frames_uint8.shape\n",
        "    dtype = torch.float16 if FLOW_DEVICE.type == \"cuda\" else torch.float32\n",
        "    cpu_t = torch.from_numpy(frames_uint8)\n",
        "    if FLOW_DEVICE.type == \"cuda\":\n",
        "        inp = cpu_t.to(FLOW_DEVICE, non_blocking=True).permute(0, 3, 1, 2).contiguous(memory_format=torch.channels_last).to(dtype).div_(255.0)\n",
        "    else:\n",
        "        inp = cpu_t.permute(0, 3, 1, 2).to(dtype).div_(255.0)\n",
        "\n",
        "    sr = net(inp)\n",
        "    if sr.shape[2] != out_h or sr.shape[3] != out_w:\n",
        "        # Resize right on the GPU in float32 with antialiasing (4x smaller PCIe copy & zero CPU Lanczos bottleneck!)\n",
        "        sr = F.interpolate(sr.float(), size=(out_h, out_w), mode=\"bicubic\", antialias=True)\n",
        "\n",
        "    out_u8 = sr.clamp_(0.0, 1.0).mul_(255.0).round_().to(torch.uint8).permute(0, 2, 3, 1).contiguous()\n",
        "    return out_u8.cpu().numpy()\n",
        "\n",
        "@torch.inference_mode()\n",
        "def upscale_single_tiled_gpu(rgb_uint8, net, net_scale, out_w, out_h, tile_size=AUTO_TILE_SIZE, tile_pad=16):\n",
        "    h, w, _ = rgb_uint8.shape\n",
        "    dtype = torch.float16 if FLOW_DEVICE.type == \"cuda\" else torch.float32\n",
        "    img_t = torch.from_numpy(rgb_uint8).to(FLOW_DEVICE).permute(2, 0, 1).unsqueeze(0)\n",
        "    if FLOW_DEVICE.type == \"cuda\":\n",
        "        img_t = img_t.contiguous(memory_format=torch.channels_last)\n",
        "    img_t = img_t.to(dtype).div_(255.0)\n",
        "\n",
        "    if w <= tile_size and h <= tile_size:\n",
        "        pad_r = (4 - (w % 4)) % 4\n",
        "        pad_b = (4 - (h % 4)) % 4\n",
        "        inp = F.pad(img_t, (0, pad_r, 0, pad_b), mode=\"replicate\") if (pad_r or pad_b) else img_t\n",
        "        out = net(inp)\n",
        "        if pad_r or pad_b:\n",
        "            out = out[:, :, : h * net_scale, : w * net_scale]\n",
        "    else:\n",
        "        out = torch.empty((1, 3, h * net_scale, w * net_scale), dtype=dtype, device=FLOW_DEVICE)\n",
        "        tiles_x = math.ceil(w / tile_size)\n",
        "        tiles_y = math.ceil(h / tile_size)\n",
        "        for ty in range(tiles_y):\n",
        "            for tx in range(tiles_x):\n",
        "                x0, y0 = tx * tile_size, ty * tile_size\n",
        "                x1, y1 = min(x0 + tile_size, w), min(y0 + tile_size, h)\n",
        "                px0, py0 = max(x0 - tile_pad, 0), max(y0 - tile_pad, 0)\n",
        "                px1, py1 = min(x1 + tile_pad, w), min(y1 + tile_pad, h)\n",
        "                patch = img_t[:, :, py0:py1, px0:px1]\n",
        "                pr = (4 - (patch.shape[3] % 4)) % 4\n",
        "                pb = (4 - (patch.shape[2] % 4)) % 4\n",
        "                if pr or pb:\n",
        "                    patch = F.pad(patch, (0, pr, 0, pb), mode=\"replicate\")\n",
        "                sr_patch = net(patch)\n",
        "                cx0, cy0 = (x0 - px0) * net_scale, (y0 - py0) * net_scale\n",
        "                cw, ch = (x1 - x0) * net_scale, (y1 - y0) * net_scale\n",
        "                out[:, :, y0 * net_scale : y1 * net_scale, x0 * net_scale : x1 * net_scale] = sr_patch[:, :, cy0 : cy0 + ch, cx0 : cx0 + cw]\n",
        "\n",
        "    if out.shape[2] != out_h or out.shape[3] != out_w:\n",
        "        out = F.interpolate(out.float(), size=(out_h, out_w), mode=\"bicubic\", antialias=True)\n",
        "\n",
        "    return out.squeeze(0).clamp_(0.0, 1.0).mul_(255.0).round_().to(torch.uint8).permute(1, 2, 0).contiguous().cpu().numpy()\n",
        "\n",
        "IMG_EXTS = {\".png\", \".jpg\", \".jpeg\", \".webp\", \".bmp\", \".tif\", \".tiff\"}\n",
        "VID_EXTS = {\".mp4\", \".mov\", \".mkv\", \".webm\", \".avi\", \".m4v\"}\n",
        "\n",
        "waiting_files = [f for f in os.listdir(INPUT_DIR) if os.path.splitext(f)[1].lower() in (IMG_EXTS | VID_EXTS)]\n",
        "print(\"-\" * 68)\n",
        "print(f\"[พร้อมใช้งาน] โฟลเดอร์ Input  : {INPUT_DIR}\")\n",
        "print(f\"[พร้อมใช้งาน] โฟลเดอร์ Output : {OUTPUT_DIR}\")\n",
        "print(f\"[คิวปัจจุบัน] พบไฟล์รอประมวลผลใน 01_Input จำนวน {len(waiting_files)} ไฟล์\")\n",
        "print(\"=\" * 68)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "flow_run_cell",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "#@title 2. เริ่มขยายไฟล์ทั้งหมดในโฟลเดอร์ 01_Input { display-mode: \"form\" }\n",
        "โมเดล = \"Real-ESRGAN Standard\" #@param [\"Real-ESRGAN Standard\", \"Real-ESRGAN Plus\", \"Real-ESRGAN Anime\"]\n",
        "สเกล = \"4K UHD\" #@param [\"4K UHD\", \"2x\", \"3x\", \"4x\"]\n",
        "ฟอร์แมตภาพนิ่ง = \"นามสกุลเดิม\" #@param [\"นามสกุลเดิม\", \"PNG\", \"JPG\", \"WEBP\"]\n",
        "คำต่อท้าย = \"_4K\" #@param {type:\"string\"}\n",
        "เร่งสปีด_Torch_Compile_สำหรับวิดีโอ = True #@param {type:\"boolean\"}\n",
        "ย้ายต้นฉบับไป_03_Done_เมื่อเสร็จ = True #@param {type:\"boolean\"}\n",
        "ตัดการเชื่อมต่อ_GPU_อัตโนมัติเมื่อทำครบ = True #@param {type:\"boolean\"}\n",
        "\n",
        "if \"get_turbo_model\" not in globals():\n",
        "    raise RuntimeError(\"กรุณากดรันปุ่ม ▶ ในหัวข้อที่ 1 (เชื่อมต่อ Google Drive & เตรียมเอนจิน Turbo AI) ก่อนครับ\")\n",
        "\n",
        "# Remount Google Drive automatically if previous run flushed & unmounted it while user opted not to unassign\n",
        "if IN_COLAB and not os.path.isdir(INPUT_DIR):\n",
        "    from google.colab import drive\n",
        "    drive.mount(\"/content/drive\", force_remount=True)\n",
        "    for _d in (INPUT_DIR, OUTPUT_DIR, DONE_DIR):\n",
        "        os.makedirs(_d, exist_ok=True)\n",
        "\n",
        "attempted_paths = set()\n",
        "\n",
        "def _scan_pending_inputs():\n",
        "    if not os.path.isdir(INPUT_DIR):\n",
        "        return []\n",
        "    found = []\n",
        "    for fn in sorted(os.listdir(INPUT_DIR)):\n",
        "        full_p = os.path.join(INPUT_DIR, fn)\n",
        "        if full_p in attempted_paths:\n",
        "            continue\n",
        "        if os.path.isfile(full_p) and os.path.splitext(fn)[1].lower() in (IMG_EXTS | VID_EXTS):\n",
        "            found.append(full_p)\n",
        "    return found\n",
        "\n",
        "queue_files = _scan_pending_inputs()\n",
        "\n",
        "if not queue_files and IN_COLAB:\n",
        "    print(\"[แจ้งเตือน] ยังไม่มีไฟล์ในโฟลเดอร์ 01_Input — อัปโหลดไฟล์ด่วนด้านล่าง หรือวางไฟล์ใน Google Drive แล้วกดรันใหม่:\")\n",
        "    from google.colab import files\n",
        "    uploaded = files.upload()\n",
        "    for name, data in uploaded.items():\n",
        "        dst = os.path.join(INPUT_DIR, name)\n",
        "        with open(dst, \"wb\") as fw:\n",
        "            fw.write(data)\n",
        "    queue_files = _scan_pending_inputs()\n",
        "\n",
        "if not queue_files:\n",
        "    print(\"ไม่มีไฟล์รูปภาพหรือวิดีโอให้ประมวลผลในรอบนี้ (คงการเชื่อมต่อเครื่องไว้ตามปกติ)\")\n",
        "else:\n",
        "    suffix = คำต่อท้าย.strip() or (\"_4K\" if สเกล == \"4K UHD\" else f\"_{สเกล}\")\n",
        "    success_count = 0\n",
        "    error_count = 0\n",
        "    wave_num = 0\n",
        "\n",
        "    def _process_one_item(idx, total_wave, src_path, suffix):\n",
        "        fname = os.path.basename(src_path)\n",
        "        stem, ext = os.path.splitext(fname)\n",
        "        ext_low = ext.lower()\n",
        "        t0 = time.time()\n",
        "        queue_len_label = total_wave\n",
        "\n",
        "        try:\n",
        "            if ext_low in IMG_EXTS:\n",
        "                im = Image.open(src_path)\n",
        "                has_alpha = im.mode in (\"RGBA\", \"LA\") or (im.mode == \"P\" and \"transparency\" in im.info)\n",
        "                rgba = im.convert(\"RGBA\") if has_alpha else im.convert(\"RGB\")\n",
        "                in_w, in_h = rgba.size\n",
        "                out_w, out_h = compute_target_dims(in_w, in_h, สเกล, force_even=False)\n",
        "\n",
        "                w_key = resolve_weight_key(โมเดล, in_w, in_h, out_w, out_h)\n",
        "                net, net_scale, _ = get_turbo_model(w_key, use_compile=False)\n",
        "\n",
        "                arr = np.array(rgba)\n",
        "                rgb_sr = upscale_single_tiled_gpu(arr[:, :, :3], net, net_scale, out_w, out_h)\n",
        "                out_pil = Image.fromarray(rgb_sr, mode=\"RGB\")\n",
        "\n",
        "                if has_alpha:\n",
        "                    alpha_pil = Image.fromarray(arr[:, :, 3], mode=\"L\").resize((out_w, out_h), Image.Resampling.BICUBIC)\n",
        "                    out_pil = out_pil.convert(\"RGBA\")\n",
        "                    out_pil.putalpha(alpha_pil)\n",
        "\n",
        "                if ฟอร์แมตภาพนิ่ง == \"PNG\":\n",
        "                    out_ext = \".png\"\n",
        "                elif ฟอร์แมตภาพนิ่ง == \"JPG\":\n",
        "                    out_ext = \".jpg\"\n",
        "                elif ฟอร์แมตภาพนิ่ง == \"WEBP\":\n",
        "                    out_ext = \".webp\"\n",
        "                else:\n",
        "                    out_ext = ext_low if ext_low in (\".png\", \".jpg\", \".jpeg\", \".webp\") else \".png\"\n",
        "\n",
        "                out_file = os.path.join(OUTPUT_DIR, f\"{stem}{suffix}{out_ext}\")\n",
        "                if out_ext in (\".jpg\", \".jpeg\"):\n",
        "                    if out_pil.mode == \"RGBA\":\n",
        "                        bg = Image.new(\"RGB\", out_pil.size, (14, 14, 14))\n",
        "                        bg.paste(out_pil, mask=out_pil.split()[3])\n",
        "                        out_pil = bg\n",
        "                    out_pil.save(out_file, quality=96, subsampling=0)\n",
        "                elif out_ext == \".webp\":\n",
        "                    out_pil.save(out_file, quality=95)\n",
        "                else:\n",
        "                    out_pil.save(out_file, compress_level=4)\n",
        "\n",
        "                dt = time.time() - t0\n",
        "                print(f\"[{idx}/{queue_len_label}] ✓ ภาพนิ่ง: {fname} ({in_w}×{in_h} ➔ {out_w}×{out_h} • {w_key}) เสร็จใน {dt:.2f}s -> {os.path.basename(out_file)}\")\n",
        "\n",
        "            else:\n",
        "                # 1) Stage input video onto fast local NVMe SSD to eliminate Google Drive FUSE read stalls\n",
        "                local_in = os.path.join(STAGE_DIR, f\"_in_video{ext_low}\")\n",
        "                shutil.copy2(src_path, local_in)\n",
        "\n",
        "                probe_cmd = [\n",
        "                    \"ffprobe\", \"-v\", \"error\", \"-select_streams\", \"v:0\",\n",
        "                    \"-show_entries\", \"stream=width,height,r_frame_rate,nb_frames\",\n",
        "                    \"-show_entries\", \"format=duration\", \"-of\", \"json\", local_in\n",
        "                ]\n",
        "                meta = json.loads(subprocess.check_output(probe_cmd).decode(\"utf-8\"))\n",
        "                st = meta[\"streams\"][0]\n",
        "                in_w, in_h = int(st[\"width\"]), int(st[\"height\"])\n",
        "                fps_str = st.get(\"r_frame_rate\", \"24/1\")\n",
        "                num, den = (fps_str.split(\"/\") + [\"1\"])[:2]\n",
        "                fps_val = float(num) / max(1.0, float(den))\n",
        "                dur = float(meta.get(\"format\", {}).get(\"duration\", 0.0) or 0.0)\n",
        "                total_frames = int(st.get(\"nb_frames\") or 0) or max(1, round(dur * fps_val))\n",
        "\n",
        "                out_w, out_h = compute_target_dims(in_w, in_h, สเกล, force_even=True)\n",
        "                w_key = resolve_weight_key(โมเดล, in_w, in_h, out_w, out_h)\n",
        "                eager_net, net_scale, kind = get_turbo_model(w_key, use_compile=False)\n",
        "                do_compile = bool(เร่งสปีด_Torch_Compile_สำหรับวิดีโอ and total_frames >= 48)\n",
        "                net, _, _ = get_turbo_model(w_key, use_compile=do_compile)\n",
        "\n",
        "                batch_size = choose_video_batch_size(in_w, in_h, kind)\n",
        "                frame_bytes = in_w * in_h * 3\n",
        "                tmp_mp4 = os.path.join(STAGE_DIR, \"_out_video.mp4\")\n",
        "                out_file = os.path.join(OUTPUT_DIR, f\"{stem}{suffix}.mp4\")\n",
        "\n",
        "                mode_desc = f\"Batch={batch_size} เฟรมพร้อมกัน\" if batch_size > 0 else f\"Tiled ({AUTO_TILE_SIZE}px)\"\n",
        "                print(f\"[{idx}/{queue_len_label}] ▶ วิดีโอ: {fname} ({in_w}×{in_h} ➔ {out_w}×{out_h} • ~{total_frames} เฟรม • {w_key} • {mode_desc})\")\n",
        "\n",
        "                # Encoder receives exact (out_w x out_h) RGB24 frames resized on GPU -> ZERO CPU Lanczos bottleneck!\n",
        "                enc_cmd = [\n",
        "                    \"ffmpeg\", \"-y\", \"-v\", \"error\",\n",
        "                    \"-f\", \"rawvideo\", \"-pix_fmt\", \"rgb24\", \"-s\", f\"{out_w}x{out_h}\", \"-r\", fps_str, \"-i\", \"pipe:0\",\n",
        "                    \"-i\", local_in, \"-map\", \"0:v:0\", \"-map\", \"1:a?\"\n",
        "                ]\n",
        "                if HAS_NVENC:\n",
        "                    enc_cmd += [\"-c:v\", \"h264_nvenc\", \"-preset\", \"p3\", \"-tune\", \"hq\", \"-cq\", \"18\", \"-b:v\", \"0\"]\n",
        "                else:\n",
        "                    enc_cmd += [\"-c:v\", \"libx264\", \"-preset\", \"fast\", \"-crf\", \"18\"]\n",
        "                enc_cmd += [\"-pix_fmt\", \"yuv420p\", \"-c:a\", \"aac\", \"-b:a\", \"192k\", \"-movflags\", \"+faststart\", tmp_mp4]\n",
        "\n",
        "                decode_q = queue.Queue(maxsize=3)\n",
        "                encode_q = queue.Queue(maxsize=3)\n",
        "                worker_err = []\n",
        "\n",
        "                def _open_decoder(use_hw):\n",
        "                    cmd = [\"ffmpeg\", \"-v\", \"error\"]\n",
        "                    if use_hw:\n",
        "                        cmd += [\"-hwaccel\", \"cuda\"]\n",
        "                    cmd += [\"-i\", local_in, \"-f\", \"rawvideo\", \"-pix_fmt\", \"rgb24\", \"pipe:1\"]\n",
        "                    return subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=frame_bytes * max(2, batch_size or 2))\n",
        "\n",
        "                def _read_exact(stream, nbytes):\n",
        "                    chunks = []\n",
        "                    rem = nbytes\n",
        "                    while rem > 0:\n",
        "                        blk = stream.read(rem)\n",
        "                        if not blk:\n",
        "                            break\n",
        "                        chunks.append(blk)\n",
        "                        rem -= len(blk)\n",
        "                    return b\"\".join(chunks)\n",
        "\n",
        "                def _decoder_worker():\n",
        "                    eff_b = max(1, batch_size)\n",
        "                    dec_p = _open_decoder(HAS_NVDEC)\n",
        "                    first_try = True\n",
        "                    try:\n",
        "                        while True:\n",
        "                            raw = _read_exact(dec_p.stdout, frame_bytes * eff_b)\n",
        "                            if first_try and len(raw) == 0 and HAS_NVDEC:\n",
        "                                # Fallback cleanly to software decode if codec isn't supported by NVDEC (e.g. AV1 on T4)\n",
        "                                try:\n",
        "                                    dec_p.stdout.close()\n",
        "                                    dec_p.wait()\n",
        "                                except Exception:\n",
        "                                    pass\n",
        "                                dec_p = _open_decoder(False)\n",
        "                                raw = _read_exact(dec_p.stdout, frame_bytes * eff_b)\n",
        "                            first_try = False\n",
        "                            n_got = len(raw) // frame_bytes\n",
        "                            if n_got == 0:\n",
        "                                break\n",
        "                            valid = raw[: n_got * frame_bytes]\n",
        "                            arr_b = np.frombuffer(valid, dtype=np.uint8).reshape((n_got, in_h, in_w, 3)).copy()\n",
        "                            decode_q.put(arr_b)\n",
        "                    except Exception as ex:\n",
        "                        worker_err.append(ex)\n",
        "                    finally:\n",
        "                        try:\n",
        "                            dec_p.stdout.close()\n",
        "                            dec_p.wait()\n",
        "                        except Exception:\n",
        "                            pass\n",
        "                        decode_q.put(None)\n",
        "\n",
        "                enc_p = subprocess.Popen(enc_cmd, stdin=subprocess.PIPE, bufsize=out_w * out_h * 3 * 2)\n",
        "\n",
        "                def _encoder_worker():\n",
        "                    try:\n",
        "                        while True:\n",
        "                            item = encode_q.get()\n",
        "                            if item is None:\n",
        "                                break\n",
        "                            enc_p.stdin.write(item)\n",
        "                    except Exception as ex:\n",
        "                        worker_err.append(ex)\n",
        "                    finally:\n",
        "                        try:\n",
        "                            enc_p.stdin.close()\n",
        "                        except Exception:\n",
        "                            pass\n",
        "\n",
        "                t_dec = threading.Thread(target=_decoder_worker, daemon=True)\n",
        "                t_enc = threading.Thread(target=_encoder_worker, daemon=True)\n",
        "                t_dec.start()\n",
        "                t_enc.start()\n",
        "\n",
        "                done_f = 0\n",
        "                t_infer_start = None\n",
        "                cur_batch_cap = batch_size\n",
        "\n",
        "                try:\n",
        "                    while True:\n",
        "                        batch_np = decode_q.get()\n",
        "                        if batch_np is None:\n",
        "                            break\n",
        "                        if worker_err:\n",
        "                            raise worker_err[0]\n",
        "\n",
        "                        if cur_batch_cap <= 0:\n",
        "                            out_list = [upscale_single_tiled_gpu(batch_np[i], net, net_scale, out_w, out_h) for i in range(batch_np.shape[0])]\n",
        "                            sr_batch = np.stack(out_list, axis=0)\n",
        "                        else:\n",
        "                            try:\n",
        "                                if batch_np.shape[0] == cur_batch_cap:\n",
        "                                    sr_batch = upscale_frames_batch_gpu(batch_np, net, net_scale, out_w, out_h)\n",
        "                                elif batch_np.shape[0] < cur_batch_cap:\n",
        "                                    # Use eager_net for the final partial tail batch to avoid a 2nd torch.compile recompilation at 99%!\n",
        "                                    sr_batch = upscale_frames_batch_gpu(batch_np, eager_net, net_scale, out_w, out_h)\n",
        "                                else:\n",
        "                                    parts = [\n",
        "                                        upscale_frames_batch_gpu(\n",
        "                                            batch_np[s : s + cur_batch_cap],\n",
        "                                            net if (batch_np[s : s + cur_batch_cap].shape[0] == cur_batch_cap) else eager_net,\n",
        "                                            net_scale, out_w, out_h\n",
        "                                        )\n",
        "                                        for s in range(0, batch_np.shape[0], cur_batch_cap)\n",
        "                                    ]\n",
        "                                    sr_batch = np.concatenate(parts, axis=0)\n",
        "                            except torch.cuda.OutOfMemoryError:\n",
        "                                torch.cuda.empty_cache()\n",
        "                                cur_batch_cap = cur_batch_cap // 2\n",
        "                                print(f\"\\n    [Auto-VRAM] ปรับขนาด Batch ลงเหลือ {max(1, cur_batch_cap)} เฟรมเพื่อให้เหมาะกับความละเอียดคลิป...\")\n",
        "                                if cur_batch_cap <= 0:\n",
        "                                    out_list = [upscale_single_tiled_gpu(batch_np[i], net, net_scale, out_w, out_h) for i in range(batch_np.shape[0])]\n",
        "                                    sr_batch = np.stack(out_list, axis=0)\n",
        "                                else:\n",
        "                                    parts = [\n",
        "                                        upscale_frames_batch_gpu(batch_np[s : s + cur_batch_cap], net, net_scale, out_w, out_h)\n",
        "                                        for s in range(0, batch_np.shape[0], cur_batch_cap)\n",
        "                                    ]\n",
        "                                    sr_batch = np.concatenate(parts, axis=0)\n",
        "\n",
        "                        if t_infer_start is None:\n",
        "                            t_infer_start = time.time()  # Measure steady-state FPS after 1st batch / torch.compile warmup\n",
        "\n",
        "                        encode_q.put(sr_batch.tobytes())\n",
        "                        done_f += batch_np.shape[0]\n",
        "\n",
        "                        elapsed_total = max(0.001, time.time() - t0)\n",
        "                        steady_dt = max(0.001, time.time() - t_infer_start) if done_f > batch_np.shape[0] else elapsed_total\n",
        "                        steady_frames = max(1, done_f - batch_np.shape[0]) if done_f > batch_np.shape[0] else done_f\n",
        "                        spd = steady_frames / steady_dt\n",
        "                        pct = min(100.0, (done_f / max(1, total_frames)) * 100.0)\n",
        "                        eta = max(0.0, (total_frames - done_f) / max(0.01, spd))\n",
        "                        print(f\"\\r    ความคืบหน้า: {done_f}/{total_frames} เฟรม ({pct:.1f}%) • สปีดจริง {spd:.2f} fps • เหลือ ~{int(eta)} วิ   \", end=\"\", flush=True)\n",
        "                finally:\n",
        "                    encode_q.put(None)\n",
        "                    t_dec.join()\n",
        "                    t_enc.join()\n",
        "                    enc_rc = enc_p.wait()\n",
        "                    try:\n",
        "                        if os.path.exists(local_in):\n",
        "                            os.remove(local_in)\n",
        "                    except Exception:\n",
        "                        pass\n",
        "\n",
        "                print()\n",
        "                if worker_err:\n",
        "                    raise worker_err[0]\n",
        "                if enc_rc != 0 or not os.path.exists(tmp_mp4):\n",
        "                    raise RuntimeError(f\"FFmpeg encode failed (code {enc_rc})\")\n",
        "\n",
        "                shutil.move(tmp_mp4, out_file)\n",
        "                dt = time.time() - t0\n",
        "                print(f\"[{idx}/{queue_len_label}] ✓ วิดีโอเสร็จสมบูรณ์ ({dt:.1f}s) -> {os.path.basename(out_file)}\")\n",
        "\n",
        "            if ย้ายต้นฉบับไป_03_Done_เมื่อเสร็จ:\n",
        "                shutil.move(src_path, os.path.join(DONE_DIR, fname))\n",
        "            return True\n",
        "\n",
        "        except Exception as err:\n",
        "            print(f\"[{idx}/{queue_len_label}] ✕ ผิดพลาด ({fname}): {err}\")\n",
        "            return False\n",
        "\n",
        "    while queue_files:\n",
        "        wave_num += 1\n",
        "        if wave_num == 1:\n",
        "            print(f\"เริ่มประมวลผล Turbo ทั้งหมด {len(queue_files)} ไฟล์ | โมเดล: {โมเดล} | สเกล: {สเกล}\\n\" + \"-\" * 68)\n",
        "        else:\n",
        "            print(f\"\\n[คิวเพิ่มเติม] พบไฟล์โยนเข้ามาใหม่ระหว่างรันอีก {len(queue_files)} ไฟล์ — ประมวลผลต่อทันที!\\n\" + \"-\" * 68)\n",
        "\n",
        "        wave_total = len(queue_files)\n",
        "        for idx, sp in enumerate(queue_files, 1):\n",
        "            attempted_paths.add(sp)\n",
        "            if _process_one_item(idx, wave_total, sp, suffix):\n",
        "                success_count += 1\n",
        "            else:\n",
        "                error_count += 1\n",
        "\n",
        "        # Re-scan 01_Input in case new files were dropped while GPU was rendering!\n",
        "        queue_files = _scan_pending_inputs() if ย้ายต้นฉบับไป_03_Done_เมื่อเสร็จ else []\n",
        "\n",
        "    print(\"=\" * 68)\n",
        "    err_note = f\" (ผิดพลาด {error_count} ไฟล์)\" if error_count > 0 else \"\"\n",
        "    print(f\"เสร็จสิ้นครบทุกไฟล์ในคิว! สำเร็จ {success_count} ไฟล์{err_note} • โฟลเดอร์ผลลัพธ์: {OUTPUT_DIR}\")\n",
        "\n",
        "    if ตัดการเชื่อมต่อ_GPU_อัตโนมัติเมื่อทำครบ and IN_COLAB and (success_count + error_count) > 0:\n",
        "        print(\"[Auto-Stop] กำลังบังคับซิงก์ไฟล์ทั้งหมดขึ้น Google Drive ให้ครบ 100% ก่อนตัดการเชื่อมต่อ...\")\n",
        "        try:\n",
        "            if hasattr(os, \"sync\"):\n",
        "                os.sync()\n",
        "        except Exception:\n",
        "            pass\n",
        "        from google.colab import drive, runtime\n",
        "        drive.flush_and_unmount()\n",
        "        print(\"[Auto-Stop] ซิงก์ขึ้น Google Drive ครบ 100% แล้ว! กำลังตัดการเชื่อมต่อและคืน GPU ใน 5 วินาที (กด ■ Stop หากต้องการยกเลิก)...\")\n",
        "        time.sleep(5)\n",
        "        runtime.unassign()"
      ]
    }
  ]
}