File size: 10,199 Bytes
1865436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import gradio as gr
import cv2
import os
import shutil
import re
import torch 
import csv
import time

from src.sts.demo.sts import handle_sts
from src.ir.ir import handle_ir
from src.ir.src.models.tc_classifier import TCClassifier
from src.tracker.signboard_track import SignboardTracker

from omegaconf import DictConfig
from hydra import compose, initialize

signboardTracker = SignboardTracker()

tracking_result_dir = ""
output_track_format = "mp4v"
output_track = ""
output_sts = ""
video_dir = ""
vd_dir = ""
labeling_dir = ""

frame_out = {}
rs = {}
results = []

# with initialize(version_base=None, config_path="src/ir/configs", job_name="ir"):
#         config = compose(config_name="test")
# config: DictConfig
# model_ir = TCClassifier(config.model.train.model_name,
#                         config.model.train.n_classes,
#                         config.model.train.lr,
#                         config.model.train.scheduler_type,
#                         config.model.train.max_steps,
#                         config.model.train.weight_decay,
#                         config.model.train.classifier_dropout,
#                         config.model.train.mixout,
#                         config.model.train.freeze_encoder)
# model_ir = model_ir.load_from_checkpoint(checkpoint_path=config.ckpt_path, map_location=torch.device("cuda"))

def create_dir(list_dir_path):
    for dir_path in list_dir_path:
        if not os.path.isdir(dir_path):
            os.makedirs(dir_path)

def get_meta_from_video(input_video):
    if input_video is not None:
        video_name = os.path.basename(input_video).split('.')[0]

    global video_dir
    video_dir = os.path.join("static/videos/", f"{video_name}")

    global vd_dir
    vd_dir = os.path.join(video_dir, os.path.basename(input_video))

    global output_track
    output_track = os.path.join(video_dir,"original")

    global tracking_result_dir
    tracking_result_dir = os.path.join(video_dir,"track/cropped")

    global output_sts
    output_sts = os.path.join(video_dir,"track/sts")

    global labeling_dir
    labeling_dir = os.path.join(video_dir,"track/labeling")

    if os.path.isdir(video_dir):
        return None
    else:
        create_dir([output_track, video_dir, os.path.join(video_dir, "track/segment"), output_sts, tracking_result_dir, labeling_dir])

        # initialize the video stream
        video_cap = cv2.VideoCapture(input_video)
        # grab the width, height, and fps of the frames in the video stream.
        frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = int(video_cap.get(cv2.CAP_PROP_FPS))

        #tổng Fps
        # total_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
        # print(total_frames)
        # # Tính tổng số giây trong video
        # total_seconds = total_frames / video_cap.get(cv2.CAP_PROP_FPS)
        # print(total_seconds)

        # initialize the FourCC and a video writer object
        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        output = cv2.VideoWriter(vd_dir, fourcc, fps, (frame_width, frame_height))

        while True:
            success, frame = video_cap.read()
            # write the frame to the output file
            if success == True:
                output.write(frame)
            else:
                break
        # print(fps)
        # return gr.Slider(1, fps, value=4, label="FPS",step=1, info="Choose between 1 and {fps}", interactive=True)
        return gr.Textbox(value=fps)

def get_signboard(evt: gr.SelectData):
    name_fr = int(evt.index) + 1
    ids_dir = tracking_result_dir
    all_ids = os.listdir(ids_dir)
    gallery=[]
    for i in all_ids:
        fr_id = str(name_fr)
        al = re.search("[\d]*_"+fr_id+".png", i)
        if al:
            id_dir = os.path.join(ids_dir, i)
            gallery.append(id_dir)
    gallery = sorted(gallery)
    return gallery, name_fr

def tracking(fps_target):
    start = time.time()
    fps_target = int(fps_target)
    global results
    results = signboardTracker.inference_signboard(fps_target, vd_dir, output_track, output_track_format, tracking_result_dir)[0]
    # print("result", results)
    fd = []
    global frame_out
    list_id = []

    with open(os.path.join(video_dir, "track/label.csv"), 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["Signboard", "Frame", "Text"])

    for frame, values in results.items():
        frame_dir = os.path.join(output_track, f"{frame}.jpg")
        # segment = os.path.join(video_dir,"segment/" + f"{frame}.jpg")
        list_boxs = []
        full = []
        list_id_tmp = []
        # print("values", values)
        for value in values:

            list_boxs.append(value['box'])  
            list_id_tmp.append(value['id'])
        _, dict_rec_sign_out = handle_sts(frame_dir, labeling_dir, list_boxs, list_id_tmp)

        # predicted = handle_ir(frame_dir, dict_rec_sign_out, os.path.join(video_dir, "ir"))
        # print(predicted)

        # fd.append(frame_dir)
        # frame_out[frame] = full
        list_id.extend(list_id_tmp)
    list_id = list(set(list_id))
    # print(list_id)
    print(time.time()-start)
    return gr.Dropdown(label="signboard",choices=list_id, interactive=True)


def get_select_index(img_id, evt: gr.SelectData):
    ids_dir = tracking_result_dir
    # print(ids_dir)
    all_ids = os.listdir(ids_dir)
    gallery = []
    for i in all_ids:
        fr_id = str(img_id)
        al = re.search("[\d]*_"+fr_id+".png", i)
        if al:
            id_dir = os.path.join(ids_dir, i)
            gallery.append(id_dir)
    gallery = sorted(gallery)

    gallery_id=[]
    id_name = gallery[evt.index]
    id = os.path.basename(id_name).split(".")[0].split("_")[0]
    for i in all_ids:
        al = re.search("^" +id + "_[\d]*.png", i)
        if al:
            id_dir = os.path.join(ids_dir, i)
            gallery_id.append(id_dir)
    gallery_id = sorted(gallery_id)
    return gallery_id

id_glb = None
def select_id(evt: gr.SelectData):
    choice=[]
    global id_glb
    id_glb = evt.value
    for key, values in results.items():
        for value in values:
            if value['id'] == evt.value:
                choice.append(int(key))
    return gr.Dropdown(label="frame", choices=choice, interactive=True)


import pandas as pd

frame_glb = None
def select_frame(evt: gr.SelectData):
    full_img = os.path.join(output_track, str(evt.value) + ".jpg")
    crop_img = os.path.join(tracking_result_dir, str(id_glb) + "_" + str(evt.value) + ".png")

    global frame_glb
    frame_glb = evt.value
    data = pd.read_csv(os.path.join(labeling_dir, str(id_glb) + "_" + str(frame_glb) + '.csv'), header=0)

    return full_img, crop_img, data

def get_data(dtfr):
    print(dtfr)
    
    # df = pd.read_csv(os.path.join(video_dir, "track/label.csv"))
    # for i, row in df.iterrows():
    #     if str(row["Signboard"]) == str(id_tmp) and str(row["Frame"]) == str(frame_tmp):
    #         # print(row["Text"])
    #         df_new = df.replace(str(row["Text"]), str(labeling))
    # print(df_new)
    dtfr.to_csv(os.path.join(labeling_dir, str(id_glb) + "_" + str(frame_glb) + '.csv'), index=False, header=True)
    return

def seg_track_app():
    ##########################################################
    ######################  Front-end ########################
    ##########################################################
    with gr.Blocks(css=".gradio-container {background-color: white}") as demo:
        gr.Markdown(
            '''
            <div style="text-align:center;">
                <span style="font-size:3em; font-weight:bold;">POI Engineeing</span>
            </div>
            '''
        )
        with gr.Row():
            # video input
            with gr.Column(scale=0.2):

                tab_video_input = gr.Row(label="Video type input")
                with tab_video_input:
                    input_video = gr.Video(label='Input video')

                tab_everything = gr.Row(label="Tracking")
                with tab_everything:
                    with gr.Row():
                        seg_signboard = gr.Button(value="Tracking", interactive=True)
                all_info = gr.Row(label="Information about video")
                with all_info:
                    with gr.Row():
                        text = gr.Textbox(label="Fps")
                        check_fps = gr.Textbox(label="Choose fps for output", interactive=True)

            with gr.Column(scale=1):
                with gr.Row():
                    with gr.Column(scale=2):
                        with gr.Row():
                            with gr.Column(scale=1):
                                id_drop = gr.Dropdown(label="Signboards",choices=[])
                            with gr.Column(scale=1):
                                fr_drop = gr.Dropdown(label="Frames",choices=[])
                        full_img = gr.Image(label="Full Image")

                    with gr.Column(scale=1):
                        crop_img = gr.Image(label="Cropped Image")
                        with gr.Row():
                            dtfr = gr.Dataframe(headers=["Tag", "Value"], datatype=["str", "str"], interactive=True)
                        with gr.Row():
                            submit = gr.Button(value="Submit", interactive=True)

    ##########################################################
    ######################  back-end #########################
    ##########################################################
        input_video.change(
            fn=get_meta_from_video,
            inputs=input_video,
            outputs=text
        )
        seg_signboard.click(
            fn=tracking,
            inputs=check_fps,
            outputs=id_drop
        )

        id_drop.select(select_id, None, fr_drop)
        fr_drop.select(select_frame, None, [full_img,crop_img, dtfr])
        submit.click(get_data, dtfr, None)

    demo.queue(concurrency_count=1)
    demo.launch(debug=True, enable_queue=True, share=True)

if __name__ == "__main__":
    seg_track_app()