"""Hugging Face Spaces entry point for MEDFE.""" import hashlib import io import json import os import sys from pathlib import Path from zipfile import ZipFile if os.environ.get("SPACE_ID") and os.environ.get("MEDFE_DEVICE", "cuda") == "cuda": import spaces else: spaces = None import torch from huggingface_hub import hf_hub_download from PIL import Image # The Gradio builder installs dependencies before copying repository files. sys.path.insert(0, str(Path(__file__).with_name("medfe_inpainting-0.2.0-py3-none-any.whl"))) from medfe.evaluation import load_generator from medfe.web_demo import CSS, DemoExample, build_demo, inference_callback MODEL = "KumaPower/MEDFE" REVISION = "7f901ee7102f7cdcedd2d9afe302a1b05478bc7a" FILENAME = "medfe-sd-partial-step120994.pt" SHA256 = "ca98198ef4cd9fad732d5709a0f3a5f9f9646743528dacde744bfb95ddb71e50" def download(filename): return Path(hf_hub_download(MODEL, filename, revision=REVISION, token=False)) checkpoint = download(FILENAME) with checkpoint.open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != SHA256: raise ValueError("MEDFE release checkpoint checksum mismatch") torch.set_num_threads(2) model, config, metadata = load_generator(checkpoint, "cuda" if spaces else "cpu") step = metadata["global_step"] del metadata run = inference_callback(model) if spaces is not None: run = spaces.GPU(duration=10)(run) examples = {} with ZipFile(Path(__file__).with_name("examples.zip")) as archive: for example in json.loads(archive.read("index.json")): with Image.open(io.BytesIO(archive.read(example["image"]))) as image: rgb = image.convert("RGB") with Image.open(io.BytesIO(archive.read(example["mask"]))) as mask: examples[example["label"]] = DemoExample(rgb, mask.convert("L")) demo, theme = build_demo(config, run, step, examples=examples) if __name__ == "__main__": demo.launch( server_name="0.0.0.0" if os.environ.get("SPACE_ID") else "127.0.0.1", server_port=7860, share=False, css=CSS, theme=theme, max_file_size="16mb", show_error=False, )