Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
176 lines
6.9 KiB
Python
176 lines
6.9 KiB
Python
"""Real-ESRGAN CPU sidecar for Menivor image upscale (MH7, Wave P PM2.1).
|
|
|
|
A small HTTP service (stdlib only) in front of Real-ESRGAN (BSD-3-Clause):
|
|
|
|
* ``POST /v1/upscale?scale=4`` with the image bytes -> the upscaled PNG;
|
|
* ``GET /healthz`` -> ``{"ok": true, "backend": ...}``.
|
|
|
|
Backends (``ESRGAN_BACKEND``: ``auto``, ``ncnn`` or ``torch``):
|
|
|
|
* ``ncnn`` runs the ``realesrgan-ncnn-vulkan`` binary with ``-g -1`` (its CPU
|
|
path). Upstream ships x86_64 binaries only and needs a Vulkan loader; on an
|
|
arm64 box it must be built from source with a software Vulkan driver, so it
|
|
is used only when ``ESRGAN_NCNN_BIN`` points at a working binary.
|
|
* ``torch`` runs the Real-ESRGAN PyTorch model on CPU (``realesrgan`` and
|
|
``basicsr`` packages, RealESRGAN_x4plus weights, tiled so memory stays
|
|
bounded). ``auto`` picks ``ncnn`` when the binary answers, else ``torch``.
|
|
|
|
One image at a time (a lock), inputs up to 1920 px on the long side, and the
|
|
seconds per image are logged so the "1080p under 20 s" target is measured on
|
|
the box before launch.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import json
|
|
import logging
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from typing import Callable
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
LOG = logging.getLogger("esrgan")
|
|
MAX_BYTES = 25 * 1024 * 1024
|
|
MAX_LONG_SIDE = int(os.getenv("ESRGAN_MAX_LONG_SIDE", "1920"))
|
|
TILE = int(os.getenv("ESRGAN_TILE", "192"))
|
|
WEIGHTS = os.getenv("ESRGAN_WEIGHTS", "/models/RealESRGAN_x4plus.pth")
|
|
NCNN_BIN = os.getenv("ESRGAN_NCNN_BIN", "")
|
|
NCNN_MODEL_DIR = os.getenv("ESRGAN_NCNN_MODELS", "/models/ncnn")
|
|
_LOCK = threading.Lock()
|
|
|
|
Backend = Callable[[bytes, int], bytes]
|
|
|
|
|
|
def image_size(data: bytes) -> tuple[int, int]:
|
|
from PIL import Image
|
|
|
|
with Image.open(io.BytesIO(data)) as im:
|
|
return im.width, im.height
|
|
|
|
|
|
def ncnn_backend(data: bytes, scale: int) -> bytes:
|
|
with tempfile.TemporaryDirectory() as work:
|
|
src, dst = os.path.join(work, "in.png"), os.path.join(work, "out.png")
|
|
from PIL import Image
|
|
|
|
with Image.open(io.BytesIO(data)) as im:
|
|
im.convert("RGB").save(src)
|
|
done = subprocess.run([NCNN_BIN, "-i", src, "-o", dst, "-s", str(scale), "-n", "realesrgan-x4plus",
|
|
"-m", NCNN_MODEL_DIR, "-g", "-1", "-t", str(TILE)],
|
|
capture_output=True, timeout=300, check=False)
|
|
if done.returncode != 0 or not os.path.exists(dst):
|
|
raise RuntimeError("ncnn backend failed")
|
|
with open(dst, "rb") as fh:
|
|
return fh.read()
|
|
|
|
|
|
_TORCH = {}
|
|
|
|
|
|
def torch_backend(data: bytes, scale: int) -> bytes:
|
|
import numpy as np
|
|
from PIL import Image
|
|
|
|
if "model" not in _TORCH:
|
|
from basicsr.archs.rrdbnet_arch import RRDBNet
|
|
from realesrgan import RealESRGANer
|
|
|
|
net = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
|
|
_TORCH["model"] = RealESRGANer(scale=4, model_path=WEIGHTS, model=net, tile=TILE, tile_pad=10, pre_pad=0,
|
|
half=False, device="cpu")
|
|
with Image.open(io.BytesIO(data)) as im:
|
|
bgr = np.array(im.convert("RGB"))[:, :, ::-1]
|
|
output, _ = _TORCH["model"].enhance(bgr, outscale=scale)
|
|
out = io.BytesIO()
|
|
Image.fromarray(output[:, :, ::-1]).save(out, format="PNG")
|
|
return out.getvalue()
|
|
|
|
|
|
def pick_backend(name: str | None = None) -> tuple[str, Backend]:
|
|
wanted = (name or os.getenv("ESRGAN_BACKEND") or "auto").strip().lower()
|
|
ncnn_ready = bool(NCNN_BIN) and shutil.which(NCNN_BIN) is not None or os.path.isfile(NCNN_BIN or "")
|
|
if wanted == "ncnn" or (wanted == "auto" and ncnn_ready):
|
|
return "ncnn", ncnn_backend
|
|
return "torch", torch_backend
|
|
|
|
|
|
def make_handler(backend_name: str, backend: Backend) -> type[BaseHTTPRequestHandler]:
|
|
class Handler(BaseHTTPRequestHandler):
|
|
server_version = "menivor-esrgan/1"
|
|
|
|
def log_message(self, fmt: str, *args) -> None: # noqa: A003 - stdlib signature
|
|
LOG.info(fmt, *args)
|
|
|
|
def _json(self, status: int, body: dict) -> None:
|
|
raw = json.dumps(body).encode()
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
|
|
def do_GET(self) -> None: # noqa: N802 - stdlib name
|
|
if urlparse(self.path).path == "/healthz":
|
|
self._json(200, {"ok": True, "backend": backend_name})
|
|
else:
|
|
self._json(404, {"error": "not found"})
|
|
|
|
def do_POST(self) -> None: # noqa: N802 - stdlib name
|
|
url = urlparse(self.path)
|
|
if url.path != "/v1/upscale":
|
|
self._json(404, {"error": "not found"})
|
|
return
|
|
scale = int((parse_qs(url.query).get("scale") or ["4"])[0])
|
|
if scale not in (2, 4):
|
|
self._json(400, {"error": "scale is 2 or 4"})
|
|
return
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
if length <= 0 or length > MAX_BYTES:
|
|
self._json(413, {"error": "image too large"})
|
|
return
|
|
data = self.rfile.read(length)
|
|
try:
|
|
width, height = image_size(data)
|
|
except Exception: # noqa: BLE001 - any decode failure is a client error
|
|
self._json(400, {"error": "not an image"})
|
|
return
|
|
if max(width, height) > MAX_LONG_SIDE:
|
|
self._json(400, {"error": f"images up to {MAX_LONG_SIDE} px on the long side"})
|
|
return
|
|
started = time.monotonic()
|
|
with _LOCK:
|
|
try:
|
|
out = backend(data, scale)
|
|
except Exception as exc: # noqa: BLE001 - reported as a 500 with no detail
|
|
LOG.error("upscale failed: %s", exc)
|
|
self._json(500, {"error": "upscale failed"})
|
|
return
|
|
LOG.info("upscaled %dx%d x%d in %.2f s (%s)", width, height, scale, time.monotonic() - started,
|
|
backend_name)
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "image/png")
|
|
self.send_header("Content-Length", str(len(out)))
|
|
self.send_header("X-Upscale-Seconds", f"{time.monotonic() - started:.2f}")
|
|
self.end_headers()
|
|
self.wfile.write(out)
|
|
|
|
return Handler
|
|
|
|
|
|
def main() -> None:
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
name, backend = pick_backend()
|
|
port = int(os.getenv("PORT", "8090"))
|
|
LOG.info("esrgan sidecar on :%d with the %s backend", port, name)
|
|
ThreadingHTTPServer(("0.0.0.0", port), make_handler(name, backend)).serve_forever() # noqa: S104 - container port
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|