clementBE commited on
Commit
19ff977
·
verified ·
1 Parent(s): 265fcb2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -28
app.py CHANGED
@@ -12,7 +12,6 @@ from torchvision.models import resnet50, ResNet50_Weights
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,9 +93,6 @@ def get_dominant_color(image, num_colors=5):
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,7 +118,9 @@ def classify_zip_and_analyze_color(zip_file):
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,13 +131,13 @@ def classify_zip_and_analyze_color(zip_file):
133
  for f in detected_faces:
134
  faces_data.append({
135
  "age": f["age"],
136
- "gender": "Homme" if f["gender"]=="Man" else "Femme",
137
  "emotion": f["dominant_emotion"]
138
  })
139
  else:
140
  faces_data.append({
141
  "age": detected_faces["age"],
142
- "gender": "Homme" if detected_faces["gender"]=="Man" else "Femme",
143
  "emotion": detected_faces["dominant_emotion"]
144
  })
145
  except Exception:
@@ -155,13 +153,10 @@ def classify_zip_and_analyze_color(zip_file):
155
  ))
156
 
157
  # Build dataframe
158
- df = pd.DataFrame(results, columns=[
159
- "Filename", "Top 3 Predictions", "Confidence",
160
- "Dominant Color", "Basic Color", "Face Info"
161
- ])
162
 
163
- # Save XLSX with zip name + date
164
- out_xlsx = os.path.join(tempfile.gettempdir(), f"{zip_name}_{date_str}_results.xlsx")
165
  df.to_excel(out_xlsx, index=False)
166
 
167
  # ---------------------------
@@ -196,24 +191,51 @@ def classify_zip_and_analyze_color(zip_file):
196
  plot2_img = Image.open(buf2)
197
 
198
  # ---------------------------
199
- # Plot 3: Gender distribution
200
  # ---------------------------
201
- gender_counts = {"Homme":0, "Femme":0}
 
 
202
  for face_list in df["Face Info"]:
203
- for face in face_list:
204
- gender_counts[face["gender"]] += 1
 
 
 
 
 
 
 
 
205
 
 
 
 
206
  fig3, ax3 = plt.subplots()
207
- ax3.bar(gender_counts.keys(), gender_counts.values(), color=["lightblue","pink"])
208
- ax3.set_title("Gender Distribution")
209
- ax3.set_ylabel("Count")
210
  buf3 = io.BytesIO()
211
  plt.savefig(buf3, format="png")
212
  plt.close(fig3)
213
  buf3.seek(0)
214
  plot3_img = Image.open(buf3)
215
 
216
- return df, out_xlsx, plot1_img, plot2_img, plot3_img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
  # ---------------------------
219
  # Gradio Interface
@@ -222,19 +244,16 @@ demo = gr.Interface(
222
  fn=classify_zip_and_analyze_color,
223
  inputs=gr.File(file_types=[".zip"], label="Upload ZIP of images"),
224
  outputs=[
225
- gr.Dataframe(
226
- headers=["Filename", "Top 3 Predictions", "Confidence",
227
- "Dominant Color", "Basic Color", "Face Info"],
228
- datatype=["str","str","str","str","str","str"]
229
- ),
230
  gr.File(label="Download XLSX"),
231
  gr.Image(type="pil", label="Basic Color Frequency"),
232
  gr.Image(type="pil", label="Top Prediction Distribution"),
233
- gr.Image(type="pil", label="Gender Distribution"),
 
234
  ],
235
  title="Image Classifier with Color & Face Analysis",
236
- description="Upload a ZIP of images. Classifies images, analyzes dominant color, detects/characterizes faces (age, gender, emotion).",
237
  )
238
 
239
  if __name__ == "__main__":
240
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
12
  from sklearn.cluster import MiniBatchKMeans
13
  import matplotlib.pyplot as plt
14
  import io
 
15
 
16
  import gradio as gr
17
 
 
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
  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
  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:
 
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
  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")
220
  plt.close(fig3)
221
  buf3.seek(0)
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)
235
+ buf4.seek(0)
236
+ plot4_img = Image.open(buf4)
237
+
238
+ return df, out_xlsx, plot1_img, plot2_img, plot3_img, plot4_img
239
 
240
  # ---------------------------
241
  # Gradio 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__":
259
+ demo.launch(server_name="0.0.0.0", server_port=7860)