Update app.py
Browse files
app.py
CHANGED
@@ -14,6 +14,8 @@ import os # Import os for path handling
|
|
14 |
|
15 |
# --- Dependency Imports (Need to be installed via pip or manual clone) ---
|
16 |
# BasicSR related imports (for SwinIR, EDSR, CodeFormer utilities)
|
|
|
|
|
17 |
try:
|
18 |
from basicsr.archs.swinir_arch import SwinIR as SwinIR_Arch
|
19 |
from basicsr.archs.edsr_arch import EDSR as EDSR_Arch
|
@@ -21,52 +23,63 @@ try:
|
|
21 |
BASESR_AVAILABLE = True
|
22 |
except ImportError:
|
23 |
print("Warning: basicsr not found. SwinIR, EDSR, and CodeFormer (using basicsr utils) will not be available.")
|
24 |
-
BASESR_AVAILABLE = False
|
25 |
|
26 |
# RealESRGAN import
|
|
|
27 |
try:
|
28 |
from realesrgan import RealESRGAN
|
29 |
REALESRGAN_AVAILABLE = True
|
30 |
except ImportError:
|
31 |
print("Warning: realesrgan not found. Real-ESRGAN-x4 will not be available.")
|
32 |
-
REALESRGAN_AVAILABLE = False
|
33 |
|
34 |
-
# CodeFormer import (
|
35 |
-
#
|
36 |
-
#
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
|
46 |
# --- Model Configuration ---
|
47 |
# Dictionary of available models and their configuration
|
48 |
-
# format: "UI Name": {"repo_id": "hf_repo_id", "filename": "weight_filename", "type": "upscale" or "face"}
|
49 |
-
MODEL_CONFIGS = {
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
}
|
57 |
-
|
58 |
-
#
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
# --- Model Loading Cache ---
|
62 |
-
# Use a simple cache to avoid reloading the same model multiple times
|
63 |
cached_model = {}
|
64 |
cached_model_name = None
|
65 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
66 |
-
print(f"Using device: {device}")
|
67 |
|
68 |
# Function to load the selected model
|
69 |
-
def load_model(model_name):
|
70 |
global cached_model, cached_model_name
|
71 |
|
72 |
if model_name == cached_model_name and cached_model is not None:
|
@@ -76,35 +89,32 @@ def load_model(model_name):
|
|
76 |
print(f"Loading model: {model_name}")
|
77 |
config = MODEL_CONFIGS.get(model_name)
|
78 |
if config is None:
|
79 |
-
|
|
|
|
|
80 |
|
81 |
try:
|
82 |
model_type = config['type']
|
83 |
model_path = hf_hub_download(repo_id=config['repo_id'], filename=config['filename'])
|
84 |
|
85 |
if model_name == "Real-ESRGAN-x4":
|
86 |
-
if not REALESRGAN_AVAILABLE: raise ImportError("realesrgan not
|
87 |
model = RealESRGAN(device, scale=config['scale'])
|
88 |
model.load_weights(model_path)
|
89 |
|
90 |
elif model_name == "SwinIR-4x":
|
91 |
-
if not BASESR_AVAILABLE: raise ImportError("basicsr not
|
92 |
-
# SwinIR requires specific initialization parameters
|
93 |
-
# These match the SwinIR_4x.pth model from the repo
|
94 |
model = SwinIR_Arch(
|
95 |
upscale=config['scale'], in_chans=3, img_size=64, window_size=8,
|
96 |
compress_ratio= -1, dilate_basis=-1, res_range=-1, attn_type='linear'
|
97 |
)
|
98 |
-
# Load weights, handling potential key mismatches if necessary
|
99 |
pretrained_dict = torch.load(model_path, map_location=device)
|
100 |
-
model.load_state_dict(pretrained_dict, strict=True)
|
101 |
-
model.eval()
|
102 |
model.to(device)
|
103 |
|
104 |
elif model_name == "EDSR-x4":
|
105 |
-
if not BASESR_AVAILABLE: raise ImportError("basicsr not
|
106 |
-
# EDSR architecture needs scale, num_feat, num_block
|
107 |
-
# Assuming typical values for EDSR_x4 from the repo
|
108 |
model = EDSR_Arch(num_feat=64, num_block=16, upscale=config['scale'])
|
109 |
pretrained_dict = torch.load(model_path, map_location=device)
|
110 |
model.load_state_dict(pretrained_dict, strict=True)
|
@@ -112,33 +122,32 @@ def load_model(model_name):
|
|
112 |
model.to(device)
|
113 |
|
114 |
elif model_name == "CodeFormer (Face Enhancement)":
|
115 |
-
if not
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
120 |
if CODEFORMER_AVAILABLE:
|
121 |
-
|
122 |
-
|
123 |
-
pretrained_dict = torch.load(model_path, map_location=device)['params_ema'] # CodeFormer often saves params_ema
|
124 |
-
# Need to handle potential DataParallel prefix if saved from DP
|
125 |
keys = list(pretrained_dict.keys())
|
126 |
if keys and keys[0].startswith('module.'):
|
127 |
pretrained_dict = {k[7:]: v for k, v in pretrained_dict.items()}
|
128 |
model.load_state_dict(pretrained_dict, strict=True)
|
129 |
model.eval()
|
130 |
model.to(device)
|
131 |
-
|
132 |
-
# Fallback
|
133 |
-
|
134 |
-
# This option is likely only possible if CodeFormer is installed *within* a basicsr environment
|
135 |
-
# or if basicsr provides the architecture. Given the complexity, let's just raise an error
|
136 |
-
# if CODEFORMER_AVAILABLE is False.
|
137 |
-
raise ImportError("CodeFormer library not found. BasicSR utilities alone are not enough to instantiate CodeFormer.")
|
138 |
|
139 |
|
140 |
else:
|
141 |
-
|
|
|
142 |
|
143 |
# Cache the loaded model
|
144 |
cached_model = model
|
@@ -147,10 +156,17 @@ def load_model(model_name):
|
|
147 |
return model, model_type
|
148 |
|
149 |
except ImportError as ie:
|
150 |
-
|
151 |
-
|
|
|
|
|
|
|
|
|
|
|
152 |
except Exception as e:
|
153 |
print(f"Error loading model {model_name}: {e}")
|
|
|
|
|
154 |
# Clear cache on error
|
155 |
cached_model = None
|
156 |
cached_model_name = None
|
@@ -159,13 +175,11 @@ def load_model(model_name):
|
|
159 |
# Function to preprocess image (PIL RGB to OpenCV BGR numpy)
|
160 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
161 |
img = np.array(image)
|
162 |
-
# OpenCV uses BGR, PIL uses RGB. Need conversion.
|
163 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
164 |
return img
|
165 |
|
166 |
# Function to postprocess image (OpenCV BGR numpy to PIL RGB)
|
167 |
def postprocess_image(img: np.ndarray) -> Image.Image:
|
168 |
-
# Ensure image is in the correct range and type before converting
|
169 |
if img.dtype != np.uint8:
|
170 |
img = np.clip(img, 0, 255).astype(np.uint8)
|
171 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
@@ -174,6 +188,7 @@ def postprocess_image(img: np.ndarray) -> Image.Image:
|
|
174 |
# Main processing function
|
175 |
def enhance_image(image: Image.Image, model_name: str):
|
176 |
if image is None:
|
|
|
177 |
return "Please upload an image.", None
|
178 |
|
179 |
status_message = f"Processing image with {model_name}..."
|
@@ -182,7 +197,7 @@ def enhance_image(image: Image.Image, model_name: str):
|
|
182 |
model, model_info = load_model(model_name)
|
183 |
|
184 |
if model is None:
|
185 |
-
# model_info contains the error message
|
186 |
return model_info, None
|
187 |
|
188 |
model_type = model_info # model_info is the type string ('upscale' or 'face')
|
@@ -195,51 +210,38 @@ def enhance_image(image: Image.Image, model_name: str):
|
|
195 |
if model_type == "upscale":
|
196 |
print(f"Applying {model_name} upscaling...")
|
197 |
if model_name == "Real-ESRGAN-x4":
|
198 |
-
|
199 |
output_np_bgr = model.predict(img_np_bgr)
|
200 |
elif model_name in ["SwinIR-4x", "EDSR-x4"]:
|
201 |
-
if not BASESR_AVAILABLE:
|
202 |
-
|
203 |
-
# These models often work with float tensors (0-1 range)
|
204 |
-
# Using basicsr utils: HWC BGR uint8 -> CHW RGB float (0-1) -> send to device
|
205 |
img_tensor = img2tensor(img_np_bgr.astype(np.float32) / 255., bgr2rgb=True, float32=True).unsqueeze(0).to(device)
|
206 |
|
207 |
with torch.no_grad():
|
208 |
output_tensor = model(img_tensor)
|
209 |
|
210 |
-
#
|
211 |
output_np_rgb = tensor2img(output_tensor, rgb2bgr=False, min_max=(0, 1))
|
212 |
output_np_bgr = cv2.cvtColor(output_np_rgb, cv2.COLOR_RGB2BGR)
|
213 |
|
214 |
else:
|
215 |
-
raise ValueError(f"Unknown upscale model: {model_name}")
|
216 |
|
217 |
status_message = f"Image upscaled successfully with {model_name}!"
|
218 |
|
219 |
elif model_type == "face":
|
220 |
print(f"Applying {model_name} face enhancement...")
|
221 |
if model_name == "CodeFormer (Face Enhancement)":
|
222 |
-
if not
|
223 |
-
|
224 |
-
# CodeFormer's enhance method typically expects uint8 BGR numpy
|
225 |
-
# It might return multiple outputs, the first is usually the enhanced image
|
226 |
-
# Example: CodeFormer's inference script might return (restored_img, bboxes)
|
227 |
-
# We assume the image is the first element.
|
228 |
-
# Note: CodeFormer often needs additional setup/parameters for GFPGAN, etc.
|
229 |
-
# This is a simplified call.
|
230 |
-
# Ensure model is on correct device before call
|
231 |
if next(model.parameters()).device != device:
|
232 |
model.to(device)
|
233 |
|
234 |
-
#
|
235 |
-
#
|
236 |
-
|
237 |
-
# This is a *placeholder* call assuming such a method exists and works like this:
|
238 |
-
output_np_bgr = model.enhance(img_np_bgr, w=0.5, adain=True)[0] # w and adain are common params
|
239 |
-
|
240 |
-
|
241 |
else:
|
242 |
-
raise ValueError(f"Unknown face enhancement model: {model_name}")
|
243 |
|
244 |
status_message = f"Face enhancement applied successfully with {model_name}!"
|
245 |
|
@@ -249,7 +251,10 @@ def enhance_image(image: Image.Image, model_name: str):
|
|
249 |
return status_message, enhanced_image
|
250 |
|
251 |
except ImportError as ie:
|
252 |
-
|
|
|
|
|
|
|
253 |
except Exception as e:
|
254 |
print(f"Error during processing: {e}")
|
255 |
import traceback
|
@@ -265,19 +270,19 @@ with gr.Blocks(title="Image Upscale & Enhancement - By FebryEnsz") as demo:
|
|
265 |
|
266 |
Upload an image and select a model to enhance it. Choose from multiple models for upscaling (to make it 'HD' or higher resolution) or face enhancement (to improve facial details and focus).
|
267 |
|
268 |
-
**Note:** This app requires specific Python libraries (`torch`, `basicsr`, `realesrgan`, `CodeFormer`) to be installed for all models to be available. If a model option is missing, its required library
|
269 |
"""
|
270 |
)
|
271 |
|
|
|
|
|
|
|
272 |
with gr.Row():
|
273 |
with gr.Column():
|
274 |
image_input = gr.Image(label="Upload Image", type="pil")
|
275 |
|
276 |
-
# Filter available choices based on loaded configs
|
277 |
-
available_models = list(MODEL_CONFIGS.keys())
|
278 |
-
|
279 |
if not available_models:
|
280 |
-
model_choice = gr.Textbox(label="Select Model", value="No models available. Check
|
281 |
enhance_button = gr.Button("Enhance Image", interactive=False)
|
282 |
print("No models are available because dependencies are missing.")
|
283 |
else:
|
@@ -286,11 +291,11 @@ with gr.Blocks(title="Image Upscale & Enhancement - By FebryEnsz") as demo:
|
|
286 |
label="Select Model",
|
287 |
value=available_models[0] # Default to the first available model
|
288 |
)
|
289 |
-
# Removed scale_slider
|
290 |
enhance_button = gr.Button("Enhance Image")
|
291 |
|
292 |
with gr.Column():
|
293 |
-
output_text = gr.Textbox(label="Status", max_lines=
|
294 |
output_image = gr.Image(label="Enhanced Image")
|
295 |
|
296 |
# Connect the button to the processing function
|
@@ -304,7 +309,8 @@ with gr.Blocks(title="Image Upscale & Enhancement - By FebryEnsz") as demo:
|
|
304 |
# Launch the Gradio app
|
305 |
if __name__ == "__main__":
|
306 |
# Set torch backend for potentially better performance on some systems
|
307 |
-
|
308 |
-
|
|
|
309 |
|
310 |
demo.launch()
|
|
|
14 |
|
15 |
# --- Dependency Imports (Need to be installed via pip or manual clone) ---
|
16 |
# BasicSR related imports (for SwinIR, EDSR, CodeFormer utilities)
|
17 |
+
# Wrap imports in try/except to handle missing libraries
|
18 |
+
BASESR_AVAILABLE = False
|
19 |
try:
|
20 |
from basicsr.archs.swinir_arch import SwinIR as SwinIR_Arch
|
21 |
from basicsr.archs.edsr_arch import EDSR as EDSR_Arch
|
|
|
23 |
BASESR_AVAILABLE = True
|
24 |
except ImportError:
|
25 |
print("Warning: basicsr not found. SwinIR, EDSR, and CodeFormer (using basicsr utils) will not be available.")
|
|
|
26 |
|
27 |
# RealESRGAN import
|
28 |
+
REALESRGAN_AVAILABLE = False
|
29 |
try:
|
30 |
from realesrgan import RealESRGAN
|
31 |
REALESRGAN_AVAILABLE = True
|
32 |
except ImportError:
|
33 |
print("Warning: realesrgan not found. Real-ESRGAN-x4 will not be available.")
|
|
|
34 |
|
35 |
+
# CodeFormer import (Often requires manual setup or specific installation)
|
36 |
+
# We assume it's importable if basicsr is available AND the CodeFormer library itself
|
37 |
+
# was somehow installed (e.g., via cloning and manual setup).
|
38 |
+
# Given the previous error, direct pip install from git often fails.
|
39 |
+
# We'll primarily rely on basicsr utilities, but a proper CodeFormer instance
|
40 |
+
# might still require its dedicated installation.
|
41 |
+
CODEFORMER_AVAILABLE = False
|
42 |
+
if BASESR_AVAILABLE: # CodeFormer often depends on basicsr utilities
|
43 |
+
try:
|
44 |
+
# Attempting a common import path if CodeFormer is installed separately
|
45 |
+
# This might need adjustment based on your CodeFormer install method
|
46 |
+
from CodeFormer import CodeFormer # Adjust import based on your CodeFormer install path
|
47 |
+
CODEFORMER_AVAILABLE = True
|
48 |
+
except ImportError:
|
49 |
+
print("Warning: CodeFormer library not directly importable. CodeFormer model might not work correctly.")
|
50 |
+
# If basicsr is available, we might still list the model but it might fail later if CodeFormer class isn't there
|
51 |
+
pass # Allow BASESR_AVAILABLE to potentially enable the config entry
|
52 |
|
53 |
|
54 |
# --- Model Configuration ---
|
55 |
# Dictionary of available models and their configuration
|
56 |
+
# format: "UI Name": {"repo_id": "hf_repo_id", "filename": "weight_filename", "type": "upscale" or "face", ...}
|
57 |
+
MODEL_CONFIGS = {}
|
58 |
+
|
59 |
+
if REALESRGAN_AVAILABLE:
|
60 |
+
MODEL_CONFIGS["Real-ESRGAN-x4"] = {"repo_id": "RealESRGAN/RealESRGAN_x4plus", "filename": "RealESRGAN_x4plus.pth", "type": "upscale", "scale": 4}
|
61 |
+
|
62 |
+
if BASESR_AVAILABLE:
|
63 |
+
MODEL_CONFIGS["SwinIR-4x"] = {"repo_id": "SwinIR/SwinIR-Large", "filename": "SwinIR_4x.pth", "type": "upscale", "scale": 4}
|
64 |
+
MODEL_CONFIGS["EDSR-x4"] = {"repo_id": "EDSR/edsr_x4", "filename": "edsr_x4.pth", "type": "upscale", "scale": 4}
|
65 |
+
# Add CodeFormer config only if basicsr is available, and potentially CODEFORMER_AVAILABLE is True
|
66 |
+
# Even if CODEFORMER_AVAILABLE is False, listing it might rely on basicsr providing necessary components (less likely)
|
67 |
+
# Given installation issues, let's only add it if the library is actually importable.
|
68 |
+
if CODEFORMER_AVAILABLE:
|
69 |
+
MODEL_CONFIGS["CodeFormer (Face Enhancement)"] = {"repo_id": "CodeFormer/codeformer", "filename": "codeformer.pth", "type": "face"}
|
70 |
+
else:
|
71 |
+
print("CodeFormer (Face Enhancement) model will not be listed due to import issues.")
|
72 |
+
|
73 |
+
# No need to filter anymore, configs are only added if available
|
74 |
|
75 |
# --- Model Loading Cache ---
|
|
|
76 |
cached_model = {}
|
77 |
cached_model_name = None
|
78 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
79 |
+
print(f"Using device: {device}") # This shows which device PyTorch detects
|
80 |
|
81 |
# Function to load the selected model
|
82 |
+
def load_model(model_name: str):
|
83 |
global cached_model, cached_model_name
|
84 |
|
85 |
if model_name == cached_model_name and cached_model is not None:
|
|
|
89 |
print(f"Loading model: {model_name}")
|
90 |
config = MODEL_CONFIGS.get(model_name)
|
91 |
if config is None:
|
92 |
+
# This case should ideally not happen if UI choices are filtered,
|
93 |
+
# but good for safety.
|
94 |
+
return None, f"Error: Model '{model_name}' not configured or dependencies missing."
|
95 |
|
96 |
try:
|
97 |
model_type = config['type']
|
98 |
model_path = hf_hub_download(repo_id=config['repo_id'], filename=config['filename'])
|
99 |
|
100 |
if model_name == "Real-ESRGAN-x4":
|
101 |
+
if not REALESRGAN_AVAILABLE: raise ImportError("realesrgan was not imported correctly.")
|
102 |
model = RealESRGAN(device, scale=config['scale'])
|
103 |
model.load_weights(model_path)
|
104 |
|
105 |
elif model_name == "SwinIR-4x":
|
106 |
+
if not BASESR_AVAILABLE: raise ImportError("basicsr was not imported correctly.")
|
|
|
|
|
107 |
model = SwinIR_Arch(
|
108 |
upscale=config['scale'], in_chans=3, img_size=64, window_size=8,
|
109 |
compress_ratio= -1, dilate_basis=-1, res_range=-1, attn_type='linear'
|
110 |
)
|
|
|
111 |
pretrained_dict = torch.load(model_path, map_location=device)
|
112 |
+
model.load_state_dict(pretrained_dict, strict=True)
|
113 |
+
model.eval()
|
114 |
model.to(device)
|
115 |
|
116 |
elif model_name == "EDSR-x4":
|
117 |
+
if not BASESR_AVAILABLE: raise ImportError("basicsr was not imported correctly.")
|
|
|
|
|
118 |
model = EDSR_Arch(num_feat=64, num_block=16, upscale=config['scale'])
|
119 |
pretrained_dict = torch.load(model_path, map_location=device)
|
120 |
model.load_state_dict(pretrained_dict, strict=True)
|
|
|
122 |
model.to(device)
|
123 |
|
124 |
elif model_name == "CodeFormer (Face Enhancement)":
|
125 |
+
if not CODEFORMER_AVAILABLE:
|
126 |
+
# This check is redundant if config is only added when available,
|
127 |
+
# but good practice.
|
128 |
+
raise ImportError("CodeFormer library was not imported correctly.")
|
129 |
+
|
130 |
+
# Ensure model_path is correct (downloaded via hf_hub_download)
|
131 |
+
# CodeFormer loading often needs specific handling for checkpoints (params_ema)
|
132 |
+
# This part is sensitive to the exact CodeFormer version/structure
|
133 |
+
# Assuming a similar loading pattern to basicsr models:
|
134 |
if CODEFORMER_AVAILABLE:
|
135 |
+
model = CodeFormer(dim_embd=512, codebook_size=1024, n_head=8, n_layer=9) # Basic instantiation
|
136 |
+
pretrained_dict = torch.load(model_path, map_location=device)['params_ema']
|
|
|
|
|
137 |
keys = list(pretrained_dict.keys())
|
138 |
if keys and keys[0].startswith('module.'):
|
139 |
pretrained_dict = {k[7:]: v for k, v in pretrained_dict.items()}
|
140 |
model.load_state_dict(pretrained_dict, strict=True)
|
141 |
model.eval()
|
142 |
model.to(device)
|
143 |
+
else:
|
144 |
+
# Fallback check, should not be reached if config is filtered
|
145 |
+
raise ImportError("CodeFormer library not available.")
|
|
|
|
|
|
|
|
|
146 |
|
147 |
|
148 |
else:
|
149 |
+
# This should not be reached with filtered configs
|
150 |
+
raise ValueError(f"Configuration missing or invalid for model: {model_name}")
|
151 |
|
152 |
# Cache the loaded model
|
153 |
cached_model = model
|
|
|
156 |
return model, model_type
|
157 |
|
158 |
except ImportError as ie:
|
159 |
+
# This catches errors if the library was *somehow* listed as available
|
160 |
+
# but then failed on a deeper import within load_model
|
161 |
+
print(f"Dependency check failed during load for {model_name}: {ie}")
|
162 |
+
# Clear cache on error
|
163 |
+
cached_model = None
|
164 |
+
cached_model_name = None
|
165 |
+
return None, f"Error: Dependency not fully available - {ie}. Model cannot be loaded."
|
166 |
except Exception as e:
|
167 |
print(f"Error loading model {model_name}: {e}")
|
168 |
+
import traceback
|
169 |
+
traceback.print_exc() # Print full traceback for debugging
|
170 |
# Clear cache on error
|
171 |
cached_model = None
|
172 |
cached_model_name = None
|
|
|
175 |
# Function to preprocess image (PIL RGB to OpenCV BGR numpy)
|
176 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
177 |
img = np.array(image)
|
|
|
178 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
179 |
return img
|
180 |
|
181 |
# Function to postprocess image (OpenCV BGR numpy to PIL RGB)
|
182 |
def postprocess_image(img: np.ndarray) -> Image.Image:
|
|
|
183 |
if img.dtype != np.uint8:
|
184 |
img = np.clip(img, 0, 255).astype(np.uint8)
|
185 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
|
|
188 |
# Main processing function
|
189 |
def enhance_image(image: Image.Image, model_name: str):
|
190 |
if image is None:
|
191 |
+
# Return tuple of (message, image)
|
192 |
return "Please upload an image.", None
|
193 |
|
194 |
status_message = f"Processing image with {model_name}..."
|
|
|
197 |
model, model_info = load_model(model_name)
|
198 |
|
199 |
if model is None:
|
200 |
+
# model_info contains the error message from load_model
|
201 |
return model_info, None
|
202 |
|
203 |
model_type = model_info # model_info is the type string ('upscale' or 'face')
|
|
|
210 |
if model_type == "upscale":
|
211 |
print(f"Applying {model_name} upscaling...")
|
212 |
if model_name == "Real-ESRGAN-x4":
|
213 |
+
if not REALESRGAN_AVAILABLE: raise ImportError("Real-ESRGAN library not available.")
|
214 |
output_np_bgr = model.predict(img_np_bgr)
|
215 |
elif model_name in ["SwinIR-4x", "EDSR-x4"]:
|
216 |
+
if not BASESR_AVAILABLE: raise ImportError(f"basicsr library not available for {model_name}")
|
217 |
+
# HWC BGR uint8 -> CHW RGB float (0-1) -> send to device
|
|
|
|
|
218 |
img_tensor = img2tensor(img_np_bgr.astype(np.float32) / 255., bgr2rgb=True, float32=True).unsqueeze(0).to(device)
|
219 |
|
220 |
with torch.no_grad():
|
221 |
output_tensor = model(img_tensor)
|
222 |
|
223 |
+
# CHW RGB float (0-1) -> HWC RGB uint8 -> Convert to BGR
|
224 |
output_np_rgb = tensor2img(output_tensor, rgb2bgr=False, min_max=(0, 1))
|
225 |
output_np_bgr = cv2.cvtColor(output_np_rgb, cv2.COLOR_RGB2BGR)
|
226 |
|
227 |
else:
|
228 |
+
raise ValueError(f"Unknown upscale model type configuration: {model_name}")
|
229 |
|
230 |
status_message = f"Image upscaled successfully with {model_name}!"
|
231 |
|
232 |
elif model_type == "face":
|
233 |
print(f"Applying {model_name} face enhancement...")
|
234 |
if model_name == "CodeFormer (Face Enhancement)":
|
235 |
+
if not CODEFORMER_AVAILABLE: raise ImportError("CodeFormer library not available.")
|
236 |
+
# Ensure model is on correct device
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
237 |
if next(model.parameters()).device != device:
|
238 |
model.to(device)
|
239 |
|
240 |
+
# Call the enhance method (adjust parameters w, adain as needed)
|
241 |
+
# CodeFormer enhance typically returns a tuple, first element is image
|
242 |
+
output_np_bgr = model.enhance(img_np_bgr, w=0.5, adain=True)[0] # Example call
|
|
|
|
|
|
|
|
|
243 |
else:
|
244 |
+
raise ValueError(f"Unknown face enhancement model type configuration: {model_name}")
|
245 |
|
246 |
status_message = f"Face enhancement applied successfully with {model_name}!"
|
247 |
|
|
|
251 |
return status_message, enhanced_image
|
252 |
|
253 |
except ImportError as ie:
|
254 |
+
# This catches errors if the library was imported initially but
|
255 |
+
# failed later when its functions/classes were called.
|
256 |
+
print(f"Error processing image due to missing dependency call: {ie}")
|
257 |
+
return f"Error processing image: Required library function not found - {ie}", None
|
258 |
except Exception as e:
|
259 |
print(f"Error during processing: {e}")
|
260 |
import traceback
|
|
|
270 |
|
271 |
Upload an image and select a model to enhance it. Choose from multiple models for upscaling (to make it 'HD' or higher resolution) or face enhancement (to improve facial details and focus).
|
272 |
|
273 |
+
**Note:** This app requires specific Python libraries (`torch`, `basicsr`, `realesrgan`, `CodeFormer`) to be installed for all models to be available. If a model option is missing, its required library was not successfully installed or found during startup. Check the Space build logs for installation errors.
|
274 |
"""
|
275 |
)
|
276 |
|
277 |
+
# Filter available choices based on loaded configs
|
278 |
+
available_models = list(MODEL_CONFIGS.keys())
|
279 |
+
|
280 |
with gr.Row():
|
281 |
with gr.Column():
|
282 |
image_input = gr.Image(label="Upload Image", type="pil")
|
283 |
|
|
|
|
|
|
|
284 |
if not available_models:
|
285 |
+
model_choice = gr.Textbox(label="Select Model", value="No models available. Check build logs for dependency errors.", interactive=False)
|
286 |
enhance_button = gr.Button("Enhance Image", interactive=False)
|
287 |
print("No models are available because dependencies are missing.")
|
288 |
else:
|
|
|
291 |
label="Select Model",
|
292 |
value=available_models[0] # Default to the first available model
|
293 |
)
|
294 |
+
# Removed scale_slider
|
295 |
enhance_button = gr.Button("Enhance Image")
|
296 |
|
297 |
with gr.Column():
|
298 |
+
output_text = gr.Textbox(label="Status", max_lines=3)
|
299 |
output_image = gr.Image(label="Enhanced Image")
|
300 |
|
301 |
# Connect the button to the processing function
|
|
|
309 |
# Launch the Gradio app
|
310 |
if __name__ == "__main__":
|
311 |
# Set torch backend for potentially better performance on some systems
|
312 |
+
# Removed MPS fallback for simplicity unless specifically needed and tested
|
313 |
+
# if torch.backends.mps.is_available():
|
314 |
+
# os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'
|
315 |
|
316 |
demo.launch()
|