Spaces:
Running on Zero

clementBE commited on
Commit
1a38d74
·
verified ·
1 Parent(s): 2e69413

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -154
app.py CHANGED
@@ -1,18 +1,14 @@
1
  import os
2
 
3
- # ---------------------------
4
- # 1. Hardware & Framework Safe Environment Setup
5
- # Must be set BEFORE importing torch, tensorflow, or cv2
6
- # ---------------------------
7
  os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
8
  os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
9
 
10
  import io
11
  import tempfile
12
  import zipfile
13
-
14
  import cv2
15
- # Prevent OpenCV thread contention crashes in containerized environments
16
  cv2.setNumThreads(0)
17
 
18
  import gradio as gr
@@ -20,11 +16,10 @@ import matplotlib.pyplot as plt
20
  import numpy as np
21
  import pandas as pd
22
  from PIL import Image
23
- from sklearn.cluster import KMeans
24
 
25
- # Optional Hugging Face ZeroGPU support
26
  try:
27
  import spaces
 
28
  HAS_SPACES = True
29
  except ImportError:
30
  HAS_SPACES = False
@@ -32,7 +27,6 @@ except ImportError:
32
  import torch
33
  import tensorflow as tf
34
 
35
- # Suppress TensorFlow GPU pre-allocation
36
  gpus = tf.config.list_physical_devices("GPU")
37
  if gpus:
38
  try:
@@ -44,15 +38,9 @@ if gpus:
44
  from deepface import DeepFace
45
  from ultralytics import YOLO
46
 
47
- # ---------------------------
48
- # Load YOLOv8 safely
49
- # ---------------------------
50
- # Initialize model on CPU first to prevent startup Exit Code 139
51
- yolo_model = YOLO("yolov8m.pt")
52
 
53
- # ---------------------------
54
- # Perceptual CIELAB Color Mapping
55
- # ---------------------------
56
  BASIC_COLOR_LAB = {
57
  "Red": (53, 80, 67),
58
  "Green": (87, -86, 83),
@@ -69,22 +57,14 @@ BASIC_COLOR_LAB = {
69
 
70
 
71
  def closest_perceptual_color(rgb_tuple):
72
- """Finds closest color in CIELAB space."""
73
  rgb_pixel = np.uint8([[list(rgb_tuple)]])
74
  lab_pixel = cv2.cvtColor(rgb_pixel, cv2.COLOR_RGB2LAB)[0][0]
75
 
76
  min_dist = float("inf")
77
  closest_name = "Gray"
78
-
79
  for name, target_lab in BASIC_COLOR_LAB.items():
80
- dist = np.sqrt(
81
- np.sum(
82
- (
83
- np.array(lab_pixel, dtype=float)
84
- - np.array(target_lab, dtype=float)
85
- )
86
- ** 2
87
- )
88
  )
89
  if dist < min_dist:
90
  min_dist = dist
@@ -93,24 +73,26 @@ def closest_perceptual_color(rgb_tuple):
93
  return closest_name
94
 
95
 
96
- def analyze_advanced_colors(image_pil, num_colors=3):
97
- """Extracts dominant hex, basic color, HSV saturation, brightness, and tone."""
98
- img_rgb = np.array(image_pil.resize((150, 150)).convert("RGB"))
99
- pixels = img_rgb.reshape(-1, 3)
100
 
101
- kmeans = KMeans(n_clusters=num_colors, n_init=3, random_state=42)
102
- kmeans.fit(pixels)
103
- counts = np.bincount(kmeans.labels_)
104
- dominant_rgb = kmeans.cluster_centers_[np.argmax(counts)].astype(int)
105
- hex_color = f"#{dominant_rgb[0]:02x}{dominant_rgb[1]:02x}{dominant_rgb[2]:02x}"
 
 
106
 
 
107
  basic_color = closest_perceptual_color(tuple(dominant_rgb))
108
 
109
- img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)
110
  mean_sat = np.mean(img_hsv[:, :, 1]) / 255.0
111
  mean_val = np.mean(img_hsv[:, :, 2]) / 255.0
112
  mean_hue = np.mean(img_hsv[:, :, 0])
113
-
114
  tone = "Warm" if (mean_hue < 45 or mean_hue > 135) else "Cool"
115
 
116
  return {
@@ -122,85 +104,37 @@ def analyze_advanced_colors(image_pil, num_colors=3):
122
  }
123
 
124
 
125
- # ---------------------------
126
- # Object Detection & Bounding Boxes
127
- # ---------------------------
128
- def detect_objects_yolo(image_pil, conf_threshold=0.35):
129
- """Runs YOLOv8 object detection with active device detection."""
130
- # Detect dynamically at execution time
131
- execution_device = "cuda" if torch.cuda.is_available() else "cpu"
132
-
133
- img_np = np.array(image_pil)
134
- results = yolo_model(
135
- img_np, conf=conf_threshold, verbose=False, device=execution_device
136
- )[0]
137
-
138
- detected_counts = {}
139
- items_detail = []
140
-
141
- for box in results.boxes:
142
- cls_id = int(box.cls[0])
143
- cls_name = yolo_model.names[cls_id]
144
- conf = float(box.conf[0])
145
-
146
- detected_counts[cls_name] = detected_counts.get(cls_name, 0) + 1
147
- items_detail.append(f"{cls_name} ({conf:.0%})")
148
-
149
- summary_str = ", ".join(
150
- [f"{cnt}x {name}" for name, cnt in detected_counts.items()]
151
- )
152
- if not summary_str:
153
- summary_str = "None detected"
154
-
155
- annotated_bgr = results.plot()
156
- annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
157
- annotated_pil = Image.fromarray(annotated_rgb)
158
-
159
- return summary_str, ", ".join(items_detail), annotated_pil
160
-
161
-
162
- # ---------------------------
163
- # Safe Face Analysis
164
- # ---------------------------
165
- def analyze_faces_safely(image_pil):
166
- """Analyzes faces via DeepFace with fallback exception handling."""
167
  try:
168
- img_cv2 = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
169
  results = DeepFace.analyze(
170
- img_cv2,
171
- actions=["age", "gender", "emotion"],
172
  enforce_detection=False,
 
173
  silent=True,
174
  )
175
- if not isinstance(results, list):
176
- results = [results]
177
-
178
- parsed_faces = []
179
- for f in results:
180
- gender_data = f.get("gender")
181
- if isinstance(gender_data, dict):
182
- dominant_gender = max(gender_data, key=gender_data.get)
183
- conf = gender_data[dominant_gender]
184
- else:
185
- dominant_gender = str(gender_data)
186
- conf = 100.0
187
-
188
- parsed_faces.append(
189
- {
190
- "age": f.get("age", 0),
191
- "gender": dominant_gender,
192
- "gender_conf": conf,
193
- "emotion": f.get("dominant_emotion", "N/A"),
194
- }
195
- )
196
- return parsed_faces
197
  except Exception:
198
- return []
199
 
200
 
201
- # ---------------------------
202
- # Plot Generation Helper
203
- # ---------------------------
204
  def build_summary_plots(df):
205
  plots = []
206
 
@@ -212,7 +146,7 @@ def build_summary_plots(df):
212
  return Image.open(buf)
213
 
214
  # Plot 1: Color Distribution
215
- fig1, ax1 = plt.subplots(figsize=(6, 4))
216
  if not df.empty and "Basic Color" in df:
217
  df["Basic Color"].value_counts().plot(
218
  kind="bar", ax=ax1, color="skyblue"
@@ -221,7 +155,7 @@ def build_summary_plots(df):
221
  plots.append(fig_to_pil(fig1))
222
 
223
  # Plot 2: Top Objects
224
- fig2, ax2 = plt.subplots(figsize=(6, 4))
225
  if not df.empty and "Detected Objects (Summary)" in df:
226
  all_objects = []
227
  for item in df["Detected Objects (Summary)"]:
@@ -231,11 +165,11 @@ def build_summary_plots(df):
231
  if len(parts) == 2:
232
  all_objects.extend([parts[1]] * int(parts[0]))
233
  if all_objects:
234
- pd.Series(all_objects).value_counts().head(15).plot(
235
  kind="barh", ax=ax2, color="salmon"
236
  )
237
  ax2.invert_yaxis()
238
- ax2.set_title("Top Detected Object Frequency")
239
  plots.append(fig_to_pil(fig2))
240
 
241
  # Plot 3 & 4: Demographic parsing
@@ -254,37 +188,35 @@ def build_summary_plots(df):
254
  else:
255
  ages_women.append(f["age"])
256
 
257
- fig3, ax3 = plt.subplots(figsize=(6, 4))
258
  ax3.bar(
259
  gender_counts.keys(), gender_counts.values(), color=["lightblue", "pink"]
260
  )
261
- ax3.set_title("Gender Distribution (Weighted)")
262
  plots.append(fig_to_pil(fig3))
263
 
264
- fig4, ax4 = plt.subplots(figsize=(6, 4))
265
  ax4.hist(
266
  [ages_men, ages_women],
267
  bins=range(0, 101, 10),
268
  color=["lightblue", "pink"],
269
  label=["Men", "Women"],
270
  )
271
- ax4.set_title("Age Distribution by Gender")
272
  ax4.legend()
273
  plots.append(fig_to_pil(fig4))
274
 
275
  return plots
276
 
277
 
278
- # ---------------------------
279
- # Core Processing Pipeline
280
- # ---------------------------
281
- def _run_processing(zip_file):
282
  if zip_file is None:
283
  return None, None, [], None, None, None, None
284
 
285
  results = []
286
  annotated_thumbnails = []
287
  zip_basename = os.path.splitext(os.path.basename(zip_file.name))[0]
 
288
 
289
  with tempfile.TemporaryDirectory() as tmpdir:
290
  with zipfile.ZipFile(zip_file.name, "r") as zip_ref:
@@ -298,59 +230,107 @@ def _run_processing(zip_file):
298
  ):
299
  image_paths.append(os.path.join(root, fname))
300
 
301
- for img_path in image_paths:
302
- fname = os.path.basename(img_path)
303
- try:
304
- image = Image.open(img_path).convert("RGB")
305
- except Exception:
 
 
 
 
 
 
 
 
 
 
306
  continue
307
 
308
- obj_summary, obj_details, bbox_thumb = detect_objects_yolo(image)
309
-
310
- bbox_thumb.thumbnail((300, 300))
311
- annotated_thumbnails.append(bbox_thumb)
312
-
313
- color_data = analyze_advanced_colors(image)
314
- faces_data = analyze_faces_safely(image)
315
-
316
- results.append(
317
- {
318
- "Filename": fname,
319
- "Detected Objects (Summary)": obj_summary,
320
- "Object Details": obj_details,
321
- "Dominant Color": color_data["hex"],
322
- "Basic Color": color_data["basic_color"],
323
- "Saturation": color_data["saturation"],
324
- "Brightness": color_data["brightness"],
325
- "Tone": color_data["tone"],
326
- "Face Info": faces_data,
327
- }
328
  )
329
 
330
- df = pd.DataFrame(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
 
 
332
  out_xlsx = os.path.join(
333
  tempfile.gettempdir(), f"{zip_basename}_analytics.xlsx"
334
  )
335
  df.to_excel(out_xlsx, index=False)
336
 
337
  p1, p2, p3, p4 = build_summary_plots(df)
338
-
339
  return df, out_xlsx, annotated_thumbnails, p1, p2, p3, p4
340
 
341
 
342
- # Apply HF ZeroGPU decorator if available
343
  if HAS_SPACES:
344
  process_zip_archive = spaces.GPU(duration=120)(_run_processing)
345
  else:
346
  process_zip_archive = _run_processing
347
 
348
 
349
- # ---------------------------
350
- # Gradio UI
351
- # ---------------------------
352
- with gr.Blocks(title="Advanced Image Analytics Dashboard") as demo:
353
- gr.Markdown("# Advanced Image Classifier & Visual Analytics")
354
 
355
  with gr.Row():
356
  file_input = gr.File(
 
1
  import os
2
 
3
+ # Prevent Thread Contention & TensorFlow GPU Pre-allocation
 
 
 
4
  os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
5
  os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
6
 
7
  import io
8
  import tempfile
9
  import zipfile
 
10
  import cv2
11
+
12
  cv2.setNumThreads(0)
13
 
14
  import gradio as gr
 
16
  import numpy as np
17
  import pandas as pd
18
  from PIL import Image
 
19
 
 
20
  try:
21
  import spaces
22
+
23
  HAS_SPACES = True
24
  except ImportError:
25
  HAS_SPACES = False
 
27
  import torch
28
  import tensorflow as tf
29
 
 
30
  gpus = tf.config.list_physical_devices("GPU")
31
  if gpus:
32
  try:
 
38
  from deepface import DeepFace
39
  from ultralytics import YOLO
40
 
41
+ # Load lightweight YOLO model
42
+ yolo_model = YOLO("yolov8n.pt")
 
 
 
43
 
 
 
 
44
  BASIC_COLOR_LAB = {
45
  "Red": (53, 80, 67),
46
  "Green": (87, -86, 83),
 
57
 
58
 
59
  def closest_perceptual_color(rgb_tuple):
 
60
  rgb_pixel = np.uint8([[list(rgb_tuple)]])
61
  lab_pixel = cv2.cvtColor(rgb_pixel, cv2.COLOR_RGB2LAB)[0][0]
62
 
63
  min_dist = float("inf")
64
  closest_name = "Gray"
 
65
  for name, target_lab in BASIC_COLOR_LAB.items():
66
+ dist = np.linalg.norm(
67
+ np.array(lab_pixel, dtype=float) - np.array(target_lab, dtype=float)
 
 
 
 
 
 
68
  )
69
  if dist < min_dist:
70
  min_dist = dist
 
73
  return closest_name
74
 
75
 
76
+ def fast_color_analysis(img_np):
77
+ """Vectorized fast color analysis on a small resized array."""
78
+ small_rgb = cv2.resize(img_np, (64, 64))
79
+ pixels = np.float32(small_rgb.reshape(-1, 3))
80
 
81
+ criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 5, 1.0)
82
+ _, labels, centers = cv2.kmeans(
83
+ pixels, 3, None, criteria, 1, cv2.KMEANS_RAND_CENTERS
84
+ )
85
+
86
+ counts = np.bincount(labels.flatten())
87
+ dominant_rgb = centers[np.argmax(counts)].astype(int)
88
 
89
+ hex_color = f"#{dominant_rgb[0]:02x}{dominant_rgb[1]:02x}{dominant_rgb[2]:02x}"
90
  basic_color = closest_perceptual_color(tuple(dominant_rgb))
91
 
92
+ img_hsv = cv2.cvtColor(small_rgb, cv2.COLOR_RGB2HSV)
93
  mean_sat = np.mean(img_hsv[:, :, 1]) / 255.0
94
  mean_val = np.mean(img_hsv[:, :, 2]) / 255.0
95
  mean_hue = np.mean(img_hsv[:, :, 0])
 
96
  tone = "Warm" if (mean_hue < 45 or mean_hue > 135) else "Cool"
97
 
98
  return {
 
104
  }
105
 
106
 
107
+ def analyze_face_crop(face_crop):
108
+ """Analyzes a cropped face patch using DeepFace without running heavy face detection again."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  try:
110
+ # Pass detector_backend='skip' to bypass DeepFace's slow face detection stage
111
  results = DeepFace.analyze(
112
+ face_crop,
113
+ actions=["age", "gender"],
114
  enforce_detection=False,
115
+ detector_backend="skip",
116
  silent=True,
117
  )
118
+ if isinstance(results, list):
119
+ results = results[0]
120
+
121
+ gender_data = results.get("gender")
122
+ if isinstance(gender_data, dict):
123
+ dominant_gender = max(gender_data, key=gender_data.get)
124
+ conf = gender_data[dominant_gender]
125
+ else:
126
+ dominant_gender = str(gender_data)
127
+ conf = 100.0
128
+
129
+ return {
130
+ "age": results.get("age", 0),
131
+ "gender": dominant_gender,
132
+ "gender_conf": conf,
133
+ }
 
 
 
 
 
 
134
  except Exception:
135
+ return None
136
 
137
 
 
 
 
138
  def build_summary_plots(df):
139
  plots = []
140
 
 
146
  return Image.open(buf)
147
 
148
  # Plot 1: Color Distribution
149
+ fig1, ax1 = plt.subplots(figsize=(5, 3))
150
  if not df.empty and "Basic Color" in df:
151
  df["Basic Color"].value_counts().plot(
152
  kind="bar", ax=ax1, color="skyblue"
 
155
  plots.append(fig_to_pil(fig1))
156
 
157
  # Plot 2: Top Objects
158
+ fig2, ax2 = plt.subplots(figsize=(5, 3))
159
  if not df.empty and "Detected Objects (Summary)" in df:
160
  all_objects = []
161
  for item in df["Detected Objects (Summary)"]:
 
165
  if len(parts) == 2:
166
  all_objects.extend([parts[1]] * int(parts[0]))
167
  if all_objects:
168
+ pd.Series(all_objects).value_counts().head(10).plot(
169
  kind="barh", ax=ax2, color="salmon"
170
  )
171
  ax2.invert_yaxis()
172
+ ax2.set_title("Top Detected Objects")
173
  plots.append(fig_to_pil(fig2))
174
 
175
  # Plot 3 & 4: Demographic parsing
 
188
  else:
189
  ages_women.append(f["age"])
190
 
191
+ fig3, ax3 = plt.subplots(figsize=(5, 3))
192
  ax3.bar(
193
  gender_counts.keys(), gender_counts.values(), color=["lightblue", "pink"]
194
  )
195
+ ax3.set_title("Gender Distribution")
196
  plots.append(fig_to_pil(fig3))
197
 
198
+ fig4, ax4 = plt.subplots(figsize=(5, 3))
199
  ax4.hist(
200
  [ages_men, ages_women],
201
  bins=range(0, 101, 10),
202
  color=["lightblue", "pink"],
203
  label=["Men", "Women"],
204
  )
205
+ ax4.set_title("Age Distribution")
206
  ax4.legend()
207
  plots.append(fig_to_pil(fig4))
208
 
209
  return plots
210
 
211
 
212
+ def _run_processing(zip_file, batch_size=16):
 
 
 
213
  if zip_file is None:
214
  return None, None, [], None, None, None, None
215
 
216
  results = []
217
  annotated_thumbnails = []
218
  zip_basename = os.path.splitext(os.path.basename(zip_file.name))[0]
219
+ device = "cuda" if torch.cuda.is_available() else "cpu"
220
 
221
  with tempfile.TemporaryDirectory() as tmpdir:
222
  with zipfile.ZipFile(zip_file.name, "r") as zip_ref:
 
230
  ):
231
  image_paths.append(os.path.join(root, fname))
232
 
233
+ # Process images in dynamic batches
234
+ for i in range(0, len(image_paths), batch_size):
235
+ batch_paths = image_paths[i : i + batch_size]
236
+ batch_imgs = []
237
+ valid_paths = []
238
+
239
+ for p in batch_paths:
240
+ try:
241
+ img = Image.open(p).convert("RGB")
242
+ batch_imgs.append(np.array(img))
243
+ valid_paths.append(p)
244
+ except Exception:
245
+ continue
246
+
247
+ if not batch_imgs:
248
  continue
249
 
250
+ # Run YOLO batch inference
251
+ yolo_results = yolo_model.predict(
252
+ batch_imgs, conf=0.35, verbose=False, device=device, imgsz=480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  )
254
 
255
+ for idx, yolo_res in enumerate(yolo_results):
256
+ fname = os.path.basename(valid_paths[idx])
257
+ img_np = batch_imgs[idx]
258
+
259
+ # Extract objects
260
+ detected_counts = {}
261
+ items_detail = []
262
+ person_crops = []
263
+
264
+ for box in yolo_res.boxes:
265
+ cls_id = int(box.cls[0])
266
+ cls_name = yolo_model.names[cls_id]
267
+ conf = float(box.conf[0])
268
+
269
+ detected_counts[cls_name] = (
270
+ detected_counts.get(cls_name, 0) + 1
271
+ )
272
+ items_detail.append(f"{cls_name} ({conf:.0%})")
273
+
274
+ # If YOLO detects a person, extract the crop directly for DeepFace
275
+ if cls_name == "person":
276
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
277
+ crop = img_np[y1:y2, x1:x2]
278
+ if crop.size > 0:
279
+ person_crops.append(crop)
280
+
281
+ summary_str = ", ".join(
282
+ [f"{cnt}x {name}" for name, cnt in detected_counts.items()]
283
+ ) or "None detected"
284
+
285
+ # Generate lightweight bounding box thumbnail
286
+ annotated_bgr = yolo_res.plot()
287
+ annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
288
+ thumb_pil = Image.fromarray(annotated_rgb)
289
+ thumb_pil.thumbnail((250, 250))
290
+ annotated_thumbnails.append(thumb_pil)
291
+
292
+ # Fast color analysis
293
+ color_data = fast_color_analysis(img_np)
294
+
295
+ # DeepFace facial analysis on person crops only
296
+ faces_data = []
297
+ for crop in person_crops[:3]: # Max 3 person crops per image
298
+ face_res = analyze_face_crop(crop)
299
+ if face_res:
300
+ faces_data.append(face_res)
301
+
302
+ results.append(
303
+ {
304
+ "Filename": fname,
305
+ "Detected Objects (Summary)": summary_str,
306
+ "Object Details": ", ".join(items_detail),
307
+ "Dominant Color": color_data["hex"],
308
+ "Basic Color": color_data["basic_color"],
309
+ "Saturation": color_data["saturation"],
310
+ "Brightness": color_data["brightness"],
311
+ "Tone": color_data["tone"],
312
+ "Face Info": faces_data,
313
+ }
314
+ )
315
 
316
+ df = pd.DataFrame(results)
317
  out_xlsx = os.path.join(
318
  tempfile.gettempdir(), f"{zip_basename}_analytics.xlsx"
319
  )
320
  df.to_excel(out_xlsx, index=False)
321
 
322
  p1, p2, p3, p4 = build_summary_plots(df)
 
323
  return df, out_xlsx, annotated_thumbnails, p1, p2, p3, p4
324
 
325
 
 
326
  if HAS_SPACES:
327
  process_zip_archive = spaces.GPU(duration=120)(_run_processing)
328
  else:
329
  process_zip_archive = _run_processing
330
 
331
 
332
+ with gr.Blocks(title="Fast Image Analytics Dashboard") as demo:
333
+ gr.Markdown("# Fast Image Classifier & Visual Analytics")
 
 
 
334
 
335
  with gr.Row():
336
  file_input = gr.File(