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