File size: 13,009 Bytes
7a4b92f
a2bc65a
7a4b92f
fbb3995
7a4b92f
fbb3995
7a4b92f
193f172
5ab0373
592e4db
 
fbb3995
 
7a4b92f
 
 
 
 
 
193f172
 
7a4b92f
 
 
26b6ea3
a2bc65a
 
7a4b92f
 
 
 
 
 
 
 
a2bc65a
 
 
 
7a4b92f
 
a2bc65a
 
 
fbb3995
 
 
 
 
 
a2bc65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4b92f
a2bc65a
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
 
5ab0373
7a4b92f
 
 
 
 
 
 
5ab0373
7a4b92f
 
 
 
 
 
5ab0373
7a4b92f
5ab0373
 
592e4db
5ab0373
 
592e4db
c780404
7a4b92f
 
 
 
592e4db
7a4b92f
 
 
5ab0373
7a4b92f
 
5ab0373
 
7a4b92f
a2bc65a
 
7a4b92f
 
 
a2bc65a
 
 
7a4b92f
a2bc65a
7a4b92f
a2bc65a
 
 
 
 
 
 
7a4b92f
0df5c51
a2bc65a
193f172
 
 
 
a2bc65a
 
 
 
 
 
193f172
 
 
 
592e4db
c780404
193f172
 
592e4db
fbb3995
 
 
 
c780404
fbb3995
 
 
 
 
 
 
 
193f172
c780404
a2bc65a
592e4db
193f172
 
5ab0373
a2bc65a
5ab0373
7a4b92f
 
592e4db
7a4b92f
 
 
 
592e4db
a2bc65a
 
 
 
 
fbb3995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2bc65a
 
592e4db
7a4b92f
 
5ab0373
 
a2bc65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193f172
a2bc65a
 
fbb3995
a2bc65a
7a4b92f
 
 
 
 
 
 
 
 
 
 
a2bc65a
 
 
 
 
 
 
 
 
7a4b92f
a2bc65a
7a4b92f
 
 
a2bc65a
7a4b92f
 
a2bc65a
 
 
 
 
 
592e4db
a2bc65a
 
 
 
 
7a4b92f
 
 
a2bc65a
7a4b92f
 
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import gradio as gr
from uploader import save_data_to_dir, create_data_dir, save_data
from main import predict_task
from gradio_scripts.state_handler import reset_state
import numpy as np
from gradio_scripts.aws_handler import upload_file
from aris import create_metadata_table
from gradio_scripts.annotation_handler import init_frames
import json
from zipfile import ZipFile
import os
from gradio_scripts.upload_ui import Upload_Gradio
from gradio_scripts.result_ui import Result_Gradio, update_result, table_headers, info_headers, js_update_tab_labels


#Initialize State & Result
state = {
    'files': [],
    'index': 1,
    'total': 1,
    'annotation_index': -1
}
result = {}


# Called when an Aris file is uploaded for inference
def on_aris_input(file_list):

    # Reset Result
    reset_state(result, state)
    state['files'] = file_list
    state['total'] = len(file_list)

    # Update loading_space to start inference on first file
    return {
        inference_handler: gr.update(value = str(np.random.rand()), visible=True),
        components['cancelBtn']: gr.update(visible=True),
        components['skipBtn']: gr.update(visible=True),
        master_tabs: gr.update(selected=1)
    }

# Called when a result zip file is uploaded for result review
def on_result_upload(zip_list, aris_list):

    if (zip_list == None): 
        zip_list = [("static/example/example_result.zip", None)]
        aris_path = "static/example/input_file.aris"
        aris_list = [(aris_path, bytearray(open(aris_path, 'rb').read()))]
    

    reset_state(result, state)

    component_updates = { 
        master_tabs: gr.update(selected=1),
        tab_labeler: gr.update(value = len(zip_list))
    }

    for i in range(len(zip_list)):
            
        # Create dir to unzip files
        dir_name = create_data_dir(str(i))

        # Check aris input 
        if (aris_list):
            aris_info = aris_list[i]
            file_name = aris_info[0].split("/")[-1]
            bytes = aris_info[1]
            valid, input_path, dir_name = save_data_to_dir(bytes, file_name, dir_name)
        else:
            input_path = None

        # Unzip result
        zip_info = zip_list[i]
        zip_name = zip_info[0]
        print(zip_name)
        with ZipFile(zip_name) as zip_file:
            ZipFile.extractall(zip_file, path=dir_name)
        unzipped = os.listdir(dir_name)
        print(unzipped)

        for file in unzipped:
            if (file.endswith("_results.mp4")):
                result["path_video"].append(os.path.join(dir_name, file))
            elif (file.endswith("_results.json")):
                result["path_json"].append(os.path.join(dir_name, file))
            elif (file.endswith("_marking.txt")):
                result["path_marking"].append(os.path.join(dir_name, file))
        
        result["aris_input"].append(input_path)
        with open(result['path_json'][-1]) as f:
            json_result = json.load(f)
            result['json_result'].append(json_result)
        fish_table, fish_info = create_metadata_table(json_result, table_headers, info_headers)
        result["fish_table"].append(fish_table)
        result["fish_info"].append(fish_info)

        update = update_result(i, state, result, inference_handler)

        for key in update.keys():
            component_updates[key] = update[key]
    
    component_updates.pop(inference_handler)
    return component_updates


# Iterative function that performs inference on the next file in line
def infer_next(_, progress=gr.Progress()):

    if state['index'] >= state['total']: 
        return {
            result_handler: gr.update(),
            inference_handler: gr.update()
        }

    # Correct progress function for batch file input
    set_progress = lambda pct, msg : progress(pct, desc=msg)
    if state['total'] > 1:
        set_progress = lambda pct, msg : progress(pct, desc="File " + str(state['index']+1) + "/" + str(state['total']) + ": " + msg)
    set_progress(0, "Starting...")

    # Save file and create a new directory for result
    file_info = state['files'][state['index']]
    file_name = file_info[0].split("/")[-1]
    bytes = file_info[1]
    valid, file_path, dir_name = save_data(bytes, file_name)
    print(dir_name)
    print(file_path)

    # Check that the file was valid
    if not valid: 
        return {
            result_handler: gr.update(),
            inference_handler: gr.update()
        }

    # Send uploaded file to AWS 
    upload_file(file_path, "fishcounting", "webapp_uploads/" + file_name)

    # Do inference
    json_result, json_filepath, zip_filepath, video_filepath, marking_filepath = predict_task(file_path, gradio_progress=set_progress)
    
    # Store result for that file
    result['json_result'].append(json_result)
    result['aris_input'].append(file_path)
    result["path_video"].append(video_filepath)
    result["path_zip"].append(zip_filepath)
    result["path_json"].append(json_filepath)
    result["path_marking"].append(marking_filepath)
    fish_table, fish_info = create_metadata_table(json_result, table_headers, info_headers)
    result["fish_table"].append(fish_table)
    result["fish_info"].append(fish_info)

    # Increase file index
    state['index'] += 1

    # Send of update to result_handler to show new result
    # Leave inference_handler update blank to avoid starting next inference until result is updated
    return {
        result_handler: gr.update(value = str(np.random.rand())),
        tab_labeler: gr.update(value = str(state['index'])),
        inference_handler: gr.update()
    }

# Show result
def on_result_ready():
    # Update result tab for last file
    i = state["index"] - 1
    return update_result(i, state, result, inference_handler)

def cancel_inference():
    return {
        master_tabs: gr.update(selected=0),
        inference_handler: gr.update(visible=False),
        components['cancelBtn']: gr.update(visible=False),
        components['skipBtn']: gr.update(visible=False)
    }


# Request loading of animation editor
def prepare_annotation(index):

    state['annotation_index'] = index

    return {
        annotation_progress: gr.update(value="<p align='center' style='font-size: large;font-style: italic;'>Loading annotation...</p><!--" + str(np.random.rand()) + "-->", visible=True),
        master_tabs: gr.update(selected=2)
    }

# Load frames and annotation information and show
def open_annotation(_, progress=gr.Progress()):
    result_index = state['annotation_index']

    set_progress = lambda pct, msg: progress(pct, desc=msg)

    annotation_html = ""
    if result["aris_input"][result_index]:
        annotations = init_frames(result["aris_input"][result_index], result['json_result'][result_index], gp=set_progress)

        # Header
        annotation_html += "<div id='annotation_header'>"
        annotation_html += "     <h1 id='annotation_frame_nbr'>Frame 0/100</h1>"
        annotation_html += "     <p id='annotation_edited'>(edited)</p>"
        annotation_html += "</div>"

        # Annotation Body
        annotation_html += "<div style='display:flex'>"
        annotation_html += "     <canvas id='canvas' style='width:50%' onmousedown='mouse_down(event)' onmousemove='mouse_move(event)' onmouseup='mouse_up()' onmouseleave='mouse_up()'></canvas>"
        annotation_html += "     <div id='annotation_display' style='width:50%'></div>"
        annotation_html += "</div>"
        
        # Dummy objects
        annotation_html += "<p id='annotation_info' style='display:none'>" + json.dumps(annotations) + "</p>"
        annotation_html += "<img id='annotation_img' onload='draw()' style='display:none'></img>"
        annotation_html += "<!--" + str(np.random.rand()) + "-->"

    return gr.update(value=annotation_html, visible=True), gr.update(visible=False), gr.update(visible=True)


components = {}

demo = gr.Blocks()
with demo:
    with gr.Blocks() as inner_body:

        # Title of page
        gr.HTML(
            """
            <h1 align="center" style="font-size:xxx-large">Caltech Fisheye</h1>
            <style>
                #marking_json thead {
                    display: none !important;
                }
                .selected.svelte-kqij2n {
                    background: linear-gradient(180deg, #66eecb47, transparent);
                }
                #annotation_frame_nbr {
                    left: calc(50% - 100px);
                    position: absolute;
                    width: 200px;
                    text-align: center;
                    font-size: x-large;
                }
                #annotation_header {
                    height: 40px;
                }
                #annotation_frame_nbr {
                    left: calc(50% - 100px);
                    position: absolute;
                    width: 200px;
                    text-align: center;
                    font-size: x-large;
                }
                #annotation_edited {
                    right: 0px;
                    position: absolute;
                    margin-top: 5px;
                }
            </style>
            <style id="tab_style"></style>
        """
        )


        with gr.Tabs() as master_tabs:
            components['master_tabs'] = master_tabs

            # Master Tab for uploading aris or result files
            with gr.Tab("Upload", id=0):
                
                # Draw Gradio components related to the upload ui
                Upload_Gradio(components)

            # Master Tab for result visualization
            with gr.Tab("Result", id=1):


                # Define annotation progress bar for event listeres, but unrender since it will be displayed later on
                annotation_progress = gr.HTML("", visible=False).unrender()
                components['annotation_progress'] = annotation_progress
                
                # Draw the gradio components related to visualzing result
                vis_components = Result_Gradio(prepare_annotation, components)
                
            # Master Tab for annotation editing
            with gr.Tab("Annotation Editor", id=2):

                # Draw the annotation loading bar here
                annotation_progress.render()

                # Add annotation editor component
                annotation_editor = gr.HTML("", visible=False)

                # Event listener for opening annotation 
                annotation_progress.change(open_annotation, annotation_progress, [annotation_editor, annotation_progress])
                
                # Event listener for running javascript defined in 'annotation_editor.js'
                with open('gradio_scripts/annotation_editor.js', 'r') as f:
                    annotation_editor.change(lambda x: gr.update(), None, annotation_editor, _js=f.read())

    # Disclaimer at the bottom of page
    gr.HTML(
            """
        <p align="center">
        <b>Note</b>: The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. 
        In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.
        </p>
        """
    )

    # Extract important components for ease of code
    input = components['input']
    inference_handler = components['inference_handler']
    result_handler = components['result_handler']
    tab_labeler = components['tab_labeler']


    inference_comps = [inference_handler, master_tabs, components['cancelBtn'], components['skipBtn']]

    # When a file is uploaded to the input, tell the inference_handler to start inference
    input.upload(on_aris_input, input, inference_comps)

    # When inference handler updates, tell result_handler to show the new result
    # Also, add inference_handler as the output in order to have it display the progress
    inference_event = inference_handler.change(infer_next, None, [inference_handler, result_handler, tab_labeler])

    # Send UI changes based on the new results to the UI_components, and tell the inference_handler to start next inference
    result_handler.change(on_result_ready, None, vis_components + [inference_handler])

    # Cancel and skip buttons
    components['cancelBtn'].click(cancel_inference, None, inference_comps, cancels=[inference_event])
    components['skipBtn'].click(cancel_inference, None, inference_comps, cancels=[inference_event])

    # Button to load a previous result and view visualization
    components['preview_result_btn'].click(
        on_result_upload, 
        [components['result_input'], components['result_aris_input']], 
        vis_components + [master_tabs, tab_labeler]
    )

demo.queue().launch()

on_result_ready()