Spaces:
Running on Zero

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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -19
app.py CHANGED
@@ -1,9 +1,20 @@
1
- import io
2
  import os
 
 
 
 
 
 
 
 
 
3
  import tempfile
4
  import zipfile
5
 
6
  import cv2
 
 
 
7
  import gradio as gr
8
  import matplotlib.pyplot as plt
9
  import numpy as np
@@ -11,7 +22,7 @@ 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
@@ -21,30 +32,23 @@ except ImportError:
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
@@ -122,10 +126,13 @@ def analyze_advanced_colors(image_pil, num_colors=3):
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 = {}
@@ -204,6 +211,7 @@ def build_summary_plots(df):
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,6 +220,7 @@ def build_summary_plots(df):
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,6 +238,7 @@ def build_summary_plots(df):
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
 
@@ -268,7 +278,6 @@ def build_summary_plots(df):
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
@@ -338,7 +347,7 @@ else:
338
 
339
 
340
  # ---------------------------
341
- # Gradio Blocks UI
342
  # ---------------------------
343
  with gr.Blocks(title="Advanced Image Analytics Dashboard") as demo:
344
  gr.Markdown("# Advanced Image Classifier & Visual Analytics")
@@ -382,5 +391,4 @@ with gr.Blocks(title="Advanced Image Analytics Dashboard") as demo:
382
  )
383
 
384
  if __name__ == "__main__":
385
- # Simplified launch for HF Space environment
386
  demo.queue().launch()
 
 
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
19
  import matplotlib.pyplot as plt
20
  import numpy as np
 
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
 
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:
39
  for gpu in gpus:
40
  tf.config.experimental.set_memory_growth(gpu, True)
41
+ except Exception:
42
+ pass
43
 
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
 
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 = {}
 
211
  buf.seek(0)
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(
 
220
  ax1.set_title("Basic Color Frequency")
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 = []
 
238
  ax2.set_title("Top Detected Object Frequency")
239
  plots.append(fig_to_pil(fig2))
240
 
241
+ # Plot 3 & 4: Demographic parsing
242
  ages_men, ages_women = [], []
243
  gender_counts = {"Man": 0.0, "Woman": 0.0}
244
 
 
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
 
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")
 
391
  )
392
 
393
  if __name__ == "__main__":
 
394
  demo.queue().launch()