Spaces:
Runtime error

jonels1988 commited on
Commit
4502895
·
verified ·
1 Parent(s): b5b74bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -42
app.py CHANGED
@@ -3,19 +3,26 @@ import os
3
  import zipfile
4
  import tempfile
5
  import traceback
 
6
 
7
  import requests
8
  import pandas as pd
9
- from PIL import Image, ImageOps, ImageEnhance
 
10
  from rembg import remove
11
  import gradio as gr
12
 
13
  # ---------- CONFIG ----------
14
- OUTPUT_SIZE = (800, 800) # width, height (square)
15
- MAX_BYTES = 300 * 1024 # 300 KB hard cap
16
  DEFAULT_WATERMARK_PATH = "watermark.png" # repo-level default watermark
17
  ID_COL_CANDIDATES = ["id", "product_id", "sku", "code", "item_id"]
18
 
 
 
 
 
 
19
  # ---------- HELPERS ----------
20
  def download_image(url, timeout=15):
21
  """Download image from URL and return RGBA PIL Image."""
@@ -105,77 +112,194 @@ def compress_png_rgba(img, max_bytes=MAX_BYTES, fast_mode=False):
105
 
106
  return data
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  def read_pairs_from_file(upload):
109
  """
110
  Accepts:
111
- - CSV with columns: (id-like, url-like), or at least one url column
112
  - TXT with one URL per line
113
- Returns a list of dicts: [{"id": "ID-or-None", "url": "https://..."}, ...]
114
- If no id column is present, IDs are auto-generated from row order (1..N).
115
  """
116
- # Try CSV
117
  try:
118
- df = pd.read_csv(upload)
119
- cols = [c for c in df.columns]
 
 
 
 
 
 
 
 
 
 
 
 
120
  lower = {str(c).lower(): c for c in cols}
121
 
122
- # find id column
123
  id_col = None
124
  for k in ID_COL_CANDIDATES:
125
  if k in lower:
126
  id_col = lower[k]
127
  break
128
  if id_col is None:
129
- # partial contains, e.g. "product id"
130
  for c in cols:
131
  if any(k in str(c).lower() for k in ID_COL_CANDIDATES):
132
  id_col = c
133
  break
134
 
135
- # find url column
136
  url_col = None
137
- # prefer explicit url/image names
138
  for c in cols:
139
  cl = str(c).lower()
140
  if "url" in cl or "image" in cl:
141
  url_col = c
142
  break
 
 
 
143
  if url_col is None:
144
- # fallback to first column if nothing obvious
145
- url_col = cols[0]
146
 
147
- series_url = df[url_col].astype(str)
148
- if id_col is not None:
149
- series_id = df[id_col].astype(str)
150
- else:
151
- series_id = (df.index + 1).astype(str)
152
 
153
  pairs = []
154
  for idx, u in series_url.items():
155
  u = u.strip()
156
  if not u or not u.lower().startswith("http"):
157
  continue
158
- pairs.append({"id": str(series_id.iloc[idx]).strip(), "url": u})
159
  if pairs:
160
  return pairs
161
  except Exception:
162
  pass
163
 
164
- # Try plain text
165
  try:
166
- upload.seek(0)
167
- text = upload.read().decode("utf-8", errors="ignore")
168
- lines = [line.strip() for line in text.splitlines() if line.strip()]
169
- pairs = [{"id": str(i + 1), "url": u} for i, u in enumerate(lines) if u.lower().startswith("http")]
170
- if pairs:
171
- return pairs
 
 
172
  except Exception:
173
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  # ---------- STREAMING RUN ----------
178
- def run_stream(csv_file, watermark_file, brightness_val, add_wm_flag, fast_mode_flag, output_mode):
 
179
  """
180
  Streams logs as it processes each image.
181
  Outputs:
@@ -231,15 +355,31 @@ def run_stream(csv_file, watermark_file, brightness_val, add_wm_flag, fast_mode_
231
 
232
  cut = remove_background_pil(src)
233
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  img = resize_to_canvas(cut, OUTPUT_SIZE)
 
 
235
  img = apply_brightness(img, float(brightness_val))
236
 
 
237
  if add_wm_flag and wm is not None:
238
  img = apply_watermark(img, wm)
239
 
 
240
  png_bytes = compress_png_rgba(img, max_bytes=MAX_BYTES, fast_mode=fast_mode_flag)
241
 
242
- # Determine filename
243
  if id_val and id_val.lower() != "nan":
244
  out_name = f"{id_val}.png"
245
  else:
@@ -250,17 +390,15 @@ def run_stream(csv_file, watermark_file, brightness_val, add_wm_flag, fast_mode_
250
  if output_mode == "ZIP":
251
  zf.writestr(out_name, png_bytes)
252
  else:
253
- # Write a temp file now and append to list
254
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
255
  tmp.write(png_bytes)
256
  tmp.flush()
257
  tmp.close()
258
- # Rename the temp file to the desired name in the same dir to preserve name on download
259
  final_path = os.path.join(os.path.dirname(tmp.name), out_name)
260
  try:
261
  os.replace(tmp.name, final_path)
262
  except Exception:
263
- final_path = tmp.name # fallback if rename fails
264
  file_list.append(final_path)
265
 
266
  logs.append(f"{prefix} Saved {out_name} ({len(png_bytes)//1024} KB)")
@@ -271,7 +409,7 @@ def run_stream(csv_file, watermark_file, brightness_val, add_wm_flag, fast_mode_
271
  logs.append(traceback.format_exc())
272
  yield (None if output_mode == "ZIP" else None), (file_list if output_mode == "Individual files" else None), "\n".join(logs[-200:])
273
 
274
- # Finalize ZIP
275
  if output_mode == "ZIP":
276
  zf.close()
277
  zip_buffer.seek(0)
@@ -288,9 +426,11 @@ def run_stream(csv_file, watermark_file, brightness_val, add_wm_flag, fast_mode_
288
  # ---------- UI ----------
289
  with gr.Blocks() as demo:
290
  gr.Markdown(
291
- "## 🖼️ MDBG — Bulk Background Removal + 800×800 PNG + Watermark\n"
292
- "Upload a CSV or TXT. If CSV includes an **ID / SKU** column (e.g., `id`, `product_id`, `sku`, `code`), "
293
- "files are named as **ID.png**. Choose **ZIP** or **Individual files** output."
 
 
294
  )
295
 
296
  with gr.Row():
@@ -306,18 +446,22 @@ with gr.Blocks() as demo:
306
  fast_mode = gr.Checkbox(value=True, label="Fast Mode (skip heavy compression)")
307
  output_mode = gr.Radio(choices=["ZIP", "Individual files"], value="ZIP", label="Output mode")
308
 
 
 
 
 
 
309
  with gr.Row():
310
  run_btn = gr.Button("🚀 Process")
311
  status = gr.Textbox(label="Log / Status", interactive=False, lines=12)
312
 
313
- # Two outputs: ZIP file OR list of files
314
  output_zip = gr.File(label="Download ZIP")
315
  output_files = gr.Files(label="Download files")
316
 
317
- # Streaming handler (generator)
318
  run_btn.click(
319
  run_stream,
320
- inputs=[csv_in, watermark_in, brightness, add_wm, fast_mode, output_mode],
 
321
  outputs=[output_zip, output_files, status]
322
  )
323
 
 
3
  import zipfile
4
  import tempfile
5
  import traceback
6
+ import csv
7
 
8
  import requests
9
  import pandas as pd
10
+ import numpy as np
11
+ from PIL import Image, ImageOps, ImageEnhance, ImageFilter
12
  from rembg import remove
13
  import gradio as gr
14
 
15
  # ---------- CONFIG ----------
16
+ OUTPUT_SIZE = (800, 800) # final width, height (square)
17
+ MAX_BYTES = 300 * 1024 # 300 KB hard cap (when Fast Mode is OFF, we try harder)
18
  DEFAULT_WATERMARK_PATH = "watermark.png" # repo-level default watermark
19
  ID_COL_CANDIDATES = ["id", "product_id", "sku", "code", "item_id"]
20
 
21
+ # Auto-enhance defaults
22
+ SMALL_SIDE_THRESHOLD = 700 # px; below this is considered "small"
23
+ BLUR_SCORE_THRESHOLD = 8.0 # heuristic gradient variance threshold (tuneable)
24
+ UPSCALE_CAP = 1600 # px; cap for upscaling long edge before final 800×800
25
+
26
  # ---------- HELPERS ----------
27
  def download_image(url, timeout=15):
28
  """Download image from URL and return RGBA PIL Image."""
 
112
 
113
  return data
114
 
115
+ # ----- Robust file reader (supports Gradio v4 dict/list/path/file-like + CSV/TXT) -----
116
+ def _open_for_read(upload):
117
+ """
118
+ Handle gr.File inputs that may be dicts/lists/paths/file-like.
119
+ Returns (binary_handle, path_string).
120
+ """
121
+ # List -> take first
122
+ if isinstance(upload, list) and upload:
123
+ upload = upload[0]
124
+ # Dict -> use temp path in 'name'
125
+ if isinstance(upload, dict) and "name" in upload:
126
+ try:
127
+ return open(upload["name"], "rb"), upload["name"]
128
+ except Exception:
129
+ pass
130
+ # Path-like
131
+ if isinstance(upload, (str, os.PathLike)) and os.path.exists(upload):
132
+ return open(upload, "rb"), str(upload)
133
+ # File-like
134
+ try:
135
+ upload.seek(0)
136
+ except Exception:
137
+ pass
138
+ return upload, getattr(upload, "name", "<stream>")
139
+
140
  def read_pairs_from_file(upload):
141
  """
142
  Accepts:
143
+ - CSV with columns: (id-like, url-like) or at least one url column
144
  - TXT with one URL per line
145
+ Returns list of {"id": "...", "url": "..."}.
 
146
  """
147
+ # --- Try CSV first ---
148
  try:
149
+ fh, _ = _open_for_read(upload)
150
+ head = fh.read(4096).decode("utf-8", errors="ignore")
151
+ fh.seek(0)
152
+ try:
153
+ dialect = csv.Sniffer().sniff(head, delimiters=",;\t|")
154
+ except Exception:
155
+ dialect = csv.get_dialect("excel")
156
+ df = pd.read_csv(fh, sep=dialect.delimiter)
157
+ try:
158
+ fh.close()
159
+ except Exception:
160
+ pass
161
+
162
+ cols = list(df.columns)
163
  lower = {str(c).lower(): c for c in cols}
164
 
165
+ # id col
166
  id_col = None
167
  for k in ID_COL_CANDIDATES:
168
  if k in lower:
169
  id_col = lower[k]
170
  break
171
  if id_col is None:
 
172
  for c in cols:
173
  if any(k in str(c).lower() for k in ID_COL_CANDIDATES):
174
  id_col = c
175
  break
176
 
177
+ # url col (prefer names containing url/image)
178
  url_col = None
 
179
  for c in cols:
180
  cl = str(c).lower()
181
  if "url" in cl or "image" in cl:
182
  url_col = c
183
  break
184
+ if url_col is None and cols:
185
+ url_col = cols[0] # fallback
186
+
187
  if url_col is None:
188
+ return []
 
189
 
190
+ series_url = df[url_col].astype(str).fillna("")
191
+ series_id = (df[id_col].astype(str).fillna("").replace({"nan": ""})) if id_col else (df.index + 1).astype(str)
 
 
 
192
 
193
  pairs = []
194
  for idx, u in series_url.items():
195
  u = u.strip()
196
  if not u or not u.lower().startswith("http"):
197
  continue
198
+ pairs.append({"id": str(series_id.iloc[idx]).strip() or str(idx + 1), "url": u})
199
  if pairs:
200
  return pairs
201
  except Exception:
202
  pass
203
 
204
+ # --- Try TXT (one URL per line) ---
205
  try:
206
+ fh, _ = _open_for_read(upload)
207
+ txt = fh.read().decode("utf-8", errors="ignore")
208
+ try:
209
+ fh.close()
210
+ except Exception:
211
+ pass
212
+ lines = [ln.strip() for ln in txt.splitlines() if ln.strip()]
213
+ return [{"id": str(i+1), "url": u} for i, u in enumerate(lines) if u.lower().startswith("http")]
214
  except Exception:
215
+ return []
216
+
217
+ # ---------- Auto-enhance: detect small/blur + upscale/sharpen ----------
218
+ def _to_grayscale_np(img_rgba):
219
+ g = img_rgba.convert("L")
220
+ return np.asarray(g, dtype=np.float32)
221
+
222
+ def _gradient_variance(gray_np):
223
+ # Simple Sobel gradients
224
+ Kx = np.array([[1,0,-1],[2,0,-2],[1,0,-1]], dtype=np.float32)
225
+ Ky = np.array([[1,2,1],[0,0,0],[-1,-2,-1]], dtype=np.float32)
226
+ # pad
227
+ pad = 1
228
+ padded = np.pad(gray_np, ((pad,pad),(pad,pad)), mode="edge")
229
+ # convolve
230
+ Gx = (
231
+ Kx[0,0]*padded[:-2,:-2] + Kx[0,1]*padded[:-2,1:-1] + Kx[0,2]*padded[:-2,2:] +
232
+ Kx[1,0]*padded[1:-1,:-2] + Kx[1,1]*padded[1:-1,1:-1] + Kx[1,2]*padded[1:-1,2:] +
233
+ Kx[2,0]*padded[2:,:-2] + Kx[2,1]*padded[2:,1:-1] + Kx[2,2]*padded[2:,2:]
234
+ )
235
+ Gy = (
236
+ Ky[0,0]*padded[:-2,:-2] + Ky[0,1]*padded[:-2,1:-1] + Ky[0,2]*padded[:-2,2:] +
237
+ Ky[1,0]*padded[1:-1,:-2] + Ky[1,1]*padded[1:-1,1:-1] + Ky[1,2]*padded[1:-1,2:] +
238
+ Ky[2,0]*padded[2:,:-2] + Ky[2,1]*padded[2:,1:-1] + Ky[2,2]*padded[2:,2:]
239
+ )
240
+ mag = np.abs(Gx) + np.abs(Gy)
241
+ return float(np.var(mag))
242
 
243
+ def auto_enhance(img_rgba, strength=1.0, denoise=False):
244
+ """
245
+ Heuristic: if too small or blur_score < threshold, do:
246
+ - optional 2x upscaling (capped)
247
+ - Unsharp Mask
248
+ - Light contrast lift
249
+ - optional median denoise before sharpen
250
+ Returns (enhanced_img, info_dict)
251
+ """
252
+ W, H = img_rgba.size
253
+ short_side = min(W, H)
254
+
255
+ # Blur score
256
+ gray = _to_grayscale_np(img_rgba)
257
+ blur_score = _gradient_variance(gray)
258
+
259
+ should_upscale = short_side < SMALL_SIDE_THRESHOLD
260
+ is_blurry = blur_score < BLUR_SCORE_THRESHOLD
261
+
262
+ info = {
263
+ "orig_size": (W, H),
264
+ "short_side": short_side,
265
+ "blur_score": round(blur_score, 2),
266
+ "upscaled": False,
267
+ "sharpened": False,
268
+ "contrast_boost": False,
269
+ "denoised": False
270
+ }
271
+
272
+ out = img_rgba
273
+
274
+ if denoise and (should_upscale or is_blurry):
275
+ out = out.filter(ImageFilter.MedianFilter(size=3))
276
+ info["denoised"] = True
277
+
278
+ # Upscale if small/blurry (max 2x and cap long edge to UPSCALE_CAP)
279
+ if should_upscale or is_blurry:
280
+ scale = 2.0 if max(W, H) * 2 <= UPSCALE_CAP else min(UPSCALE_CAP / max(W, H), 2.0)
281
+ if scale > 1.01:
282
+ new_w = int(W * scale)
283
+ new_h = int(H * scale)
284
+ out = out.resize((new_w, new_h), resample=Image.Resampling.LANCZOS)
285
+ info["upscaled"] = True
286
+
287
+ # Unsharp mask (strength scaled)
288
+ radius = 1.5 * strength
289
+ percent = int(150 * strength) # 150–300 typical
290
+ out = out.filter(ImageFilter.UnsharpMask(radius=radius, percent=percent, threshold=2))
291
+ info["sharpened"] = True
292
+
293
+ # Slight contrast lift
294
+ c = ImageEnhance.Contrast(out)
295
+ out = c.enhance(1.0 + 0.08 * strength) # +8% per strength
296
+ info["contrast_boost"] = True
297
+
298
+ return out, info
299
 
300
  # ---------- STREAMING RUN ----------
301
+ def run_stream(csv_file, watermark_file, brightness_val, add_wm_flag, fast_mode_flag,
302
+ output_mode, auto_enhance_flag, enhance_strength, denoise_flag):
303
  """
304
  Streams logs as it processes each image.
305
  Outputs:
 
355
 
356
  cut = remove_background_pil(src)
357
 
358
+ # --- Auto-enhance (before final 800×800) ---
359
+ if auto_enhance_flag:
360
+ enhanced, info = auto_enhance(cut, strength=float(enhance_strength), denoise=bool(denoise_flag))
361
+ logs.append(f"{prefix} Auto-enhance: blur={info['blur_score']} short_side={info['short_side']} "
362
+ f"{'UPSCALED' if info['upscaled'] else ''} "
363
+ f"{'SHARPEN' if info['sharpened'] else ''} "
364
+ f"{'CONTRAST' if info['contrast_boost'] else ''} "
365
+ f"{'DENOISE' if info['denoised'] else ''}".strip())
366
+ cut = enhanced
367
+ yield None, (file_list if output_mode == "Individual files" else None), "\n".join(logs[-200:])
368
+
369
+ # Final normalization to 800×800
370
  img = resize_to_canvas(cut, OUTPUT_SIZE)
371
+
372
+ # Brightness
373
  img = apply_brightness(img, float(brightness_val))
374
 
375
+ # Watermark
376
  if add_wm_flag and wm is not None:
377
  img = apply_watermark(img, wm)
378
 
379
+ # Compress PNG (Fast Mode may skip heavy quantization)
380
  png_bytes = compress_png_rgba(img, max_bytes=MAX_BYTES, fast_mode=fast_mode_flag)
381
 
382
+ # Determine filename (prefer ID)
383
  if id_val and id_val.lower() != "nan":
384
  out_name = f"{id_val}.png"
385
  else:
 
390
  if output_mode == "ZIP":
391
  zf.writestr(out_name, png_bytes)
392
  else:
 
393
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
394
  tmp.write(png_bytes)
395
  tmp.flush()
396
  tmp.close()
 
397
  final_path = os.path.join(os.path.dirname(tmp.name), out_name)
398
  try:
399
  os.replace(tmp.name, final_path)
400
  except Exception:
401
+ final_path = tmp.name
402
  file_list.append(final_path)
403
 
404
  logs.append(f"{prefix} Saved {out_name} ({len(png_bytes)//1024} KB)")
 
409
  logs.append(traceback.format_exc())
410
  yield (None if output_mode == "ZIP" else None), (file_list if output_mode == "Individual files" else None), "\n".join(logs[-200:])
411
 
412
+ # Finalize output(s)
413
  if output_mode == "ZIP":
414
  zf.close()
415
  zip_buffer.seek(0)
 
426
  # ---------- UI ----------
427
  with gr.Blocks() as demo:
428
  gr.Markdown(
429
+ "## 🖼️ MDBG — Bulk Background Removal + 800×800 PNG + Watermark + Auto-Enhance\n"
430
+ "• Removes backgrounds (free U²-Net via rembg)\n"
431
+ "• Normalizes to **800×800** transparent PNG (clear at required pixel size)\n"
432
+ "• Optional **Auto-Enhance** for small/blurred images: upscale → sharpen → contrast\n"
433
+ "• ID-based filenames (use CSV with `id,url`), output **ZIP** or **Individual files**"
434
  )
435
 
436
  with gr.Row():
 
446
  fast_mode = gr.Checkbox(value=True, label="Fast Mode (skip heavy compression)")
447
  output_mode = gr.Radio(choices=["ZIP", "Individual files"], value="ZIP", label="Output mode")
448
 
449
+ with gr.Row():
450
+ auto_enhance_flag = gr.Checkbox(value=True, label="Auto-Enhance small/blur images")
451
+ enhance_strength = gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Enhancement strength")
452
+ denoise_flag = gr.Checkbox(value=False, label="Denoise before sharpen")
453
+
454
  with gr.Row():
455
  run_btn = gr.Button("🚀 Process")
456
  status = gr.Textbox(label="Log / Status", interactive=False, lines=12)
457
 
 
458
  output_zip = gr.File(label="Download ZIP")
459
  output_files = gr.Files(label="Download files")
460
 
 
461
  run_btn.click(
462
  run_stream,
463
+ inputs=[csv_in, watermark_in, brightness, add_wm, fast_mode, output_mode,
464
+ auto_enhance_flag, enhance_strength, denoise_flag],
465
  outputs=[output_zip, output_files, status]
466
  )
467