File size: 9,449 Bytes
7a4b92f
 
 
 
 
 
 
 
26b6ea3
5ab0373
 
 
 
7a4b92f
5ab0373
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ab0373
 
 
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26b6ea3
 
5ab0373
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ab0373
7a4b92f
 
 
 
 
 
 
5ab0373
7a4b92f
 
 
 
 
 
5ab0373
7a4b92f
5ab0373
 
7a4b92f
5ab0373
 
7a4b92f
 
 
 
 
 
 
 
5ab0373
7a4b92f
 
5ab0373
 
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
5ab0373
7a4b92f
 
5ab0373
7a4b92f
 
 
 
 
5ab0373
7a4b92f
0df5c51
5ab0373
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
5ab0373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
5ab0373
 
 
 
 
 
 
 
 
7a4b92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0df5c51
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
import gradio as gr
from uploader import save_data
from main import predict_task
from state_handler import load_example_result, reset_state
from file_reader import File
import numpy as np
from aws_handler import upload_file
from aris import create_metadata_table
import cv2
import base64
from bbox import draggable_js
from annotation_handler import load_frames
import json

max_tabs = 10
table_headers = ["TOTAL" , "FRAME_NUM", "DIR", "R", "THETA", "L", "TIME", "DATE", "SPECIES"]
info_headers = [
    "TOTAL_TIME", "DATE", "START", "END",
    "TOTAL_FISH", "UPSTREAM_FISH", "DOWNSTREAM_FISH", "NONDIRECTIONAL_FISH", 
    "TOTAL_FRAMES", "FRAME_RATE", 
    "UPSTREAM_MOTION", "INTENSITY", "THRESHOLD", "WINDOW_START", "WINDOW_END", "WATER_TEMP"
]
css = """
#result_json {
    height: 500px;
    overflow: scroll !important;
}
#marking_json textarea {
    height: 100% !important;
}
#marking_json label {
    height: calc(100% - 30px) !important;
}
#canvas {
    align-self: center;
}
"""
js_update_tabs = """
    async () => {
        let el_list = document.getElementById("result_handler").getElementsByClassName("svelte-1kcgrqr")
        let idx = (el_list[1].value === "LOADING") ? 1 : parseInt(el_list[1].value)
        console.log(idx)
        style_sheet = document.getElementById("tab_style")
        style_sheet.innerHTML = ""
        for (let i = 1; i <= idx; i++) {
            style_sheet.innerHTML += "button.svelte-kqij2n:nth-child(" + i + "):before {content: 'Result " + i + "';}"
        }
    }
"""

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




# Start function, called on file upload
def on_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)
    }

# Iterative function that performs inference on the next file in line
def handle_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
    metadata, json_filepath, zip_filepath, video_filepath, marking_filepath = predict_task(file_path, gradio_progress=set_progress)
    
    # Store result for that file
    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(metadata, 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(state["index"])),
        inference_handler: gr.update()
    }

# Show result UI based on example data
def show_example_data():
    load_example_result(result, table_headers, info_headers)
    state["index"] = 1
    return gr.update(value=str(state["index"])) 

def show_data():
    # Get last index
    i = state["index"] - 1

    # If index is larger than max_tabs, only add file to zip list
    if i >= max_tabs:
        return {
            zip_out: gr.update(value=result["path_zip"])
        }

    # Check if inference is done
    not_done = state['index'] < state['total']

    # Send update to UI, and to inference_handler to start next file inference
    return {
        zip_out: gr.update(value=result["path_zip"]),
        tabs[i]['tab']: gr.update(),
        tabs[i]['video']: gr.update(value=result["path_video"][i], visible=True),
        tabs[i]['metadata']: gr.update(value=result["fish_info"][i], visible=True),
        tabs[i]['table']: gr.update(value=result["fish_table"][i], visible=True),
        tab_parent: gr.update(selected=i),
        inference_handler: gr.update(value = str(np.random.rand()), visible=not_done)
    }



def init_annotation():

    frame_info = load_frames("static/example/input_file.aris", "static/example/640 2018-07-09_115439_results.json")

    html = "<div style='display:flex'>"
    html += "<canvas id='canvas' style='width:50%' onmousedown='mouse_down(event)' onmousemove='mouse_move(event)' onmouseup='mouse_up()' onmouseleave='mouse_up()'></canvas>"
    html += "<div id='annotation_display' style='width:50%'></div>"
    html += "</div>"
    html += "<p id='annotation_info' style='display:none'>" + json.dumps(frame_info) + "</p>"
    html += "<img id='annotation_img' onload='draw()' style='display:none'></img>"
    return html
    




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

        # Title of page
        gr.HTML(
            """
        <h1 align="center" style="font-size:xxx-large">Caltech Fisheye</h1>
        <p align="center">Submit an .aris file to analyze result.</p>
        <style id="tab_style"></style>
        """
        )

        annotation_editor = gr.HTML("""""")
        with open('annotation_editor.js', 'r') as f:
            js = f.read()
            print(js)
            annotation_editor.change(lambda x: gr.update(), None, annotation_editor, _js=js)
        gr.Button("Edit Annotation").click(init_annotation, None, annotation_editor)

    
        
        #Input field for aris submission
        input = File(file_types=[".aris", ".ddf"], type="binary", label="ARIS Input", file_count="multiple")

        # Dummy element to call inference events, this also displays the inference progress
        inference_handler = gr.Text(value=str(np.random.rand()), visible=False)

        # Dummy element to call UI events
        result_handler = gr.Text(value="LOADING", visible=False, elem_id="result_handler")

        # List of all UI components that will recieve outputs from the result_handler
        UI_components = []

        # Zip file output
        zip_out = gr.File(label="ZIP Output", interactive=False)
        UI_components.append(zip_out)

        # Create result tabs
        tabs = []
        with gr.Tabs() as tab_parent:
            UI_components.append(tab_parent)
            for i in range(max_tabs):
                with gr.Tab(label="", id=i, elem_id="result_tab"+str(i)) as tab:
                    with gr.Row():
                        metadata_out = gr.JSON(label="Info", visible=False, elem_id="marking_json")
                        video_out = gr.Video(label='Annotated Video', interactive=False, visible=False)
                    table_out = gr.Matrix(label='Indentified Fish', headers=table_headers, interactive=False, visible=False)
                    tabs.append({
                        'tab': tab,
                        'metadata': metadata_out,
                        'video': video_out,
                        'table': table_out
                    })
                    UI_components.extend([tab, metadata_out, video_out, table_out])

    # Button to show example result
    #gr.Button(value="Show Example Result").click(show_example_data, None, result_handler)

    # 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>
        """
    )

    # When a file is uploaded to the input, tell the inference_handler to start inference
    input.upload(fn=on_input, inputs=input, outputs=[inference_handler])

    # 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_handler.change(handle_next, None, [result_handler, inference_handler])

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

demo.queue().launch()

show_data()