Spaces:
Running on Zero

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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -55
app.py CHANGED
@@ -1,15 +1,17 @@
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
15
  import matplotlib.pyplot as plt
@@ -19,7 +21,6 @@ from PIL import Image
19
 
20
  try:
21
  import spaces
22
-
23
  HAS_SPACES = True
24
  except ImportError:
25
  HAS_SPACES = False
@@ -27,6 +28,8 @@ except ImportError:
27
  import torch
28
  import tensorflow as tf
29
 
 
 
30
  gpus = tf.config.list_physical_devices("GPU")
31
  if gpus:
32
  try:
@@ -41,6 +44,11 @@ from ultralytics import YOLO
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),
@@ -74,7 +82,7 @@ def closest_perceptual_color(rgb_tuple):
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
 
@@ -104,35 +112,48 @@ def fast_color_analysis(img_np):
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):
@@ -176,7 +197,7 @@ def build_summary_plots(df):
176
  ages_men, ages_women = [], []
177
  gender_counts = {"Man": 0.0, "Woman": 0.0}
178
 
179
- for face_list in df["Face Info"]:
180
  for f in face_list:
181
  g = f["gender"]
182
  conf = min(f["gender_conf"] / 100.0, 0.9)
@@ -209,7 +230,7 @@ def build_summary_plots(df):
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
 
@@ -230,7 +251,7 @@ def _run_processing(zip_file, batch_size=16):
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 = []
@@ -247,19 +268,17 @@ def _run_processing(zip_file, batch_size=16):
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])
@@ -271,33 +290,22 @@ def _run_processing(zip_file, batch_size=16):
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
  {
 
1
  import os
2
 
3
+ # Prevent Thread Contention & Suppress TensorFlow Overhead
4
  os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
5
  os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
6
+ os.environ["OMP_NUM_THREADS"] = "1"
7
 
8
  import io
9
  import tempfile
10
  import zipfile
11
  import cv2
12
 
13
+ # Restrict threads inside sub-processes to prevent ZeroGPU deadlocks
14
+ cv2.setNumThreads(1)
15
 
16
  import gradio as gr
17
  import matplotlib.pyplot as plt
 
21
 
22
  try:
23
  import spaces
 
24
  HAS_SPACES = True
25
  except ImportError:
26
  HAS_SPACES = False
 
28
  import torch
29
  import tensorflow as tf
30
 
31
+ torch.set_num_threads(1)
32
+
33
  gpus = tf.config.list_physical_devices("GPU")
34
  if gpus:
35
  try:
 
44
  # Load lightweight YOLO model
45
  yolo_model = YOLO("yolov8n.pt")
46
 
47
+ # Load lightweight OpenCV Face Detector for fast face extraction
48
+ face_cascade = cv2.CascadeClassifier(
49
+ cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
50
+ )
51
+
52
  BASIC_COLOR_LAB = {
53
  "Red": (53, 80, 67),
54
  "Green": (87, -86, 83),
 
82
 
83
 
84
  def fast_color_analysis(img_np):
85
+ """Vectorized fast color analysis on a small downsampled array."""
86
  small_rgb = cv2.resize(img_np, (64, 64))
87
  pixels = np.float32(small_rgb.reshape(-1, 3))
88
 
 
112
  }
113
 
114
 
115
+ def extract_and_analyze_faces(img_np):
116
+ """Detects faces fast via OpenCV Haar Cascades and runs DeepFace only on valid face crops."""
117
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
118
+ faces = face_cascade.detectMultiScale(
119
+ gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
120
+ )
121
+
122
+ faces_data = []
123
+ for x, y, w, h in faces[:3]: # Limit to max 3 faces per image for speed
124
+ face_crop = img_np[y : y + h, x : x + w]
125
+ if face_crop.size == 0:
126
+ continue
127
+ try:
128
+ results = DeepFace.analyze(
129
+ face_crop,
130
+ actions=["age", "gender"],
131
+ enforce_detection=False,
132
+ detector_backend="skip",
133
+ silent=True,
134
+ )
135
+ if isinstance(results, list):
136
+ results = results[0]
137
+
138
+ gender_data = results.get("gender")
139
+ if isinstance(gender_data, dict):
140
+ dominant_gender = max(gender_data, key=gender_data.get)
141
+ conf = gender_data[dominant_gender]
142
+ else:
143
+ dominant_gender = str(gender_data)
144
+ conf = 100.0
145
+
146
+ faces_data.append(
147
+ {
148
+ "age": results.get("age", 0),
149
+ "gender": dominant_gender,
150
+ "gender_conf": conf,
151
+ }
152
+ )
153
+ except Exception:
154
+ continue
155
+
156
+ return faces_data
157
 
158
 
159
  def build_summary_plots(df):
 
197
  ages_men, ages_women = [], []
198
  gender_counts = {"Man": 0.0, "Woman": 0.0}
199
 
200
+ for face_list in df.get("Face Info", []):
201
  for f in face_list:
202
  g = f["gender"]
203
  conf = min(f["gender_conf"] / 100.0, 0.9)
 
230
  return plots
231
 
232
 
233
+ def _run_processing(zip_file, batch_size=8):
234
  if zip_file is None:
235
  return None, None, [], None, None, None, None
236
 
 
251
  ):
252
  image_paths.append(os.path.join(root, fname))
253
 
254
+ # Process in batch chunks
255
  for i in range(0, len(image_paths), batch_size):
256
  batch_paths = image_paths[i : i + batch_size]
257
  batch_imgs = []
 
268
  if not batch_imgs:
269
  continue
270
 
271
+ # Run YOLO batch prediction
272
  yolo_results = yolo_model.predict(
273
+ batch_imgs, conf=0.35, verbose=False, device=device, imgsz=320
274
  )
275
 
276
  for idx, yolo_res in enumerate(yolo_results):
277
  fname = os.path.basename(valid_paths[idx])
278
  img_np = batch_imgs[idx]
279
 
 
280
  detected_counts = {}
281
  items_detail = []
 
282
 
283
  for box in yolo_res.boxes:
284
  cls_id = int(box.cls[0])
 
290
  )
291
  items_detail.append(f"{cls_name} ({conf:.0%})")
292
 
 
 
 
 
 
 
 
293
  summary_str = ", ".join(
294
  [f"{cnt}x {name}" for name, cnt in detected_counts.items()]
295
  ) or "None detected"
296
 
297
+ # Generate lightweight thumbnail
298
  annotated_bgr = yolo_res.plot()
299
  annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
300
  thumb_pil = Image.fromarray(annotated_rgb)
301
+ thumb_pil.thumbnail((200, 200))
302
  annotated_thumbnails.append(thumb_pil)
303
 
304
  # Fast color analysis
305
  color_data = fast_color_analysis(img_np)
306
 
307
+ # Fast face detection + DeepFace demographic analysis
308
+ faces_data = extract_and_analyze_faces(img_np)
 
 
 
 
309
 
310
  results.append(
311
  {