""" Morphaze HuggingFace Space — ReStyle + GFPGAN Avatar Preprocessing Provides face preprocessing for the Morphaze avatar pipeline: - ReStyle GAN inversion → cleaned face + W+ latent code - GFPGAN face restoration → enhanced face for degraded inputs API (auto-generated by Gradio): POST /api/predict — accepts {"data": [image, model_name]} model_name: "restyle" (default) or "gfpgan" Deploy: 1. Create HF Space with Gradio SDK 2. Clone restyle-encoder repo into Space: git clone https://github.com/yuval-alaluf/restyle-encoder 3. Download weights: mkdir -p pretrained_models wget -O pretrained_models/restyle_psp_ffhq_encode.pt wget -O pretrained_models/GFPGANv1.4.pth https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth 4. Push to HF Version: 2.0.0 (production-hardened) """ import logging import time import json import base64 import io import os import sys # HfFolder was removed from huggingface_hub>=0.26 but gradio[oauth] still uses it. # Patch it back before gradio is imported (affects both gradio 4.x and 5.0.x). try: from huggingface_hub import HfFolder # noqa: F401 — exists, nothing to do except ImportError: import huggingface_hub as _hfh class _HfFolder: @staticmethod def get_token(): try: from huggingface_hub import get_token return get_token() except Exception: return None @staticmethod def save_token(token: str) -> None: pass _hfh.HfFolder = _HfFolder # type: ignore[attr-defined] import gradio as gr import torch import numpy as np from PIL import Image # ── Logging ────────────────────────────────────────────────── logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S", ) log = logging.getLogger("morphaze-space") # ── Constants ──────────────────────────────────────────────── VERSION = "2.0.0" MAX_IMAGE_DIM = 4096 # Maximum input dimension (prevents OOM) MIN_IMAGE_DIM = 64 # Minimum input dimension MAX_ASPECT_RATIO = 4 # Maximum w/h or h/w ratio RESTYLE_MODEL_PATH = "pretrained_models/restyle_psp_ffhq_encode.pt" GFPGAN_MODEL_PATH = "pretrained_models/GFPGANv1.4.pth" # ── Device ─────────────────────────────────────────────────── DEVICE = "cuda" if torch.cuda.is_available() else "cpu" log.info(f"Device: {DEVICE} | PyTorch: {torch.__version__} | Version: {VERSION}") # ═══════════════════════════════════════════════════════════════ # INPUT VALIDATION # ═══════════════════════════════════════════════════════════════ def _validate_face_input(image: Image.Image) -> str | None: """Validate input image. Returns error string or None if valid.""" if image is None: return "No image provided." w, h = image.size if w < MIN_IMAGE_DIM or h < MIN_IMAGE_DIM: return f"Image too small ({w}x{h}). Minimum {MIN_IMAGE_DIM}x{MIN_IMAGE_DIM}." if w > MAX_IMAGE_DIM or h > MAX_IMAGE_DIM: return f"Image too large ({w}x{h}). Maximum {MAX_IMAGE_DIM}x{MAX_IMAGE_DIM}." if max(w, h) / max(min(w, h), 1) > MAX_ASPECT_RATIO: return f"Extreme aspect ratio ({w}x{h}). Please upload a face photo." # Reject blank/uniform images arr = np.array(image.convert("RGB")) if arr.std() < 5.0: return "Image appears blank or uniform. Please upload a face photo." return None # ═══════════════════════════════════════════════════════════════ # RESTYLE MODEL (singleton, lazy-loaded) # ═══════════════════════════════════════════════════════════════ _restyle_model = None def _load_restyle(): """Load ReStyle model (singleton). Returns (net, opts) or raises.""" global _restyle_model if _restyle_model is not None: return _restyle_model if not os.path.exists(RESTYLE_MODEL_PATH): raise FileNotFoundError( f"ReStyle weights not found at {RESTYLE_MODEL_PATH}. " f"Download them first (see docstring)." ) # Add restyle-encoder to path for model imports restyle_dir = "./restyle-encoder" if os.path.isdir(restyle_dir) and restyle_dir not in sys.path: sys.path.insert(0, restyle_dir) from argparse import Namespace from models.psp import pSp log.info(f"Loading ReStyle from {RESTYLE_MODEL_PATH}...") ckpt = torch.load(RESTYLE_MODEL_PATH, map_location="cpu") opts = Namespace(**ckpt["opts"]) opts.checkpoint_path = RESTYLE_MODEL_PATH opts.n_iters_per_batch = 5 net = pSp(opts) net.eval() if DEVICE == "cuda": net.cuda() _restyle_model = (net, opts) log.info("ReStyle loaded successfully") return _restyle_model # ═══════════════════════════════════════════════════════════════ # GFPGAN MODEL (singleton, lazy-loaded) # ═══════════════════════════════════════════════════════════════ _gfpgan_restorer = None def _load_gfpgan(): """Load GFPGAN restorer (singleton). Returns GFPGANer or raises.""" global _gfpgan_restorer if _gfpgan_restorer is not None: return _gfpgan_restorer if not os.path.exists(GFPGAN_MODEL_PATH): raise FileNotFoundError( f"GFPGAN weights not found at {GFPGAN_MODEL_PATH}. " f"Download them first (see docstring)." ) from gfpgan import GFPGANer log.info(f"Loading GFPGAN from {GFPGAN_MODEL_PATH}...") _gfpgan_restorer = GFPGANer( model_path=GFPGAN_MODEL_PATH, upscale=2, arch="clean", channel_multiplier=2, ) log.info("GFPGAN loaded successfully") return _gfpgan_restorer # ═══════════════════════════════════════════════════════════════ # INFERENCE FUNCTIONS # ═══════════════════════════════════════════════════════════════ def restyle_predict(image: Image.Image) -> dict: """Run ReStyle GAN inversion on a face image.""" net, opts = _load_restyle() import torchvision.transforms as transforms from utils.common import tensor2im from utils.inference_utils import run_on_batch # Ensure RGB if image.mode != "RGB": image = image.convert("RGB") # Downsize if too large (prevents OOM) w, h = image.size if max(w, h) > 1024: scale = 1024 / max(w, h) image = image.resize((int(w * scale), int(h * scale)), Image.LANCZOS) transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), ]) input_tensor = transform(image).unsqueeze(0).to(DEVICE) # Average image for initialization with torch.no_grad(): avg_image = net( net.latent_avg.unsqueeze(0), input_code=True, randomize_noise=False, return_latents=False, average_code=True, )[0].to(DEVICE).float().detach() # Run 5 iterative refinement steps start = time.time() with torch.no_grad(): result_batch, result_latents = run_on_batch( input_tensor, net, opts, avg_image ) processing_time = time.time() - start # Get final result image final_image = tensor2im(result_batch[0][-1]) # Encode result as base64 buf = io.BytesIO() final_image.save(buf, format="PNG") image_b64 = base64.b64encode(buf.getvalue()).decode() # Get W+ latent code (18×512 = 9216 floats) latent = result_latents[0][-1].cpu().numpy().flatten().tolist() assert len(latent) == 9216, f"Expected 9216 latent dims, got {len(latent)}" # Free GPU memory if DEVICE == "cuda": torch.cuda.empty_cache() log.info(f"ReStyle inference: {processing_time:.2f}s, latent={len(latent)} dims") return { "image": image_b64, "latent": latent, "processing_time": round(processing_time, 3), "version": VERSION, } def gfpgan_restore(image: Image.Image) -> dict: """Restore degraded face using GFPGAN.""" import cv2 restorer = _load_gfpgan() # Ensure RGB if image.mode != "RGB": image = image.convert("RGB") # Downsize if too large w, h = image.size if max(w, h) > 2048: scale = 2048 / max(w, h) image = image.resize((int(w * scale), int(h * scale)), Image.LANCZOS) start = time.time() img_np = np.array(image)[:, :, ::-1] # RGB → BGR for cv2 _, _, output = restorer.enhance(img_np, paste_back=True) output_rgb = output[:, :, ::-1] # BGR → RGB processing_time = time.time() - start result = Image.fromarray(output_rgb) buf = io.BytesIO() result.save(buf, format="PNG") image_b64 = base64.b64encode(buf.getvalue()).decode() # Free GPU memory if DEVICE == "cuda": torch.cuda.empty_cache() log.info(f"GFPGAN inference: {processing_time:.2f}s, output={output_rgb.shape}") return { "image": image_b64, "processing_time": round(processing_time, 3), "output_size": list(output_rgb.shape[:2]), "version": VERSION, } # ═══════════════════════════════════════════════════════════════ # MAIN PREDICT FUNCTION (Gradio entry point) # ═══════════════════════════════════════════════════════════════ def predict(image, model_name="restyle"): """Main entry point — validates input, routes to model, handles errors.""" # Validate input error = _validate_face_input(image) if error: return {"error": error, "version": VERSION} try: if model_name == "gfpgan": return gfpgan_restore(image) return restyle_predict(image) except FileNotFoundError as e: log.error(f"Model not found: {e}") return {"error": str(e), "version": VERSION} except torch.cuda.OutOfMemoryError: torch.cuda.empty_cache() log.error("CUDA OOM — try a smaller image") return {"error": "GPU out of memory. Try a smaller image.", "version": VERSION} except Exception as e: log.error(f"Inference failed: {type(e).__name__}: {e}") return {"error": f"Inference failed: {str(e)[:200]}", "version": VERSION} # ═══════════════════════════════════════════════════════════════ # GRADIO INTERFACE # ═══════════════════════════════════════════════════════════════ demo = gr.Interface( fn=predict, inputs=[ gr.Image(type="pil", label="Face Photo"), gr.Dropdown( choices=["restyle", "gfpgan"], value="restyle", label="Model", ), ], outputs=gr.JSON(label="Result"), title="Morphaze Avatar Preprocessor", description=( "Face preprocessing for the Morphaze avatar pipeline. " "ReStyle: returns cleaned face + W+ latent code. " "GFPGAN: restores degraded/blurry faces." ), flagging_mode="never", concurrency_limit=2, ) # Enable queue for long-running GPU inference demo.queue(max_size=10) if __name__ == "__main__": log.info(f"Starting Morphaze Space v{VERSION}") demo.launch()