Spaces:
Sleeping
Sleeping
Download inference.py from maharbig2002/DocRes-Appearance: direct link, hf CLI and curl.
- Browser
- Download file 6.98 kB
-
https://huggingface.co/spaces/maharbig2002/DocRes-Appearance/resolve/main/inference.py
- Command line
-
hf download hf://spaces/maharbig2002/DocRes-Appearance/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/maharbig2002/DocRes-Appearance/resolve/main/inference.py
6.98 kB
| from collections import OrderedDict | |
| import cv2 | |
| import numpy as np | |
| import torch | |
| from data.preprocess.crop_merge_image import stride_integral | |
| from models.restormer_arch import Restormer | |
| def select_device(device_name): | |
| if device_name == "auto": | |
| if torch.cuda.is_available(): | |
| return torch.device("cuda") | |
| if torch.backends.mps.is_available(): | |
| return torch.device("mps") | |
| return torch.device("cpu") | |
| if device_name == "cuda" and not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA was requested, but it is not available") | |
| if device_name == "mps" and not torch.backends.mps.is_available(): | |
| raise RuntimeError("MPS was requested, but it is not available") | |
| return torch.device(device_name) | |
| def inference_dtype(device, precision): | |
| if precision == "fp32": | |
| return torch.float32 | |
| if precision == "fp16": | |
| if device.type == "cpu": | |
| raise RuntimeError("fp16 inference is only supported for cuda and mps devices") | |
| return torch.float16 | |
| return torch.float16 if device.type in {"cuda", "mps"} else torch.float32 | |
| def convert_state_dict(state_dict): | |
| converted = OrderedDict() | |
| for key, value in state_dict.items(): | |
| name = key[7:] if key.startswith("module.") else key | |
| converted[name] = value | |
| return converted | |
| def normalize_positive_int(value): | |
| if value is None: | |
| return None | |
| value = int(value) | |
| return value if value > 0 else None | |
| def blend_with_original(original, restored, strength=1.0): | |
| strength = float(strength) | |
| if strength >= 1.0: | |
| return restored.copy() | |
| if strength <= 0.0: | |
| return original.copy() | |
| if original.ndim != restored.ndim: | |
| raise ValueError( | |
| "Original and restored images must have the same number of dimensions" | |
| ) | |
| if original.shape[:2] != restored.shape[:2]: | |
| restored = resize_array( | |
| restored, | |
| (original.shape[1], original.shape[0]), | |
| interpolation=cv2.INTER_LINEAR, | |
| ) | |
| if ( | |
| original.ndim == 3 | |
| and restored.ndim == 3 | |
| and original.shape[2] != restored.shape[2] | |
| ): | |
| raise ValueError( | |
| "Original and restored images must have the same number of channels" | |
| ) | |
| blended = cv2.addWeighted( | |
| restored.astype(np.float32), | |
| strength, | |
| original.astype(np.float32), | |
| 1.0 - strength, | |
| 0.0, | |
| ) | |
| return np.clip(blended, 0, 255).astype(np.uint8) | |
| def appearance_prompt(img, prompt_size=1024): | |
| prompt_size = normalize_positive_int(prompt_size) | |
| original_size = (img.shape[1], img.shape[0]) | |
| prompt_source = img | |
| if prompt_size: | |
| prompt_source = cv2.resize( | |
| img, | |
| (prompt_size, prompt_size), | |
| interpolation=cv2.INTER_AREA, | |
| ) | |
| result_norm_planes = [] | |
| for plane in cv2.split(prompt_source): | |
| dilated_img = cv2.dilate(plane, np.ones((7, 7), np.uint8)) | |
| bg_img = cv2.medianBlur(dilated_img, 21) | |
| diff_img = 255 - cv2.absdiff(plane, bg_img) | |
| norm_img = cv2.normalize( | |
| diff_img, | |
| None, | |
| alpha=0, | |
| beta=255, | |
| norm_type=cv2.NORM_MINMAX, | |
| dtype=cv2.CV_8UC1, | |
| ) | |
| result_norm_planes.append(norm_img) | |
| prompt = cv2.merge(result_norm_planes) | |
| if prompt_size: | |
| prompt = cv2.resize(prompt, original_size, interpolation=cv2.INTER_LINEAR) | |
| return prompt | |
| def load_model(model_path, device, precision): | |
| model = Restormer( | |
| inp_channels=6, | |
| out_channels=3, | |
| dim=48, | |
| num_blocks=[2, 3, 3, 4], | |
| num_refinement_blocks=4, | |
| heads=[1, 2, 4, 8], | |
| ffn_expansion_factor=2.66, | |
| bias=False, | |
| LayerNorm_type="WithBias", | |
| ) | |
| checkpoint = torch.load(model_path, map_location="cpu") | |
| state_dict = checkpoint.get("model_state", checkpoint) | |
| model.load_state_dict(convert_state_dict(state_dict)) | |
| model.eval() | |
| model.to(device=device, dtype=inference_dtype(device, precision)) | |
| return model | |
| def run_model_array(model, model_input, device, precision): | |
| model_input, padding_h, padding_w = stride_integral(model_input, 8) | |
| model_input = model_input.astype(np.float32) / 255.0 | |
| model_input = torch.from_numpy(model_input.transpose(2, 0, 1)).unsqueeze(0) | |
| model_input = model_input.to(device=device, dtype=inference_dtype(device, precision)) | |
| with torch.inference_mode(): | |
| pred = model(model_input) | |
| pred = torch.clamp(pred, 0, 1) | |
| pred = pred[0].permute(1, 2, 0).cpu().numpy() | |
| pred = (pred * 255).astype(np.uint8) | |
| return pred[padding_h:, padding_w:] | |
| def resize_array(image, size, interpolation): | |
| if image.ndim < 3 or image.shape[2] <= 4: | |
| return cv2.resize(image, size, interpolation=interpolation) | |
| return np.stack( | |
| [ | |
| cv2.resize(image[:, :, channel], size, interpolation=interpolation) | |
| for channel in range(image.shape[2]) | |
| ], | |
| axis=-1, | |
| ) | |
| def resize_model_input_to_square(model_input, max_size): | |
| if not max_size: | |
| return model_input, False | |
| height, width = model_input.shape[:2] | |
| if max(height, width) <= max_size: | |
| return model_input, False | |
| return resize_array( | |
| model_input, | |
| (max_size, max_size), | |
| interpolation=cv2.INTER_AREA, | |
| ), True | |
| def apply_lowres_correction(image, lowres_restored, max_size): | |
| resized_image = cv2.resize( | |
| image, | |
| (max_size, max_size), | |
| interpolation=cv2.INTER_AREA, | |
| ).astype(np.float32) | |
| lowres_restored = lowres_restored.astype(np.float32) | |
| lowres_restored[lowres_restored == 0] = 1.0 | |
| correction = resized_image / lowres_restored | |
| correction = cv2.resize( | |
| correction, | |
| (image.shape[1], image.shape[0]), | |
| interpolation=cv2.INTER_LINEAR, | |
| ) | |
| correction[correction == 0] = 1e-5 | |
| return np.clip(image.astype(np.float32) / correction, 0, 255).astype(np.uint8) | |
| def restore_appearance_array(model, image, device, precision, max_size=1280, prompt_size=1024): | |
| max_size = normalize_positive_int(max_size) | |
| prompt = appearance_prompt(image, prompt_size=prompt_size) | |
| model_input = np.concatenate((image, prompt), axis=-1) | |
| inference_input, resized_for_inference = resize_model_input_to_square(model_input, max_size) | |
| restored = run_model_array(model, inference_input, device, precision) | |
| if resized_for_inference: | |
| restored = apply_lowres_correction(image, restored, max_size) | |
| return prompt, restored | |
| def restore_appearance(model, image_path, device, precision, max_size=1280, prompt_size=1024): | |
| image = cv2.imread(str(image_path), cv2.IMREAD_COLOR) | |
| if image is None: | |
| raise FileNotFoundError(f"Could not read input image: {image_path}") | |
| return restore_appearance_array(model, image, device, precision, max_size, prompt_size) | |