File size: 5,755 Bytes
9066d0b
b6e6733
9066d0b
b6e6733
9066d0b
c1a6c5e
 
b6e6733
c1a6c5e
 
 
 
 
 
 
 
 
b6e6733
654b942
 
 
 
 
 
 
 
 
b6e6733
9066d0b
c1a6c5e
b6e6733
c1a6c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9066d0b
c1a6c5e
 
9031590
c1a6c5e
9066d0b
 
 
c1a6c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76d1760
654b942
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1a6c5e
 
b6e6733
c1a6c5e
 
 
 
 
 
 
b6e6733
c1a6c5e
 
 
 
 
 
654b942
c1a6c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654b942
 
c1a6c5e
 
654b942
 
c1a6c5e
 
 
 
 
 
 
 
 
654b942
c1a6c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654b942
c1a6c5e
 
 
 
654b942
c1a6c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9066d0b
c1a6c5e
 
 
 
 
9066d0b
 
c1a6c5e
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
import os
from io import BytesIO
from multiprocessing import Pool, cpu_count
from datasets import load_dataset
from PIL import Image
import gradio as gr
import pandas as pd

imagenet_hard_dataset = load_dataset("taesiri/imagenet-hard", split="validation")
THUMBNAIL_PATH = "dataset/thumbnails"
os.makedirs(THUMBNAIL_PATH, exist_ok=True)

max_size = (480, 480)

all_origins = set()
all_labels = set()
dataset_df = None

beautiful_dataset_names = {
    "imagenet": "ImageNet",
    "imagenet_a": "ImageNet-A",
    "imagenet_r": "ImageNet-R",
    "imagenet_sketch": "ImageNet-Sketch",
    "objectnet": "ObjectNet",
    "imagenet_v2": "ImageNet-V2",
}


def process_image(i):
    global all_origins
    image = imagenet_hard_dataset[i]["image"].convert("RGB")
    url_prefix = "https://imagenet-hard.taesiri.ai/"

    origin = imagenet_hard_dataset[i]["origin"]
    label = imagenet_hard_dataset[i]["english_label"]

    save_path = os.path.join(THUMBNAIL_PATH, origin)
    # make sure the folder exists
    os.makedirs(save_path, exist_ok=True)
    image_path = os.path.join(save_path, f"{i}.jpg")

    image.thumbnail(max_size, Image.LANCZOS)

    image.save(image_path, "JPEG", quality=100)

    url = url_prefix + image_path

    return {
        "preview": url,
        "filepath": image_path,
        "origin": imagenet_hard_dataset[i]["origin"],
        "labels": imagenet_hard_dataset[i]["english_label"],
    }


# PREPROCESSING
if os.path.exists("dataset.pkl"):
    dataset_df = pd.read_pickle("dataset.pkl")
    all_origins = set(dataset_df["origin"])
    all_labels = set().union(*dataset_df["labels"])
else:
    with Pool(cpu_count()) as pool:
        samples_data = pool.map(process_image, range(len(imagenet_hard_dataset)))
        dataset_df = pd.DataFrame(samples_data)
        print(dataset_df)
        all_origins = set(dataset_df["origin"])
        all_labels = set().union(*dataset_df["labels"])
        # save dataframe on disk
        dataset_df.to_csv("dataset.csv")
        dataset_df.to_pickle("dataset.pkl")


def get_values_for_the_slice(slice_df):
    returned_values = []
    for row in slice_df.itertuples():
        # returned_values.append(gr.update(value=row.preview))
        labels = ", ".join(row.labels)
        # replace _ with space
        labels = labels.replace("_", " ")

        dataset_name = beautiful_dataset_names[row.origin]

        label_string = f"{labels} -  ({dataset_name})"
        returned_values.append(gr.update(label=label_string, value=row.preview))
        # returned_values.append(gr.update(value=beautiful_dataset_names[row.origin]))

    if len(returned_values) < 16:
        returned_values.extend([None] * (16 - len(returned_values)))

    return returned_values


def get_slice(origin, label):
    global dataset_df

    if not origin and not label:
        filtered_df = dataset_df
    else:
        filtered_df = dataset_df[
            (dataset_df["origin"] == origin if origin else True)
            & (dataset_df["labels"].apply(lambda x: label in x) if label else True)
        ]

    max_value = len(filtered_df) // 16

    start_index = 0
    end_index = start_index + 16

    slice_df = filtered_df.iloc[start_index:end_index]
    returned_values = get_values_for_the_slice(slice_df)

    filtered_df = gr.Dataframe(filtered_df, datatype="markdown")
    return filtered_df, gr.update(maximum=max_value, value=0), *returned_values


def reset_filters_fn():
    return gr.update(value=None), gr.update(value=None)


def make_grid(grid_size):
    list_of_components = []

    with gr.Row():
        for row_counter in range(grid_size[0]):
            with gr.Column():
                for col_counter in range(grid_size[1]):
                    item_image = gr.Image()
                    # with gr.Accordion("Click for details", open=False):
                    # item_source = gr.Textbox(label="Source Dataset")

                    list_of_components.append(item_image)
                    # list_of_components.append(item_source)
                    # list_of_components.append(item_labels)

    return list_of_components


def slider_upadte(slider, df):
    start_index = (slider) * 16
    end_index = start_index + 16

    slice_df = df.iloc[start_index:end_index]
    returned_values = get_values_for_the_slice(slice_df)

    return returned_values


with gr.Blocks() as demo:
    gr.Markdown("# ImageNet-Hard Browser")
    # add link to home page and dataset
    gr.HTML("")
    gr.HTML()
    gr.HTML(
        """
    <center>
        <span style="font-size: 14px; vertical-align: middle;">
            <a href='https://zoom.taesiri.ai/'>Project Home Page</a> &nbsp;|&nbsp;
            <a href='https://huggingface.co/datasets/taesiri/imagenet-hard'>Dataset</a>
        </span>
    </center>
    """
    )

    with gr.Row():
        origin_dropdown = gr.Dropdown(all_origins, label="Origin")
        label_dropdown = gr.Dropdown(all_labels, label="Category")
    with gr.Row():
        show_btn = gr.Button("Show")
        reset_filters = gr.Button("Reset Filters")

    preview_dataframe = gr.Dataframe(visible=False)

    gr.Markdown("## Preview")

    maximum_vale = len(dataset_df) // 16

    preview_slider = gr.Slider(minimum=1, maximum=maximum_vale, step=1, value=1)
    all_components = make_grid((4, 4))

    show_btn.click(
        fn=get_slice,
        inputs=[origin_dropdown, label_dropdown],
        outputs=[preview_dataframe, preview_slider, *all_components],
    )

    reset_filters.click(
        fn=reset_filters_fn,
        inputs=[],
        outputs=[origin_dropdown, label_dropdown],
    )

    preview_slider.change(
        fn=slider_upadte,
        inputs=[preview_slider, preview_dataframe],
        outputs=[*all_components],
    )


demo.launch()