File size: 11,218 Bytes
2e1b62d
bb68d34
2e1b62d
bb68d34
 
7206ed3
2e1b62d
6db6a87
2e1b62d
 
 
56f79a3
 
 
2e1b62d
a8badba
2e1b62d
 
e66cf77
2e1b62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8badba
2e1b62d
 
 
 
a8badba
0da9dca
2e1b62d
 
 
 
0da9dca
2e1b62d
 
 
 
 
 
 
0da9dca
7206ed3
3e17a60
2e1b62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7206ed3
3e17a60
2e1b62d
3e17a60
2e1b62d
 
 
 
 
3e17a60
 
2e1b62d
 
3e17a60
b11b05c
7206ed3
2e1b62d
 
b11b05c
 
2e1b62d
 
 
7206ed3
a8badba
2e1b62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca54db1
2e1b62d
ca54db1
 
 
 
2e1b62d
ca54db1
2e1b62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca54db1
 
 
2e1b62d
 
ca54db1
2e1b62d
ca54db1
2e1b62d
 
ca54db1
 
 
2e1b62d
 
 
 
 
 
 
 
 
 
 
 
 
ca54db1
 
2e1b62d
ca54db1
 
2e1b62d
ca54db1
2e1b62d
 
 
 
 
 
 
 
 
 
a4e7597
2e1b62d
 
 
a4e7597
 
 
 
2e1b62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# Adapted from https://huggingface.co/spaces/hlydecker/MegaDetector_v5
# Adapted from https://huggingface.co/spaces/sofmi/MegaDetector_DLClive/blob/main/app.py
# Adapted from https://huggingface.co/spaces/Neslihan/megadetector_dlcmodels/blob/main/app.py
# Adapted from  https://huggingface.co/spaces/DeepLabCut/MegaDetector_DeepLabCut

import os
import threading

import gradio as gr
import numpy as np
import yaml
from dlclibrary.dlcmodelzoo.modelzoo_download import (
    download_huggingface_model,
)
from dlclive import Processor

# import transformers
from PIL import Image

from detection_utils import crop_animal_detections, predict_md
from dlc_utils import predict_dlc
from pytorch_utils import PYTORCH_MODELS, load_superanimal, predict_superanimal
from ui_utils import (
    confidence_legend_html,
    dlc_theme,
    gradio_description_and_examples,
    gradio_inputs_for_MD_DLC,
    gradio_outputs_for_MD_DLC,
)
from viz_utils import (
    draw_bbox_w_text,
    draw_keypoints_on_image,
    keypoint_confidence_rows,
    save_annotated_image,
    save_results_as_json,
    save_results_only_dlc,
    save_results_pytorch,
)

# TESTING (passes) download the SuperAnimal models:
# model = 'superanimal_topviewmouse'
# train_dir = 'DLC_models/sa-tvm'
# download_huggingface_model(model, train_dir)

# megadetector and dlc model look up
MD_models_dict = {
    "md_v5a": "MD_models/md_v5a.0.0.pt",  #
    "md_v5b": "MD_models/md_v5b.0.0.pt",
}

BACKENDS = ["PyTorch", "TensorFlow (legacy)"]

# TF (legacy) DLC models: model zoo name and target dir, per SuperAnimal
DLC_models_dict = {
    "superanimal_topviewmouse": ("superanimal_topviewmouse_dlcrnet", "DLC_models/sa-tvm"),
    "superanimal_quadruped": ("superanimal_quadruped_dlcrnet", "DLC_models/sa-q"),
}


#####################################################
def finalize_outputs(img_output, download_file, kpts_per_animal, map_label_id_to_str, color_by_confidence, colormap):
    annotated_file = save_annotated_image(img_output)
    confidence_rows = keypoint_confidence_rows(kpts_per_animal, map_label_id_to_str)
    legend = confidence_legend_html(colormap) if color_by_confidence else ""
    return img_output, legend, download_file, annotated_file, confidence_rows


#####################################################
def predict_pipeline_pytorch(
    img_input,
    superanimal,
    flag_dlc_only,
    flag_show_str_labels,
    bbox_likelihood_th,
    kpts_likelihood_th,
    font_style,
    font_size,
    keypt_color,
    marker_size,
    flag_color_by_confidence,
    colormap,
    bbox_color,
):
    # detection + pose with the SuperAnimal PyTorch models (keypoints in image coords)
    img_output, animals, bodyparts = predict_superanimal(
        img_input, superanimal, bbox_likelihood_th, kpts_likelihood_th, full_image=flag_dlc_only
    )
    map_label_id_to_str = dict(enumerate(bodyparts))

    for animal in animals:
        draw_keypoints_on_image(
            img_output,
            animal["kpts"],
            map_label_id_to_str,
            flag_show_str_labels,
            use_normalized_coordinates=False,
            font_style=font_style,
            font_size=font_size,
            keypt_color=keypt_color,
            marker_size=marker_size,
            color_by_confidence=flag_color_by_confidence,
            colormap=colormap,
        )
        if not flag_dlc_only:
            draw_bbox_w_text(img_output, animal["bbox"], font_size=font_size, bbox_color=bbox_color)

    pose_model, detector = PYTORCH_MODELS[superanimal]
    download_file = save_results_pytorch(
        animals,
        map_label_id_to_str,
        superanimal,
        pose_model,
        None if flag_dlc_only else detector,
        image_size=img_input.size,
        annotated_size=img_output.size,
    )
    return finalize_outputs(
        img_output,
        download_file,
        [animal["kpts"] for animal in animals],
        map_label_id_to_str,
        flag_color_by_confidence,
        colormap,
    )


#####################################################
def predict_pipeline(
    img_input,
    backend,
    mega_model_input,
    dlc_model_input_str,
    flag_dlc_only,
    flag_show_str_labels,
    bbox_likelihood_th,
    kpts_likelihood_th,
    font_style,
    font_size,
    keypt_color,
    marker_size,
    flag_color_by_confidence,
    colormap,
    bbox_color,
):

    if backend == "PyTorch":
        return predict_pipeline_pytorch(
            img_input,
            dlc_model_input_str,
            flag_dlc_only,
            flag_show_str_labels,
            bbox_likelihood_th,
            kpts_likelihood_th,
            font_style,
            font_size,
            keypt_color,
            marker_size,
            flag_color_by_confidence,
            colormap,
            bbox_color,
        )

    # TensorFlow (legacy): MegaDetector crops + DLCLive
    dlc_model_name, dlc_model_dir = DLC_models_dict[dlc_model_input_str]

    if not flag_dlc_only:
        ############################################################
        # ### Run Megadetector
        md_results = predict_md(
            img_input,
            MD_models_dict[mega_model_input],  # mega_model_input,
            size=640,
        )  # Image.fromarray(results.imgs[0])

        ################################################################
        # Obtain animal crops (and their bboxes) with confidence above th
        list_crops, list_bboxes = crop_animal_detections(img_input, md_results, bbox_likelihood_th)

        ############################################################

    ## Get DLC model and label map

    # If model is found: do not download (previous execution is likely within same day)
    # TODO: can we ask the user whether to reload dlc model if a directory is found?
    path_to_DLCmodel = dlc_model_dir
    if not (os.path.isdir(dlc_model_dir) and len(os.listdir(dlc_model_dir)) > 0):
        download_huggingface_model(dlc_model_name, path_to_DLCmodel)

    # extract map label ids to strings
    pose_cfg_path = os.path.join(dlc_model_dir, "pose_cfg.yaml")
    with open(pose_cfg_path) as stream:
        pose_cfg_dict = yaml.safe_load(stream)
    map_label_id_to_str = dict(
        [
            (k, v)
            for k, v in zip(
                [
                    el[0] for el in pose_cfg_dict["all_joints"]
                ],  # pose_cfg_dict['all_joints'] is a list of one-element lists,
                pose_cfg_dict["all_joints_names"],
                strict=True,
            )
        ]
    )

    ##############################################################
    # Run DLC and visualize results
    dlc_proc = Processor()  # TODO: update deeplabcut.video_inference_superanimal() once merged

    # if required: ignore MD crops and run DLC on full image [mostly for testing]
    if flag_dlc_only:
        # compute kpts on input img
        list_kpts_per_crop = predict_dlc([np.asarray(img_input)], kpts_likelihood_th, path_to_DLCmodel, dlc_proc)
        # draw kpts on input img #fix!
        draw_keypoints_on_image(
            img_input,
            list_kpts_per_crop[0],  # a numpy array with shape [num_keypoints, 2].
            map_label_id_to_str,
            flag_show_str_labels,
            use_normalized_coordinates=False,
            font_style=font_style,
            font_size=font_size,
            keypt_color=keypt_color,
            marker_size=marker_size,
            color_by_confidence=flag_color_by_confidence,
            colormap=colormap,
        )

        donw_file = save_results_only_dlc(
            list_kpts_per_crop[0], map_label_id_to_str, dlc_model_name, image_size=img_input.size
        )

        return finalize_outputs(
            img_input, donw_file, [list_kpts_per_crop[0]], map_label_id_to_str, flag_color_by_confidence, colormap
        )

    else:
        # Compute kpts for each crop
        list_kpts_per_crop = predict_dlc(list_crops, kpts_likelihood_th, path_to_DLCmodel, dlc_proc)

        # resize input image to match megadetector output
        img_background = img_input.resize((md_results.ims[0].shape[1], md_results.ims[0].shape[0]))

        # draw keypoints on each crop and paste to background img
        for np_crop, kpts_crop, bb_per_animal in zip(list_crops, list_kpts_per_crop, list_bboxes, strict=True):
            img_crop = Image.fromarray(np_crop)

            # Draw keypts on crop
            draw_keypoints_on_image(
                img_crop,
                kpts_crop,  # a numpy array with shape [num_keypoints, 2].
                map_label_id_to_str,
                flag_show_str_labels,
                use_normalized_coordinates=False,  # if True, then I should use md_results.xyxyn for list_kpts_crop
                font_style=font_style,
                font_size=font_size,
                keypt_color=keypt_color,
                marker_size=marker_size,
                color_by_confidence=flag_color_by_confidence,
                colormap=colormap,
            )

            # Paste crop in original image
            img_background.paste(img_crop, box=tuple([int(t) for t in bb_per_animal[:2]]))

            # Plot bbox
            draw_bbox_w_text(img_background, bb_per_animal, font_size=font_size, bbox_color=bbox_color)

        # Save detection results as json
        download_file = save_results_as_json(
            md_results,
            list_kpts_per_crop,
            list_bboxes,
            map_label_id_to_str,
            dlc_model_name,
            mega_model_input,
            image_size=img_input.size,
        )

        return finalize_outputs(
            img_background, download_file, list_kpts_per_crop, map_label_id_to_str, flag_color_by_confidence, colormap
        )


#########################################################
# Define user interface and launch
[gr_title, gr_description, examples] = gradio_description_and_examples()

with gr.Blocks(title=gr_title) as demo:
    gr.Markdown(f"# {gr_title}\n{gr_description}")
    with gr.Row():
        with gr.Column():
            inputs = gradio_inputs_for_MD_DLC(BACKENDS, list(MD_models_dict.keys()), list(DLC_models_dict.keys()))
            run_button = gr.Button("Run", variant="primary")
        with gr.Column():
            outputs = gradio_outputs_for_MD_DLC()

    # the MegaDetector choice only applies to the TensorFlow (legacy) backend
    gr_backend_input, gr_mega_model_input = inputs[1], inputs[2]
    gr_backend_input.change(
        lambda backend: gr.update(visible=backend != "PyTorch"), inputs=gr_backend_input, outputs=gr_mega_model_input
    )

    run_button.click(predict_pipeline, inputs=inputs, outputs=outputs, api_name="predict")

    # cached on first click, so a failing download cannot block startup
    gr.Examples(examples, inputs=inputs, outputs=outputs, fn=predict_pipeline, cache_examples=True, cache_mode="lazy")

# download and build the default model while the app starts; a request arriving
# earlier waits on the same lock instead of downloading again
threading.Thread(target=load_superanimal, args=("superanimal_quadruped",), daemon=True).start()

demo.queue(default_concurrency_limit=1)  # PyTorch runners are not thread-safe
demo.launch(theme=dlc_theme())