Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -18,16 +18,12 @@ import gradio as gr
|
|
| 18 |
from deepface import DeepFace
|
| 19 |
import cv2
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
# Device setup
|
| 23 |
-
# ---------------------------
|
| 24 |
if not torch.cuda.is_available():
|
| 25 |
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 26 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
# Load ResNet50
|
| 30 |
-
# ---------------------------
|
| 31 |
weights = ResNet50_Weights.DEFAULT
|
| 32 |
model = resnet50(weights=weights).to(device)
|
| 33 |
model.eval()
|
|
@@ -68,9 +64,7 @@ def get_dominant_color(image,num_colors=5):
|
|
| 68 |
hex_color = f"#{dominant_color[0]:02x}{dominant_color[1]:02x}{dominant_color[2]:02x}"
|
| 69 |
return dominant_color, hex_color
|
| 70 |
|
| 71 |
-
# ---------------------------
|
| 72 |
# Core analysis
|
| 73 |
-
# ---------------------------
|
| 74 |
def classify_zip_and_analyze_color(zip_file):
|
| 75 |
results = []
|
| 76 |
images_dict = {} # store images for preview
|
|
@@ -125,13 +119,87 @@ def classify_zip_and_analyze_color(zip_file):
|
|
| 125 |
))
|
| 126 |
|
| 127 |
df = pd.DataFrame(results, columns=["Filename","Top 3 Predictions","Confidence","Dominant Color","Basic Color","Face Info"])
|
| 128 |
-
|
| 129 |
out_xlsx = os.path.join(tempfile.gettempdir(), f"{zip_name}_{date_str}_results.xlsx")
|
| 130 |
df.to_excel(out_xlsx,index=False)
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
def show_preview(filename, images_dict):
|
| 136 |
return images_dict.get(filename, None)
|
| 137 |
|
|
@@ -141,17 +209,28 @@ def show_preview(filename, images_dict):
|
|
| 141 |
with gr.Blocks() as demo:
|
| 142 |
uploaded_zip = gr.File(label="Upload ZIP of images", file_types=[".zip"])
|
| 143 |
output_df = gr.Dataframe(headers=["Filename","Top 3 Predictions","Confidence","Dominant Color","Basic Color","Face Info"])
|
|
|
|
| 144 |
image_preview = gr.Image(label="Image Preview")
|
| 145 |
download_file = gr.File(label="Download XLSX")
|
| 146 |
-
images_state = gr.State()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
analyze_btn = gr.Button("Run Analysis")
|
| 149 |
|
| 150 |
def run_analysis(zip_file):
|
| 151 |
-
df, images_dict, out_xlsx = classify_zip_and_analyze_color(zip_file)
|
| 152 |
-
return df, images_dict, out_xlsx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
|
| 155 |
-
output_df.select(show_preview, inputs=[output_df, images_state], outputs=image_preview)
|
| 156 |
|
| 157 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 18 |
from deepface import DeepFace
|
| 19 |
import cv2
|
| 20 |
|
| 21 |
+
# Device
|
|
|
|
|
|
|
| 22 |
if not torch.cuda.is_available():
|
| 23 |
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 24 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 25 |
|
| 26 |
+
# Model
|
|
|
|
|
|
|
| 27 |
weights = ResNet50_Weights.DEFAULT
|
| 28 |
model = resnet50(weights=weights).to(device)
|
| 29 |
model.eval()
|
|
|
|
| 64 |
hex_color = f"#{dominant_color[0]:02x}{dominant_color[1]:02x}{dominant_color[2]:02x}"
|
| 65 |
return dominant_color, hex_color
|
| 66 |
|
|
|
|
| 67 |
# Core analysis
|
|
|
|
| 68 |
def classify_zip_and_analyze_color(zip_file):
|
| 69 |
results = []
|
| 70 |
images_dict = {} # store images for preview
|
|
|
|
| 119 |
))
|
| 120 |
|
| 121 |
df = pd.DataFrame(results, columns=["Filename","Top 3 Predictions","Confidence","Dominant Color","Basic Color","Face Info"])
|
|
|
|
| 122 |
out_xlsx = os.path.join(tempfile.gettempdir(), f"{zip_name}_{date_str}_results.xlsx")
|
| 123 |
df.to_excel(out_xlsx,index=False)
|
| 124 |
|
| 125 |
+
# ---------------------------
|
| 126 |
+
# Plot 1: Basic color frequency
|
| 127 |
+
# ---------------------------
|
| 128 |
+
fig1, ax1 = plt.subplots()
|
| 129 |
+
color_counts = df["Basic Color"].value_counts()
|
| 130 |
+
ax1.bar(color_counts.index, color_counts.values, color="skyblue")
|
| 131 |
+
ax1.set_title("Basic Color Frequency")
|
| 132 |
+
ax1.set_ylabel("Count")
|
| 133 |
+
buf1 = io.BytesIO()
|
| 134 |
+
plt.savefig(buf1, format="png")
|
| 135 |
+
plt.close(fig1)
|
| 136 |
+
buf1.seek(0)
|
| 137 |
+
plot1_img = Image.open(buf1)
|
| 138 |
+
|
| 139 |
+
# ---------------------------
|
| 140 |
+
# Plot 2: Top prediction distribution
|
| 141 |
+
# ---------------------------
|
| 142 |
+
fig2, ax2 = plt.subplots()
|
| 143 |
+
preds_flat = []
|
| 144 |
+
for p in df["Top 3 Predictions"]:
|
| 145 |
+
preds_flat.extend(p.split(", "))
|
| 146 |
+
pred_counts = pd.Series(preds_flat).value_counts().head(20)
|
| 147 |
+
ax2.barh(pred_counts.index[::-1], pred_counts.values[::-1], color="salmon")
|
| 148 |
+
ax2.set_title("Top Prediction Distribution")
|
| 149 |
+
ax2.set_xlabel("Count")
|
| 150 |
+
buf2 = io.BytesIO()
|
| 151 |
+
plt.savefig(buf2, format="png", bbox_inches="tight")
|
| 152 |
+
plt.close(fig2)
|
| 153 |
+
buf2.seek(0)
|
| 154 |
+
plot2_img = Image.open(buf2)
|
| 155 |
+
|
| 156 |
+
# ---------------------------
|
| 157 |
+
# Gender & Age
|
| 158 |
+
# ---------------------------
|
| 159 |
+
ages_male, ages_female = [], []
|
| 160 |
+
gender_confidence = {"Homme":0, "Femme":0}
|
| 161 |
+
for face_list in df["Face Info"]:
|
| 162 |
+
for face in face_list:
|
| 163 |
+
age = face["age"]
|
| 164 |
+
gender_dict = face["gender"]
|
| 165 |
+
gender = max(gender_dict, key=gender_dict.get)
|
| 166 |
+
conf = float(gender_dict[gender])/100
|
| 167 |
+
weight = min(conf,0.9)
|
| 168 |
+
gender_trans = "Homme" if gender=="Man" else "Femme"
|
| 169 |
+
gender_confidence[gender_trans] += weight
|
| 170 |
+
if gender_trans=="Homme":
|
| 171 |
+
ages_male.append(age)
|
| 172 |
+
else:
|
| 173 |
+
ages_female.append(age)
|
| 174 |
+
|
| 175 |
+
# Gender distribution
|
| 176 |
+
fig3, ax3 = plt.subplots()
|
| 177 |
+
ax3.bar(gender_confidence.keys(), gender_confidence.values(), color=["lightblue","pink"])
|
| 178 |
+
ax3.set_title("Gender Distribution (Weighted ≤90%)")
|
| 179 |
+
ax3.set_ylabel("Sum of Confidence")
|
| 180 |
+
buf3 = io.BytesIO()
|
| 181 |
+
plt.savefig(buf3, format="png")
|
| 182 |
+
plt.close(fig3)
|
| 183 |
+
buf3.seek(0)
|
| 184 |
+
plot3_img = Image.open(buf3)
|
| 185 |
+
|
| 186 |
+
# Age distribution
|
| 187 |
+
fig4, ax4 = plt.subplots()
|
| 188 |
+
bins = range(0,101,5)
|
| 189 |
+
ax4.hist([ages_male, ages_female], bins=bins, color=["lightblue","pink"], label=["Homme","Femme"], edgecolor="black")
|
| 190 |
+
ax4.set_title("Age Distribution by Gender")
|
| 191 |
+
ax4.set_xlabel("Age")
|
| 192 |
+
ax4.set_ylabel("Count")
|
| 193 |
+
ax4.legend()
|
| 194 |
+
buf4 = io.BytesIO()
|
| 195 |
+
plt.savefig(buf4, format="png")
|
| 196 |
+
plt.close(fig4)
|
| 197 |
+
buf4.seek(0)
|
| 198 |
+
plot4_img = Image.open(buf4)
|
| 199 |
+
|
| 200 |
+
return df, list(images_dict.keys()), images_dict, out_xlsx, plot1_img, plot2_img, plot3_img, plot4_img
|
| 201 |
+
|
| 202 |
+
# Show selected image preview
|
| 203 |
def show_preview(filename, images_dict):
|
| 204 |
return images_dict.get(filename, None)
|
| 205 |
|
|
|
|
| 209 |
with gr.Blocks() as demo:
|
| 210 |
uploaded_zip = gr.File(label="Upload ZIP of images", file_types=[".zip"])
|
| 211 |
output_df = gr.Dataframe(headers=["Filename","Top 3 Predictions","Confidence","Dominant Color","Basic Color","Face Info"])
|
| 212 |
+
image_dropdown = gr.Dropdown(label="Select image to preview")
|
| 213 |
image_preview = gr.Image(label="Image Preview")
|
| 214 |
download_file = gr.File(label="Download XLSX")
|
| 215 |
+
images_state = gr.State()
|
| 216 |
+
|
| 217 |
+
plot1 = gr.Image(label="Basic Color Frequency")
|
| 218 |
+
plot2 = gr.Image(label="Top Prediction Distribution")
|
| 219 |
+
plot3 = gr.Image(label="Gender Distribution")
|
| 220 |
+
plot4 = gr.Image(label="Age Distribution by Gender")
|
| 221 |
|
| 222 |
analyze_btn = gr.Button("Run Analysis")
|
| 223 |
|
| 224 |
def run_analysis(zip_file):
|
| 225 |
+
df, filenames, images_dict, out_xlsx, p1, p2, p3, p4 = classify_zip_and_analyze_color(zip_file)
|
| 226 |
+
return df, filenames, images_dict, out_xlsx, p1, p2, p3, p4
|
| 227 |
+
|
| 228 |
+
analyze_btn.click(
|
| 229 |
+
run_analysis,
|
| 230 |
+
inputs=uploaded_zip,
|
| 231 |
+
outputs=[output_df, image_dropdown, images_state, download_file, plot1, plot2, plot3, plot4]
|
| 232 |
+
)
|
| 233 |
|
| 234 |
+
image_dropdown.change(show_preview, inputs=[image_dropdown, images_state], outputs=image_preview)
|
|
|
|
| 235 |
|
| 236 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|