File size: 22,840 Bytes
52a8aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
from flask import Flask, request, render_template, session, redirect, url_for,render_template_string
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from datetime import timedelta
import json
import datetime
import os
from tqdm import tqdm
import random

# ======== static and global variables ========
static_root_path="/data/xuan/video_eval/webpage/video_eval_bench"
root_dir="/data/xuan/video_eval"

app = Flask(__name__,static_folder='/data/xuan/video_eval/webpage/video_eval_bench')
app.secret_key = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=100)
PORT_NUM = 22002
subpath = "/video_eval_bench/"

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

base_model_mapping={"0":"pika",
             "1":"t2vz",
             "2":"vc2",
             "3":"ms",
             "4":"lavie_base",
             "5":"anidiff",
             "6":"lvdm",
             "7":"hotshot",
             "8":"zs_576w",
             }

local_video_dir="./videos_display"
res_dir="./res/res_current"
text_files_dir="text_files"
text_en_path=f"./{text_files_dir}/text_en_display.jsonl"
text_zh_path=f"./{text_files_dir}/text_zh_display.jsonl"
user_info_path=f"./{text_files_dir}/user_info.json"
reported_problem_log=f"./{text_files_dir}/problem_reported.json"
sampled_id_file=f"./{text_files_dir}/sampled_id.json"
num_que=7


# ======== preparing video-ids and videos  =========
video_id_list=[]
videos=[]

sampled_id_data=json.load(open(sampled_id_file, 'r'))
video_id_list=sampled_id_data["sampled_id"]

# if LOCAL_VIDEO == 1 and os.path.exists(f"{static_root_path}/{local_video_dir}/"):
#     raw_videos=sorted([file for file in 
#                        os.listdir(f"{static_root_path}/{local_video_dir}/") if file.endswith(('.mp4'))])
    
#     video_id_list=[f.split(".")[0] for f in raw_videos]

num_vid_each_user=1000

print("len of video_id_list ",len(video_id_list))

videos_all=[f"{v_id}.mp4" for v_id in video_id_list]
print(video_id_list[:30])


# ======= preparing text prompts ======== 
text_prompts_en_all=[]
text_prompts_zh_all=[]
with open(text_en_path,"r") as f:
    for line in f:
        text_prompts_en_all.append(json.loads(line))
with open(text_zh_path,"r") as f:
    for line in f:
        text_prompts_zh_all.append(json.loads(line))


# text_en_all=[]
# text_zh_all=[]
# with open(text_en_path,"r") as f:
#     for line in f:
#         text_en_all.append(json.loads(line))
# with open(text_zh_path,"r") as f:
#     for line in f:
#         text_zh_all.append(json.loads(line))

# text_prompts_en=[]
# text_prompts_zh=[]
# not_found=[]
# for i in tqdm(range(len(video_id_list))):
#     video_id=video_id_list[i]
#     found=False
#     for tmp_idx,x in enumerate(text_en_all):
#         if int(x['id']) == int(video_id):
#             text_prompts_en.append(x)
#             text_prompts_zh.append(text_zh_all[tmp_idx])
#             found=True
#             break
#     if not found:
#         not_found.append(video_id)
#         print(f"{i+1}-th video in sampled_id not found.")
# with open("/data/xuan/video_eval/not_found.txt","w") as f:
#     for item in not_found:
#         f.write(item+"\n")


# ======== textual static contents ========
with open(f'./templates/html_text_en/start.txt', 'r') as file:
    before_start=file.read()
with open(f'./templates/html_text_zh/start_zh.txt', 'r') as file:
    before_start_zh=file.read()
subscore_def_en_list=[]
subscore_files=["visual.txt","object.txt","dynamic.txt","motion.txt","align.txt","factual.txt","overall.txt"]
for _,fname in enumerate(subscore_files):
    with open(f'./templates/html_text_en/{fname}', 'r') as file:
        content = file.read()
    subscore_def_en_list.append(content)
subscore_def_zh_list=[]
subscore_zh_files=["visual_zh.txt","object_zh.txt","dynamic_zh.txt","motion_zh.txt","align_zh.txt","factual_zh.txt","overall_zh.txt"]
for _,fname in enumerate(subscore_zh_files):
    with open(f'./templates/html_text_zh/{fname}', 'r') as file:
        content = file.read()
    subscore_def_zh_list.append(content)


# ========= resources for pre-annotating trial =========
pre_anno_video_dir="pre_anno/pre_anno_videos"
pre_anno_text_en_path=f"{static_root_path}/pre_anno/pre_anno_text_en.json"
pre_anno_text_zh_path=f"{static_root_path}/pre_anno/pre_anno_text_en.json"
pre_anno_ref_en_path=f"{static_root_path}/pre_anno/pre_anno_ref_en.json"
pre_anno_ref_zh_path=f"{static_root_path}/pre_anno/pre_anno_ref_zh.json"
pre_anno_videos=sorted([file for file in os.listdir(f"{static_root_path}/{pre_anno_video_dir}") if file.endswith(('.mp4'))])
pre_anno_prompts_en = json.load(open(pre_anno_text_en_path, "r")) 
pre_anno_prompts_zh = json.load(open(pre_anno_text_zh_path, "r"))



# ======== user info ========
current_user_dict={}
if os.path.exists(f"{user_info_path}"):
    user_data= json.load(open(f'{user_info_path}', 'r'))
    users=list(user_data.keys())
    print("users ",users)
else:
    with open(f"{user_info_path}","w") as f:
        json.dump({},f,indent=4)
        pass
    user_data={}
    users=[]

s_idx_user_mapping={}
for user in users:
    curr_user_dict=user_data.get(user)
    s_idx=curr_user_dict["s_idx"]
    s_idx_user_mapping[f"{s_idx}"]=curr_user_dict["username"]

# ========= validation info ========
annotators=users
answers_all=[]
VALIDATE_USER_NAME="video_admin"


# ======== user login part ========
class User(UserMixin):
    def __init__(self, id):
        print("user init")
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    if user_id in users:
        print("load user ",user_id)
        return User(user_id)
    else:
        print("user_id not in users_list")
    return None



# ======== webpage contents ========
@app.route(f'{subpath}',methods=['GET'])
def start():
    return redirect(url_for('welcome'))


@app.route(f'{subpath}welcome', methods=['GET','POST'])
def welcome():
    session['current_idx']=0
    session["pre_anno_answers"]={}
    session['admin']=None
    session['s_idx_val']=0
    session['e_idx_val']=len(video_id_list)-1

    html_file="welcome.html"
    subscore_def=subscore_def_en_list
    before_start_anno=before_start

    language = request.form.get('language',"en")
    session["language"]=language
    print("welcome language", language)
    if language=="zh":
        session["language"]="zh"
        html_file="welcome_zh.html"
        subscore_def=subscore_def_zh_list
        before_start_anno=before_start_zh

    
    return render_template(html_file,\
                    before_start_anno=before_start_anno,\
                           visual_def=subscore_def[0],\
                           object_def=subscore_def[1],\
                           dynamic_def=subscore_def[2],\
                            motion_def=subscore_def[3],\
                            align_def=subscore_def[4],\
                            factual_def=subscore_def[5],\
                            overall_def=subscore_def[6])


@app.route(f'{subpath}login', methods=['POST'])
def login():
    username = request.form['username']
    ans_path=f""
    if username in users:
        print("user ",username)
        curr_user_dict = user_data.get(username)
        ans_path=f"{res_dir}/ans_{username}.jsonl"
        
    else:
        return redirect(url_for('welcome'))
        # print("new user ",username)
        # users.append(username)
        # new_user_dict={"username":username,
        #     "timestamp":datetime.datetime.now().strftime('%Y-%m-%d-%H_%M_%S'),
        #     "current_idx":0}
        
        # user_data[username]=new_user_dict
        # with open(f"{user_info_path}","w") as f:
        #     json.dump(user_data,f,indent=4)

        # ans_path=f"{res_dir}/ans_{username}_{new_user_dict['timestamp']}.jsonl"
        # with open(f"{ans_path}","w") as f:
        #     None
        
    user = User(username)
    login_user(user)

    curr_user_dict=user_data.get(username)
    session['username'] = curr_user_dict["username"]
    session['s_idx']=curr_user_dict['s_idx']
    session['e_idx']=curr_user_dict['e_idx']
    session['current_idx']=curr_user_dict['current_idx']
    return redirect(url_for('display'))


@app.route(f'{subpath}logout',methods=['POST'])
@login_required
def logout():
    logout_user()
    session.pop('username', None)
    session.pop('s_idx', None)
    session.pop('e_idx', None)
    session.pop('current_idx', None)
    language=request.form.get('language',"en")
    session["language"]=language
    print("after logout ",language)
    return redirect(url_for('welcome'))


@app.route(f'{subpath}pre-annotating-trial',methods=['GET','POST'])
def pre_anno():
    current_idx=int(session.get("current_idx",0))
    print("curr_idx in pre-anno ",current_idx)

    if current_idx <= len(pre_anno_videos)-1:
        vid_name=pre_anno_videos[current_idx].split(".")[0]
        print("video name in pre-anno ",f"{vid_name}.mp4")

        answer_data_list_en = json.load(open(pre_anno_ref_en_path, "r"))
        answer_data_list_zh = json.load(open(pre_anno_ref_zh_path, "r"))

        current_answers=[]
        if vid_name in list(session["pre_anno_answers"].keys()):
            current_answers=session["pre_anno_answers"][vid_name]
        answered_vid_list=list(session["pre_anno_answers"].keys())

        refs=answer_data_list_en[current_idx]["ref"]
        current_reasons_en=answer_data_list_en[current_idx]["reasons"]
        current_reasons_zh=answer_data_list_zh[current_idx]["reasons"]

        print("current_answers (list) ",current_answers)
        print("answered_videos", answered_vid_list)

        html_file="pre_anno.html"
        subscore_def=subscore_def_en_list
        pre_anno_prompts=pre_anno_prompts_en
        reasons=current_reasons_en
        before_start_anno=before_start
        
        language=session.get("language","en")
        print("language in pre-anno ",language)
        if language=="zh":
            html_file="pre_anno_zh.html"
            subscore_def=subscore_def_zh_list
            pre_anno_prompts=pre_anno_prompts_zh
            reasons=current_reasons_zh
            before_start_anno=before_start_zh
        
        return render_template(html_file, \
            before_start_anno=before_start_anno,\
            subscore_def=subscore_def,\
            num_que=num_que,
            start_index=0,end_index=len(pre_anno_videos)-1,
            current_idx=current_idx,\
            vid_name=vid_name,\
            video=f"{pre_anno_video_dir}/{pre_anno_videos[current_idx]}", \
            text_prompt=pre_anno_prompts[current_idx]["text"],\
            current_answers=current_answers,\
            current_reasons=reasons,\
            current_refs=refs,\
            answered_vid_list=answered_vid_list
                    )
    else:
        current_idx=0
        session["current_idx"]=current_idx

        print("curr_idx in pre-anno ",current_idx)
        return redirect(url_for('pre_anno'))

@app.route(f'{subpath}pre-annotating-submit',methods=['POST'])
def pre_anno_submit():
    current_idx = int(request.form['current_idx'])
    vid_name=request.form['video'].split("/")[-1].split(".")[0]

    answer_list=[]
    for i in range(num_que):
        answer_list.append(request.form.get(f'q{i+1}'))
    
    if vid_name not in session['pre_anno_answers']:
        session['pre_anno_answers'][vid_name]=answer_list
        session.modified = True
    else:
        session['pre_anno_answers'][vid_name]=answer_list

    session['current_idx'] = current_idx + 1
    session.modified = True

    print("in pre-anno submit, session[\'answers\'] ",session['pre_anno_answers'])
    print("idx after pre-anno submission ", session.get("current_idx",0))

    return redirect(url_for('pre_anno'))


@app.route(f'{subpath}annotating',methods=['GET','POST'])
def display():
    s_idx=session["s_idx"]
    e_idx=session["e_idx"]
    videos_curr_user=videos_all[s_idx:e_idx+1]
    text_prompts_en=text_prompts_en_all[s_idx:e_idx+1]
    text_prompts_zh=text_prompts_zh_all[s_idx:e_idx+1]
    username=session["username"]
    ans_file=f"{res_dir}/ans_{username}.jsonl"
    current_idx=int(session.get("current_idx",0))
    print("curr_idx in display ",current_idx)
    
    slice_start_idx=0
    slice_end_idx=len(videos_curr_user)-1
    if current_idx <= slice_end_idx:
        vid_name=videos_curr_user[current_idx].split(".")[0]
        print("video name in display ",f"{vid_name}.mp4")
        
        video=f"{local_video_dir}/{videos_curr_user[current_idx]}"

        answer_data_dict={}
        with open(ans_file,'r') as f:
            data=[json.loads(line) for line in f]
            for d in data:
                answer_data_dict.update(d)

        answered_vid_list=list(answer_data_dict.keys())
        unanswered_least_idx=0
        for video_tmp_idx,vid in enumerate(videos_curr_user):
            tmp_name=vid.split(".")[0]
            tmp_ans=answer_data_dict.get(tmp_name,["None" for _ in range(num_que)])
            if "None" in tmp_ans:
                unanswered_least_idx=video_tmp_idx
                break
        
        current_answers=[]
        if vid_name in answered_vid_list:
            current_answers=answer_data_dict[vid_name]
        # print("answered_vid_list",answered_vid_list)
        print("current_answers (list) ",current_answers)

        html_file="display.html"
        subscore_def=subscore_def_en_list
        before_start_anno=before_start
        prompt=text_prompts_en[current_idx]["text"]
        language=session.get("language","en")
        print("language in display ",language)

        if language=="zh":
            html_file="display_zh.html"
            subscore_def=subscore_def_zh_list
            before_start_anno=before_start_zh
            prompt=text_prompts_zh[current_idx]["text"]

        return render_template(html_file, \
            before_start_anno=before_start_anno,\
            num_que=num_que,\
            subscore_def=subscore_def,\
            start_index=slice_start_idx,\
            end_index=slice_end_idx,\
            current_idx=current_idx,\
            unanswered_least_idx=unanswered_least_idx,\
            vid_name=vid_name,\
            video=video,\
            text_prompt=prompt,\
            answered_vid_list=answered_vid_list,\
            current_answers=current_answers,\
            _is_val=0)

    else:
        current_idx=0
        session["current_idx"]=current_idx
        user_data[username]['current_idx']=session['current_idx']
        with open(f"{user_info_path}","w") as file:
            json.dump(user_data, file, indent=4)

        print("curr_idx in display ",current_idx)
        return redirect(url_for('display'))


@app.route(f'{subpath}validate', methods=['GET','POST'])
def validate():
    admin = request.form.get('admin')
    if admin == None:
        admin = session.get("admin",None)

    if admin != VALIDATE_USER_NAME:
        return redirect(url_for('welcome'))
    
    current_idx=int(session.get("current_idx",0))
    print("in validate curr_idx,", current_idx)

    vid_name=videos_all[current_idx].split(".")[0]
    print("video name in val ",f"{vid_name}.mp4")

    video=f"{local_video_dir}/{videos_all[current_idx]}"
    print("video ",video)

    video_pos_idx=video_id_list.index(vid_name)
    s_idx=int(video_pos_idx/num_vid_each_user)*num_vid_each_user
    session["s_idx"]=s_idx

    username=s_idx_user_mapping[f"{s_idx}"]
    annotators=[username]
    ans_path=f"{res_dir}/ans_{username}.jsonl"
    current_answers_all=[]
    answer_data_list=[]

    with open(f"{ans_path}", "r") as f:
        data_list = list(f)
        answer_data_list = [json.loads(x) for x in data_list]
    answer_data_dict={}
    for d in answer_data_list:
        answer_data_dict.update(d)
    if vid_name in list(answer_data_dict.keys()):
        current_answers=answer_data_dict[vid_name]
    else:
        current_answers=[None for _ in range(num_que)]
    current_answers_all.append(current_answers)
    
    answers_all.append(answer_data_dict)
    print("answers_all", answers_all)
    
    # for _,ann in enumerate(annotators):
    #     print(ann)
    #     user_dict=user_info.get(ann)
    #     user_name=ann
    #     ans_path=f"{res_dir}/ans_{user_name}.jsonl"

    #     answer_data_list=[]
    #     with open(f"{ans_path}", "r") as f:
    #         data_list = list(f)
    #         answer_data_list = [json.loads(x) for x in data_list]
    #     answer_data_dict={}
    #     for d in answer_data_list:
    #         answer_data_dict.update(d)

    #     if vid_name in list(answer_data_dict.keys()):
    #         current_answers=answer_data_dict[vid_name]
    #     else:
    #         current_answers=[None for _ in range(num_que)]
    #     current_answers_all.append(current_answers)
        
    #     answers_all.append(answer_data_dict)

    print("answers_all", answers_all)

    return render_template("validate.html",\
                           num_row=num_que,\
                           num_colm=len(annotators),\
                           start_index=0,\
                           end_index=len(video_id_list)-1,\
                           current_idx=current_idx,\
                           annotators=annotators,\
                           video=video, \
                           text_prompt=text_prompts_en_all[current_idx]["text"],\
                           current_answers_all=current_answers_all,\
                            _is_val=1)


@app.route(f'{subpath}navigate_main', methods=['POST'])
def navigate_main():
    s_idx=session["s_idx"]
    e_idx=session["e_idx"]
    slice_end_idx=e_idx-s_idx
    direction = request.form['direction']
    current_idx = int(request.form['current_idx'])

    if direction == 'last':
        if current_idx>0:
            current_idx -= 1
        else:
            current_idx = slice_end_idx
    elif direction == 'next':
        if current_idx < slice_end_idx:
            current_idx += 1
        else:
            current_idx = 0

    session["current_idx"]=current_idx
    print("idx after navigation ", session.get("current_idx",0))
    
    print("navigaiton of display")
    return redirect(url_for('display'))

@app.route(f'{subpath}navigate_turn', methods=['POST'])
def navigate_turn():
    s_idx=session["s_idx"]
    e_idx=session["e_idx"]
    slice_end_idx=e_idx-s_idx
    current_idx = int(request.form['current_idx'])
    next_idx = request.form['next_idx']
    if next_idx.isdigit():
        if int(next_idx)>=1 and int(next_idx)<=slice_end_idx+1:
            session["current_idx"]=int(next_idx)-1
    else:
        session["current_idx"]=current_idx
    return redirect(url_for('display'))



@app.route(f'{subpath}navigate_val', methods=['POST'])
def navigate_val():
    s_idx=session["s_idx_val"]
    e_idx=session["e_idx_val"]
    slice_end_idx=e_idx-s_idx
    admin=request.form.get('admin')
    direction = request.form['direction']
    current_idx = int(session.get("current_idx",0))

    if direction == 'last':
        if current_idx>0:
            current_idx -= 1
        else:
            current_idx = slice_end_idx
    elif direction == 'next':
        if current_idx < slice_end_idx:
            current_idx += 1
        else:
            current_idx = 0

    session["current_idx"]=current_idx
    session["admin"]=admin

    print("idx after navigation ", session.get("current_idx",0))
    print("admin in navigation ", session.get("admin",None))
    
    print("navigaiton of val")
    return redirect(url_for('validate'))

@app.route(f'{subpath}navigate_turn_val', methods=['POST'])
def navigate_turn_val():
    s_idx=session["s_idx_val"]
    e_idx=session["e_idx_val"]
    slice_end_idx=e_idx-s_idx
    admin=request.form.get('admin')
    current_idx = int(request.form['current_idx'])
    next_idx = request.form['next_idx']
    if next_idx.isdigit():
        if int(next_idx)>=1 and int(next_idx)<=slice_end_idx+1:
            session["current_idx"]=int(next_idx)-1
    else:
        session["current_idx"]=current_idx
    session["admin"]=admin
    return redirect(url_for('validate'))

@app.route(f'{subpath}navigate_pre_anno', methods=['POST'])
def navigate_pre_anno():
    pre_anno_end_index=len(pre_anno_videos)-1
    direction = request.form['direction']
    current_idx = int(request.form['current_idx'])

    if direction == 'last':
        if current_idx>0:
            current_idx -= 1
        else:
            current_idx = pre_anno_end_index
    elif direction == 'next':
        if current_idx < pre_anno_end_index:
            current_idx += 1
        else:
            current_idx = 0

    session["current_idx"]=current_idx
    print("idx after navigation ", session.get("current_idx",0))
    
    print("navigaiton of pre-annotation")
    return redirect(url_for('pre_anno'))


@app.route(f'{subpath}submit', methods=['POST'])
def submit():
    username = session['username']
    ans_file=f"{res_dir}/ans_{username}.jsonl"

    problem_reported=request.form.get('problem',0)
    current_idx = int(request.form['current_idx'])
    vid_name=request.form['video'].split("/")[-1].split(".")[0]
    text=request.form['text_prompt']

    answer_list=[]
    if not problem_reported:
        for i in range(num_que):
            answer_list.append(str(request.form.get(f'q{i+1}')))
    else:
        answer_list=["-1" for _ in range(num_que)]
        with open(f"{reported_problem_log}","r") as problem_log:
            problem_list=json.load(problem_log)
        problem_list.append({
                "username":username,
                "text_prompt":text,
                "video_name":request.form['video']
            }) 
        
        with open(f"{reported_problem_log}","w") as problem_log:
            json.dump(problem_list,problem_log,indent=4)

    answer_dict={vid_name:answer_list}

    answer_data_dict={}
    with open(ans_file,'r') as f:
        data=[json.loads(line) for line in f]
        for d in data:
            answer_data_dict.update(d)
    answer_data_dict[vid_name]=answer_list

    with open(ans_file,"a") as file:
        json.dump(answer_dict, file)
        file.write('\n')

    session['current_idx'] = current_idx + 1
    session.modified = True

    #print("in submit, session[\'answers\'] ",session['answers'])
    print("idx after submission ", session.get("current_idx",0))

    user_data[username]['current_idx']=session['current_idx']
    with open(f"{user_info_path}","w") as file:
        json.dump(user_data, file, indent=4)

    return redirect(url_for('display'))


if __name__ == '__main__':
    app.run(port=PORT_NUM)
    # app.run(debug=True,port=PORT_NUM)


# gunicorn -w 4 -b 0.0.0.0:22002 al_flask:app
# ps aux | grep gunicorn
    
# tmux new-session -s flaskapp
# tmux list-sessions
# tmux attach-session -t flaskapp
# tmux kill-session -t flaskapp