ComfyUI × PopNow

在 ComfyUI 執行雲端 AI 模型

一個小小的自訂節點,把 PopNow 所有圖片、影片和音訊模型放進你的 ComfyUI 節點圖。不用顯示卡、不用下載模型:它送出任務、等待,再把結果交給下一個節點。

四步安裝完成

  1. 把下方程式碼存成 ComfyUI 資料夾裡的 custom_nodes/popnow_api.py。
  2. 在啟動 ComfyUI 的環境設定 POPNOW_API_KEY,然後重新啟動 ComfyUI。
  3. 在畫布上按兩下,搜尋 PopNow,加入 PopNow Generate 節點。
  4. 輸入模型名稱和提示詞,加入佇列。圖片模型輸出 IMAGE;影片和音訊存進 output 資料夾。

節點程式碼

純 Python,只用到 requests、Pillow、NumPy 和 PyTorch,這些 ComfyUI 都已內建。執行前請先讀一遍:它刻意寫得很短。

custom_nodes/popnow_api.py
"""PopNow API node for ComfyUI.

Save as ComfyUI/custom_nodes/popnow_api.py, set POPNOW_API_KEY, restart ComfyUI.
Runs any PopNow image, video or audio model in the cloud and returns the result.
Docs: https://popnow.ai/docs
"""
import io
import json
import os
import time
import uuid

import numpy as np
import requests
import torch
from PIL import Image

import folder_paths

BASE = "https://api.popnow.ai/api/v1"
TERMINAL = ("succeeded", "failed", "canceled", "expired")


def _headers(extra=None):
    key = os.environ.get("POPNOW_API_KEY")
    if not key:
        raise RuntimeError("Set POPNOW_API_KEY before starting ComfyUI")
    return {"Authorization": f"Bearer {key}", **(extra or {})}


def _call(method, path, **kwargs):
    headers = _headers(kwargs.pop("headers", None))
    body = requests.request(method, BASE + path, headers=headers, timeout=60, **kwargs).json()
    if body.get("code") != 200:
        raise RuntimeError(f'PopNow {body.get("code")}: {body.get("msg")}')
    return body["data"]


def _upload(image):
    """IMAGE tensor -> PNG -> upload -> popnow:// reference."""
    arr = (image[0].cpu().numpy() * 255).clip(0, 255).astype(np.uint8)
    buf = io.BytesIO()
    Image.fromarray(arr).save(buf, format="PNG")
    data = buf.getvalue()
    ticket = _call("POST", "/common/upload-url", json={"contentType": "image/png", "bytes": len(data)})
    requests.put(ticket["uploadUrl"], data=data, headers=ticket.get("headers", {}), timeout=120).raise_for_status()
    return _call("POST", f'/files/{ticket["fileId"]}/commit')["uri"]


class PopNowGenerate:
    CATEGORY = "PopNow"
    RETURN_TYPES = ("IMAGE", "STRING", "STRING")
    RETURN_NAMES = ("image", "url", "path")
    FUNCTION = "run"

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "model": ("STRING", {"default": "google/nano-banana-2.1/text-to-image"}),
                "prompt": ("STRING", {"multiline": True, "default": "A ceramic teapot on a linen cloth, soft window light, muted palette"}),
                "options": ("STRING", {"multiline": True, "default": "{\"aspect_ratio\":\"16:9\",\"resolution\":\"1k\",\"output_format\":\"png\"}"}),
            },
            "optional": {
                "image": ("IMAGE",),
                "image_field": ("STRING", {"default": "image_url"}),
            },
        }

    def run(self, model, prompt, options, image=None, image_field="image_url"):
        task_input = json.loads(options or "{}")
        if prompt.strip():
            task_input.setdefault("prompt", prompt)
        if image is not None:
            ref = _upload(image)
            task_input[image_field] = [ref] if image_field.endswith("s") else ref

        task_id = _call(
            "POST",
            "/jobs/createTask",
            headers={"Idempotency-Key": str(uuid.uuid4())},
            json={"model": model, "input": task_input},
        )["taskId"]

        delay = 2.0
        while True:
            time.sleep(delay)
            task = _call("GET", "/jobs/recordInfo", params={"taskId": task_id})
            assets = (task.get("output") or {}).get("assets") or []
            copying = any(a.get("pending") and not a.get("unavailable") for a in assets)
            if task["state"] in TERMINAL and not copying:
                break
            delay = min(delay * 1.5, 15.0)
        if task["state"] != "succeeded" or not assets:
            raise RuntimeError(f'PopNow {task["state"]}: {task.get("errorMessage", "no detail")}')

        asset = assets[0]
        content = requests.get(asset["url"], timeout=300).content
        mime = asset.get("mime", "")
        if mime.startswith("image/"):
            pil = Image.open(io.BytesIO(content)).convert("RGB")
            tensor = torch.from_numpy(np.asarray(pil).astype(np.float32) / 255.0)[None,]
            return (tensor, asset["url"], "")

        ext = {"video/mp4": ".mp4", "video/webm": ".webm", "audio/mpeg": ".mp3", "audio/wav": ".wav"}.get(mime, ".bin")
        path = os.path.join(folder_paths.get_output_directory(), f"popnow_{task_id}{ext}")
        with open(path, "wb") as f:
            f.write(content)
        # Video and audio: a small blank IMAGE keeps the graph valid; use the path output.
        return (torch.zeros((1, 64, 64, 3)), asset["url"], path)


NODE_CLASS_MAPPINGS = {"PopNowGenerate": PopNowGenerate}
NODE_DISPLAY_NAME_MAPPINGS = {"PopNowGenerate": "PopNow Generate"}

輸入與輸出

model
模型名稱,例如 google/nano-banana-2.1/text-to-image。每個模型的 API 頁都有。
prompt
要生成的內容。不需要提示詞的模型留空即可。
options
其他欄位,寫成 JSON,例如 resolution 或 duration_seconds。模型的 API 頁列出了全部欄位。
image
選填的 IMAGE 輸入。節點會自動上傳,並填進 image_field 指定的欄位。
image_field
圖片要填進哪個輸入欄位:多數影片模型是 image_url,圖片編輯是 image_urls。
image · url · path
圖片模型輸出 IMAGE;影片和音訊另外給出檔案網址和本機路徑。

為什麼在 ComfyUI 使用雲端模型

  • 不需要顯示卡

    需要 24 GB 以上記憶體的影片模型在我們這邊執行,你的電腦只負責送出提示詞。

  • 和本機節點搭配

    在本機做首幀,用 Kling 或 Seedance 讓它動起來,再回到本機放大。

  • 每次價格清清楚楚

    每個模型都事先標好點數價格,失敗的執行會退還點數。

適合入門的模型

ComfyUI 常見問題

這是官方套件嗎?

這是我們在本頁公開的單一檔案,不是套件庫裡的套件。複製、讀一遍,API 有變動時回來這裡更新。

ComfyUI Desktop 和 Comfy Cloud 能用嗎?

只要能加入自訂節點、能設定環境變數就能用:ComfyUI 可攜版、Desktop 和自架伺服器都可以。

怎麼取回影片影格?

節點會把影片存進 ComfyUI 的 output 資料夾並回傳路徑。用影片載入節點讀進來,就能繼續處理每一格。

跑一次要多少錢?

和網站同一份點數,每個模型的 API 頁都有價格。實驗階段可以在主控台替金鑰設定每日上限。