Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,382 +1,272 @@
|
|
| 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
|
| 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
|
| 18 |
import numpy as np
|
| 19 |
import pandas as pd
|
| 20 |
from PIL import Image
|
| 21 |
-
|
| 22 |
-
try:
|
| 23 |
-
import spaces
|
| 24 |
-
HAS_SPACES = True
|
| 25 |
-
except ImportError:
|
| 26 |
-
HAS_SPACES = False
|
| 27 |
-
|
| 28 |
import torch
|
| 29 |
-
import
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
if gpus:
|
| 35 |
-
try:
|
| 36 |
-
for gpu in gpus:
|
| 37 |
-
tf.config.experimental.set_memory_growth(gpu, True)
|
| 38 |
-
except Exception:
|
| 39 |
-
pass
|
| 40 |
|
|
|
|
| 41 |
from deepface import DeepFace
|
| 42 |
-
|
| 43 |
-
|
| 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 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
"Black": (0, 0, 0),
|
| 62 |
-
"White": (
|
| 63 |
-
"Gray": (
|
| 64 |
}
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
rgb_pixel = np.uint8([[list(rgb_tuple)]])
|
| 69 |
-
lab_pixel = cv2.cvtColor(rgb_pixel, cv2.COLOR_RGB2LAB)[0][0]
|
| 70 |
-
|
| 71 |
min_dist = float("inf")
|
| 72 |
-
|
| 73 |
-
for name,
|
| 74 |
-
dist =
|
| 75 |
-
np.array(lab_pixel, dtype=float) - np.array(target_lab, dtype=float)
|
| 76 |
-
)
|
| 77 |
if dist < min_dist:
|
| 78 |
min_dist = dist
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
hex_color = f"#{dominant_rgb[0]:02x}{dominant_rgb[1]:02x}{dominant_rgb[2]:02x}"
|
| 98 |
-
basic_color = closest_perceptual_color(tuple(dominant_rgb))
|
| 99 |
-
|
| 100 |
-
img_hsv = cv2.cvtColor(small_rgb, cv2.COLOR_RGB2HSV)
|
| 101 |
-
mean_sat = np.mean(img_hsv[:, :, 1]) / 255.0
|
| 102 |
-
mean_val = np.mean(img_hsv[:, :, 2]) / 255.0
|
| 103 |
-
mean_hue = np.mean(img_hsv[:, :, 0])
|
| 104 |
-
tone = "Warm" if (mean_hue < 45 or mean_hue > 135) else "Cool"
|
| 105 |
-
|
| 106 |
-
return {
|
| 107 |
-
"hex": hex_color,
|
| 108 |
-
"basic_color": basic_color,
|
| 109 |
-
"saturation": f"{mean_sat:.1%}",
|
| 110 |
-
"brightness": f"{mean_val:.1%}",
|
| 111 |
-
"tone": tone,
|
| 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):
|
| 160 |
-
plots = []
|
| 161 |
-
|
| 162 |
-
def fig_to_pil(fig):
|
| 163 |
-
buf = io.BytesIO()
|
| 164 |
-
plt.savefig(buf, format="png", bbox_inches="tight")
|
| 165 |
-
plt.close(fig)
|
| 166 |
-
buf.seek(0)
|
| 167 |
-
return Image.open(buf)
|
| 168 |
-
|
| 169 |
-
# Plot 1: Color Distribution
|
| 170 |
-
fig1, ax1 = plt.subplots(figsize=(5, 3))
|
| 171 |
-
if not df.empty and "Basic Color" in df:
|
| 172 |
-
df["Basic Color"].value_counts().plot(
|
| 173 |
-
kind="bar", ax=ax1, color="skyblue"
|
| 174 |
-
)
|
| 175 |
-
ax1.set_title("Basic Color Frequency")
|
| 176 |
-
plots.append(fig_to_pil(fig1))
|
| 177 |
-
|
| 178 |
-
# Plot 2: Top Objects
|
| 179 |
-
fig2, ax2 = plt.subplots(figsize=(5, 3))
|
| 180 |
-
if not df.empty and "Detected Objects (Summary)" in df:
|
| 181 |
-
all_objects = []
|
| 182 |
-
for item in df["Detected Objects (Summary)"]:
|
| 183 |
-
if item != "None detected":
|
| 184 |
-
for sub in item.split(", "):
|
| 185 |
-
parts = sub.split("x ")
|
| 186 |
-
if len(parts) == 2:
|
| 187 |
-
all_objects.extend([parts[1]] * int(parts[0]))
|
| 188 |
-
if all_objects:
|
| 189 |
-
pd.Series(all_objects).value_counts().head(10).plot(
|
| 190 |
-
kind="barh", ax=ax2, color="salmon"
|
| 191 |
-
)
|
| 192 |
-
ax2.invert_yaxis()
|
| 193 |
-
ax2.set_title("Top Detected Objects")
|
| 194 |
-
plots.append(fig_to_pil(fig2))
|
| 195 |
-
|
| 196 |
-
# Plot 3 & 4: Demographic parsing
|
| 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)
|
| 204 |
-
if g in gender_counts:
|
| 205 |
-
gender_counts[g] += conf
|
| 206 |
-
|
| 207 |
-
if g.lower() in ["man", "male"]:
|
| 208 |
-
ages_men.append(f["age"])
|
| 209 |
-
else:
|
| 210 |
-
ages_women.append(f["age"])
|
| 211 |
-
|
| 212 |
-
fig3, ax3 = plt.subplots(figsize=(5, 3))
|
| 213 |
-
ax3.bar(
|
| 214 |
-
gender_counts.keys(), gender_counts.values(), color=["lightblue", "pink"]
|
| 215 |
-
)
|
| 216 |
-
ax3.set_title("Gender Distribution")
|
| 217 |
-
plots.append(fig_to_pil(fig3))
|
| 218 |
-
|
| 219 |
-
fig4, ax4 = plt.subplots(figsize=(5, 3))
|
| 220 |
-
ax4.hist(
|
| 221 |
-
[ages_men, ages_women],
|
| 222 |
-
bins=range(0, 101, 10),
|
| 223 |
-
color=["lightblue", "pink"],
|
| 224 |
-
label=["Men", "Women"],
|
| 225 |
-
)
|
| 226 |
-
ax4.set_title("Age Distribution")
|
| 227 |
-
ax4.legend()
|
| 228 |
-
plots.append(fig_to_pil(fig4))
|
| 229 |
-
|
| 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 |
-
|
| 237 |
results = []
|
| 238 |
-
|
|
|
|
|
|
|
| 239 |
zip_basename = os.path.splitext(os.path.basename(zip_file.name))[0]
|
| 240 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 241 |
|
| 242 |
with tempfile.TemporaryDirectory() as tmpdir:
|
| 243 |
-
with zipfile.ZipFile(zip_file.name,
|
| 244 |
zip_ref.extractall(tmpdir)
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
if fname.lower().endswith(
|
| 250 |
-
(".png", ".jpg", ".jpeg", ".webp", ".bmp")
|
| 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 = []
|
| 258 |
-
valid_paths = []
|
| 259 |
-
|
| 260 |
-
for p in batch_paths:
|
| 261 |
try:
|
| 262 |
-
|
| 263 |
-
batch_imgs.append(np.array(img))
|
| 264 |
-
valid_paths.append(p)
|
| 265 |
except Exception:
|
| 266 |
continue
|
| 267 |
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
yolo_results = yolo_model.predict(
|
| 273 |
-
batch_imgs, conf=0.35, verbose=False, device=device, imgsz=320
|
| 274 |
-
)
|
| 275 |
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
conf = float(box.conf[0])
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
)
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
}
|
| 322 |
-
)
|
| 323 |
-
|
| 324 |
-
df = pd.DataFrame(results)
|
| 325 |
-
out_xlsx = os.path.join(
|
| 326 |
-
tempfile.gettempdir(), f"{zip_basename}_analytics.xlsx"
|
| 327 |
-
)
|
| 328 |
df.to_excel(out_xlsx, index=False)
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
if __name__ == "__main__":
|
| 382 |
-
demo.
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import zipfile
|
| 3 |
+
import tempfile
|
| 4 |
+
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
import pandas as pd
|
| 7 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from torchvision import transforms
|
| 11 |
+
from torchvision.models import resnet50, ResNet50_Weights
|
| 12 |
+
from sklearn.cluster import MiniBatchKMeans
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import io
|
| 15 |
|
| 16 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# Face analysis
|
| 19 |
from deepface import DeepFace
|
| 20 |
+
import cv2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# ---------------------------
|
| 23 |
+
# Force CPU if no CUDA
|
| 24 |
+
# ---------------------------
|
| 25 |
+
if not torch.cuda.is_available():
|
| 26 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 27 |
+
|
| 28 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 29 |
+
|
| 30 |
+
# ---------------------------
|
| 31 |
+
# Load ResNet50
|
| 32 |
+
# ---------------------------
|
| 33 |
+
weights = ResNet50_Weights.DEFAULT
|
| 34 |
+
model = resnet50(weights=weights).to(device)
|
| 35 |
+
model.eval()
|
| 36 |
+
|
| 37 |
+
# ---------------------------
|
| 38 |
+
# Transformations
|
| 39 |
+
# ---------------------------
|
| 40 |
+
transform = transforms.Compose([
|
| 41 |
+
transforms.Resize(256),
|
| 42 |
+
transforms.CenterCrop(224),
|
| 43 |
+
transforms.ToTensor(),
|
| 44 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 45 |
+
std=[0.229, 0.224, 0.225]),
|
| 46 |
+
])
|
| 47 |
+
|
| 48 |
+
# ---------------------------
|
| 49 |
+
# ImageNet labels
|
| 50 |
+
# ---------------------------
|
| 51 |
+
LABELS_URL = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
|
| 52 |
+
imagenet_classes = [line.strip() for line in requests.get(LABELS_URL).text.splitlines()]
|
| 53 |
+
|
| 54 |
+
# ---------------------------
|
| 55 |
+
# Basic color utilities
|
| 56 |
+
# ---------------------------
|
| 57 |
+
BASIC_COLORS = {
|
| 58 |
+
"Red": (255, 0, 0),
|
| 59 |
+
"Green": (0, 255, 0),
|
| 60 |
+
"Blue": (0, 0, 255),
|
| 61 |
+
"Yellow": (255, 255, 0),
|
| 62 |
+
"Cyan": (0, 255, 255),
|
| 63 |
+
"Magenta": (255, 0, 255),
|
| 64 |
"Black": (0, 0, 0),
|
| 65 |
+
"White": (255, 255, 255),
|
| 66 |
+
"Gray": (128, 128, 128),
|
| 67 |
}
|
| 68 |
|
| 69 |
+
def closest_basic_color(rgb):
|
| 70 |
+
r, g, b = rgb
|
|
|
|
|
|
|
|
|
|
| 71 |
min_dist = float("inf")
|
| 72 |
+
closest_color = None
|
| 73 |
+
for name, (cr, cg, cb) in BASIC_COLORS.items():
|
| 74 |
+
dist = (r - cr) ** 2 + (g - cg) ** 2 + (b - cb) ** 2
|
|
|
|
|
|
|
| 75 |
if dist < min_dist:
|
| 76 |
min_dist = dist
|
| 77 |
+
closest_color = name
|
| 78 |
+
return closest_color
|
| 79 |
+
|
| 80 |
+
def get_dominant_color(image, num_colors=5):
|
| 81 |
+
image = image.resize((300, 300))
|
| 82 |
+
pixels = np.array(image).reshape(-1, 3)
|
| 83 |
+
kmeans = MiniBatchKMeans(n_clusters=num_colors, random_state=0, n_init=5)
|
| 84 |
+
kmeans.fit(pixels)
|
| 85 |
+
dominant_color = kmeans.cluster_centers_[np.argmax(np.bincount(kmeans.labels_))]
|
| 86 |
+
dominant_color = tuple(dominant_color.astype(int))
|
| 87 |
+
hex_color = f"#{dominant_color[0]:02x}{dominant_color[1]:02x}{dominant_color[2]:02x}"
|
| 88 |
+
return dominant_color, hex_color
|
| 89 |
+
|
| 90 |
+
# ---------------------------
|
| 91 |
+
# Core function
|
| 92 |
+
# ---------------------------
|
| 93 |
+
def classify_zip_and_analyze_color(zip_file):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
results = []
|
| 95 |
+
thumbnails = []
|
| 96 |
+
|
| 97 |
+
# Name XLSX after zip
|
| 98 |
zip_basename = os.path.splitext(os.path.basename(zip_file.name))[0]
|
|
|
|
| 99 |
|
| 100 |
with tempfile.TemporaryDirectory() as tmpdir:
|
| 101 |
+
with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
|
| 102 |
zip_ref.extractall(tmpdir)
|
| 103 |
|
| 104 |
+
for fname in sorted(os.listdir(tmpdir)):
|
| 105 |
+
if fname.lower().endswith(('.png', '.jpg', '.jpeg')):
|
| 106 |
+
img_path = os.path.join(tmpdir, fname)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
try:
|
| 108 |
+
image = Image.open(img_path).convert("RGB")
|
|
|
|
|
|
|
| 109 |
except Exception:
|
| 110 |
continue
|
| 111 |
|
| 112 |
+
# Thumbnail for gallery (higher-quality)
|
| 113 |
+
thumb = image.copy()
|
| 114 |
+
thumb = thumb.resize((200, 200), Image.LANCZOS)
|
| 115 |
+
thumbnails.append(thumb)
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
# Classification
|
| 118 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 119 |
+
with torch.no_grad():
|
| 120 |
+
output = model(input_tensor)
|
| 121 |
+
probs = F.softmax(output, dim=1)[0]
|
| 122 |
|
| 123 |
+
top3_prob, top3_idx = torch.topk(probs, 3)
|
| 124 |
+
preds = [(imagenet_classes[idx], f"{prob.item()*100:.2f}%") for idx, prob in zip(top3_idx, top3_prob)]
|
| 125 |
|
| 126 |
+
# Dominant color
|
| 127 |
+
rgb, hex_color = get_dominant_color(image)
|
| 128 |
+
basic_color = closest_basic_color(rgb)
|
|
|
|
| 129 |
|
| 130 |
+
# Face detection & characterization
|
| 131 |
+
faces_data = []
|
| 132 |
+
try:
|
| 133 |
+
img_cv2 = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 134 |
+
detected_faces = DeepFace.analyze(
|
| 135 |
+
img_cv2, actions=["age", "gender", "emotion"], enforce_detection=False
|
| 136 |
)
|
| 137 |
+
if isinstance(detected_faces, list):
|
| 138 |
+
for f in detected_faces:
|
| 139 |
+
faces_data.append({
|
| 140 |
+
"age": f["age"],
|
| 141 |
+
"gender": f["gender"],
|
| 142 |
+
"emotion": f["dominant_emotion"]
|
| 143 |
+
})
|
| 144 |
+
else:
|
| 145 |
+
faces_data.append({
|
| 146 |
+
"age": detected_faces["age"],
|
| 147 |
+
"gender": detected_faces["gender"],
|
| 148 |
+
"emotion": detected_faces["dominant_emotion"]
|
| 149 |
+
})
|
| 150 |
+
except Exception:
|
| 151 |
+
faces_data = []
|
| 152 |
+
|
| 153 |
+
results.append((
|
| 154 |
+
fname,
|
| 155 |
+
", ".join([p[0] for p in preds]),
|
| 156 |
+
", ".join([p[1] for p in preds]),
|
| 157 |
+
hex_color,
|
| 158 |
+
basic_color,
|
| 159 |
+
faces_data
|
| 160 |
+
))
|
| 161 |
+
|
| 162 |
+
# Build dataframe
|
| 163 |
+
df = pd.DataFrame(results, columns=["Filename", "Top 3 Predictions", "Confidence", "Dominant Color", "Basic Color", "Face Info"])
|
| 164 |
+
|
| 165 |
+
# Save XLSX
|
| 166 |
+
out_xlsx = os.path.join(tempfile.gettempdir(), f"{zip_basename}_results.xlsx")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
df.to_excel(out_xlsx, index=False)
|
| 168 |
|
| 169 |
+
# ---------------------------
|
| 170 |
+
# Plots
|
| 171 |
+
# ---------------------------
|
| 172 |
+
# 1. Basic color frequency
|
| 173 |
+
fig1, ax1 = plt.subplots()
|
| 174 |
+
color_counts = df["Basic Color"].value_counts()
|
| 175 |
+
ax1.bar(color_counts.index, color_counts.values, color="skyblue")
|
| 176 |
+
ax1.set_title("Basic Color Frequency")
|
| 177 |
+
ax1.set_ylabel("Count")
|
| 178 |
+
buf1 = io.BytesIO()
|
| 179 |
+
plt.savefig(buf1, format="png")
|
| 180 |
+
plt.close(fig1)
|
| 181 |
+
buf1.seek(0)
|
| 182 |
+
plot1_img = Image.open(buf1)
|
| 183 |
+
|
| 184 |
+
# 2. Top prediction distribution
|
| 185 |
+
fig2, ax2 = plt.subplots()
|
| 186 |
+
preds_flat = []
|
| 187 |
+
for p in df["Top 3 Predictions"]:
|
| 188 |
+
preds_flat.extend(p.split(", "))
|
| 189 |
+
pred_counts = pd.Series(preds_flat).value_counts().head(20)
|
| 190 |
+
ax2.barh(pred_counts.index[::-1], pred_counts.values[::-1], color="salmon")
|
| 191 |
+
ax2.set_title("Top Prediction Distribution")
|
| 192 |
+
ax2.set_xlabel("Count")
|
| 193 |
+
buf2 = io.BytesIO()
|
| 194 |
+
plt.savefig(buf2, format="png", bbox_inches="tight")
|
| 195 |
+
plt.close(fig2)
|
| 196 |
+
buf2.seek(0)
|
| 197 |
+
plot2_img = Image.open(buf2)
|
| 198 |
+
|
| 199 |
+
# 3. Gender distribution (weighted)
|
| 200 |
+
ages = []
|
| 201 |
+
gender_confidence = {"Man": 0, "Woman": 0}
|
| 202 |
+
for face_list in df["Face Info"]:
|
| 203 |
+
for face in face_list:
|
| 204 |
+
ages.append(face["age"])
|
| 205 |
+
gender_dict = face["gender"]
|
| 206 |
+
gender = max(gender_dict, key=gender_dict.get)
|
| 207 |
+
conf = float(gender_dict[gender]) / 100
|
| 208 |
+
weight = min(conf, 0.9)
|
| 209 |
+
if gender in gender_confidence:
|
| 210 |
+
gender_confidence[gender] += weight
|
| 211 |
+
else:
|
| 212 |
+
gender_confidence[gender] = weight
|
| 213 |
+
|
| 214 |
+
fig3, ax3 = plt.subplots()
|
| 215 |
+
ax3.bar(gender_confidence.keys(), gender_confidence.values(), color=["lightblue", "pink"])
|
| 216 |
+
ax3.set_title("Gender Distribution (Weighted ≤90%)")
|
| 217 |
+
ax3.set_ylabel("Sum of Confidence")
|
| 218 |
+
buf3 = io.BytesIO()
|
| 219 |
+
plt.savefig(buf3, format="png")
|
| 220 |
+
plt.close(fig3)
|
| 221 |
+
buf3.seek(0)
|
| 222 |
+
plot3_img = Image.open(buf3)
|
| 223 |
+
|
| 224 |
+
# 4. Age distribution by gender
|
| 225 |
+
ages_men = []
|
| 226 |
+
ages_women = []
|
| 227 |
+
for face_list in df["Face Info"]:
|
| 228 |
+
for face in face_list:
|
| 229 |
+
age = face["age"]
|
| 230 |
+
gender_dict = face["gender"]
|
| 231 |
+
gender = max(gender_dict, key=gender_dict.get)
|
| 232 |
+
if gender.lower() == "man":
|
| 233 |
+
ages_men.append(age)
|
| 234 |
+
else:
|
| 235 |
+
ages_women.append(age)
|
| 236 |
+
|
| 237 |
+
fig4, ax4 = plt.subplots()
|
| 238 |
+
bins = range(0, 101, 5)
|
| 239 |
+
ax4.hist([ages_men, ages_women], bins=bins, color=["lightblue", "pink"], label=["Men", "Women"], stacked=False)
|
| 240 |
+
ax4.set_title("Age Distribution by Gender")
|
| 241 |
+
ax4.set_xlabel("Age")
|
| 242 |
+
ax4.set_ylabel("Count")
|
| 243 |
+
ax4.legend()
|
| 244 |
+
buf4 = io.BytesIO()
|
| 245 |
+
plt.savefig(buf4, format="png")
|
| 246 |
+
plt.close(fig4)
|
| 247 |
+
buf4.seek(0)
|
| 248 |
+
plot4_img = Image.open(buf4)
|
| 249 |
+
|
| 250 |
+
return df, out_xlsx, thumbnails, plot1_img, plot2_img, plot3_img, plot4_img
|
| 251 |
+
|
| 252 |
+
# ---------------------------
|
| 253 |
+
# Gradio Interface
|
| 254 |
+
# ---------------------------
|
| 255 |
+
demo = gr.Interface(
|
| 256 |
+
fn=classify_zip_and_analyze_color,
|
| 257 |
+
inputs=gr.File(file_types=[".zip"], label="Upload ZIP of images"),
|
| 258 |
+
outputs=[
|
| 259 |
+
gr.Dataframe(headers=["Filename", "Top 3 Predictions", "Confidence", "Dominant Color", "Basic Color", "Face Info"]),
|
| 260 |
+
gr.File(label="Download XLSX"),
|
| 261 |
+
gr.Gallery(label="Thumbnails", show_label=True, elem_id="thumbnail-gallery", columns=5),
|
| 262 |
+
gr.Image(type="pil", label="Basic Color Frequency"),
|
| 263 |
+
gr.Image(type="pil", label="Top Prediction Distribution"),
|
| 264 |
+
gr.Image(type="pil", label="Gender Distribution (Weighted ≤90%)"),
|
| 265 |
+
gr.Image(type="pil", label="Age Distribution by Gender"),
|
| 266 |
+
],
|
| 267 |
+
title="Image Classifier with Color & Face Analysis",
|
| 268 |
+
description="Upload a ZIP of images. Classifies images, analyzes dominant color, detects faces, and displays thumbnails.",
|
| 269 |
+
)
|
| 270 |
|
| 271 |
if __name__ == "__main__":
|
| 272 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|