wykonos commited on
Commit
42e16aa
·
verified ·
1 Parent(s): b3a4057

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -115
app.py CHANGED
@@ -2,10 +2,12 @@
2
  # Advanced Image Augmentation Tool for Gradio
3
  #
4
  # This script creates a comprehensive web interface for applying various image transformations.
5
- # It uses the modern gr.ImageEditor component for interactive cropping, ensuring
6
- # compatibility with recent versions of the Gradio library.
7
- # Users can upload an image, interactively adjust parameters for augmentations,
8
- # and dynamically define the operational range (min/max values) for each slider.
 
 
9
  #
10
 
11
  import gradio as gr
@@ -42,29 +44,18 @@ def apply_transformations(
42
  ):
43
  """
44
  Applies a series of transformations to an input image based on user-defined parameters.
45
-
46
- Args:
47
- image (dict or np.array): The input from gr.ImageEditor, which can be a dict
48
- containing 'background' or a direct np.array.
49
- apply_mosaic_trigger (bool): A flag to trigger the mosaic augmentation.
50
- crop_box (tuple): Coordinates (x1, y1, x2, y2) for cropping.
51
- ... (all other args are the same)
52
-
53
- Returns:
54
- tuple: A tuple containing the original image preview, the transformed image,
55
- and a reset boolean for the mosaic trigger.
56
  """
57
- # Handle the input from gr.ImageEditor, which is a dictionary
58
  if isinstance(image, dict) and image.get("background") is not None:
59
  image_data = image["background"]
60
  elif isinstance(image, np.ndarray):
61
  image_data = image
62
  else:
63
- return None, None, False
 
64
 
65
  # Convert NumPy array to PIL Image
66
  img = Image.fromarray(image_data).convert("RGB")
67
- original_for_preview = img.copy()
68
 
69
  # Enhanced Augmentation: Mosaic
70
  if apply_mosaic_trigger:
@@ -88,95 +79,62 @@ def apply_transformations(
88
  except (ValueError, TypeError):
89
  pass
90
 
91
- # Geometric Augmentation: Scale
92
- if scale_factor != 1.0:
93
- w, h = img.size
94
- new_size = (int(w * scale_factor), int(h * scale_factor))
95
- img = img.resize(new_size, Image.Resampling.LANCZOS)
96
-
97
- # Geometric Augmentation: Shear
98
- if shear_x != 0 or shear_y != 0:
99
- img = img.transform(img.size, Image.Transform.AFFINE, (1, shear_x, 0, shear_y, 1, 0), Image.Resampling.BICUBIC)
100
-
101
- # Geometric Augmentation: Rotate
102
- if rotation_angle != 0:
103
- img = img.rotate(rotation_angle, expand=True, fillcolor=(128, 128, 128))
104
-
105
- # Geometric Augmentation: Flip
106
  if h_flip: img = ImageOps.mirror(img)
107
  if v_flip: img = ImageOps.flip(img)
108
-
109
- # Color Augmentation: Brightness, Contrast, Saturation
110
  if brightness != 1.0: img = ImageEnhance.Brightness(img).enhance(brightness)
111
  if contrast != 1.0: img = ImageEnhance.Contrast(img).enhance(contrast)
112
  if saturation != 1.0: img = ImageEnhance.Color(img).enhance(saturation)
113
 
114
- # Color Augmentation: Hue (using OpenCV for robust HSV conversion)
115
  if hue != 0:
116
- np_img_rgb = np.array(img)
117
- hsv_img = cv2.cvtColor(np_img_rgb, cv2.COLOR_RGB2HSV)
118
  hsv_img[:, :, 0] = (hsv_img[:, :, 0].astype(int) + hue) % 180
119
  img = Image.fromarray(cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB))
120
 
121
- # Color Augmentation: Exposure (Gamma Correction)
122
  if gamma != 1.0:
123
  inv_gamma = 1.0 / gamma
124
  table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
125
- if img.mode == 'L':
126
- img = img.point(table)
127
- else:
128
- r, g, b = img.split()
129
- r, g, b = r.point(table), g.point(table), b.point(table)
130
- img = Image.merge('RGB', (r, g, b))
131
 
132
- # Filter Augmentation: Sharpen
133
  if sharpen_factor > 0:
134
  for _ in range(int(sharpen_factor)): img = img.filter(ImageFilter.SHARPEN)
135
-
136
- # Filter Augmentation: Blur
137
  if blur_radius > 0: img = img.filter(ImageFilter.GaussianBlur(radius=blur_radius))
138
 
139
- # Enhanced Augmentation: Cutout
140
  if cutout_n_holes > 0 and cutout_ratio > 0:
141
- w, h = img.size
142
  np_img = np.array(img)
143
- mask_value = int(np.mean(np_img))
144
  hole_w, hole_h = int(w * cutout_ratio), int(h * cutout_ratio)
145
  if hole_w > 0 and hole_h > 0:
146
  for _ in range(cutout_n_holes):
147
  y1, x1 = random.randint(0, h - hole_h), random.randint(0, w - hole_w)
148
- y2, x2 = y1 + hole_h, x1 + hole_w
149
- np_img[y1:y2, x1:x2] = mask_value
150
  img = Image.fromarray(np_img)
151
 
152
- # Filter Augmentation: Noise
153
  if noise_intensity > 0:
154
  np_img = np.array(img)
155
  noise = np.random.normal(0, noise_intensity, np_img.shape)
156
- np_img = np.clip(np_img + noise, 0, 255).astype(np.uint8)
157
- img = Image.fromarray(np_img)
158
 
159
- # Color Augmentation: Grayscale and Invert
160
  if grayscale: img = ImageOps.grayscale(img)
161
  if invert: img = ImageOps.invert(img.convert('RGB') if img.mode != 'L' else img)
162
 
163
- # Return final images and reset the mosaic trigger to False
164
- return original_for_preview, img, False
165
 
166
  # --- UI Helper Functions ---
167
 
168
  def process_selection(evt: gr.SelectData):
169
- """Callback function to capture the coordinates of a user's selection on the input image for cropping."""
170
  return (evt.index[0], evt.index[1], evt.index[2], evt.index[3])
171
 
172
  def update_slider(min_val, max_val, current_val):
173
- """Updates a Gradio slider's properties (min, max, value) dynamically."""
174
  if min_val > max_val: min_val = max_val
175
  new_val = max(min_val, min(max_val, current_val))
176
  return gr.update(minimum=min_val, maximum=max_val, value=new_val)
177
 
178
  def reset_all_controls():
179
- """Returns a tuple of default values to reset all UI components to their initial state."""
180
  return (
181
  False, None, 1.0, 0, False, False, 0.0, 0.0, 1.0, 1.0, 1.0, 0, 1.0, False, False, 0.0, 0, 0, 0, 0.0,
182
  0.1, 3.0, -180, 180, -0.5, 0.5, -0.5, 0.5, 0.0, 3.0, 0.0, 3.0, 0.0, 3.0,
@@ -184,11 +142,8 @@ def reset_all_controls():
184
  None, None
185
  )
186
 
187
- def on_upload_or_clear(image):
188
- """Handles the event of uploading or clearing an image, resetting all controls."""
189
- outputs = reset_all_controls()
190
- if image is None: return outputs
191
- return outputs[:-2] + (image, None)
192
 
193
  # --- Gradio UI Layout ---
194
 
@@ -202,72 +157,48 @@ with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}")
202
  with gr.Row(variant="panel"):
203
  with gr.Column(scale=1, min_width=400):
204
  gr.Markdown("### Main Control Panel")
205
-
206
  with gr.Accordion("Geometric Transformations", open=True):
207
  scale_slider = gr.Slider(0.1, 3.0, 1.0, step=0.05, label="Scale")
208
  rotation_slider = gr.Slider(-180, 180, 0, step=1, label="Rotation Angle")
209
  with gr.Row():
210
- rotate_90_btn = gr.Button("Rotate 90°")
211
- rotate_180_btn = gr.Button("Rotate 180°")
212
- rotate_270_btn = gr.Button("Rotate 270°")
213
- shear_x_slider = gr.Slider(-0.5, 0.5, 0.0, step=0.01, label="Shear X")
214
- shear_y_slider = gr.Slider(-0.5, 0.5, 0.0, step=0.01, label="Shear Y")
215
- with gr.Row():
216
- h_flip_check = gr.Checkbox(label="Horizontal Flip")
217
- v_flip_check = gr.Checkbox(label="Vertical Flip")
218
 
219
  with gr.Accordion("Color & Tone Adjustments", open=True):
220
- brightness_slider = gr.Slider(0.0, 3.0, 1.0, step=0.05, label="Brightness")
221
- contrast_slider = gr.Slider(0.0, 3.0, 1.0, step=0.05, label="Contrast")
222
- saturation_slider = gr.Slider(0.0, 3.0, 1.0, step=0.05, label="Saturation")
223
- hue_slider = gr.Slider(-90, 90, 0, step=1, label="Hue")
224
- gamma_slider = gr.Slider(0.2, 2.2, 1.0, step=0.05, label="Exposure (Gamma)")
225
- with gr.Row():
226
- grayscale_check = gr.Checkbox(label="Grayscale")
227
- invert_check = gr.Checkbox(label="Invert Colors")
228
 
229
  with gr.Accordion("Filters & Distortions", open=True):
230
- blur_slider = gr.Slider(0.0, 15.0, 0.0, step=0.1, label="Blur Radius")
231
- sharpen_slider = gr.Slider(0, 5, 0, step=1, label="Sharpen Intensity")
232
- noise_slider = gr.Slider(0, 50, 0, step=1, label="Add Noise")
233
 
234
  with gr.Accordion("Enhanced Augmentations", open=False):
235
- gr.Markdown("**Cutout**: Erases random rectangular patches from the image.")
236
- cutout_n_slider = gr.Slider(0, 50, 0, step=1, label="Number of Holes")
237
- cutout_ratio_slider = gr.Slider(0.0, 0.5, 0.0, step=0.01, label="Hole Size Ratio")
238
- gr.Markdown("**Mosaic**: Splits the image into 4 quadrants and shuffles them.")
239
  mosaic_btn = gr.Button("Apply Mosaic")
240
 
241
  with gr.Accordion("Parameter Range Control (Advanced)", open=False):
242
- gr.Markdown("Define the min/max for the sliders in the main panel.")
243
  with gr.Tabs():
244
  with gr.TabItem("Geometric"):
245
- scale_min, scale_max = gr.Number(0.1, label="Scale Min"), gr.Number(3.0, label="Scale Max")
246
- rotation_min, rotation_max = gr.Number(-180, label="Rotation Min"), gr.Number(180, label="Rotation Max")
247
- shear_x_min, shear_x_max = gr.Number(-0.5, label="Shear X Min"), gr.Number(0.5, label="Shear X Max")
248
- shear_y_min, shear_y_max = gr.Number(-0.5, label="Shear Y Min"), gr.Number(0.5, label="Shear Y Max")
249
  with gr.TabItem("Color"):
250
- brightness_min, brightness_max = gr.Number(0.0, label="Brightness Min"), gr.Number(3.0, label="Brightness Max")
251
- contrast_min, contrast_max = gr.Number(0.0, label="Contrast Min"), gr.Number(3.0, label="Contrast Max")
252
- saturation_min, saturation_max = gr.Number(0.0, label="Saturation Min"), gr.Number(3.0, label="Saturation Max")
253
- hue_min, hue_max = gr.Number(-90, label="Hue Min"), gr.Number(90, label="Hue Max")
254
  gamma_min, gamma_max = gr.Number(0.2, label="Exposure Min"), gr.Number(2.2, label="Exposure Max")
255
  with gr.TabItem("Filters/Other"):
256
- blur_min, blur_max = gr.Number(0.0, label="Blur Min"), gr.Number(15.0, label="Blur Max")
257
- noise_min, noise_max = gr.Number(0, label="Noise Min"), gr.Number(50, label="Noise Max")
258
- cutout_n_min, cutout_n_max = gr.Number(0, label="Holes Min"), gr.Number(50, label="Holes Max")
259
- cutout_ratio_min, cutout_ratio_max = gr.Number(0.0, label="Ratio Min"), gr.Number(0.5, label="Ratio Max")
260
 
261
  reset_btn = gr.Button("Reset All Settings", variant="stop", size="lg")
262
 
263
  with gr.Column(scale=3):
264
- # FIXED: Replaced gr.Image with gr.ImageEditor
265
- image_input = gr.ImageEditor(type="numpy", label="Original Image (Select an area to crop)")
266
  image_output = gr.Image(label="Transformed Image", interactive=False)
267
  gr.Examples(
268
  examples=[os.path.join(os.path.dirname(__file__), f) for f in ["cat.jpg", "cheetah.jpg", "lion.jpg"] if os.path.exists(os.path.join(os.path.dirname(__file__), f))],
269
- inputs=image_input,
270
- label="Example Images"
271
  )
272
 
273
  all_inputs = [
@@ -289,25 +220,31 @@ with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}")
289
  image_input, image_output
290
  ]
291
 
 
 
 
292
  for component in all_inputs:
293
  if component not in [image_input, crop_box_state, mosaic_trigger]:
294
- component.change(fn=apply_transformations, inputs=all_inputs, outputs=[image_input, image_output, mosaic_trigger])
295
 
296
- # The 'select' event is built into ImageEditor
297
  image_input.select(fn=process_selection, inputs=None, outputs=[crop_box_state]).then(
298
- fn=apply_transformations, inputs=all_inputs, outputs=[image_input, image_output, mosaic_trigger])
299
 
300
- # The 'change' event in ImageEditor fires on upload and clear
301
- image_input.change(fn=on_upload_or_clear, inputs=[image_input], outputs=all_resettable_outputs)
302
- reset_btn.click(fn=on_upload_or_clear, inputs=[image_input], outputs=all_resettable_outputs)
 
303
 
 
304
  rotate_90_btn.click(lambda x: (x + 90) % 360, inputs=[rotation_slider], outputs=[rotation_slider])
305
  rotate_180_btn.click(lambda: 180, inputs=None, outputs=[rotation_slider])
306
  rotate_270_btn.click(lambda: -90, inputs=None, outputs=[rotation_slider])
307
 
308
  mosaic_btn.click(lambda: True, None, mosaic_trigger).then(
309
- fn=apply_transformations, inputs=all_inputs, outputs=[image_input, image_output, mosaic_trigger])
310
 
 
311
  range_map = {
312
  (scale_min, scale_max): scale_slider, (rotation_min, rotation_max): rotation_slider,
313
  (shear_x_min, shear_x_max): shear_x_slider, (shear_y_min, shear_y_max): shear_y_slider,
 
2
  # Advanced Image Augmentation Tool for Gradio
3
  #
4
  # This script creates a comprehensive web interface for applying various image transformations.
5
+ # It uses the modern gr.ImageEditor component for interactive cropping.
6
+ #
7
+ # CRITICAL FIX: The event handling logic has been revised to prevent feedback loops.
8
+ # Instead of using a broad .change() event on the ImageEditor, this version uses
9
+ # specific .upload(), .clear(), and .select() events. Transformation triggers
10
+ # now ONLY update the output image, not the input, which resolves the flickering/resetting issue.
11
  #
12
 
13
  import gradio as gr
 
44
  ):
45
  """
46
  Applies a series of transformations to an input image based on user-defined parameters.
 
 
 
 
 
 
 
 
 
 
 
47
  """
48
+ # Handle the dictionary input from gr.ImageEditor, which contains the background image
49
  if isinstance(image, dict) and image.get("background") is not None:
50
  image_data = image["background"]
51
  elif isinstance(image, np.ndarray):
52
  image_data = image
53
  else:
54
+ # If there's no image data, return None for output and reset mosaic trigger
55
+ return None, False
56
 
57
  # Convert NumPy array to PIL Image
58
  img = Image.fromarray(image_data).convert("RGB")
 
59
 
60
  # Enhanced Augmentation: Mosaic
61
  if apply_mosaic_trigger:
 
79
  except (ValueError, TypeError):
80
  pass
81
 
82
+ # Apply other transformations...
83
+ if scale_factor != 1.0: img = img.resize((int(img.width * scale_factor), int(img.height * scale_factor)), Image.Resampling.LANCZOS)
84
+ if shear_x != 0 or shear_y != 0: img = img.transform(img.size, Image.Transform.AFFINE, (1, shear_x, 0, shear_y, 1, 0), Image.Resampling.BICUBIC)
85
+ if rotation_angle != 0: img = img.rotate(rotation_angle, expand=True, fillcolor=(128, 128, 128))
 
 
 
 
 
 
 
 
 
 
 
86
  if h_flip: img = ImageOps.mirror(img)
87
  if v_flip: img = ImageOps.flip(img)
 
 
88
  if brightness != 1.0: img = ImageEnhance.Brightness(img).enhance(brightness)
89
  if contrast != 1.0: img = ImageEnhance.Contrast(img).enhance(contrast)
90
  if saturation != 1.0: img = ImageEnhance.Color(img).enhance(saturation)
91
 
 
92
  if hue != 0:
93
+ hsv_img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2HSV)
 
94
  hsv_img[:, :, 0] = (hsv_img[:, :, 0].astype(int) + hue) % 180
95
  img = Image.fromarray(cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB))
96
 
 
97
  if gamma != 1.0:
98
  inv_gamma = 1.0 / gamma
99
  table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
100
+ img = ImageOps.point(img, table)
 
 
 
 
 
101
 
 
102
  if sharpen_factor > 0:
103
  for _ in range(int(sharpen_factor)): img = img.filter(ImageFilter.SHARPEN)
 
 
104
  if blur_radius > 0: img = img.filter(ImageFilter.GaussianBlur(radius=blur_radius))
105
 
 
106
  if cutout_n_holes > 0 and cutout_ratio > 0:
 
107
  np_img = np.array(img)
108
+ h, w, _ = np_img.shape
109
  hole_w, hole_h = int(w * cutout_ratio), int(h * cutout_ratio)
110
  if hole_w > 0 and hole_h > 0:
111
  for _ in range(cutout_n_holes):
112
  y1, x1 = random.randint(0, h - hole_h), random.randint(0, w - hole_w)
113
+ np_img[y1:y1+hole_h, x1:x1+hole_w] = int(np.mean(np_img))
 
114
  img = Image.fromarray(np_img)
115
 
 
116
  if noise_intensity > 0:
117
  np_img = np.array(img)
118
  noise = np.random.normal(0, noise_intensity, np_img.shape)
119
+ img = Image.fromarray(np.clip(np_img + noise, 0, 255).astype(np.uint8))
 
120
 
 
121
  if grayscale: img = ImageOps.grayscale(img)
122
  if invert: img = ImageOps.invert(img.convert('RGB') if img.mode != 'L' else img)
123
 
124
+ # Return final image for the output component and reset the mosaic trigger
125
+ return img, False
126
 
127
  # --- UI Helper Functions ---
128
 
129
  def process_selection(evt: gr.SelectData):
 
130
  return (evt.index[0], evt.index[1], evt.index[2], evt.index[3])
131
 
132
  def update_slider(min_val, max_val, current_val):
 
133
  if min_val > max_val: min_val = max_val
134
  new_val = max(min_val, min(max_val, current_val))
135
  return gr.update(minimum=min_val, maximum=max_val, value=new_val)
136
 
137
  def reset_all_controls():
 
138
  return (
139
  False, None, 1.0, 0, False, False, 0.0, 0.0, 1.0, 1.0, 1.0, 0, 1.0, False, False, 0.0, 0, 0, 0, 0.0,
140
  0.1, 3.0, -180, 180, -0.5, 0.5, -0.5, 0.5, 0.0, 3.0, 0.0, 3.0, 0.0, 3.0,
 
142
  None, None
143
  )
144
 
145
+ def on_upload_or_clear():
146
+ return reset_all_controls()
 
 
 
147
 
148
  # --- Gradio UI Layout ---
149
 
 
157
  with gr.Row(variant="panel"):
158
  with gr.Column(scale=1, min_width=400):
159
  gr.Markdown("### Main Control Panel")
160
+ # All control panels remain the same...
161
  with gr.Accordion("Geometric Transformations", open=True):
162
  scale_slider = gr.Slider(0.1, 3.0, 1.0, step=0.05, label="Scale")
163
  rotation_slider = gr.Slider(-180, 180, 0, step=1, label="Rotation Angle")
164
  with gr.Row():
165
+ rotate_90_btn, rotate_180_btn, rotate_270_btn = gr.Button("Rotate 90°"), gr.Button("Rotate 180°"), gr.Button("Rotate 270°")
166
+ shear_x_slider, shear_y_slider = gr.Slider(-0.5, 0.5, 0.0, step=0.01, label="Shear X"), gr.Slider(-0.5, 0.5, 0.0, step=0.01, label="Shear Y")
167
+ h_flip_check, v_flip_check = gr.Checkbox(label="Horizontal Flip"), gr.Checkbox(label="Vertical Flip")
 
 
 
 
 
168
 
169
  with gr.Accordion("Color & Tone Adjustments", open=True):
170
+ brightness_slider, contrast_slider, saturation_slider = gr.Slider(0.0, 3.0, 1.0, step=0.05, label="Brightness"), gr.Slider(0.0, 3.0, 1.0, step=0.05, label="Contrast"), gr.Slider(0.0, 3.0, 1.0, step=0.05, label="Saturation")
171
+ hue_slider, gamma_slider = gr.Slider(-90, 90, 0, step=1, label="Hue"), gr.Slider(0.2, 2.2, 1.0, step=0.05, label="Exposure (Gamma)")
172
+ grayscale_check, invert_check = gr.Checkbox(label="Grayscale"), gr.Checkbox(label="Invert Colors")
 
 
 
 
 
173
 
174
  with gr.Accordion("Filters & Distortions", open=True):
175
+ blur_slider, sharpen_slider, noise_slider = gr.Slider(0.0, 15.0, 0.0, step=0.1, label="Blur Radius"), gr.Slider(0, 5, 0, step=1, label="Sharpen Intensity"), gr.Slider(0, 50, 0, step=1, label="Add Noise")
 
 
176
 
177
  with gr.Accordion("Enhanced Augmentations", open=False):
178
+ cutout_n_slider, cutout_ratio_slider = gr.Slider(0, 50, 0, step=1, label="Number of Holes"), gr.Slider(0.0, 0.5, 0.0, step=0.01, label="Hole Size Ratio")
 
 
 
179
  mosaic_btn = gr.Button("Apply Mosaic")
180
 
181
  with gr.Accordion("Parameter Range Control (Advanced)", open=False):
 
182
  with gr.Tabs():
183
  with gr.TabItem("Geometric"):
184
+ scale_min, scale_max, rotation_min, rotation_max = gr.Number(0.1, label="Scale Min"), gr.Number(3.0, label="Scale Max"), gr.Number(-180, label="Rotation Min"), gr.Number(180, label="Rotation Max")
185
+ shear_x_min, shear_x_max, shear_y_min, shear_y_max = gr.Number(-0.5, label="Shear X Min"), gr.Number(0.5, label="Shear X Max"), gr.Number(-0.5, label="Shear Y Min"), gr.Number(0.5, label="Shear Y Max")
 
 
186
  with gr.TabItem("Color"):
187
+ brightness_min, brightness_max, contrast_min, contrast_max = gr.Number(0.0, label="Brightness Min"), gr.Number(3.0, label="Brightness Max"), gr.Number(0.0, label="Contrast Min"), gr.Number(3.0, label="Contrast Max")
188
+ saturation_min, saturation_max, hue_min, hue_max = gr.Number(0.0, label="Saturation Min"), gr.Number(3.0, label="Saturation Max"), gr.Number(-90, label="Hue Min"), gr.Number(90, label="Hue Max")
 
 
189
  gamma_min, gamma_max = gr.Number(0.2, label="Exposure Min"), gr.Number(2.2, label="Exposure Max")
190
  with gr.TabItem("Filters/Other"):
191
+ blur_min, blur_max, noise_min, noise_max = gr.Number(0.0, label="Blur Min"), gr.Number(15.0, label="Blur Max"), gr.Number(0, label="Noise Min"), gr.Number(50, label="Noise Max")
192
+ cutout_n_min, cutout_n_max, cutout_ratio_min, cutout_ratio_max = gr.Number(0, label="Holes Min"), gr.Number(50, label="Holes Max"), gr.Number(0.0, label="Ratio Min"), gr.Number(0.5, label="Ratio Max")
 
 
193
 
194
  reset_btn = gr.Button("Reset All Settings", variant="stop", size="lg")
195
 
196
  with gr.Column(scale=3):
197
+ image_input = gr.ImageEditor(type="numpy", label="Original Image (Select an area to crop)", interactive=True)
 
198
  image_output = gr.Image(label="Transformed Image", interactive=False)
199
  gr.Examples(
200
  examples=[os.path.join(os.path.dirname(__file__), f) for f in ["cat.jpg", "cheetah.jpg", "lion.jpg"] if os.path.exists(os.path.join(os.path.dirname(__file__), f))],
201
+ inputs=image_input, label="Example Images"
 
202
  )
203
 
204
  all_inputs = [
 
220
  image_input, image_output
221
  ]
222
 
223
+ # STABLE EVENT HANDLING
224
+ # 1. Any change in a control slider/checkbox triggers the transformation function.
225
+ # CRITICAL: The output is ONLY the output image, not the input. This prevents the loop.
226
  for component in all_inputs:
227
  if component not in [image_input, crop_box_state, mosaic_trigger]:
228
+ component.change(fn=apply_transformations, inputs=all_inputs, outputs=[image_output, mosaic_trigger])
229
 
230
+ # 2. Selecting a crop area updates the crop state, then triggers transformation.
231
  image_input.select(fn=process_selection, inputs=None, outputs=[crop_box_state]).then(
232
+ fn=apply_transformations, inputs=all_inputs, outputs=[image_output, mosaic_trigger])
233
 
234
+ # 3. Use SPECIFIC events for upload/clear to reset the entire UI.
235
+ image_input.upload(fn=on_upload_or_clear, inputs=None, outputs=all_resettable_outputs)
236
+ image_input.clear(fn=on_upload_or_clear, inputs=None, outputs=all_resettable_outputs)
237
+ reset_btn.click(fn=on_upload_or_clear, inputs=None, outputs=all_resettable_outputs)
238
 
239
+ # Other event handlers
240
  rotate_90_btn.click(lambda x: (x + 90) % 360, inputs=[rotation_slider], outputs=[rotation_slider])
241
  rotate_180_btn.click(lambda: 180, inputs=None, outputs=[rotation_slider])
242
  rotate_270_btn.click(lambda: -90, inputs=None, outputs=[rotation_slider])
243
 
244
  mosaic_btn.click(lambda: True, None, mosaic_trigger).then(
245
+ fn=apply_transformations, inputs=all_inputs, outputs=[image_output, mosaic_trigger])
246
 
247
+ # Range control handlers remain the same
248
  range_map = {
249
  (scale_min, scale_max): scale_slider, (rotation_min, rotation_max): rotation_slider,
250
  (shear_x_min, shear_x_max): shear_x_slider, (shear_y_min, shear_y_max): shear_y_slider,