KristofGaming39 commited on
Commit
2ec25b3
·
verified ·
1 Parent(s): 1f54c14

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import time
4
+ import gc
5
+ import torch
6
+ from gfpgan import GFPGANer
7
+ from basicsr.archs.rrdbnet_arch import RRDBNet
8
+ from basicsr.utils.download_util import load_file_from_url
9
+ from realesrgan import RealESRGANer
10
+
11
+ # === GPU MEMORY MONITORING ===
12
+ def print_simple_gpu_memory():
13
+ allocated = torch.cuda.memory_allocated(0) / 1024**3
14
+ reserved = torch.cuda.memory_reserved(0) / 1024**3
15
+ print(f"[GPU Memory] Allocated: {allocated:.2f} GB | Reserved: {reserved:.2f} GB")
16
+
17
+ # === GFPGAN STEP ===
18
+ def run_gfpgan(image_path, output_path, model_path='GFPGAN\GFPGAN\experiments\pretrained_models\GFPGANv1.4.pth'):
19
+ gfpganer = GFPGANer(
20
+ model_path=model_path,
21
+ upscale=2,
22
+ arch='clean',
23
+ channel_multiplier=2,
24
+ bg_upsampler=None
25
+ )
26
+
27
+ img = cv2.imread(image_path)
28
+ if img is None:
29
+ raise FileNotFoundError(f"Input image not found: {image_path}")
30
+
31
+ _, _, restored_img = gfpganer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
32
+ cv2.imwrite(output_path, restored_img)
33
+ print(f"[+] GFPGAN output saved: {output_path}")
34
+ return output_path
35
+
36
+ # === RealESRGAN STEP ===
37
+ def run_realesrgan(input_path, output_path, model_name='RealESRGAN_x4plus', outscale=4, gpu_id=None):
38
+ if model_name == 'RealESRGAN_x4plus':
39
+ model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
40
+ netscale = 4
41
+ file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth']
42
+ else:
43
+ raise NotImplementedError(f'Model {model_name} not implemented')
44
+
45
+ model_path = os.path.join('weights', model_name + '.pth')
46
+ if not os.path.isfile(model_path):
47
+ ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
48
+ for url in file_url:
49
+ model_path = load_file_from_url(url=url, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)
50
+
51
+ upsampler = RealESRGANer(
52
+ scale=netscale,
53
+ model_path=model_path,
54
+ dni_weight=None,
55
+ model=model,
56
+ tile=512, # <<< IMPORTANT for 4 GB VRAM!
57
+ tile_pad=10,
58
+ pre_pad=0,
59
+ half=False,
60
+ gpu_id=gpu_id
61
+ )
62
+
63
+ img = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
64
+ if img is None:
65
+ raise FileNotFoundError(f'Input image not found: {input_path}')
66
+
67
+ output, _ = upsampler.enhance(img, outscale=outscale)
68
+
69
+ output_dir = os.path.dirname(output_path)
70
+ if output_dir and not os.path.exists(output_dir):
71
+ os.makedirs(output_dir, exist_ok=True)
72
+
73
+ cv2.imwrite(output_path, output)
74
+ print(f"[+] RealESRGAN output saved: {output_path}")
75
+ return output_path
76
+
77
+ # === Combined Workflow ===
78
+ def combined_enhance(input_img_path, rescale_factor, output_dir):
79
+ start_time = time.perf_counter()
80
+
81
+ base_name = os.path.splitext(os.path.basename(input_img_path))[0]
82
+
83
+ # Step 1: GFPGAN enhancement
84
+ gfpgan_out = os.path.join(output_dir, f"{base_name}_GFPGAN.png")
85
+ run_gfpgan(input_img_path, gfpgan_out)
86
+
87
+ print("[GPU Memory after GFPGAN]")
88
+ print_simple_gpu_memory()
89
+
90
+ # Free memory before loading RealESRGAN
91
+ gc.collect()
92
+ torch.cuda.empty_cache()
93
+ print("[*] Cleared GPU cache before RealESRGAN")
94
+
95
+ # Step 2: RealESRGAN enhancement using GFPGAN result
96
+ realesrgan_out = os.path.join(output_dir, f"{base_name}_GFPGAN_RealESRGAN_combined.png")
97
+ run_realesrgan(gfpgan_out, realesrgan_out, outscale=rescale_factor)
98
+
99
+ print("[GPU Memory after RealESRGAN]")
100
+ print_simple_gpu_memory()
101
+
102
+ print(f"[***] Final combined image saved at: {realesrgan_out}")
103
+
104
+ # Get resolution and file size info
105
+ img = cv2.imread(realesrgan_out)
106
+ height, width = img.shape[:2]
107
+ file_size_bytes = os.path.getsize(realesrgan_out)
108
+ file_size_mb = file_size_bytes / (1024 * 1024)
109
+
110
+ end_time = time.perf_counter()
111
+ elapsed = end_time - start_time
112
+ mins, secs = divmod(elapsed, 60)
113
+ hours, mins = divmod(mins, 60)
114
+
115
+ print(f"[***] Image resolution: {width}x{height}, file size: {file_size_mb:.2f} MB")
116
+ print(f"[***] Total processing time: {int(hours):02d}h:{int(mins):02d}m:{secs:05.2f}s")
117
+
118
+ return realesrgan_out
119
+
120
+ import gradio as gr
121
+ import os
122
+
123
+ # Your core functions like combined_enhance must be defined/imported before this
124
+ def wrapped_combined_enhance(image, scale_factor):
125
+ temp_input_path = "temp_input.png"
126
+ temp_output_dir = "output"
127
+ os.makedirs(temp_output_dir, exist_ok=True)
128
+ image.save(temp_input_path)
129
+
130
+ try:
131
+ final_path = combined_enhance(temp_input_path, int(scale_factor), temp_output_dir)
132
+ return final_path, "Enhancement succeeded!"
133
+ except Exception as e:
134
+ return None, f"[ERROR]: {str(e)}"
135
+
136
+ with gr.Blocks(title="AI Face Enhancer (GFPGAN + RealESRGAN)") as demo:
137
+ gr.Markdown("# ✨ Face Enhancer Pro")
138
+
139
+ with gr.Row():
140
+ with gr.Column():
141
+ input_img = gr.Image(type="pil", label="Upload Image")
142
+ scale_slider= gr.Slider(1, 4, value=2, step=1, label="Upscale Factor")
143
+ enhance_btn = gr.Button("Enhance")
144
+ status_box = gr.Textbox(label="Status / Logs", lines=6, interactive=False)
145
+ with gr.Column():
146
+ output_img = gr.Image(label="Enhanced Output")
147
+
148
+ def ui_callback(image, scale):
149
+ if image is None:
150
+ return None, "⚠️ Please upload an image first."
151
+ out_path, status = wrapped_combined_enhance(image, scale)
152
+ # return filepath (or None) and status string
153
+ return out_path, status
154
+
155
+ enhance_btn.click(
156
+ fn=ui_callback,
157
+ inputs=[input_img, scale_slider],
158
+ outputs=[output_img, status_box]
159
+ )
160
+
161
+ demo.launch()