syedaoon commited on
Commit
a753f35
Β·
verified Β·
1 Parent(s): 4b06b53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -95
app.py CHANGED
@@ -7,108 +7,82 @@ import os
7
 
8
  print("πŸš€ Starting ZeroIG app...")
9
 
10
- class ZeroIGEnhancer:
11
- def __init__(self):
12
- self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
13
- print(f"Using device: {self.device}")
14
- self.model = self.load_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- def load_model(self):
17
- try:
18
- from model import Finetunemodel, Network
 
 
 
 
19
 
20
- # Check for trained weights
21
- model_path = "./weights/model.pt"
22
- if os.path.exists(model_path):
23
- model = Finetunemodel(model_path)
24
- print("βœ… Loaded trained ZeroIG model")
25
- else:
26
- model = Network()
27
- print("⚠️ Using ZeroIG with random weights")
28
 
29
- model.to(self.device)
30
- model.eval()
31
- return model
 
 
 
 
 
 
32
 
33
- except Exception as e:
34
- print(f"⚠️ Could not load ZeroIG model: {e}")
35
- return None
36
-
37
- def enhance_image(self, image):
38
- if image is None:
39
- return None
40
 
41
- try:
42
- if self.model is not None:
43
- # Resize image if too large to prevent memory issues
44
- max_size = 800
45
- if max(image.size) > max_size:
46
- ratio = max_size / max(image.size)
47
- new_size = tuple(int(dim * ratio) for dim in image.size)
48
- image = image.resize(new_size, Image.Resampling.LANCZOS)
49
-
50
- # Convert to tensor
51
- transform = transforms.ToTensor()
52
- input_tensor = transform(image).unsqueeze(0).to(self.device)
53
-
54
- with torch.no_grad():
55
- if hasattr(self.model, 'enhance') and hasattr(self.model, 'denoise_1'):
56
- # Finetunemodel - returns (enhanced, denoised)
57
- enhanced, denoised = self.model(input_tensor)
58
- result_tensor = denoised
59
- else:
60
- # Network model - returns multiple outputs
61
- outputs = self.model(input_tensor)
62
- result_tensor = outputs[13] # H3 is the final denoised result
63
-
64
- # Convert back to PIL
65
- result_tensor = result_tensor.squeeze(0).cpu().clamp(0, 1)
66
- to_pil = transforms.ToPILImage()
67
- return to_pil(result_tensor)
68
-
69
- else:
70
- # Fallback: simple enhancement
71
- img_array = np.array(image).astype(np.float32)
72
- enhanced = np.clip(img_array * 1.8, 0, 255).astype(np.uint8)
73
- return Image.fromarray(enhanced)
74
-
75
- except Exception as e:
76
- print(f"Enhancement error: {e}")
77
- # Fallback enhancement
78
- img_array = np.array(image).astype(np.float32)
79
- enhanced = np.clip(img_array * 1.5, 0, 255).astype(np.uint8)
80
  return Image.fromarray(enhanced)
 
 
 
 
 
 
 
81
 
82
- # Initialize the enhancer
83
- enhancer = ZeroIGEnhancer()
84
-
85
- def process_image(image):
86
- """Process uploaded image"""
87
- return enhancer.enhance_image(image)
88
-
89
- # Create Gradio interface - simplified for HF Spaces
90
- print("Creating Gradio interface...")
91
 
92
- interface = gr.Interface(
93
- fn=process_image,
94
- inputs=gr.Image(type="pil", label="πŸ“· Upload Low-Light Image"),
95
- outputs=gr.Image(type="pil", label="✨ Enhanced Image"),
96
- title="🌟 ZeroIG: Zero-Shot Low-Light Enhancement",
97
- description="""
98
- **CVPR 2024** - Zero-shot illumination-guided joint denoising and adaptive enhancement for low-light images.
99
-
100
- πŸ”Έ Upload a low-light or dark image
101
- πŸ”Έ Get enhanced version with noise reduction
102
- πŸ”Έ No training data required!
103
-
104
- πŸ“„ [Paper](https://openaccess.thecvf.com/content/CVPR2024/papers/Shi_ZERO-IG_Zero-Shot_Illumination-Guided_Joint_Denoising_and_Adaptive_Enhancement_for_Low-Light_CVPR_2024_paper.pdf) | πŸ’» [Code](https://github.com/Doyle59217/ZeroIG)
105
- """,
106
- examples=None,
107
- cache_examples=False,
108
- flagging_mode="never"
109
  )
110
 
111
- # Launch - configured specifically for Hugging Face Spaces
112
- if __name__ == "__main__":
113
- print("πŸš€ Launching Gradio interface...")
114
- interface.launch()
 
7
 
8
  print("πŸš€ Starting ZeroIG app...")
9
 
10
+ # Load ZeroIG model
11
+ def load_zeroig():
12
+ try:
13
+ from model import Finetunemodel, Network
14
+
15
+ model_path = "./weights/model.pt"
16
+ if os.path.exists(model_path):
17
+ model = Finetunemodel(model_path)
18
+ print("βœ… Loaded trained ZeroIG model")
19
+ else:
20
+ model = Network()
21
+ print("⚠️ Using ZeroIG with random weights")
22
+
23
+ model.eval()
24
+ return model
25
+ except Exception as e:
26
+ print(f"⚠️ Could not load ZeroIG: {e}")
27
+ return None
28
+
29
+ # Initialize model
30
+ zeroig_model = load_zeroig()
31
+
32
+ def enhance_image(image):
33
+ """Enhance low-light image"""
34
+ if image is None:
35
+ return None
36
 
37
+ try:
38
+ if zeroig_model is not None:
39
+ # Resize if too large
40
+ if max(image.size) > 800:
41
+ ratio = 800 / max(image.size)
42
+ new_size = tuple(int(dim * ratio) for dim in image.size)
43
+ image = image.resize(new_size, Image.Resampling.LANCZOS)
44
 
45
+ # Convert to tensor
46
+ transform = transforms.ToTensor()
47
+ input_tensor = transform(image).unsqueeze(0)
 
 
 
 
 
48
 
49
+ with torch.no_grad():
50
+ if hasattr(zeroig_model, 'enhance'):
51
+ # Finetunemodel
52
+ enhanced, denoised = zeroig_model(input_tensor)
53
+ result = denoised
54
+ else:
55
+ # Network model
56
+ outputs = zeroig_model(input_tensor)
57
+ result = outputs[13] # H3 output
58
 
59
+ # Convert back to image
60
+ result = result.squeeze(0).clamp(0, 1)
61
+ to_pil = transforms.ToPILImage()
62
+ return to_pil(result)
 
 
 
63
 
64
+ else:
65
+ # Simple fallback
66
+ img_array = np.array(image)
67
+ enhanced = np.clip(img_array * 1.8, 0, 255).astype(np.uint8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  return Image.fromarray(enhanced)
69
+
70
+ except Exception as e:
71
+ print(f"Error: {e}")
72
+ # Emergency fallback
73
+ img_array = np.array(image)
74
+ enhanced = np.clip(img_array * 1.5, 0, 255).astype(np.uint8)
75
+ return Image.fromarray(enhanced)
76
 
77
+ # Create interface with minimal parameters
78
+ print("Creating interface...")
 
 
 
 
 
 
 
79
 
80
+ demo = gr.Interface(
81
+ fn=enhance_image,
82
+ inputs=gr.Image(type="pil"),
83
+ outputs=gr.Image(type="pil"),
84
+ title="ZeroIG: Low-Light Enhancement"
 
 
 
 
 
 
 
 
 
 
 
 
85
  )
86
 
87
+ print("πŸš€ Launching...")
88
+ demo.launch()