Spaces:
Running on Zero

clementBE commited on
Commit
68d7d88
·
verified ·
1 Parent(s): 3ce03b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1194 -185
app.py CHANGED
@@ -1,59 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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),
@@ -66,207 +114,1168 @@ BASIC_COLORS = {
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)
 
 
 
 
 
1
+ # ============================================================
2
+ # ZIP IMAGE ANALYSIS
3
+ # ============================================================
4
+ #
5
+ # Features:
6
+ # 1. Recursive ZIP image extraction
7
+ # 2. ResNet50 ImageNet classification
8
+ # 3. Dominant color detection
9
+ # 4. Face detection with DeepFace
10
+ # 5. Age estimation with DeepFace
11
+ # 6. Face count statistics
12
+ # 7. Diagnostic error reporting
13
+ # 8. XLSX export
14
+ # 9. Gradio interface
15
+ #
16
+ # ============================================================
17
+
18
  import os
19
+ import io
20
  import zipfile
21
  import tempfile
22
+ import traceback
23
+
24
  import numpy as np
25
  import pandas as pd
26
+
27
  from PIL import Image
28
+
29
  import torch
30
  import torch.nn.functional as F
31
+
32
  from torchvision import transforms
33
  from torchvision.models import resnet50, ResNet50_Weights
34
+
35
  from sklearn.cluster import MiniBatchKMeans
36
+
37
  import matplotlib.pyplot as plt
 
38
 
39
  import gradio as gr
40
 
 
41
  from deepface import DeepFace
42
  import cv2
43
 
 
 
 
 
 
44
 
45
+ # ============================================================
46
+ # 1. DEVICE
47
+ # ============================================================
48
+
49
+ if torch.cuda.is_available():
50
+ device = torch.device("cuda")
51
+ else:
52
+ device = torch.device("cpu")
53
+
54
+ print("=" * 70)
55
+ print("IMAGE ANALYSIS APPLICATION")
56
+ print("=" * 70)
57
+ print(f"PyTorch device: {device}")
58
+ print(f"CUDA available: {torch.cuda.is_available()}")
59
+ print("=" * 70)
60
+
61
+
62
+ # ============================================================
63
+ # 2. RESNET50
64
+ # ============================================================
65
+
66
+ print("Loading ResNet50...")
67
 
 
 
 
68
  weights = ResNet50_Weights.DEFAULT
69
+
70
+ model = resnet50(weights=weights)
71
+ model = model.to(device)
72
  model.eval()
73
 
74
+ print("ResNet50 loaded.")
75
+
76
+
77
+ # ============================================================
78
+ # 3. IMAGE TRANSFORMATION
79
+ # ============================================================
80
+
81
  transform = transforms.Compose([
82
  transforms.Resize(256),
83
  transforms.CenterCrop(224),
84
  transforms.ToTensor(),
85
+ transforms.Normalize(
86
+ mean=[0.485, 0.456, 0.406],
87
+ std=[0.229, 0.224, 0.225]
88
+ ),
89
  ])
90
 
 
 
 
 
 
91
 
92
+ # ============================================================
93
+ # 4. IMAGENET LABELS
94
+ # ============================================================
95
+
96
+ imagenet_classes = weights.meta["categories"]
97
+
98
+ print(f"Loaded {len(imagenet_classes)} ImageNet classes.")
99
+
100
+
101
+ # ============================================================
102
+ # 5. COLORS
103
+ # ============================================================
104
+
105
  BASIC_COLORS = {
106
  "Red": (255, 0, 0),
107
  "Green": (0, 255, 0),
 
114
  "Gray": (128, 128, 128),
115
  }
116
 
117
+
118
  def closest_basic_color(rgb):
119
+
120
  r, g, b = rgb
121
+
122
  min_dist = float("inf")
123
  closest_color = None
124
+
125
  for name, (cr, cg, cb) in BASIC_COLORS.items():
126
+
127
+ dist = (
128
+ (r - cr) ** 2 +
129
+ (g - cg) ** 2 +
130
+ (b - cb) ** 2
131
+ )
132
+
133
  if dist < min_dist:
134
  min_dist = dist
135
  closest_color = name
136
+
137
  return closest_color
138
 
139
+
140
+ # ============================================================
141
+ # 6. DOMINANT COLOR
142
+ # ============================================================
143
+
144
  def get_dominant_color(image, num_colors=5):
145
+
146
+ image_small = image.copy()
147
+ image_small.thumbnail((300, 300))
148
+
149
+ pixels = np.array(image_small)
150
+
151
+ if pixels.ndim != 3:
152
+ raise ValueError("Image does not have RGB channels.")
153
+
154
+ pixels = pixels.reshape(-1, 3)
155
+
156
+ # Avoid excessive computation
157
+ if len(pixels) > 50000:
158
+
159
+ rng = np.random.default_rng(0)
160
+
161
+ indices = rng.choice(
162
+ len(pixels),
163
+ size=50000,
164
+ replace=False
165
+ )
166
+
167
+ pixels = pixels[indices]
168
+
169
+ kmeans = MiniBatchKMeans(
170
+ n_clusters=num_colors,
171
+ random_state=0,
172
+ n_init=5
173
+ )
174
+
175
  kmeans.fit(pixels)
176
+
177
+ labels = kmeans.labels_
178
+
179
+ counts = np.bincount(labels)
180
+
181
+ dominant_color = kmeans.cluster_centers_[
182
+ np.argmax(counts)
183
+ ]
184
+
185
+ dominant_color = tuple(
186
+ dominant_color.astype(int)
187
+ )
188
+
189
+ hex_color = (
190
+ f"#{dominant_color[0]:02x}"
191
+ f"{dominant_color[1]:02x}"
192
+ f"{dominant_color[2]:02x}"
193
+ )
194
+
195
  return dominant_color, hex_color
196
 
197
+
198
+ # ============================================================
199
+ # 7. RESNET CLASSIFICATION
200
+ # ============================================================
201
+
202
+ def classify_image(image):
203
+
204
+ input_tensor = transform(image)
205
+
206
+ input_tensor = input_tensor.unsqueeze(0)
207
+
208
+ input_tensor = input_tensor.to(device)
209
+
210
+ with torch.no_grad():
211
+
212
+ output = model(input_tensor)
213
+
214
+ probs = F.softmax(output, dim=1)[0]
215
+
216
+ top3_prob, top3_idx = torch.topk(
217
+ probs,
218
+ 3
219
+ )
220
+
221
+ predictions = []
222
+
223
+ for idx, prob in zip(
224
+ top3_idx,
225
+ top3_prob
226
+ ):
227
+
228
+ idx = int(idx.item())
229
+
230
+ predictions.append({
231
+ "label": imagenet_classes[idx],
232
+ "confidence": float(prob.item() * 100)
233
+ })
234
+
235
+ return predictions
236
+
237
+
238
+ # ============================================================
239
+ # 8. DEEPFACE ANALYSIS
240
+ # ============================================================
241
+
242
+ def analyze_faces(image):
243
+
244
+ """
245
+ Runs DeepFace face analysis.
246
+
247
+ This version deliberately analyzes face presence and age,
248
+ while retaining detailed diagnostic information about errors.
249
+ """
250
+
251
+ result = {
252
+ "faces": [],
253
+ "face_count": 0,
254
+ "error": ""
255
+ }
256
+
257
+ try:
258
+
259
+ img_array = np.array(image)
260
+
261
+ img_cv2 = cv2.cvtColor(
262
+ img_array,
263
+ cv2.COLOR_RGB2BGR
264
+ )
265
+
266
+ analysis = DeepFace.analyze(
267
+
268
+ img_cv2,
269
+
270
+ actions=[
271
+ "age"
272
+ ],
273
+
274
+ enforce_detection=False,
275
+
276
+ detector_backend="opencv",
277
+
278
+ silent=True
279
+ )
280
+
281
+ # DeepFace can return either:
282
+ # dict
283
+ # or
284
+ # list of dicts
285
+
286
+ if isinstance(analysis, dict):
287
+
288
+ analysis = [analysis]
289
+
290
+ elif not isinstance(analysis, list):
291
+
292
+ analysis = []
293
+
294
+ for face in analysis:
295
+
296
+ if not isinstance(face, dict):
297
+ continue
298
+
299
+ age = face.get("age")
300
+
301
+ region = face.get(
302
+ "region",
303
+ {}
304
+ )
305
+
306
+ face_info = {
307
+ "age": age,
308
+ "region": region
309
+ }
310
+
311
+ result["faces"].append(
312
+ face_info
313
+ )
314
+
315
+ result["face_count"] = len(
316
+ result["faces"]
317
+ )
318
+
319
+ except Exception as e:
320
+
321
+ result["error"] = (
322
+ f"{type(e).__name__}: {str(e)}"
323
+ )
324
+
325
+ print(
326
+ "DeepFace error:",
327
+ result["error"]
328
+ )
329
+
330
+ return result
331
+
332
+
333
+ # ============================================================
334
+ # 9. FIND IMAGES RECURSIVELY
335
+ # ============================================================
336
+
337
+ def find_images(root_directory):
338
+
339
+ extensions = (
340
+ ".png",
341
+ ".jpg",
342
+ ".jpeg",
343
+ ".webp",
344
+ ".bmp",
345
+ ".tif",
346
+ ".tiff"
347
+ )
348
+
349
+ image_files = []
350
+
351
+ for root, dirs, files in os.walk(
352
+ root_directory
353
+ ):
354
+
355
+ for filename in files:
356
+
357
+ if filename.lower().endswith(
358
+ extensions
359
+ ):
360
+
361
+ image_files.append(
362
+ os.path.join(
363
+ root,
364
+ filename
365
+ )
366
+ )
367
+
368
+ return sorted(image_files)
369
+
370
+
371
+ # ============================================================
372
+ # 10. SAFE FILE NAME
373
+ # ============================================================
374
+
375
+ def get_relative_filename(
376
+ filepath,
377
+ root
378
+ ):
379
+
380
+ try:
381
+
382
+ return os.path.relpath(
383
+ filepath,
384
+ root
385
+ )
386
+
387
+ except Exception:
388
+
389
+ return os.path.basename(
390
+ filepath
391
+ )
392
+
393
+
394
+ # ============================================================
395
+ # 11. MAIN ANALYSIS
396
+ # ============================================================
397
+
398
+ def classify_zip_and_analyze_color(
399
+ zip_file,
400
+ progress=gr.Progress()
401
+ ):
402
+
403
+ if zip_file is None:
404
+
405
+ raise gr.Error(
406
+ "Please upload a ZIP file."
407
+ )
408
+
409
+ # --------------------------------------------------------
410
+ # ZIP filename
411
+ # --------------------------------------------------------
412
+
413
+ zip_path = zip_file.name
414
+
415
+ zip_basename = os.path.splitext(
416
+ os.path.basename(zip_path)
417
+ )[0]
418
+
419
+ print()
420
+ print("=" * 70)
421
+ print(f"Processing: {zip_basename}")
422
+ print("=" * 70)
423
+
424
  results = []
425
+
426
  thumbnails = []
427
 
428
+ # --------------------------------------------------------
429
+ # Temporary directory
430
+ # --------------------------------------------------------
431
 
432
  with tempfile.TemporaryDirectory() as tmpdir:
433
+
434
+ # ----------------------------------------------------
435
+ # Extract ZIP
436
+ # ----------------------------------------------------
437
+
438
+ print("Extracting ZIP...")
439
+
440
+ try:
441
+
442
+ with zipfile.ZipFile(
443
+ zip_path,
444
+ "r"
445
+ ) as zip_ref:
446
+
447
+ zip_ref.extractall(
448
+ tmpdir
449
+ )
450
+
451
+ except Exception as e:
452
+
453
+ raise gr.Error(
454
+ f"Could not extract ZIP: {e}"
455
+ )
456
+
457
+ # ----------------------------------------------------
458
+ # Find images recursively
459
+ # ----------------------------------------------------
460
+
461
+ image_files = find_images(
462
+ tmpdir
463
+ )
464
+
465
+ print(
466
+ f"Images found: {len(image_files)}"
467
+ )
468
+
469
+ if len(image_files) == 0:
470
+
471
+ raise gr.Error(
472
+ "No images were found in the ZIP."
473
+ )
474
+
475
+ # ----------------------------------------------------
476
+ # Process images
477
+ # ----------------------------------------------------
478
+
479
+ for i, img_path in enumerate(
480
+ image_files
481
+ ):
482
+
483
+ progress(
484
+ (i + 1) / len(image_files),
485
+ desc=(
486
+ f"Processing image "
487
+ f"{i + 1}/{len(image_files)}"
488
+ )
489
+ )
490
+
491
+ filename = get_relative_filename(
492
+ img_path,
493
+ tmpdir
494
+ )
495
+
496
+ print(
497
+ f"[{i + 1}/{len(image_files)}] "
498
+ f"{filename}"
499
+ )
500
+
501
+ # ------------------------------------------------
502
+ # Open image
503
+ # ------------------------------------------------
504
+
505
+ try:
506
+
507
+ image = Image.open(
508
+ img_path
509
+ ).convert("RGB")
510
+
511
+ except Exception as e:
512
+
513
+ print(
514
+ f" Image error: {e}"
515
+ )
516
+
517
+ results.append({
518
+
519
+ "Filename": filename,
520
+
521
+ "Top 1 Prediction": "",
522
+
523
+ "Top 1 Confidence": np.nan,
524
+
525
+ "Top 2 Prediction": "",
526
+
527
+ "Top 2 Confidence": np.nan,
528
+
529
+ "Top 3 Prediction": "",
530
+
531
+ "Top 3 Confidence": np.nan,
532
+
533
+ "Dominant Color": "",
534
+
535
+ "Basic Color": "",
536
+
537
+ "Face Count": 0,
538
+
539
+ "Age Estimates": "",
540
+
541
+ "Face Analysis Error":
542
+ f"Image error: {e}"
543
+ })
544
+
545
+ continue
546
+
547
+ # ------------------------------------------------
548
+ # Thumbnail
549
+ # ------------------------------------------------
550
+
551
+ thumb = image.copy()
552
+
553
+ thumb.thumbnail(
554
+ (300, 300),
555
+ Image.LANCZOS
556
+ )
557
+
558
+ thumbnails.append(
559
+ (thumb, filename)
560
+ )
561
+
562
+ # ------------------------------------------------
563
+ # ResNet
564
+ # ------------------------------------------------
565
+
566
+ try:
567
+
568
+ predictions = classify_image(
569
+ image
570
+ )
571
+
572
+ except Exception as e:
573
+
574
+ print(
575
+ f" ResNet error: {e}"
576
+ )
577
+
578
+ predictions = []
579
+
580
+ # ------------------------------------------------
581
+ # Color
582
+ # ------------------------------------------------
583
+
584
+ try:
585
+
586
+ rgb, hex_color = (
587
+ get_dominant_color(
588
+ image
589
  )
590
+ )
591
+
592
+ basic_color = (
593
+ closest_basic_color(
594
+ rgb
595
+ )
596
+ )
597
+
598
+ except Exception as e:
599
+
600
+ print(
601
+ f" Color error: {e}"
602
+ )
603
+
604
+ hex_color = ""
605
+
606
+ basic_color = ""
607
+
608
+ # ------------------------------------------------
609
+ # DeepFace
610
+ # ------------------------------------------------
611
+
612
+ face_result = analyze_faces(
613
+ image
614
+ )
615
+
616
+ faces = face_result[
617
+ "faces"
618
+ ]
619
+
620
+ face_count = face_result[
621
+ "face_count"
622
+ ]
623
+
624
+ face_error = face_result[
625
+ "error"
626
+ ]
627
+
628
+ ages = []
629
+
630
+ for face in faces:
631
+
632
+ age = face.get(
633
+ "age"
634
+ )
635
+
636
+ if age is not None:
637
+
638
+ try:
639
+
640
+ ages.append(
641
+ float(age)
642
+ )
643
+
644
+ except Exception:
645
+ pass
646
+
647
+ # ------------------------------------------------
648
+ # Prediction values
649
+ # ------------------------------------------------
650
+
651
+ prediction_values = [
652
+ "",
653
+ "",
654
+ ""
655
+ ]
656
+
657
+ confidence_values = [
658
+ np.nan,
659
+ np.nan,
660
+ np.nan
661
+ ]
662
+
663
+ for j, prediction in enumerate(
664
+ predictions[:3]
665
+ ):
666
+
667
+ prediction_values[j] = (
668
+ prediction["label"]
669
+ )
670
+
671
+ confidence_values[j] = (
672
+ prediction["confidence"]
673
+ )
674
+
675
+ # ------------------------------------------------
676
+ # Result
677
+ # ------------------------------------------------
678
+
679
+ results.append({
680
+
681
+ "Filename": filename,
682
+
683
+ "Top 1 Prediction":
684
+ prediction_values[0],
685
+
686
+ "Top 1 Confidence":
687
+ confidence_values[0],
688
+
689
+ "Top 2 Prediction":
690
+ prediction_values[1],
691
+
692
+ "Top 2 Confidence":
693
+ confidence_values[1],
694
+
695
+ "Top 3 Prediction":
696
+ prediction_values[2],
697
+
698
+ "Top 3 Confidence":
699
+ confidence_values[2],
700
+
701
+ "Dominant Color":
702
  hex_color,
703
+
704
+ "Basic Color":
705
  basic_color,
706
+
707
+ "Face Count":
708
+ face_count,
709
+
710
+ "Age Estimates":
711
+ ", ".join(
712
+ [
713
+ str(
714
+ round(age)
715
+ )
716
+ for age in ages
717
+ ]
718
+ ),
719
+
720
+ "Face Analysis Error":
721
+ face_error
722
+ })
723
+
724
+ # ========================================================
725
+ # DATAFRAME
726
+ # ========================================================
727
+
728
+ df = pd.DataFrame(
729
+ results
730
+ )
731
+
732
+ # ========================================================
733
+ # SUMMARY
734
+ # ========================================================
735
+
736
+ print()
737
+ print("=" * 70)
738
+ print("ANALYSIS SUMMARY")
739
+ print("=" * 70)
740
+
741
+ print(
742
+ f"Images processed: {len(df)}"
743
+ )
744
+
745
+ if "Face Count" in df.columns:
746
+
747
+ total_faces = int(
748
+ df["Face Count"].sum()
749
+ )
750
+
751
+ images_with_faces = int(
752
+ (df["Face Count"] > 0).sum()
753
+ )
754
+
755
+ print(
756
+ f"Total detected faces: "
757
+ f"{total_faces}"
758
+ )
759
+
760
+ print(
761
+ f"Images containing faces: "
762
+ f"{images_with_faces}"
763
+ )
764
+
765
+ errors = df[
766
+ "Face Analysis Error"
767
+ ].fillna("").astype(str)
768
+
769
+ error_count = (
770
+ errors.str.len() > 0
771
+ ).sum()
772
+
773
+ print(
774
+ f"Images with DeepFace errors: "
775
+ f"{error_count}"
776
+ )
777
+
778
+ # ========================================================
779
+ # XLSX
780
+ # ========================================================
781
+
782
+ out_xlsx = os.path.join(
783
+ tempfile.gettempdir(),
784
+ f"{zip_basename}_results.xlsx"
785
+ )
786
+
787
+ with pd.ExcelWriter(
788
+ out_xlsx,
789
+ engine="openpyxl"
790
+ ) as writer:
791
+
792
+ df.to_excel(
793
+ writer,
794
+ sheet_name="Image Analysis",
795
+ index=False
796
+ )
797
+
798
+ # ----------------------------------------------------
799
+ # Summary sheet
800
+ # ----------------------------------------------------
801
+
802
+ summary = pd.DataFrame({
803
+
804
+ "Metric": [
805
+ "Images processed",
806
+ "Images containing faces",
807
+ "Total detected faces",
808
+ "Images with DeepFace errors"
809
+ ],
810
+
811
+ "Value": [
812
+
813
+ len(df),
814
+
815
+ int(
816
+ (
817
+ df["Face Count"] > 0
818
+ ).sum()
819
+ ),
820
+
821
+ int(
822
+ df["Face Count"].sum()
823
+ ),
824
+
825
+ int(error_count)
826
+ ]
827
+ })
828
+
829
+ summary.to_excel(
830
+ writer,
831
+ sheet_name="Summary",
832
+ index=False
833
+ )
834
+
835
+ # ========================================================
836
+ # PLOT 1 — BASIC COLOR
837
+ # ========================================================
838
+
839
+ fig1, ax1 = plt.subplots(
840
+ figsize=(9, 5)
841
+ )
842
+
843
+ color_counts = (
844
+ df["Basic Color"]
845
+ .replace("", np.nan)
846
+ .dropna()
847
+ .value_counts()
848
+ )
849
+
850
+ if len(color_counts) > 0:
851
+
852
+ ax1.bar(
853
+ color_counts.index,
854
+ color_counts.values
855
+ )
856
+
857
+ ax1.set_title(
858
+ "Basic Color Frequency"
859
+ )
860
+
861
+ ax1.set_ylabel(
862
+ "Number of images"
863
+ )
864
+
865
+ ax1.tick_params(
866
+ axis="x",
867
+ rotation=45
868
+ )
869
+
870
+ else:
871
+
872
+ ax1.text(
873
+ 0.5,
874
+ 0.5,
875
+ "No color data available",
876
+ ha="center",
877
+ va="center"
878
+ )
879
+
880
+ ax1.set_axis_off()
881
+
882
+ fig1.tight_layout()
883
+
884
  buf1 = io.BytesIO()
885
+
886
+ fig1.savefig(
887
+ buf1,
888
+ format="png",
889
+ dpi=150,
890
+ bbox_inches="tight"
891
+ )
892
+
893
  plt.close(fig1)
894
+
895
  buf1.seek(0)
 
896
 
897
+ plot1_img = Image.open(
898
+ buf1
899
+ ).convert("RGB")
900
+
901
+ # ========================================================
902
+ # PLOT 2 — TOP PREDICTIONS
903
+ # ========================================================
904
+
905
+ fig2, ax2 = plt.subplots(
906
+ figsize=(10, 7)
907
+ )
908
+
909
  preds_flat = []
910
+
911
+ for col in [
912
+ "Top 1 Prediction",
913
+ "Top 2 Prediction",
914
+ "Top 3 Prediction"
915
+ ]:
916
+
917
+ preds_flat.extend(
918
+ df[col]
919
+ .replace("", np.nan)
920
+ .dropna()
921
+ .tolist()
922
+ )
923
+
924
+ if preds_flat:
925
+
926
+ pred_counts = (
927
+ pd.Series(
928
+ preds_flat
929
+ )
930
+ .value_counts()
931
+ .head(20)
932
+ )
933
+
934
+ ax2.barh(
935
+ pred_counts.index[::-1],
936
+ pred_counts.values[::-1]
937
+ )
938
+
939
+ ax2.set_title(
940
+ "ImageNet Prediction Distribution"
941
+ )
942
+
943
+ ax2.set_xlabel(
944
+ "Count"
945
+ )
946
+
947
+ else:
948
+
949
+ ax2.text(
950
+ 0.5,
951
+ 0.5,
952
+ "No prediction data available",
953
+ ha="center",
954
+ va="center"
955
+ )
956
+
957
+ ax2.set_axis_off()
958
+
959
+ fig2.tight_layout()
960
+
961
  buf2 = io.BytesIO()
962
+
963
+ fig2.savefig(
964
+ buf2,
965
+ format="png",
966
+ dpi=150,
967
+ bbox_inches="tight"
968
+ )
969
+
970
  plt.close(fig2)
971
+
972
  buf2.seek(0)
973
+
974
+ plot2_img = Image.open(
975
+ buf2
976
+ ).convert("RGB")
977
+
978
+ # ========================================================
979
+ # PLOT 3 — FACE DETECTION
980
+ # ========================================================
981
+
982
+ fig3, ax3 = plt.subplots(
983
+ figsize=(8, 5)
984
+ )
985
+
986
+ face_images = int(
987
+ (
988
+ df["Face Count"] > 0
989
+ ).sum()
990
+ )
991
+
992
+ no_face_images = int(
993
+ (
994
+ df["Face Count"] == 0
995
+ ).sum()
996
+ )
997
+
998
+ ax3.bar(
999
+ [
1000
+ "Images with faces",
1001
+ "Images without faces"
1002
+ ],
1003
+ [
1004
+ face_images,
1005
+ no_face_images
1006
+ ]
1007
+ )
1008
+
1009
+ ax3.set_title(
1010
+ "Face Detection"
1011
+ )
1012
+
1013
+ ax3.set_ylabel(
1014
+ "Number of images"
1015
+ )
1016
+
1017
+ ax3.tick_params(
1018
+ axis="x",
1019
+ rotation=20
1020
+ )
1021
+
1022
+ fig3.tight_layout()
1023
+
1024
  buf3 = io.BytesIO()
1025
+
1026
+ fig3.savefig(
1027
+ buf3,
1028
+ format="png",
1029
+ dpi=150,
1030
+ bbox_inches="tight"
1031
+ )
1032
+
1033
  plt.close(fig3)
1034
+
1035
  buf3.seek(0)
1036
+
1037
+ plot3_img = Image.open(
1038
+ buf3
1039
+ ).convert("RGB")
1040
+
1041
+ # ========================================================
1042
+ # PLOT 4 — FACE COUNT PER IMAGE
1043
+ # ========================================================
1044
+
1045
+ fig4, ax4 = plt.subplots(
1046
+ figsize=(8, 5)
1047
+ )
1048
+
1049
+ face_count_distribution = (
1050
+ df["Face Count"]
1051
+ .value_counts()
1052
+ .sort_index()
1053
+ )
1054
+
1055
+ ax4.bar(
1056
+ face_count_distribution.index.astype(str),
1057
+ face_count_distribution.values
1058
+ )
1059
+
1060
+ ax4.set_title(
1061
+ "Number of Detected Faces per Image"
1062
+ )
1063
+
1064
+ ax4.set_xlabel(
1065
+ "Number of faces"
1066
+ )
1067
+
1068
+ ax4.set_ylabel(
1069
+ "Number of images"
1070
+ )
1071
+
1072
+ fig4.tight_layout()
1073
+
1074
  buf4 = io.BytesIO()
1075
+
1076
+ fig4.savefig(
1077
+ buf4,
1078
+ format="png",
1079
+ dpi=150,
1080
+ bbox_inches="tight"
1081
+ )
1082
+
1083
  plt.close(fig4)
1084
+
1085
  buf4.seek(0)
 
1086
 
1087
+ plot4_img = Image.open(
1088
+ buf4
1089
+ ).convert("RGB")
1090
+
1091
+ # ========================================================
1092
+ # PLOT 5 — AGE DISTRIBUTION
1093
+ # ========================================================
1094
+
1095
+ all_ages = []
1096
+
1097
+ for face_list in df["Age Estimates"]:
1098
+
1099
+ if not isinstance(
1100
+ face_list,
1101
+ str
1102
+ ):
1103
+ continue
1104
+
1105
+ if not face_list.strip():
1106
+ continue
1107
+
1108
+ for value in face_list.split(","):
1109
+
1110
+ try:
1111
+
1112
+ all_ages.append(
1113
+ float(value.strip())
1114
+ )
1115
+
1116
+ except Exception:
1117
+ pass
1118
+
1119
+ fig5, ax5 = plt.subplots(
1120
+ figsize=(9, 5)
1121
+ )
1122
+
1123
+ if all_ages:
1124
+
1125
+ ax5.hist(
1126
+ all_ages,
1127
+ bins=range(
1128
+ 0,
1129
+ 101,
1130
+ 5
1131
+ )
1132
+ )
1133
+
1134
+ ax5.set_title(
1135
+ "Estimated Age Distribution"
1136
+ )
1137
+
1138
+ ax5.set_xlabel(
1139
+ "Estimated age"
1140
+ )
1141
+
1142
+ ax5.set_ylabel(
1143
+ "Number of detected faces"
1144
+ )
1145
+
1146
+ else:
1147
+
1148
+ ax5.text(
1149
+ 0.5,
1150
+ 0.5,
1151
+ "No age estimates available",
1152
+ ha="center",
1153
+ va="center"
1154
+ )
1155
+
1156
+ ax5.set_axis_off()
1157
+
1158
+ fig5.tight_layout()
1159
+
1160
+ buf5 = io.BytesIO()
1161
+
1162
+ fig5.savefig(
1163
+ buf5,
1164
+ format="png",
1165
+ dpi=150,
1166
+ bbox_inches="tight"
1167
+ )
1168
+
1169
+ plt.close(fig5)
1170
+
1171
+ buf5.seek(0)
1172
+
1173
+ plot5_img = Image.open(
1174
+ buf5
1175
+ ).convert("RGB")
1176
+
1177
+ # ========================================================
1178
+ # FINAL OUTPUT
1179
+ # ========================================================
1180
+
1181
+ print()
1182
+ print("=" * 70)
1183
+ print("DONE")
1184
+ print("=" * 70)
1185
+
1186
+ return (
1187
+ df,
1188
+ out_xlsx,
1189
+ thumbnails,
1190
+ plot1_img,
1191
+ plot2_img,
1192
+ plot3_img,
1193
+ plot4_img,
1194
+ plot5_img
1195
+ )
1196
+
1197
+
1198
+ # ============================================================
1199
+ # 12. GRADIO INTERFACE
1200
+ # ============================================================
1201
 
 
 
 
1202
  demo = gr.Interface(
1203
+
1204
  fn=classify_zip_and_analyze_color,
1205
+
1206
+ inputs=[
1207
+ gr.File(
1208
+ file_types=[".zip"],
1209
+ label="Upload ZIP of images"
1210
+ )
1211
+ ],
1212
+
1213
  outputs=[
1214
+
1215
+ gr.Dataframe(
1216
+ label="Image Analysis",
1217
+ interactive=False
1218
+ ),
1219
+
1220
+ gr.File(
1221
+ label="Download XLSX"
1222
+ ),
1223
+
1224
+ gr.Gallery(
1225
+ label="Thumbnails",
1226
+ show_label=True,
1227
+ columns=5,
1228
+ rows=3,
1229
+ height="auto"
1230
+ ),
1231
+
1232
+ gr.Image(
1233
+ type="pil",
1234
+ label="Basic Color Frequency"
1235
+ ),
1236
+
1237
+ gr.Image(
1238
+ type="pil",
1239
+ label="ImageNet Prediction Distribution"
1240
+ ),
1241
+
1242
+ gr.Image(
1243
+ type="pil",
1244
+ label="Face Detection"
1245
+ ),
1246
+
1247
+ gr.Image(
1248
+ type="pil",
1249
+ label="Faces per Image"
1250
+ ),
1251
+
1252
+ gr.Image(
1253
+ type="pil",
1254
+ label="Estimated Age Distribution"
1255
+ )
1256
  ],
1257
+
1258
+ title=(
1259
+ "ZIP Image Classifier, Color & Face Analysis"
1260
+ ),
1261
+
1262
+ description=(
1263
+ "Upload a ZIP containing images. "
1264
+ "The application recursively finds images, "
1265
+ "classifies them with ResNet50, calculates "
1266
+ "dominant colors, detects faces, estimates age, "
1267
+ "and reports DeepFace errors."
1268
+ )
1269
  )
1270
 
1271
+
1272
+ # ============================================================
1273
+ # 13. LAUNCH
1274
+ # ============================================================
1275
+
1276
  if __name__ == "__main__":
1277
+
1278
+ demo.launch(
1279
+ server_name="0.0.0.0",
1280
+ server_port=7860
1281
+ )