Spaces:
Running on Zero

clementBE commited on
Commit
4ac7aea
·
verified ·
1 Parent(s): 1bce0ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -28
app.py CHANGED
@@ -8,21 +8,47 @@ import gradio as gr
8
  import matplotlib.pyplot as plt
9
  import numpy as np
10
  import pandas as pd
11
- from deepface import DeepFace
12
  from PIL import Image
13
  from sklearn.cluster import KMeans
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  from ultralytics import YOLO
15
 
 
 
 
 
16
  # ---------------------------
17
  # Load YOLOv8 for Object Detection
18
  # ---------------------------
19
- # Options: yolov8n.pt (fastest), yolov8m.pt (medium/accurate), yolov8x.pt (highest precision)
20
  yolo_model = YOLO("yolov8m.pt")
 
21
 
22
  # ---------------------------
23
  # Perceptual CIELAB Color Mapping
24
  # ---------------------------
25
- # Target colors defined in CIELAB space for perceptual human accuracy
26
  BASIC_COLOR_LAB = {
27
  "Red": (53, 80, 67),
28
  "Green": (87, -86, 83),
@@ -39,7 +65,7 @@ BASIC_COLOR_LAB = {
39
 
40
 
41
  def closest_perceptual_color(rgb_tuple):
42
- """Finds the closest human-perceived color using CIELAB distance (Delta E)."""
43
  rgb_pixel = np.uint8([[list(rgb_tuple)]])
44
  lab_pixel = cv2.cvtColor(rgb_pixel, cv2.COLOR_RGB2LAB)[0][0]
45
 
@@ -64,25 +90,22 @@ def closest_perceptual_color(rgb_tuple):
64
 
65
 
66
  def analyze_advanced_colors(image_pil, num_colors=3):
67
- """Extracts dominant hex, CIELAB basic color, HSV saturation, brightness, and tone."""
68
  img_rgb = np.array(image_pil.resize((150, 150)).convert("RGB"))
69
  pixels = img_rgb.reshape(-1, 3)
70
 
71
- # 1. K-Means Clustering for Dominant RGB
72
  kmeans = KMeans(n_clusters=num_colors, n_init=3, random_state=42)
73
  kmeans.fit(pixels)
74
  counts = np.bincount(kmeans.labels_)
75
  dominant_rgb = kmeans.cluster_centers_[np.argmax(counts)].astype(int)
76
  hex_color = f"#{dominant_rgb[0]:02x}{dominant_rgb[1]:02x}{dominant_rgb[2]:02x}"
77
 
78
- # 2. Perceptual Basic Color
79
  basic_color = closest_perceptual_color(tuple(dominant_rgb))
80
 
81
- # 3. HSV Channel Metrics
82
  img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)
83
  mean_sat = np.mean(img_hsv[:, :, 1]) / 255.0
84
  mean_val = np.mean(img_hsv[:, :, 2]) / 255.0
85
- mean_hue = np.mean(img_hsv[:, :, 0]) # Hue is 0-180 in OpenCV
86
 
87
  tone = "Warm" if (mean_hue < 45 or mean_hue > 135) else "Cool"
88
 
@@ -99,14 +122,15 @@ def analyze_advanced_colors(image_pil, num_colors=3):
99
  # Object Detection & Bounding Boxes
100
  # ---------------------------
101
  def detect_objects_yolo(image_pil, conf_threshold=0.35):
102
- """Runs YOLOv8 object detection and produces bounding-boxed thumbnail visualization."""
103
  img_np = np.array(image_pil)
104
- results = yolo_model(img_np, conf=conf_threshold, verbose=False)[0]
 
 
105
 
106
  detected_counts = {}
107
  items_detail = []
108
 
109
- # Process detections
110
  for box in results.boxes:
111
  cls_id = int(box.cls[0])
112
  cls_name = yolo_model.names[cls_id]
@@ -121,7 +145,6 @@ def detect_objects_yolo(image_pil, conf_threshold=0.35):
121
  if not summary_str:
122
  summary_str = "None detected"
123
 
124
- # Render image with bounding box overlays for thumbnail
125
  annotated_bgr = results.plot()
126
  annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
127
  annotated_pil = Image.fromarray(annotated_rgb)
@@ -133,7 +156,7 @@ def detect_objects_yolo(image_pil, conf_threshold=0.35):
133
  # Safe Face Analysis
134
  # ---------------------------
135
  def analyze_faces_safely(image_pil):
136
- """Analyzes faces while accommodating DeepFace API version variance."""
137
  try:
138
  img_cv2 = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
139
  results = DeepFace.analyze(
@@ -181,7 +204,6 @@ def build_summary_plots(df):
181
  buf.seek(0)
182
  return Image.open(buf)
183
 
184
- # Plot 1: Color Distribution
185
  fig1, ax1 = plt.subplots(figsize=(6, 4))
186
  if not df.empty and "Basic Color" in df:
187
  df["Basic Color"].value_counts().plot(
@@ -190,7 +212,6 @@ def build_summary_plots(df):
190
  ax1.set_title("Basic Color Frequency")
191
  plots.append(fig_to_pil(fig1))
192
 
193
- # Plot 2: Top Detected Objects
194
  fig2, ax2 = plt.subplots(figsize=(6, 4))
195
  if not df.empty and "Detected Objects (Summary)" in df:
196
  all_objects = []
@@ -208,7 +229,6 @@ def build_summary_plots(df):
208
  ax2.set_title("Top Detected Object Frequency")
209
  plots.append(fig_to_pil(fig2))
210
 
211
- # Parse Face Data
212
  ages_men, ages_women = [], []
213
  gender_counts = {"Man": 0.0, "Woman": 0.0}
214
 
@@ -224,7 +244,6 @@ def build_summary_plots(df):
224
  else:
225
  ages_women.append(f["age"])
226
 
227
- # Plot 3: Gender Distribution
228
  fig3, ax3 = plt.subplots(figsize=(6, 4))
229
  ax3.bar(
230
  gender_counts.keys(), gender_counts.values(), color=["lightblue", "pink"]
@@ -232,7 +251,6 @@ def build_summary_plots(df):
232
  ax3.set_title("Gender Distribution (Weighted)")
233
  plots.append(fig_to_pil(fig3))
234
 
235
- # Plot 4: Age Distribution
236
  fig4, ax4 = plt.subplots(figsize=(6, 4))
237
  ax4.hist(
238
  [ages_men, ages_women],
@@ -250,7 +268,8 @@ def build_summary_plots(df):
250
  # ---------------------------
251
  # Core Processing Pipeline
252
  # ---------------------------
253
- def process_zip_archive(zip_file):
 
254
  if zip_file is None:
255
  return None, None, [], None, None, None, None
256
 
@@ -277,17 +296,12 @@ def process_zip_archive(zip_file):
277
  except Exception:
278
  continue
279
 
280
- # Object Detection
281
  obj_summary, obj_details, bbox_thumb = detect_objects_yolo(image)
282
 
283
- # Store thumbnail with bounding boxes
284
  bbox_thumb.thumbnail((300, 300))
285
  annotated_thumbnails.append(bbox_thumb)
286
 
287
- # Perceptual Color Analysis
288
  color_data = analyze_advanced_colors(image)
289
-
290
- # Facial Analytics
291
  faces_data = analyze_faces_safely(image)
292
 
293
  results.append(
@@ -306,18 +320,23 @@ def process_zip_archive(zip_file):
306
 
307
  df = pd.DataFrame(results)
308
 
309
- # Save Excel report
310
  out_xlsx = os.path.join(
311
  tempfile.gettempdir(), f"{zip_basename}_analytics.xlsx"
312
  )
313
  df.to_excel(out_xlsx, index=False)
314
 
315
- # Generate charts
316
  p1, p2, p3, p4 = build_summary_plots(df)
317
 
318
  return df, out_xlsx, annotated_thumbnails, p1, p2, p3, p4
319
 
320
 
 
 
 
 
 
 
 
321
  # ---------------------------
322
  # Gradio Blocks UI
323
  # ---------------------------
@@ -363,4 +382,5 @@ with gr.Blocks(title="Advanced Image Analytics Dashboard") as demo:
363
  )
364
 
365
  if __name__ == "__main__":
366
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
8
  import matplotlib.pyplot as plt
9
  import numpy as np
10
  import pandas as pd
 
11
  from PIL import Image
12
  from sklearn.cluster import KMeans
13
+
14
+ # Hugging Face ZeroGPU support
15
+ try:
16
+ import spaces
17
+ HAS_SPACES = True
18
+ except ImportError:
19
+ HAS_SPACES = False
20
+
21
+ import torch
22
+ import tensorflow as tf
23
+
24
+ # ---------------------------
25
+ # GPU Memory Management Fix
26
+ # ---------------------------
27
+ # Prevent TensorFlow (DeepFace) from pre-allocating 100% of GPU VRAM
28
+ gpus = tf.config.list_physical_devices("GPU")
29
+ if gpus:
30
+ try:
31
+ for gpu in gpus:
32
+ tf.config.experimental.set_memory_growth(gpu, True)
33
+ except RuntimeError as e:
34
+ print(f"TensorFlow GPU setup notice: {e}")
35
+
36
+ from deepface import DeepFace
37
  from ultralytics import YOLO
38
 
39
+ # Detect runtime hardware device
40
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
41
+ print(f"Running pipeline on device: {DEVICE}")
42
+
43
  # ---------------------------
44
  # Load YOLOv8 for Object Detection
45
  # ---------------------------
 
46
  yolo_model = YOLO("yolov8m.pt")
47
+ yolo_model.to(DEVICE)
48
 
49
  # ---------------------------
50
  # Perceptual CIELAB Color Mapping
51
  # ---------------------------
 
52
  BASIC_COLOR_LAB = {
53
  "Red": (53, 80, 67),
54
  "Green": (87, -86, 83),
 
65
 
66
 
67
  def closest_perceptual_color(rgb_tuple):
68
+ """Finds closest color in CIELAB space."""
69
  rgb_pixel = np.uint8([[list(rgb_tuple)]])
70
  lab_pixel = cv2.cvtColor(rgb_pixel, cv2.COLOR_RGB2LAB)[0][0]
71
 
 
90
 
91
 
92
  def analyze_advanced_colors(image_pil, num_colors=3):
93
+ """Extracts dominant hex, basic color, HSV saturation, brightness, and tone."""
94
  img_rgb = np.array(image_pil.resize((150, 150)).convert("RGB"))
95
  pixels = img_rgb.reshape(-1, 3)
96
 
 
97
  kmeans = KMeans(n_clusters=num_colors, n_init=3, random_state=42)
98
  kmeans.fit(pixels)
99
  counts = np.bincount(kmeans.labels_)
100
  dominant_rgb = kmeans.cluster_centers_[np.argmax(counts)].astype(int)
101
  hex_color = f"#{dominant_rgb[0]:02x}{dominant_rgb[1]:02x}{dominant_rgb[2]:02x}"
102
 
 
103
  basic_color = closest_perceptual_color(tuple(dominant_rgb))
104
 
 
105
  img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)
106
  mean_sat = np.mean(img_hsv[:, :, 1]) / 255.0
107
  mean_val = np.mean(img_hsv[:, :, 2]) / 255.0
108
+ mean_hue = np.mean(img_hsv[:, :, 0])
109
 
110
  tone = "Warm" if (mean_hue < 45 or mean_hue > 135) else "Cool"
111
 
 
122
  # Object Detection & Bounding Boxes
123
  # ---------------------------
124
  def detect_objects_yolo(image_pil, conf_threshold=0.35):
125
+ """Runs YOLOv8 object detection targeting GPU device."""
126
  img_np = np.array(image_pil)
127
+ results = yolo_model(
128
+ img_np, conf=conf_threshold, verbose=False, device=DEVICE
129
+ )[0]
130
 
131
  detected_counts = {}
132
  items_detail = []
133
 
 
134
  for box in results.boxes:
135
  cls_id = int(box.cls[0])
136
  cls_name = yolo_model.names[cls_id]
 
145
  if not summary_str:
146
  summary_str = "None detected"
147
 
 
148
  annotated_bgr = results.plot()
149
  annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
150
  annotated_pil = Image.fromarray(annotated_rgb)
 
156
  # Safe Face Analysis
157
  # ---------------------------
158
  def analyze_faces_safely(image_pil):
159
+ """Analyzes faces via DeepFace with fallback exception handling."""
160
  try:
161
  img_cv2 = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
162
  results = DeepFace.analyze(
 
204
  buf.seek(0)
205
  return Image.open(buf)
206
 
 
207
  fig1, ax1 = plt.subplots(figsize=(6, 4))
208
  if not df.empty and "Basic Color" in df:
209
  df["Basic Color"].value_counts().plot(
 
212
  ax1.set_title("Basic Color Frequency")
213
  plots.append(fig_to_pil(fig1))
214
 
 
215
  fig2, ax2 = plt.subplots(figsize=(6, 4))
216
  if not df.empty and "Detected Objects (Summary)" in df:
217
  all_objects = []
 
229
  ax2.set_title("Top Detected Object Frequency")
230
  plots.append(fig_to_pil(fig2))
231
 
 
232
  ages_men, ages_women = [], []
233
  gender_counts = {"Man": 0.0, "Woman": 0.0}
234
 
 
244
  else:
245
  ages_women.append(f["age"])
246
 
 
247
  fig3, ax3 = plt.subplots(figsize=(6, 4))
248
  ax3.bar(
249
  gender_counts.keys(), gender_counts.values(), color=["lightblue", "pink"]
 
251
  ax3.set_title("Gender Distribution (Weighted)")
252
  plots.append(fig_to_pil(fig3))
253
 
 
254
  fig4, ax4 = plt.subplots(figsize=(6, 4))
255
  ax4.hist(
256
  [ages_men, ages_women],
 
268
  # ---------------------------
269
  # Core Processing Pipeline
270
  # ---------------------------
271
+ # Wrapper function to support ZeroGPU allocation on HF Spaces
272
+ def _run_processing(zip_file):
273
  if zip_file is None:
274
  return None, None, [], None, None, None, None
275
 
 
296
  except Exception:
297
  continue
298
 
 
299
  obj_summary, obj_details, bbox_thumb = detect_objects_yolo(image)
300
 
 
301
  bbox_thumb.thumbnail((300, 300))
302
  annotated_thumbnails.append(bbox_thumb)
303
 
 
304
  color_data = analyze_advanced_colors(image)
 
 
305
  faces_data = analyze_faces_safely(image)
306
 
307
  results.append(
 
320
 
321
  df = pd.DataFrame(results)
322
 
 
323
  out_xlsx = os.path.join(
324
  tempfile.gettempdir(), f"{zip_basename}_analytics.xlsx"
325
  )
326
  df.to_excel(out_xlsx, index=False)
327
 
 
328
  p1, p2, p3, p4 = build_summary_plots(df)
329
 
330
  return df, out_xlsx, annotated_thumbnails, p1, p2, p3, p4
331
 
332
 
333
+ # Apply HF ZeroGPU decorator if available
334
+ if HAS_SPACES:
335
+ process_zip_archive = spaces.GPU(duration=120)(_run_processing)
336
+ else:
337
+ process_zip_archive = _run_processing
338
+
339
+
340
  # ---------------------------
341
  # Gradio Blocks UI
342
  # ---------------------------
 
382
  )
383
 
384
  if __name__ == "__main__":
385
+ # Simplified launch for HF Space environment
386
+ demo.queue().launch()