lucky0146 commited on
Commit
18cbd80
·
verified ·
1 Parent(s): a13cb91

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import torch
4
+ from gfpgan import GFPGANer
5
+ import numpy as np
6
+ import os
7
+
8
+ # Initialize GFPGANer (this will be done once when the app starts)
9
+ # It's important to place model loading outside the prediction function if possible
10
+ # to avoid reloading it on every call, which is slow.
11
+ MODEL_PATH = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth'
12
+
13
+ # Check if the model file already exists to avoid re-downloading every time
14
+ # This is a simple check; a more robust solution might involve checking file integrity.
15
+ # For Hugging Face Spaces, files in the repo are persistent.
16
+ # If running locally, this helps avoid re-downloads if the script is restarted.
17
+ local_model_path = "GFPGANv1.3.pth"
18
+ if not os.path.exists(local_model_path):
19
+ print(f"Downloading model to {local_model_path}...")
20
+ torch.hub.download_url_to_file(MODEL_PATH, local_model_path, progress=True)
21
+ print("Model download complete.")
22
+ else:
23
+ print(f"Model {local_model_path} already exists.")
24
+
25
+
26
+ restorer = GFPGANer(
27
+ model_path=local_model_path, # Use local path after download
28
+ upscale=2,
29
+ arch='clean',
30
+ channel_multiplier=2,
31
+ bg_upsampler=None, # Can be 'realesrgan' if RealESRGAN is installed and background upsampling is desired
32
+ device='cpu'
33
+ )
34
+
35
+ def gfpgan_restore_face(input_image_np):
36
+ """
37
+ Restores faces in an input image using GFPGAN.
38
+ input_image_np: A NumPy array representing the input image (BGR format from cv2.imdecode).
39
+ Returns a NumPy array representing the restored image (BGR format).
40
+ """
41
+ if input_image_np is None:
42
+ raise gr.Error("Error: Could not read input image. Please upload a valid image.")
43
+
44
+ # GFPGAN expects BGR images, which cv2.imdecode provides if the image has color.
45
+ # If the image is grayscale, cv2.imdecode might return a 2D array.
46
+ # GFPGANer.enhance handles BGR or Grayscale images.
47
+
48
+ try:
49
+ # The enhance method returns: cropped_faces, restored_faces, restored_img
50
+ # restored_img is the full image with faces pasted back
51
+ _, _, restored_img = restorer.enhance(
52
+ input_image_np,
53
+ has_aligned=False,
54
+ only_center_face=False
55
+ # paste_to_img=True was removed as it's default or handled internally in newer versions
56
+ )
57
+ except Exception as e:
58
+ print(f"Error during GFPGAN processing: {e}")
59
+ raise gr.Error(f"GFPGAN processing failed: {e}. Check server logs for details.")
60
+
61
+ if restored_img is None:
62
+ # This might happen if no faces are detected or an error occurs
63
+ # Return the original image or an error message
64
+ print("No faces were detected or restored by GFPGAN.")
65
+ # raise gr.Error("No faces detected or an error occurred during restoration. Returning original image.")
66
+ return input_image_np # Or an image indicating no faces found
67
+
68
+ return restored_img # Return BGR image
69
+
70
+ # Define the Gradio interface
71
+ iface = gr.Interface(
72
+ fn=gfpgan_restore_face,
73
+ inputs=gr.Image(type="numpy", label="Upload Input Image"),
74
+ outputs=gr.Image(type="numpy", label="Restored Output Image"),
75
+ title="GFPGAN Face Restoration (CPU)",
76
+ description="Upload an image with faces to restore them using GFPGAN. Runs on CPU, so it might be slow for large images.",
77
+ allow_flagging="never"
78
+ )
79
+
80
+ if __name__ == '__main__':
81
+ # For Hugging Face Spaces, you typically don't need app.launch() in app.py
82
+ # The Space will run it. For local testing:
83
+ iface.launch()