omaralaa2004 commited on
Commit
c2ea759
Β·
verified Β·
1 Parent(s): ad88aa3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -203
app.py CHANGED
@@ -2,8 +2,8 @@ import gradio as gr
2
  import cv2
3
  import numpy as np
4
  from PIL import Image, ImageFilter, ImageEnhance
5
- import io
6
- import os
7
 
8
  class RefinedEnhancer:
9
  """Refined photo enhancer - natural colors and clarity focused"""
@@ -13,40 +13,44 @@ class RefinedEnhancer:
13
 
14
  def enhance_image(self, image, scale=None, enhance_colors=True, enhance_clarity=True):
15
  """Main enhancement function - natural and clear"""
 
 
 
16
  print(f"🎯 Enhancing image...")
17
- if scale:
18
- print(f"πŸ“ Scale factor: {scale}x")
19
-
20
- # Convert to RGB if needed
21
- if image.mode != 'RGB':
22
- image = image.convert('RGB')
23
-
24
- print(f"πŸ“Έ Original size: {image.size}")
25
-
26
- # Step 1: Gentle noise reduction (very minimal)
27
- print("πŸ”„ Step 1: Gentle cleanup...")
28
- processed = self.gentle_cleanup(image)
29
 
30
- # Step 2: Optional upscaling
31
- if scale and scale > 1:
32
- print(f"πŸ”„ Step 2: Upscaling to {scale}x...")
33
- new_size = (int(image.width * scale), int(image.height * scale))
34
- processed = processed.resize(new_size, Image.LANCZOS)
35
- else:
36
- print("πŸ”„ Step 2: Keeping original size...")
37
-
38
- # Step 3: Natural color enhancement
39
- if enhance_colors:
40
- print("πŸ”„ Step 3: Natural color enhancement...")
41
- processed = self.natural_color_enhancement(processed)
42
-
43
- # Step 4: Clarity improvement
44
- if enhance_clarity:
45
- print("πŸ”„ Step 4: Clarity improvement...")
46
- processed = self.clarity_improvement(processed)
47
-
48
- print(f"βœ… Final size: {processed.size}")
49
- return processed
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  def gentle_cleanup(self, image):
52
  """Very gentle cleanup - minimal noise reduction"""
@@ -54,268 +58,190 @@ class RefinedEnhancer:
54
  # Convert to OpenCV format
55
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
56
 
57
- # Ultra-gentle noise reduction (very conservative)
58
- denoised = cv2.fastNlMeansDenoisingColored(cv_image, None, 2, 2, 7, 21)
59
 
60
  # Convert back to PIL
61
  return Image.fromarray(cv2.cvtColor(denoised, cv2.COLOR_BGR2RGB))
62
- except Exception as e:
63
- print(f"Cleanup failed, using original: {e}")
64
  return image
65
 
66
  def natural_color_enhancement(self, image):
67
  """Natural color enhancement - subtle but noticeable"""
68
  try:
69
- # Convert to OpenCV for better color space control
70
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
71
 
72
  # Convert to HSV for better color control
73
  hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)
74
 
75
- # Enhance saturation naturally (only in mid-tones)
76
- # This prevents over-saturation of already saturated colors
77
  saturation = hsv[:, :, 1].astype(np.float32)
78
-
79
- # Create a mask for mid-tone saturation (avoid already saturated areas)
80
  mask = (saturation > 30) & (saturation < 200)
81
-
82
- # Apply gentle saturation boost only to mid-tones
83
- saturation[mask] = saturation[mask] * 1.08 # 8% increase only for mid-tones
84
  saturation = np.clip(saturation, 0, 255).astype(np.uint8)
85
  hsv[:, :, 1] = saturation
86
 
87
- # Convert back to BGR then RGB
88
  enhanced = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
89
 
90
- # Subtle contrast enhancement using CLAHE (very gentle)
91
  lab = cv2.cvtColor(enhanced, cv2.COLOR_BGR2LAB)
92
- clahe = cv2.createCLAHE(clipLimit=1.1, tileGridSize=(8, 8)) # Even more gentle
93
  lab[:, :, 0] = clahe.apply(lab[:, :, 0])
94
  enhanced = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
95
 
96
  # Convert back to PIL
97
  return Image.fromarray(cv2.cvtColor(enhanced, cv2.COLOR_BGR2RGB))
98
- except Exception as e:
99
- print(f"Color enhancement failed, using original: {e}")
100
  return image
101
 
102
  def clarity_improvement(self, image):
103
  """Improve clarity without over-smoothing"""
104
  try:
105
- # Method 1: Gentle unsharp mask for edge enhancement
106
  sharpened = image.filter(ImageFilter.UnsharpMask(radius=0.8, percent=40, threshold=3))
107
 
108
- # Method 2: Subtle detail enhancement
109
- # Convert to OpenCV for more control
110
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
111
-
112
- # Create a high-pass filter for detail enhancement
113
  gaussian = cv2.GaussianBlur(cv_image, (0, 0), 2.0)
114
  detail_enhanced = cv2.addWeighted(cv_image, 1.3, gaussian, -0.3, 0)
115
-
116
- # Convert back to PIL
117
  detail_enhanced_pil = Image.fromarray(cv2.cvtColor(detail_enhanced, cv2.COLOR_BGR2RGB))
118
 
119
- # Blend the two methods gently
120
- # 70% original sharpening, 30% detail enhancement
121
  final = Image.blend(sharpened, detail_enhanced_pil, 0.3)
122
-
123
- # Final gentle blend with original to avoid over-processing
124
- result = Image.blend(image, final, 0.6) # 60% enhanced, 40% original
125
 
126
  return result
127
- except Exception as e:
128
- print(f"Clarity improvement failed, using original: {e}")
129
  return image
130
 
131
- # Initialize the enhancer
132
  enhancer = RefinedEnhancer()
133
 
134
- def smart_auto_enhance(image):
135
  """Auto enhancement with smart defaults"""
136
  if image is None:
137
  return None, "❌ No image provided"
138
 
139
  try:
140
- # Check original image size and set smart defaults
141
- original_width, original_height = image.size
142
- total_pixels = original_width * original_height
143
 
144
- # Smart upscaling decision
145
- if total_pixels < 500000: # Less than 0.5MP
146
  scale = 3
147
- scale_info = "πŸš€ Auto-applying 3x upscaling (small image)"
148
- elif total_pixels < 2000000: # Less than 2MP
149
  scale = 2
150
- scale_info = "πŸš€ Auto-applying 2x upscaling (medium image)"
151
  else:
152
  scale = None
153
- scale_info = "πŸš€ Keeping original size (large image)"
154
-
155
- # Default enhancements (always enabled)
156
- enhance_colors = True
157
- enhance_clarity = True
158
-
159
- # Enhance image
160
- enhanced_image = enhancer.enhance_image(
161
- image,
162
- scale=scale,
163
- enhance_colors=enhance_colors,
164
- enhance_clarity=enhance_clarity
165
- )
166
 
167
- # Create info message
168
- enhancements = []
169
- if scale:
170
- enhancements.append(f"{scale}x Upscaled")
171
- if enhance_colors:
172
- enhancements.append("Natural Colors")
173
- if enhance_clarity:
174
- enhancements.append("Clarity Improved")
175
-
176
- enhancement_text = " + ".join(enhancements) if enhancements else "No Enhancement"
177
 
178
- info_message = f"""Enhancement Complete!
 
179
 
180
- Original: {original_width} Γ— {original_height} pixels
181
- Enhanced: {enhanced_image.size[0]} Γ— {enhanced_image.size[1]} pixels
182
 
183
- Applied Enhancements:
184
- {enhancement_text}
185
-
186
- {scale_info}
187
- """
188
 
189
- return enhanced_image, info_message
190
 
191
  except Exception as e:
192
- return None, f"❌ Enhancement failed: {str(e)}"
193
 
194
- def custom_enhance(image, upscale_factor, enhance_colors, enhance_clarity):
195
- """Custom enhancement with user controls"""
196
  if image is None:
197
  return None, "❌ No image provided"
198
 
199
  try:
200
- # Set scale based on upscale factor
201
- scale = int(upscale_factor) if upscale_factor > 1 else None
202
-
203
- # Enhance image
204
- enhanced_image = enhancer.enhance_image(
205
- image,
206
- scale=scale,
207
- enhance_colors=enhance_colors,
208
- enhance_clarity=enhance_clarity
209
- )
210
 
211
- # Create info message
212
  enhancements = []
213
  if scale:
214
- enhancements.append(f"{scale}x Upscaled")
215
- if enhance_colors:
216
- enhancements.append("Natural Colors")
217
- if enhance_clarity:
218
- enhancements.append("Clarity Improved")
219
 
220
- enhancement_text = " + ".join(enhancements) if enhancements else "No Enhancement"
221
-
222
- info_message = f"""Custom Enhancement Complete!
223
 
224
  Original: {image.size[0]} Γ— {image.size[1]} pixels
225
- Enhanced: {enhanced_image.size[0]} Γ— {enhanced_image.size[1]} pixels
226
 
227
- Applied Enhancements:
228
- {enhancement_text}
229
- """
230
 
231
- return enhanced_image, info_message
232
 
233
  except Exception as e:
234
- return None, f"❌ Enhancement failed: {str(e)}"
235
 
236
- # Create Gradio interface with fixed configuration
237
- def create_interface():
238
- with gr.Blocks(title="Refined Photo Enhancer", theme=gr.themes.Soft()) as demo:
239
- gr.Markdown("""
240
- # 🎨 Refined Photo Enhancer
241
- ### Natural Colors & Clarity Enhancement
242
-
243
- Upload your photo and choose between **Smart Auto** mode or **Custom** controls!
244
- """)
245
-
246
  with gr.Tab("πŸš€ Smart Auto"):
247
  with gr.Row():
248
  with gr.Column():
249
- auto_input = gr.Image(label="Upload your photo", type="pil")
250
- auto_button = gr.Button("✨ Auto Enhance", variant="primary")
251
-
252
  with gr.Column():
253
- auto_output = gr.Image(label="Enhanced photo")
254
- auto_info = gr.Textbox(label="Enhancement info", lines=6)
255
 
256
- auto_button.click(
257
- fn=smart_auto_enhance,
258
- inputs=[auto_input],
259
- outputs=[auto_output, auto_info]
260
- )
261
 
262
- with gr.Tab("πŸŽ›οΈ Custom Controls"):
 
263
  with gr.Row():
264
  with gr.Column():
265
- custom_input = gr.Image(label="Upload your photo", type="pil")
266
- upscale_factor = gr.Slider(
267
- minimum=1, maximum=4, value=2, step=1,
268
- label="Upscale Factor"
269
- )
270
- enhance_colors = gr.Checkbox(
271
- value=True, label="Natural Color Enhancement"
272
- )
273
- enhance_clarity = gr.Checkbox(
274
- value=True, label="Clarity Improvement"
275
- )
276
- custom_button = gr.Button("🎯 Custom Enhance", variant="primary")
277
-
278
  with gr.Column():
279
- custom_output = gr.Image(label="Enhanced photo")
280
- custom_info = gr.Textbox(label="Enhancement info", lines=6)
281
 
282
- custom_button.click(
283
- fn=custom_enhance,
284
- inputs=[custom_input, upscale_factor, enhance_colors, enhance_clarity],
285
- outputs=[custom_output, custom_info]
286
- )
287
 
288
  gr.Markdown("""
289
- **πŸ’‘ Tips:**
290
- - Small images (< 800Γ—600): Auto-upscaling recommended
291
- - Medium images (800Γ—600 to 1920Γ—1080): Optional upscaling
292
- - Large images (> 1920Γ—1080): Usually no upscaling needed
293
- - Best for: Natural photos, portraits, landscapes
294
- """)
295
 
296
- return demo
297
 
298
- # Launch the app with proper configuration
299
  if __name__ == "__main__":
300
- import warnings
301
- warnings.filterwarnings("ignore", category=UserWarning)
302
 
303
  try:
304
- demo = create_interface()
305
- print("πŸš€ Launching Refined Photo Enhancer...")
306
- print("πŸ“‘ Creating public link...")
307
-
308
- # Fixed launch configuration
309
- demo.launch(
310
- share=True, # Enable sharing for cloud environments
311
- server_name="0.0.0.0", # Allow external access
312
- server_port=7860, # Standard port
313
- debug=False, # Disable debug mode for production
314
- show_error=True, # Show errors for debugging
315
- quiet=True # Suppress some warnings
316
- )
317
  except Exception as e:
318
- print(f"❌ Failed to launch app: {e}")
319
- print("πŸ”„ Trying alternative launch configuration...")
320
- demo = create_interface()
321
- demo.launch(share=True, quiet=True)
 
2
  import cv2
3
  import numpy as np
4
  from PIL import Image, ImageFilter, ImageEnhance
5
+ import warnings
6
+ warnings.filterwarnings("ignore")
7
 
8
  class RefinedEnhancer:
9
  """Refined photo enhancer - natural colors and clarity focused"""
 
13
 
14
  def enhance_image(self, image, scale=None, enhance_colors=True, enhance_clarity=True):
15
  """Main enhancement function - natural and clear"""
16
+ if image is None:
17
+ return None
18
+
19
  print(f"🎯 Enhancing image...")
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ try:
22
+ # Convert to RGB if needed
23
+ if image.mode != 'RGB':
24
+ image = image.convert('RGB')
25
+
26
+ print(f"πŸ“Έ Original size: {image.size}")
27
+
28
+ # Step 1: Gentle noise reduction
29
+ print("πŸ”„ Step 1: Gentle cleanup...")
30
+ processed = self.gentle_cleanup(image)
31
+
32
+ # Step 2: Optional upscaling
33
+ if scale and scale > 1:
34
+ print(f"πŸ”„ Step 2: Upscaling to {scale}x...")
35
+ new_size = (int(image.width * scale), int(image.height * scale))
36
+ processed = processed.resize(new_size, Image.LANCZOS)
37
+
38
+ # Step 3: Natural color enhancement
39
+ if enhance_colors:
40
+ print("πŸ”„ Step 3: Natural color enhancement...")
41
+ processed = self.natural_color_enhancement(processed)
42
+
43
+ # Step 4: Clarity improvement
44
+ if enhance_clarity:
45
+ print("πŸ”„ Step 4: Clarity improvement...")
46
+ processed = self.clarity_improvement(processed)
47
+
48
+ print(f"βœ… Final size: {processed.size}")
49
+ return processed
50
+
51
+ except Exception as e:
52
+ print(f"Enhancement error: {e}")
53
+ return image # Return original if processing fails
54
 
55
  def gentle_cleanup(self, image):
56
  """Very gentle cleanup - minimal noise reduction"""
 
58
  # Convert to OpenCV format
59
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
60
 
61
+ # Ultra-gentle noise reduction
62
+ denoised = cv2.fastNlMeansDenoisingColored(cv_image, None, 3, 3, 7, 21)
63
 
64
  # Convert back to PIL
65
  return Image.fromarray(cv2.cvtColor(denoised, cv2.COLOR_BGR2RGB))
66
+ except:
 
67
  return image
68
 
69
  def natural_color_enhancement(self, image):
70
  """Natural color enhancement - subtle but noticeable"""
71
  try:
72
+ # Convert to OpenCV format
73
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
74
 
75
  # Convert to HSV for better color control
76
  hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)
77
 
78
+ # Enhance saturation naturally
 
79
  saturation = hsv[:, :, 1].astype(np.float32)
 
 
80
  mask = (saturation > 30) & (saturation < 200)
81
+ saturation[mask] = saturation[mask] * 1.08
 
 
82
  saturation = np.clip(saturation, 0, 255).astype(np.uint8)
83
  hsv[:, :, 1] = saturation
84
 
85
+ # Convert back to BGR
86
  enhanced = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
87
 
88
+ # Subtle contrast enhancement
89
  lab = cv2.cvtColor(enhanced, cv2.COLOR_BGR2LAB)
90
+ clahe = cv2.createCLAHE(clipLimit=1.1, tileGridSize=(8, 8))
91
  lab[:, :, 0] = clahe.apply(lab[:, :, 0])
92
  enhanced = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
93
 
94
  # Convert back to PIL
95
  return Image.fromarray(cv2.cvtColor(enhanced, cv2.COLOR_BGR2RGB))
96
+ except:
 
97
  return image
98
 
99
  def clarity_improvement(self, image):
100
  """Improve clarity without over-smoothing"""
101
  try:
102
+ # Gentle unsharp mask
103
  sharpened = image.filter(ImageFilter.UnsharpMask(radius=0.8, percent=40, threshold=3))
104
 
105
+ # Subtle detail enhancement
 
106
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
 
 
107
  gaussian = cv2.GaussianBlur(cv_image, (0, 0), 2.0)
108
  detail_enhanced = cv2.addWeighted(cv_image, 1.3, gaussian, -0.3, 0)
 
 
109
  detail_enhanced_pil = Image.fromarray(cv2.cvtColor(detail_enhanced, cv2.COLOR_BGR2RGB))
110
 
111
+ # Blend methods
 
112
  final = Image.blend(sharpened, detail_enhanced_pil, 0.3)
113
+ result = Image.blend(image, final, 0.6)
 
 
114
 
115
  return result
116
+ except:
 
117
  return image
118
 
119
+ # Initialize enhancer
120
  enhancer = RefinedEnhancer()
121
 
122
+ def process_image_auto(image):
123
  """Auto enhancement with smart defaults"""
124
  if image is None:
125
  return None, "❌ No image provided"
126
 
127
  try:
128
+ # Get image info
129
+ w, h = image.size
130
+ total_pixels = w * h
131
 
132
+ # Smart scaling
133
+ if total_pixels < 500000:
134
  scale = 3
135
+ scale_info = "Applied 3x upscaling (small image)"
136
+ elif total_pixels < 2000000:
137
  scale = 2
138
+ scale_info = "Applied 2x upscaling (medium image)"
139
  else:
140
  scale = None
141
+ scale_info = "Kept original size (large image)"
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
+ # Enhance
144
+ enhanced = enhancer.enhance_image(image, scale=scale, enhance_colors=True, enhance_clarity=True)
 
 
 
 
 
 
 
 
145
 
146
+ # Info message
147
+ info = f"""Enhancement Complete!
148
 
149
+ Original: {w} Γ— {h} pixels
150
+ Enhanced: {enhanced.size[0]} Γ— {enhanced.size[1]} pixels
151
 
152
+ Enhancements Applied:
153
+ β€’ Natural color enhancement
154
+ β€’ Clarity improvement
155
+ β€’ {scale_info}
156
+ """
157
 
158
+ return enhanced, info
159
 
160
  except Exception as e:
161
+ return None, f"❌ Error: {str(e)}"
162
 
163
+ def process_image_custom(image, upscale, colors, clarity):
164
+ """Custom enhancement"""
165
  if image is None:
166
  return None, "❌ No image provided"
167
 
168
  try:
169
+ scale = int(upscale) if upscale > 1 else None
170
+ enhanced = enhancer.enhance_image(image, scale=scale, enhance_colors=colors, enhance_clarity=clarity)
 
 
 
 
 
 
 
 
171
 
 
172
  enhancements = []
173
  if scale:
174
+ enhancements.append(f"{scale}x upscaling")
175
+ if colors:
176
+ enhancements.append("Natural colors")
177
+ if clarity:
178
+ enhancements.append("Clarity improvement")
179
 
180
+ info = f"""Custom Enhancement Complete!
 
 
181
 
182
  Original: {image.size[0]} Γ— {image.size[1]} pixels
183
+ Enhanced: {enhanced.size[0]} Γ— {enhanced.size[1]} pixels
184
 
185
+ Applied: {', '.join(enhancements) if enhancements else 'No enhancements'}
186
+ """
 
187
 
188
+ return enhanced, info
189
 
190
  except Exception as e:
191
+ return None, f"❌ Error: {str(e)}"
192
 
193
+ # Create interface - simplified version
194
+ def create_app():
195
+ # Use basic Blocks without theme to avoid compatibility issues
196
+ with gr.Blocks() as app:
197
+ gr.Markdown("# 🎨 Refined Photo Enhancer")
198
+ gr.Markdown("### Natural Colors & Clarity Enhancement")
199
+
200
+ # Auto tab
 
 
201
  with gr.Tab("πŸš€ Smart Auto"):
202
  with gr.Row():
203
  with gr.Column():
204
+ input1 = gr.Image(type="pil", label="Upload Photo")
205
+ btn1 = gr.Button("✨ Auto Enhance")
 
206
  with gr.Column():
207
+ output1 = gr.Image(label="Enhanced Photo")
208
+ info1 = gr.Textbox(label="Info", lines=8)
209
 
210
+ btn1.click(process_image_auto, inputs=[input1], outputs=[output1, info1])
 
 
 
 
211
 
212
+ # Custom tab
213
+ with gr.Tab("πŸŽ›οΈ Custom"):
214
  with gr.Row():
215
  with gr.Column():
216
+ input2 = gr.Image(type="pil", label="Upload Photo")
217
+ upscale = gr.Slider(1, 4, value=2, step=1, label="Upscale Factor")
218
+ colors = gr.Checkbox(value=True, label="Color Enhancement")
219
+ clarity = gr.Checkbox(value=True, label="Clarity Enhancement")
220
+ btn2 = gr.Button("🎯 Custom Enhance")
 
 
 
 
 
 
 
 
221
  with gr.Column():
222
+ output2 = gr.Image(label="Enhanced Photo")
223
+ info2 = gr.Textbox(label="Info", lines=8)
224
 
225
+ btn2.click(process_image_custom, inputs=[input2, upscale, colors, clarity], outputs=[output2, info2])
 
 
 
 
226
 
227
  gr.Markdown("""
228
+ **Tips:**
229
+ - Small images: Auto-upscaling recommended
230
+ - Large images: Usually no upscaling needed
231
+ - Best for: Natural photos, portraits, landscapes
232
+ """)
 
233
 
234
+ return app
235
 
236
+ # Launch
237
  if __name__ == "__main__":
238
+ print("πŸš€ Starting Refined Photo Enhancer...")
 
239
 
240
  try:
241
+ app = create_app()
242
+ app.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
243
  except Exception as e:
244
+ print(f"Launch error: {e}")
245
+ print("Trying basic launch...")
246
+ app = create_app()
247
+ app.launch()