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
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
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_v2/video_eval_bench"
root_dir="/data/xuan/video_eval"

app = Flask(__name__,static_folder='/data/xuan/video_eval/webpage_v2/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=5


# ======== 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","temporal.txt","dynamic.txt","align.txt","factual.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","temporal_zh.txt","dynamic_zh.txt","align_zh.txt","factual_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_v2
# 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="zh/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],\
                           temporal_def=subscore_def[1],\
                           dynamic_def=subscore_def[2],\
                            
                            align_def=subscore_def[3],\
                            factual_def=subscore_def[4])


@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}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())
        # checked_vid_list=[list(item.keys())[0] for item in data[1000:]]
        # print(len(checked_vid_list))
        
        # unanswered_least_idx=0
        # for video_tmp_idx,vid in enumerate(videos_curr_user):
        #     tmp_name=vid.split(".")[0]
        #     if tmp_name not in checked_vid_list:
        #         unanswered_least_idx=video_tmp_idx
        #         break
                
        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="zh/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}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}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}
    
    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