CoolFace
Apppublic

blackmoon113/CodeFormer

sourceHugging Faceapache-2.0updated 4y agoView on Hugging Face
0likes
app.py263 linesDownload Raw Back to root
1"""2This file is used for deploying hugging face demo:3https://huggingface.co/spaces/sczhou/CodeFormer4"""5 6import sys7sys.path.append('CodeFormer')8import os9import cv210import torch11import torch.nn.functional as F12import gradio as gr13 14from torchvision.transforms.functional import normalize15 16from basicsr.utils import imwrite, img2tensor, tensor2img17from basicsr.utils.download_util import load_file_from_url18from facelib.utils.face_restoration_helper import FaceRestoreHelper19from facelib.utils.misc import is_gray20from basicsr.archs.rrdbnet_arch import RRDBNet21from basicsr.utils.realesrgan_utils import RealESRGANer22 23from basicsr.utils.registry import ARCH_REGISTRY24 25 26os.system("pip freeze")27 28pretrain_model_url = {29    'codeformer': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth',30    'detection': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth',31    'parsing': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth',32    'realesrgan': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth'33}34# download weights35if not os.path.exists('CodeFormer/weights/CodeFormer/codeformer.pth'):36    load_file_from_url(url=pretrain_model_url['codeformer'], model_dir='CodeFormer/weights/CodeFormer', progress=True, file_name=None)37if not os.path.exists('CodeFormer/weights/facelib/detection_Resnet50_Final.pth'):38    load_file_from_url(url=pretrain_model_url['detection'], model_dir='CodeFormer/weights/facelib', progress=True, file_name=None)39if not os.path.exists('CodeFormer/weights/facelib/parsing_parsenet.pth'):40    load_file_from_url(url=pretrain_model_url['parsing'], model_dir='CodeFormer/weights/facelib', progress=True, file_name=None)41if not os.path.exists('CodeFormer/weights/realesrgan/RealESRGAN_x2plus.pth'):42    load_file_from_url(url=pretrain_model_url['realesrgan'], model_dir='CodeFormer/weights/realesrgan', progress=True, file_name=None)43 44# download images45torch.hub.download_url_to_file(46    'https://replicate.com/api/models/sczhou/codeformer/files/fa3fe3d1-76b0-4ca8-ac0d-0a925cb0ff54/06.png',47    '01.png')48torch.hub.download_url_to_file(49    'https://replicate.com/api/models/sczhou/codeformer/files/a1daba8e-af14-4b00-86a4-69cec9619b53/04.jpg',50    '02.jpg')51torch.hub.download_url_to_file(52    'https://replicate.com/api/models/sczhou/codeformer/files/542d64f9-1712-4de7-85f7-3863009a7c3d/03.jpg',53    '03.jpg')54torch.hub.download_url_to_file(55    'https://replicate.com/api/models/sczhou/codeformer/files/a11098b0-a18a-4c02-a19a-9a7045d68426/010.jpg',56    '04.jpg')57torch.hub.download_url_to_file(58    'https://replicate.com/api/models/sczhou/codeformer/files/7cf19c2c-e0cf-4712-9af8-cf5bdbb8d0ee/012.jpg',59    '05.jpg')60 61def imread(img_path):62    img = cv2.imread(img_path)63    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)64    return img65 66# set enhancer with RealESRGAN67def set_realesrgan():68    half = True if torch.cuda.is_available() else False69    model = RRDBNet(70        num_in_ch=3,71        num_out_ch=3,72        num_feat=64,73        num_block=23,74        num_grow_ch=32,75        scale=2,76    )77    upsampler = RealESRGANer(78        scale=2,79        model_path="CodeFormer/weights/realesrgan/RealESRGAN_x2plus.pth",80        model=model,81        tile=400,82        tile_pad=40,83        pre_pad=0,84        half=half,85    )86    return upsampler87 88upsampler = set_realesrgan()89device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')90codeformer_net = ARCH_REGISTRY.get("CodeFormer")(91    dim_embd=512,92    codebook_size=1024,93    n_head=8,94    n_layers=9,95    connect_list=["32", "64", "128", "256"],96).to(device)97ckpt_path = "CodeFormer/weights/CodeFormer/codeformer.pth"98checkpoint = torch.load(ckpt_path)["params_ema"]99codeformer_net.load_state_dict(checkpoint)100codeformer_net.eval()101 102os.makedirs('output', exist_ok=True)103 104def inference(image, background_enhance, face_upsample, upscale, codeformer_fidelity):105    """Run a single prediction on the model"""106    try: # global try107        # take the default setting for the demo108        has_aligned = False109        only_center_face = False110        draw_box = False111        detection_model = "retinaface_resnet50"112 113        upscale = int(upscale) # covert type to int114        face_helper = FaceRestoreHelper(115            upscale,116            face_size=512,117            crop_ratio=(1, 1),118            det_model=detection_model,119            save_ext="png",120            use_parse=True,121            device=device,122        )123        bg_upsampler = upsampler if background_enhance else None124        face_upsampler = upsampler if face_upsample else None125 126        img = cv2.imread(str(image), cv2.IMREAD_COLOR)127 128        if has_aligned:129            # the input faces are already cropped and aligned130            img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_LINEAR)131            face_helper.is_gray = is_gray(img, threshold=5)132            if face_helper.is_gray:133                print('Grayscale input: True')134            face_helper.cropped_faces = [img]135        else:136            face_helper.read_image(img)137            # get face landmarks for each face138            num_det_faces = face_helper.get_face_landmarks_5(139            only_center_face=only_center_face, resize=640, eye_dist_threshold=5140            )141            print(f"\tdetect {num_det_faces} faces")142            # align and warp each face143            face_helper.align_warp_face()144 145        # face restoration for each cropped face146        for idx, cropped_face in enumerate(face_helper.cropped_faces):147            # prepare data148            cropped_face_t = img2tensor(149                cropped_face / 255.0, bgr2rgb=True, float32=True150            )151            normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)152            cropped_face_t = cropped_face_t.unsqueeze(0).to(device)153 154            try:155                with torch.no_grad():156                    output = codeformer_net(157                        cropped_face_t, w=codeformer_fidelity, adain=True158                    )[0]159                    restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))160                del output161                torch.cuda.empty_cache()162            except RuntimeError as error:163                print(f"\tFailed inference for CodeFormer: {error}")164                restored_face = tensor2img(165                    cropped_face_t, rgb2bgr=True, min_max=(-1, 1)166                )167 168            restored_face = restored_face.astype("uint8")169            face_helper.add_restored_face(restored_face)170 171        # paste_back172        if not has_aligned:173            # upsample the background174            if bg_upsampler is not None:175                # Now only support RealESRGAN for upsampling background176                bg_img = bg_upsampler.enhance(img, outscale=upscale)[0]177            else:178                bg_img = None179            face_helper.get_inverse_affine(None)180            # paste each restored face to the input image181            if face_upsample and face_upsampler is not None:182                restored_img = face_helper.paste_faces_to_input_image(183                    upsample_img=bg_img,184                    draw_box=draw_box,185                    face_upsampler=face_upsampler,186                )187            else:188                restored_img = face_helper.paste_faces_to_input_image(189                    upsample_img=bg_img, draw_box=draw_box190                )191 192        # save restored img193        save_path = f'output/out.png'194        imwrite(restored_img, str(save_path))195 196        restored_img = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)197        return restored_img, save_path198    except Exception as error:199        print('global exception', error)200        return None, None201 202 203title = "CodeFormer: Robust Face Restoration and Enhancement Network"204description = r"""<center><img src='https://user-images.githubusercontent.com/14334509/189166076-94bb2cac-4f4e-40fb-a69f-66709e3d98f5.png' alt='CodeFormer logo'></center>205<b>Official Gradio demo</b> for <a href='https://github.com/sczhou/CodeFormer' target='_blank'><b>Towards Robust Blind Face Restoration with Codebook Lookup Transformer (NeurIPS 2022)</b></a>.<br>206๐Ÿ”ฅ CodeFormer is a robust face restoration algorithm for old photos or AI-generated faces.<br>207๐Ÿค— Try CodeFormer for improved stable-diffusion generation!<br>208"""209article = r"""210If CodeFormer is helpful, please help to โญ the <a href='https://github.com/sczhou/CodeFormer' target='_blank'>Github Repo</a>. Thanks! 211[![GitHub Stars](https://img.shields.io/github/stars/sczhou/CodeFormer?style=social)](https://github.com/sczhou/CodeFormer)212 213---214 215๐Ÿ“ **Citation**216 217If our work is useful for your research, please consider citing:218```bibtex219@inproceedings{zhou2022codeformer,220    author = {Zhou, Shangchen and Chan, Kelvin C.K. and Li, Chongyi and Loy, Chen Change},221    title = {Towards Robust Blind Face Restoration with Codebook Lookup TransFormer},222    booktitle = {NeurIPS},223    year = {2022}224}225```226 227๐Ÿ“‹ **License**228 229This project is licensed under <a rel="license" href="https://github.com/sczhou/CodeFormer/blob/master/LICENSE">S-Lab License 1.0</a>. 230Redistribution and use for non-commercial purposes should follow this license.231 232๐Ÿ“ง **Contact**233 234If you have any questions, please feel free to reach me out at <b>shangchenzhou@gmail.com</b>.235 236![visitors](https://visitor-badge.laobi.icu/badge?page_id=sczhou/CodeFormer)237"""238 239demo = gr.Interface(240    inference, [241        gr.inputs.Image(type="filepath", label="Input"),242        gr.inputs.Checkbox(default=True, label="Background_Enhance"),243        gr.inputs.Checkbox(default=True, label="Face_Upsample"),244        gr.inputs.Number(default=2, label="Rescaling_Factor"),245        gr.Slider(0, 1, value=0.5, step=0.01, label='Codeformer_Fidelity: 0 for better quality, 1 for better identity')246    ], [247        gr.outputs.Image(type="numpy", label="Output"),248        gr.outputs.File(label="Download the output")249    ],250    title=title,251    description=description,252    article=article,       253    examples=[254        ['01.png', True, True, 2, 0.7],255        ['02.jpg', True, True, 2, 0.7],256        ['03.jpg', True, True, 2, 0.7],257        ['04.jpg', True, True, 2, 0.1],258        ['05.jpg', True, True, 2, 0.1]259      ]260    )261 262demo.queue(concurrency_count=4)263demo.launch()