Spaces:
Build error
Build error
Download app.py from Prodya-Avatar/avatar-restyle: direct link, hf CLI and curl.
- Browser
- Download file 4.31 kB
-
https://huggingface.co/spaces/Prodya-Avatar/avatar-restyle/resolve/main/app.py
- Command line
-
hf download hf://spaces/Prodya-Avatar/avatar-restyle/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Prodya-Avatar/avatar-restyle/resolve/main/app.py
4.31 kB
| """ | |
| HuggingFace Space — ReStyle + GFPGAN Avatar Preprocessing | |
| This Space runs on free ZeroGPU and provides two endpoints: | |
| 1. /api/predict — ReStyle GAN inversion (mandatory preprocessing) | |
| 2. /api/restore — GFPGAN face restoration (optional) | |
| Deploy: | |
| 1. Create HF Space: huggingface-cli repo create [username]/restyle-avatar --type space --sdk gradio | |
| 2. Copy this directory to the Space repo | |
| 3. Download ReStyle weights to the Space: | |
| wget https://drive.google.com/... -O pretrained_models/restyle_psp_ffhq_encode.pt | |
| 4. Push to HF: git push | |
| The Space auto-deploys and gets free ZeroGPU allocation. | |
| """ | |
| import gradio as gr | |
| import torch | |
| import numpy as np | |
| from PIL import Image | |
| import time | |
| import json | |
| import base64 | |
| import io | |
| # --- ReStyle Inference --- | |
| restyle_model = None | |
| def load_restyle(): | |
| global restyle_model | |
| if restyle_model is not None: | |
| return restyle_model | |
| import sys | |
| sys.path.insert(0, "./restyle-encoder") | |
| from argparse import Namespace | |
| from models.psp import pSp | |
| model_path = "pretrained_models/restyle_psp_ffhq_encode.pt" | |
| ckpt = torch.load(model_path, map_location="cpu") | |
| opts = Namespace(**ckpt["opts"]) | |
| opts.checkpoint_path = model_path | |
| opts.n_iters_per_batch = 5 | |
| net = pSp(opts) | |
| net.eval() | |
| if torch.cuda.is_available(): | |
| net.cuda() | |
| restyle_model = (net, opts) | |
| return restyle_model | |
| 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 | |
| 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) | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| input_tensor = input_tensor.to(device) | |
| # Get 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() | |
| return { | |
| "image": image_b64, | |
| "latent": latent, | |
| "processing_time": processing_time, | |
| } | |
| # --- GFPGAN Restoration --- | |
| def gfpgan_restore(image: Image.Image) -> dict: | |
| """Restore degraded face using GFPGAN.""" | |
| from gfpgan import GFPGANer | |
| import cv2 | |
| restorer = GFPGANer( | |
| model_path="pretrained_models/GFPGANv1.4.pth", | |
| upscale=2, arch="clean", channel_multiplier=2, | |
| ) | |
| img_np = np.array(image)[:, :, ::-1] # RGB → BGR for cv2 | |
| _, _, output = restorer.enhance(img_np, paste_back=True) | |
| output_rgb = output[:, :, ::-1] # BGR → RGB | |
| result = Image.fromarray(output_rgb) | |
| buf = io.BytesIO() | |
| result.save(buf, format="PNG") | |
| image_b64 = base64.b64encode(buf.getvalue()).decode() | |
| return {"image": image_b64} | |
| # --- Gradio Interface --- | |
| def predict(image, model_name="restyle"): | |
| if model_name == "gfpgan": | |
| return json.dumps(gfpgan_restore(image)) | |
| return json.dumps(restyle_predict(image)) | |
| 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="Avatar ReStyle Preprocessor", | |
| description="Mandatory face preprocessing for the Avatar pipeline. Returns cleaned face + W+ latent code.", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |