clementBE commited on
Commit
c0ff534
·
verified ·
1 Parent(s): 113442f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -26
app.py CHANGED
@@ -12,6 +12,7 @@ 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
 
@@ -93,6 +94,9 @@ def get_dominant_color(image, num_colors=5):
93
  def classify_zip_and_analyze_color(zip_file):
94
  results = []
95
 
 
 
 
96
  with tempfile.TemporaryDirectory() as tmpdir:
97
  with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
98
  zip_ref.extractall(tmpdir)
@@ -118,9 +122,7 @@ def classify_zip_and_analyze_color(zip_file):
118
  rgb, hex_color = get_dominant_color(image)
119
  basic_color = closest_basic_color(rgb)
120
 
121
- # ---------------------------
122
  # Face detection & characterization
123
- # ---------------------------
124
  faces_data = []
125
  try:
126
  img_cv2 = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
@@ -131,32 +133,40 @@ def classify_zip_and_analyze_color(zip_file):
131
  for f in detected_faces:
132
  faces_data.append({
133
  "age": f["age"],
134
- "gender": f["gender"], # dict of probabilities
135
  "emotion": f["dominant_emotion"]
136
  })
137
  else:
138
  faces_data.append({
139
  "age": detected_faces["age"],
140
- "gender": detected_faces["gender"], # dict
141
  "emotion": detected_faces["dominant_emotion"]
142
  })
143
  except Exception:
144
  faces_data = []
145
 
 
 
 
 
146
  results.append((
147
  fname,
148
  ", ".join([p[0] for p in preds]),
149
  ", ".join([p[1] for p in preds]),
150
  hex_color,
151
  basic_color,
152
- faces_data
 
153
  ))
154
 
155
  # Build dataframe
156
- df = pd.DataFrame(results, columns=["Filename", "Top 3 Predictions", "Confidence", "Dominant Color", "Basic Color", "Face Info"])
 
 
 
157
 
158
- # Save XLSX
159
- out_xlsx = os.path.join(tempfile.gettempdir(), "results.xlsx")
160
  df.to_excel(out_xlsx, index=False)
161
 
162
  # ---------------------------
@@ -191,29 +201,31 @@ def classify_zip_and_analyze_color(zip_file):
191
  plot2_img = Image.open(buf2)
192
 
193
  # ---------------------------
194
- # Extract age and weighted gender (confidence ≤ 0.9)
195
  # ---------------------------
196
- ages = []
197
- gender_confidence = {"Man": 0, "Woman": 0}
198
 
199
  for face_list in df["Face Info"]:
200
- for face in face_list: # each face is a dict
201
- ages.append(face["age"])
202
- gender_dict = face["gender"] # dict of probabilities
203
  gender = max(gender_dict, key=gender_dict.get)
204
- conf = float(gender_dict[gender]) / 100 # convert % to 0-1
205
  weight = min(conf, 0.9)
206
- if gender in gender_confidence:
207
- gender_confidence[gender] += weight
 
 
208
  else:
209
- gender_confidence[gender] = weight
210
 
211
  # ---------------------------
212
- # Plot 3: Gender distribution (weighted ≤ 0.9)
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% Confidence)")
217
  ax3.set_ylabel("Sum of Confidence")
218
  buf3 = io.BytesIO()
219
  plt.savefig(buf3, format="png")
@@ -222,13 +234,15 @@ def classify_zip_and_analyze_color(zip_file):
222
  plot3_img = Image.open(buf3)
223
 
224
  # ---------------------------
225
- # Plot 4: Age distribution
226
  # ---------------------------
227
  fig4, ax4 = plt.subplots()
228
- ax4.hist(ages, bins=range(0, 101, 5), color="lightgreen", edgecolor="black")
229
- ax4.set_title("Age Distribution")
 
230
  ax4.set_xlabel("Age")
231
  ax4.set_ylabel("Count")
 
232
  buf4 = io.BytesIO()
233
  plt.savefig(buf4, format="png")
234
  plt.close(fig4)
@@ -244,15 +258,19 @@ demo = gr.Interface(
244
  fn=classify_zip_and_analyze_color,
245
  inputs=gr.File(file_types=[".zip"], label="Upload ZIP of images"),
246
  outputs=[
247
- gr.Dataframe(headers=["Filename", "Top 3 Predictions", "Confidence", "Dominant Color", "Basic Color", "Face Info"]),
 
 
 
 
248
  gr.File(label="Download XLSX"),
249
  gr.Image(type="pil", label="Basic Color Frequency"),
250
  gr.Image(type="pil", label="Top Prediction Distribution"),
251
  gr.Image(type="pil", label="Gender Distribution (Weighted ≤90%)"),
252
- gr.Image(type="pil", label="Age Distribution"),
253
  ],
254
  title="Image Classifier with Color & Face Analysis",
255
- description="Upload a ZIP of images. Classifies images, analyzes dominant color, and detects/characterizes faces (age, gender, emotion).",
256
  )
257
 
258
  if __name__ == "__main__":
 
12
  from sklearn.cluster import MiniBatchKMeans
13
  import matplotlib.pyplot as plt
14
  import io
15
+ from datetime import datetime
16
 
17
  import gradio as gr
18
 
 
94
  def classify_zip_and_analyze_color(zip_file):
95
  results = []
96
 
97
+ zip_name = os.path.splitext(os.path.basename(zip_file.name))[0]
98
+ date_str = datetime.now().strftime("%Y%m%d")
99
+
100
  with tempfile.TemporaryDirectory() as tmpdir:
101
  with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
102
  zip_ref.extractall(tmpdir)
 
122
  rgb, hex_color = get_dominant_color(image)
123
  basic_color = closest_basic_color(rgb)
124
 
 
125
  # Face detection & characterization
 
126
  faces_data = []
127
  try:
128
  img_cv2 = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
 
133
  for f in detected_faces:
134
  faces_data.append({
135
  "age": f["age"],
136
+ "gender": f["gender"],
137
  "emotion": f["dominant_emotion"]
138
  })
139
  else:
140
  faces_data.append({
141
  "age": detected_faces["age"],
142
+ "gender": detected_faces["gender"],
143
  "emotion": detected_faces["dominant_emotion"]
144
  })
145
  except Exception:
146
  faces_data = []
147
 
148
+ # Thumbnail preview
149
+ thumbnail = image.copy()
150
+ thumbnail.thumbnail((64, 64))
151
+
152
  results.append((
153
  fname,
154
  ", ".join([p[0] for p in preds]),
155
  ", ".join([p[1] for p in preds]),
156
  hex_color,
157
  basic_color,
158
+ faces_data,
159
+ thumbnail
160
  ))
161
 
162
  # Build dataframe
163
+ df = pd.DataFrame(results, columns=[
164
+ "Filename", "Top 3 Predictions", "Confidence",
165
+ "Dominant Color", "Basic Color", "Face Info", "Thumbnail"
166
+ ])
167
 
168
+ # Save XLSX with zip name + date
169
+ out_xlsx = os.path.join(tempfile.gettempdir(), f"{zip_name}_{date_str}_results.xlsx")
170
  df.to_excel(out_xlsx, index=False)
171
 
172
  # ---------------------------
 
201
  plot2_img = Image.open(buf2)
202
 
203
  # ---------------------------
204
+ # Extract ages and genders
205
  # ---------------------------
206
+ ages_male, ages_female = [], []
207
+ gender_confidence = {"Homme": 0, "Femme": 0}
208
 
209
  for face_list in df["Face Info"]:
210
+ for face in face_list:
211
+ age = face["age"]
212
+ gender_dict = face["gender"]
213
  gender = max(gender_dict, key=gender_dict.get)
214
+ conf = float(gender_dict[gender]) / 100
215
  weight = min(conf, 0.9)
216
+ gender_trans = "Homme" if gender == "Man" else "Femme"
217
+ gender_confidence[gender_trans] += weight
218
+ if gender_trans == "Homme":
219
+ ages_male.append(age)
220
  else:
221
+ ages_female.append(age)
222
 
223
  # ---------------------------
224
+ # Plot 3: Gender distribution
225
  # ---------------------------
226
  fig3, ax3 = plt.subplots()
227
  ax3.bar(gender_confidence.keys(), gender_confidence.values(), color=["lightblue", "pink"])
228
+ ax3.set_title("Gender Distribution (Weighted ≤90%)")
229
  ax3.set_ylabel("Sum of Confidence")
230
  buf3 = io.BytesIO()
231
  plt.savefig(buf3, format="png")
 
234
  plot3_img = Image.open(buf3)
235
 
236
  # ---------------------------
237
+ # Plot 4: Age distribution by gender
238
  # ---------------------------
239
  fig4, ax4 = plt.subplots()
240
+ bins = range(0, 101, 5)
241
+ ax4.hist([ages_male, ages_female], bins=bins, color=["lightblue", "pink"], label=["Homme", "Femme"], edgecolor="black")
242
+ ax4.set_title("Age Distribution by Gender")
243
  ax4.set_xlabel("Age")
244
  ax4.set_ylabel("Count")
245
+ ax4.legend()
246
  buf4 = io.BytesIO()
247
  plt.savefig(buf4, format="png")
248
  plt.close(fig4)
 
258
  fn=classify_zip_and_analyze_color,
259
  inputs=gr.File(file_types=[".zip"], label="Upload ZIP of images"),
260
  outputs=[
261
+ gr.Dataframe(
262
+ headers=["Filename", "Top 3 Predictions", "Confidence",
263
+ "Dominant Color", "Basic Color", "Face Info", "Thumbnail"],
264
+ datatype=["str","str","str","str","str","str","pil"]
265
+ ),
266
  gr.File(label="Download XLSX"),
267
  gr.Image(type="pil", label="Basic Color Frequency"),
268
  gr.Image(type="pil", label="Top Prediction Distribution"),
269
  gr.Image(type="pil", label="Gender Distribution (Weighted ≤90%)"),
270
+ gr.Image(type="pil", label="Age Distribution by Gender"),
271
  ],
272
  title="Image Classifier with Color & Face Analysis",
273
+ description="Upload a ZIP of images. Classifies images, analyzes dominant color, detects/characterizes faces (age, gender, emotion), and shows thumbnails.",
274
  )
275
 
276
  if __name__ == "__main__":