lucky0146 commited on
Commit
6cb5bc8
·
verified ·
1 Parent(s): e0c28a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -26
app.py CHANGED
@@ -1,5 +1,6 @@
1
  # app.py
2
- # Updated: 2025-04-05 18:43:16 IST (Ludhiana, Punjab, India)
 
3
 
4
  import gradio as gr
5
  import torch
@@ -11,7 +12,7 @@ import warnings
11
  import traceback # Import traceback for detailed error printing
12
 
13
  print("--- Script Start ---")
14
- print(f"Current Time (IST): {time.strftime('%Y-%m-%d %H:%M:%S')}")
15
 
16
  # Suppress specific warnings or all warnings if needed
17
  warnings.filterwarnings("ignore")
@@ -36,39 +37,32 @@ except Exception as e:
36
 
37
  # --- Initialize Model (only if import succeeded) ---
38
  if 'CodeFormer' in globals(): # Check if import was successful
39
- print("Attempting to initialize CodeFormer model...")
40
  try:
41
  # Use CPU explicitly
42
  device = torch.device("cpu")
43
  print(f"Using device: {device}")
44
 
45
- # Initialize CodeFormer.
46
- # Relying on the package to handle pretrained weight download/loading.
47
- # Common parameters: bg_upsampler='realesrgan', face_upsample=True
48
- # These details might depend on the exact version of the 'codeformer' pip package.
49
- codeformer_net = CodeFormer(
50
- dim_embd=512,
51
- codebook_size=1024,
52
- n_head=8,
53
- n_layers=9,
54
- connect_list=['32', '64', '128', '256']
55
- # Add other necessary parameters based on the package's specific API if needed
56
- ).to(device)
57
-
58
- # Load pretrained weights - The package *should* ideally handle this,
59
- # either during init or via a specific method. If this implicit loading fails,
60
- # you might need to investigate the specific package's API for loading weights.
61
- # We are assuming here the class instantiation handles it or makes weights available.
62
- # Let's skip manual torch.load unless proven necessary by failure.
63
 
64
  codeformer_net.eval()
65
  is_initialized = True
66
- print("CodeFormer model initialized successfully.")
67
 
68
  except FileNotFoundError as e:
69
  init_error_message = f"Error: Could not find CodeFormer model weights. The package might have failed to download them automatically, or they are expected at a specific path. Check package docs and Space logs. Details: {e}\n{traceback.format_exc()}"
70
  print(init_error_message)
71
  codeformer_net = None # Ensure model is None if init fails
 
 
 
 
 
72
  except Exception as e:
73
  init_error_message = f"Error initializing CodeFormer model: {e}\n{traceback.format_exc()}"
74
  print(init_error_message)
@@ -122,6 +116,8 @@ def enhance_image(input_img, fidelity_weight, background_enhance, face_upsample)
122
  # `w` corresponds to fidelity_weight.
123
  print("Starting CodeFormer enhancement...")
124
  with torch.no_grad():
 
 
125
  output_bgr, _, _ = codeformer_net.enhance(
126
  img_bgr,
127
  w=fidelity_weight,
@@ -149,11 +145,13 @@ def enhance_image(input_img, fidelity_weight, background_enhance, face_upsample)
149
 
150
  # --- Gradio Interface Definition ---
151
  title = "CodeFormer Image Enhancement (CPU Demo)"
 
 
152
  description = f"""
153
  Upload an image to enhance its quality, particularly for faces, using CodeFormer.
154
  **Note:** This demo runs on a free Hugging Face CPU. Processing will be **SLOW** (expect seconds to minutes per image).
155
  Adjust the fidelity weight (0 = max quality enhancement, 1 = closer to original). Optionally enhance background and upsample faces.
156
- **Status:** {'Model Loaded Successfully.' if is_initialized else f'Model Load FAILED: {init_error_message}'} Check Logs for details if failed.
157
  """
158
  article = "<p style='text-align: center'>CodeFormer CPU Demo | <a href='https://github.com/sczhou/CodeFormer' target='_blank'>Official Repo</a></p>"
159
 
@@ -165,7 +163,7 @@ if os.path.exists("examples"):
165
  ["examples/face2.png", 0.5, True, True],
166
  ["examples/bg1.png", 0.8, True, False],
167
  ]
168
- print("Example files found.")
169
  else:
170
  print("Note: 'examples' folder not found. Gradio examples will be empty.")
171
 
@@ -194,7 +192,6 @@ try:
194
  except Exception as e:
195
  print(f"FATAL: Failed to define Gradio interface: {e}\n{traceback.format_exc()}")
196
  # If interface definition fails, we can't launch.
197
- # Raising an error might provide more info in logs, or just print and exit.
198
  raise RuntimeError("Could not create Gradio Interface.") from e
199
 
200
 
@@ -209,4 +206,3 @@ if __name__ == "__main__":
209
  print(f"FATAL: Failed to launch Gradio interface: {e}\n{traceback.format_exc()}")
210
  # Exit if launch fails. Logs should show the error.
211
  exit(1)
212
-
 
1
  # app.py
2
+ # Updated: 2025-04-05 18:49:54 PM IST (Ludhiana, Punjab, India)
3
+ # Fix: Simplified CodeFormer() initialization call to resolve TypeError.
4
 
5
  import gradio as gr
6
  import torch
 
12
  import traceback # Import traceback for detailed error printing
13
 
14
  print("--- Script Start ---")
15
+ print(f"Current Time (IST): {time.strftime('%Y-%m-%d %H:%M:%S')}") # Using system time from HF Space
16
 
17
  # Suppress specific warnings or all warnings if needed
18
  warnings.filterwarnings("ignore")
 
37
 
38
  # --- Initialize Model (only if import succeeded) ---
39
  if 'CodeFormer' in globals(): # Check if import was successful
40
+ print("Attempting to initialize CodeFormer model with simplified call...")
41
  try:
42
  # Use CPU explicitly
43
  device = torch.device("cpu")
44
  print(f"Using device: {device}")
45
 
46
+ # *** MODIFIED LINE BELOW ***
47
+ # Call constructor WITHOUT detailed arguments like dim_embd, etc.
48
+ # Assume the package uses defaults and handles pretrained weights.
49
+ codeformer_net = CodeFormer().to(device)
50
+ # If the above line fails, another common pattern for packages is:
51
+ # codeformer_net = CodeFormer(pretrained=True).to(device) # Uncomment and try this if the first fails
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  codeformer_net.eval()
54
  is_initialized = True
55
+ print("CodeFormer model initialized successfully (using simplified init).")
56
 
57
  except FileNotFoundError as e:
58
  init_error_message = f"Error: Could not find CodeFormer model weights. The package might have failed to download them automatically, or they are expected at a specific path. Check package docs and Space logs. Details: {e}\n{traceback.format_exc()}"
59
  print(init_error_message)
60
  codeformer_net = None # Ensure model is None if init fails
61
+ except TypeError as e:
62
+ # Catch TypeErrors specifically from the init call
63
+ init_error_message = f"TypeError during CodeFormer init. The constructor signature might be different in this package version (e.g., does it need 'pretrained=True'?). Details: {e}\n{traceback.format_exc()}"
64
+ print(init_error_message)
65
+ codeformer_net = None
66
  except Exception as e:
67
  init_error_message = f"Error initializing CodeFormer model: {e}\n{traceback.format_exc()}"
68
  print(init_error_message)
 
116
  # `w` corresponds to fidelity_weight.
117
  print("Starting CodeFormer enhancement...")
118
  with torch.no_grad():
119
+ # Ensure enhance method signature matches the package API
120
+ # Assuming enhance(image, w, face_upsample, bg_upsampler, adain=True) is correct
121
  output_bgr, _, _ = codeformer_net.enhance(
122
  img_bgr,
123
  w=fidelity_weight,
 
145
 
146
  # --- Gradio Interface Definition ---
147
  title = "CodeFormer Image Enhancement (CPU Demo)"
148
+ # Dynamically update description based on model load status
149
+ status_message = 'Model Loaded Successfully.' if is_initialized else f'Model Load FAILED: {init_error_message}'
150
  description = f"""
151
  Upload an image to enhance its quality, particularly for faces, using CodeFormer.
152
  **Note:** This demo runs on a free Hugging Face CPU. Processing will be **SLOW** (expect seconds to minutes per image).
153
  Adjust the fidelity weight (0 = max quality enhancement, 1 = closer to original). Optionally enhance background and upsample faces.
154
+ **Status:** {status_message} Check Logs for details if failed.
155
  """
156
  article = "<p style='text-align: center'>CodeFormer CPU Demo | <a href='https://github.com/sczhou/CodeFormer' target='_blank'>Official Repo</a></p>"
157
 
 
163
  ["examples/face2.png", 0.5, True, True],
164
  ["examples/bg1.png", 0.8, True, False],
165
  ]
166
+ print("Example files folder found.")
167
  else:
168
  print("Note: 'examples' folder not found. Gradio examples will be empty.")
169
 
 
192
  except Exception as e:
193
  print(f"FATAL: Failed to define Gradio interface: {e}\n{traceback.format_exc()}")
194
  # If interface definition fails, we can't launch.
 
195
  raise RuntimeError("Could not create Gradio Interface.") from e
196
 
197
 
 
206
  print(f"FATAL: Failed to launch Gradio interface: {e}\n{traceback.format_exc()}")
207
  # Exit if launch fails. Logs should show the error.
208
  exit(1)