Spaces:
Running on Zero
Running on Zero
Commit Β·
8ffd7db
1
Parent(s): b4a4a63
Update app.py
Browse files4 unmodified lines567891011121314151617283 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234313 unmodified lines3573583593603613624 unmodified linesimport spacesimport torchimport randomimport cv2from PIL import Imagefrom typing import Iterable# ββ requirements.txt should include: βββββββββββββββββββββββββββββββββββββββββ# basicsr# realesrgan# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfrom diffusers import Flux2KleinPipeline283 unmodified linesdef apply_realesrgan(image: Image.Image, scale: int) -> Image.Image:"""Upscale a PIL image using Real-ESRGAN.scale=2 uses RealESRGAN_x2plus; scale=4 uses RealESRGAN_x4plus.Imports are lazy so the packages are only required when upscaling is used."""try:from basicsr.archs.rrdbnet_arch import RRDBNetfrom realesrgan import RealESRGANerexcept ImportError:raise gr.Error("Real-ESRGAN is not installed. Add 'basicsr' and 'realesrgan' to requirements.txt.")if scale == 2:model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)model_url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth"sr_scale = 2else: # 4Γmodel = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)model_url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"sr_scale = 4upsampler = RealESRGANer(scale=sr_scale,model_path=model_url,model=model,tile=512, # tile to keep VRAM usage manageabletile_pad=10,pre_pad=0,half=True, # bfloat16/fp16 β matches the rest of the pipelinedevice=device,)img_np = np.array(image)img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)output_bgr, _ = upsampler.enhance(img_bgr, outscale=sr_scale)output_rgb = cv2.cvtColor(output_bgr, cv2.COLOR_BGR2RGB)return Image.fromarray(output_rgb)@spaces.GPU13 unmodified linesgc.collect()torch.cuda.empty_cache()if not input_images:raise gr.Error("Please upload at least one image.")4 unmodified lines56789101112131415283 unmodified lines29930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934013 unmodified lines3543553563573583593603613623634 unmodified linesimport spacesimport torchimport randomfrom PIL import Imagefrom typing import Iterable# ββ requirements.txt should include: βββββββββββββββββββββββββββββββββββββββββ# spandrel# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfrom diffusers import Flux2KleinPipeline283 unmodified linesdef apply_realesrgan(image: Image.Image, scale: int) -> Image.Image:"""Upscale a PIL image using Real-ESRGAN via spandrel.scale=2 uses RealESRGAN_x2plus; scale=4 uses RealESRGAN_x4plus.Model weights are downloaded once and cached by torch.hub."""try:from spandrel import ImageModelDescriptor, ModelLoaderexcept ImportError:raise gr.Error("spandrel is not installed. Add 'spandrel' to requirements.txt.")import urllib.requestMODEL_URLS = {2: ("https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth", "RealESRGAN_x2plus.pth"),4: ("https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", "RealESRGAN_x4plus.pth"),}url, filename = MODEL_URLS[scale]cache_path = os.path.join(torch.hub.get_dir(), filename)if not os.path.exists(cache_path):print(f"Downloading {filename}β¦")urllib.request.urlretrieve(url, cache_path)model = ModelLoader().load_from_file(cache_path)if not isinstance(model, ImageModelDescriptor):raise gr.Error(f"Loaded model is not a single-image descriptor: {type(model)}")model = model.model.to(device).eval()img_np = np.array(image).astype(np.float32) / 255.0 # H W C, RGBimg_t = torch.from_numpy(img_np).permute(2, 0, 1).unsqueeze(0).to(device) # 1 C H Wwith torch.no_grad():out_t = model(img_t)out_np = out_t.squeeze(0).permute(1, 2, 0).clamp(0, 1).cpu().numpy()return Image.fromarray((out_np * 255).astype(np.uint8))@spaces.GPU13 unmodified linesgc.collect()torch.cuda.empty_cache()# Guard against stale MCP schema sending the old output_scale float valueif not isinstance(upscale_factor, str) or upscale_factor not in ("None", "2Γ", "4Γ"):upscale_factor = "None"if not input_images:raise gr.Error("Please upload at least one image.")
app.py+35-34