File size: 12,845 Bytes
d986a84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc78349
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d986a84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693ee99
d986a84
 
 
 
 
 
 
 
e5d4029
693ee99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""
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 <URL>
     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()