File size: 9,591 Bytes
328faae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301006f
328faae
 
 
 
 
 
 
 
265fcb2
328faae
79d7042
92e5b44
 
517b23e
 
328faae
517b23e
265fcb2
92e5b44
265fcb2
92e5b44
 
 
265fcb2
 
 
 
 
 
 
301006f
517b23e
301006f
517b23e
 
265fcb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517b23e
265fcb2
 
 
 
 
517b23e
265fcb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ff977
265fcb2
328faae
517b23e
265fcb2
92e5b44
bca99a0
328faae
bca99a0
328faae
bca99a0
 
 
265fcb2
 
 
 
 
 
 
bca99a0
328faae
bca99a0
 
265fcb2
 
bca99a0
 
265fcb2
 
 
 
 
 
 
 
2137e43
19ff977
 
265fcb2
517b23e
19ff977
517b23e
19ff977
517b23e
19ff977
 
 
 
 
bca99a0
 
19ff977
517b23e
19ff977
265fcb2
 
 
 
 
bca99a0
2137e43
 
 
 
 
 
 
 
 
 
 
 
 
19ff977
2137e43
 
 
19ff977
 
2137e43
19ff977
 
 
 
 
 
517b23e
92e5b44
4de83f5
328faae
4de83f5
265fcb2
 
 
 
19ff977
265fcb2
301006f
265fcb2
 
19ff977
2137e43
265fcb2
 
517b23e
265fcb2
 
 
301006f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import os
import zipfile
import tempfile
import requests
import numpy as np
import pandas as pd
from PIL import Image
import torch
import torch.nn.functional as F
from torchvision import transforms
from torchvision.models import resnet50, ResNet50_Weights
from sklearn.cluster import MiniBatchKMeans
import matplotlib.pyplot as plt
import io

import gradio as gr

# Face analysis
from deepface import DeepFace
import cv2

# ---------------------------
# Force CPU if no CUDA
# ---------------------------
if not torch.cuda.is_available():
    os.environ["CUDA_VISIBLE_DEVICES"] = ""

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# ---------------------------
# Load ResNet50
# ---------------------------
weights = ResNet50_Weights.DEFAULT
model = resnet50(weights=weights).to(device)
model.eval()

# ---------------------------
# Transformations
# ---------------------------
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

# ---------------------------
# ImageNet labels
# ---------------------------
LABELS_URL = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
imagenet_classes = [line.strip() for line in requests.get(LABELS_URL).text.splitlines()]

# ---------------------------
# Basic color utilities
# ---------------------------
BASIC_COLORS = {
    "Red": (255, 0, 0),
    "Green": (0, 255, 0),
    "Blue": (0, 0, 255),
    "Yellow": (255, 255, 0),
    "Cyan": (0, 255, 255),
    "Magenta": (255, 0, 255),
    "Black": (0, 0, 0),
    "White": (255, 255, 255),
    "Gray": (128, 128, 128),
}

def closest_basic_color(rgb):
    r, g, b = rgb
    min_dist = float("inf")
    closest_color = None
    for name, (cr, cg, cb) in BASIC_COLORS.items():
        dist = (r - cr) ** 2 + (g - cg) ** 2 + (b - cb) ** 2
        if dist < min_dist:
            min_dist = dist
            closest_color = name
    return closest_color

def get_dominant_color(image, num_colors=5):
    image = image.resize((300, 300))
    pixels = np.array(image).reshape(-1, 3)
    kmeans = MiniBatchKMeans(n_clusters=num_colors, random_state=0, n_init=5)
    kmeans.fit(pixels)
    dominant_color = kmeans.cluster_centers_[np.argmax(np.bincount(kmeans.labels_))]
    dominant_color = tuple(dominant_color.astype(int))
    hex_color = f"#{dominant_color[0]:02x}{dominant_color[1]:02x}{dominant_color[2]:02x}"
    return dominant_color, hex_color

# ---------------------------
# Core function
# ---------------------------
def classify_zip_and_analyze_color(zip_file):
    results = []
    thumbnails = []

    # Name XLSX after zip
    zip_basename = os.path.splitext(os.path.basename(zip_file.name))[0]

    with tempfile.TemporaryDirectory() as tmpdir:
        with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
            zip_ref.extractall(tmpdir)

        for fname in sorted(os.listdir(tmpdir)):
            if fname.lower().endswith(('.png', '.jpg', '.jpeg')):
                img_path = os.path.join(tmpdir, fname)
                try:
                    image = Image.open(img_path).convert("RGB")
                except Exception:
                    continue

                # Thumbnail for gallery (higher-quality)
                thumb = image.copy()
                thumb = thumb.resize((200, 200), Image.LANCZOS)
                thumbnails.append(thumb)

                # Classification
                input_tensor = transform(image).unsqueeze(0).to(device)
                with torch.no_grad():
                    output = model(input_tensor)
                    probs = F.softmax(output, dim=1)[0]

                top3_prob, top3_idx = torch.topk(probs, 3)
                preds = [(imagenet_classes[idx], f"{prob.item()*100:.2f}%") for idx, prob in zip(top3_idx, top3_prob)]

                # Dominant color
                rgb, hex_color = get_dominant_color(image)
                basic_color = closest_basic_color(rgb)

                # Face detection & characterization
                faces_data = []
                try:
                    img_cv2 = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
                    detected_faces = DeepFace.analyze(
                        img_cv2, actions=["age", "gender", "emotion"], enforce_detection=False
                    )
                    if isinstance(detected_faces, list):
                        for f in detected_faces:
                            faces_data.append({
                                "age": f["age"],
                                "gender": f["gender"],
                                "emotion": f["dominant_emotion"]
                            })
                    else:
                        faces_data.append({
                            "age": detected_faces["age"],
                            "gender": detected_faces["gender"],
                            "emotion": detected_faces["dominant_emotion"]
                        })
                except Exception:
                    faces_data = []

                results.append((
                    fname,
                    ", ".join([p[0] for p in preds]),
                    ", ".join([p[1] for p in preds]),
                    hex_color,
                    basic_color,
                    faces_data
                ))

    # Build dataframe
    df = pd.DataFrame(results, columns=["Filename", "Top 3 Predictions", "Confidence", "Dominant Color", "Basic Color", "Face Info"])

    # Save XLSX
    out_xlsx = os.path.join(tempfile.gettempdir(), f"{zip_basename}_results.xlsx")
    df.to_excel(out_xlsx, index=False)

    # ---------------------------
    # Plots
    # ---------------------------
    # 1. Basic color frequency
    fig1, ax1 = plt.subplots()
    color_counts = df["Basic Color"].value_counts()
    ax1.bar(color_counts.index, color_counts.values, color="skyblue")
    ax1.set_title("Basic Color Frequency")
    ax1.set_ylabel("Count")
    buf1 = io.BytesIO()
    plt.savefig(buf1, format="png")
    plt.close(fig1)
    buf1.seek(0)
    plot1_img = Image.open(buf1)

    # 2. Top prediction distribution
    fig2, ax2 = plt.subplots()
    preds_flat = []
    for p in df["Top 3 Predictions"]:
        preds_flat.extend(p.split(", "))
    pred_counts = pd.Series(preds_flat).value_counts().head(20)
    ax2.barh(pred_counts.index[::-1], pred_counts.values[::-1], color="salmon")
    ax2.set_title("Top Prediction Distribution")
    ax2.set_xlabel("Count")
    buf2 = io.BytesIO()
    plt.savefig(buf2, format="png", bbox_inches="tight")
    plt.close(fig2)
    buf2.seek(0)
    plot2_img = Image.open(buf2)

    # 3. Gender distribution (weighted)
    ages = []
    gender_confidence = {"Man": 0, "Woman": 0}
    for face_list in df["Face Info"]:
        for face in face_list:
            ages.append(face["age"])
            gender_dict = face["gender"]
            gender = max(gender_dict, key=gender_dict.get)
            conf = float(gender_dict[gender]) / 100
            weight = min(conf, 0.9)
            if gender in gender_confidence:
                gender_confidence[gender] += weight
            else:
                gender_confidence[gender] = weight

    fig3, ax3 = plt.subplots()
    ax3.bar(gender_confidence.keys(), gender_confidence.values(), color=["lightblue", "pink"])
    ax3.set_title("Gender Distribution (Weighted ≤90%)")
    ax3.set_ylabel("Sum of Confidence")
    buf3 = io.BytesIO()
    plt.savefig(buf3, format="png")
    plt.close(fig3)
    buf3.seek(0)
    plot3_img = Image.open(buf3)

    # 4. Age distribution by gender
    ages_men = []
    ages_women = []
    for face_list in df["Face Info"]:
        for face in face_list:
            age = face["age"]
            gender_dict = face["gender"]
            gender = max(gender_dict, key=gender_dict.get)
            if gender.lower() == "man":
                ages_men.append(age)
            else:
                ages_women.append(age)

    fig4, ax4 = plt.subplots()
    bins = range(0, 101, 5)
    ax4.hist([ages_men, ages_women], bins=bins, color=["lightblue", "pink"], label=["Men", "Women"], stacked=False)
    ax4.set_title("Age Distribution by Gender")
    ax4.set_xlabel("Age")
    ax4.set_ylabel("Count")
    ax4.legend()
    buf4 = io.BytesIO()
    plt.savefig(buf4, format="png")
    plt.close(fig4)
    buf4.seek(0)
    plot4_img = Image.open(buf4)

    return df, out_xlsx, thumbnails, plot1_img, plot2_img, plot3_img, plot4_img

# ---------------------------
# Gradio Interface
# ---------------------------
demo = gr.Interface(
    fn=classify_zip_and_analyze_color,
    inputs=gr.File(file_types=[".zip"], label="Upload ZIP of images"),
    outputs=[
        gr.Dataframe(headers=["Filename", "Top 3 Predictions", "Confidence", "Dominant Color", "Basic Color", "Face Info"]),
        gr.File(label="Download XLSX"),
        gr.Gallery(label="Thumbnails", show_label=True, elem_id="thumbnail-gallery", columns=5),
        gr.Image(type="pil", label="Basic Color Frequency"),
        gr.Image(type="pil", label="Top Prediction Distribution"),
        gr.Image(type="pil", label="Gender Distribution (Weighted ≤90%)"),
        gr.Image(type="pil", label="Age Distribution by Gender"),
    ],
    title="Image Classifier with Color & Face Analysis",
    description="Upload a ZIP of images. Classifies images, analyzes dominant color, detects faces, and displays thumbnails.",
)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)