Spaces:
Sleeping
Sleeping
File size: 12,062 Bytes
7670b16 a7ffe55 c91f75f 83e5a4c af9aa0c 8db6229 9d0eab4 7670b16 66897ef bb641ad 66897ef 19a05d0 4e68dcf 8174cbb 1f016ad f19f22f 7eab692 1ed9279 bf32cb4 f19f22f 1ed9279 bf32cb4 7eab692 027bc4a 7eab692 f19f22f 9d0eab4 66897ef 83e5a4c 1237651 83e5a4c 7670b16 83e5a4c 7670b16 4259255 19a05d0 a4bc7df 83e5a4c a4bc7df 5214878 a4bc7df 332e8c3 b74a384 19a05d0 7670b16 9d0eab4 a4bc7df 83e5a4c 26e4709 7670b16 1237651 9d0eab4 1237651 9d0eab4 7e0be42 9d0eab4 1237651 7e0be42 b48ceb9 1237651 9d0eab4 1237651 9d0eab4 7670b16 7e1033f 83e5a4c eef3de8 4590483 029752b 9a041b9 e7d96e2 348b569 eef3de8 83e5a4c 9d0eab4 7670b16 2150951 19a05d0 9d0eab4 19a05d0 9d0eab4 19a05d0 7670b16 83e5a4c 7670b16 07ca38c 7670b16 07ca38c 7670b16 a4bc7df 83e5a4c 1955e12 eef3de8 19a05d0 eef3de8 348b569 eef3de8 1955e12 19a05d0 7670b16 eef3de8 9d0eab4 7670b16 a4bc7df 7670b16 58238f7 |
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 |
import gradio as gr
import os
import random
import numpy as np
import pandas as pd
import gdown
import base64
from time import gmtime, strftime
from csv import writer
import json
from datasets import load_dataset
from hfserver import HuggingFaceDatasetSaver, HuggingFaceDatasetJSONSaver
ENVS = ['ShadowHand', 'ShadowHandCatchAbreast', 'ShadowHandOver', 'ShadowHandBlockStack', 'ShadowHandCatchUnderarm',
'ShadowHandCatchOver2Underarm', 'ShadowHandBottleCap', 'ShadowHandLiftUnderarm', 'ShadowHandTwoCatchUnderarm',
'ShadowHandDoorOpenInward', 'ShadowHandDoorOpenOutward', 'ShadowHandDoorCloseInward', 'ShadowHandDoorCloseOutward',
'ShadowHandPushBlock', 'ShadowHandKettle',
'ShadowHandScissors', 'ShadowHandPen', 'ShadowHandSwingCup', 'ShadowHandGraspAndPlace', 'ShadowHandSwitch']
# download data from huggingface dataset
# dataset = load_dataset("quantumiracle-git/robotinder-data")
os.remove('.git/hooks/pre-push') # https://github.com/git-lfs/git-lfs/issues/853
LOAD_DATA_GOOGLE_DRIVE = True
if LOAD_DATA_GOOGLE_DRIVE: # download data from google drive
# url = 'https://drive.google.com/drive/folders/1JuNQS4R7axTezWj1x4KRAuRt_L26ApxA?usp=sharing' # './processed/' folder in google drive
# url = 'https://drive.google.com/drive/folders/1o8Q9eX-J7F326zv4g2MZWlzR46uVkUF2?usp=sharing' # './processed_zip/' folder in google drive
# url = 'https://drive.google.com/drive/folders/1ZWgpPiZwnWfwlwta8Tu-Jtu2HsS7HAEa?usp=share_link' # './filter_processed_zip/' folder in google drive
url = 'https://drive.google.com/drive/folders/1AYOBLhkgYDeTyGktXN1wpNlwvWVxO8pt?usp=share_link' # './split_processed_zip/' folder in google drive
output = './'
id = url.split('/')[-1]
os.system(f"gdown --id {id} -O {output} --folder --no-cookies --remaining-ok")
# VIDEO_PATH = 'processed_zip'
# VIDEO_PATH = 'filter_processed_zip'
VIDEO_PATH = 'split_processed_zip'
import zipfile
from os import listdir
from os.path import isfile, join, isdir
# unzip the zip files to the same location and delete zip files
path_to_zip_file = VIDEO_PATH
zip_files = [join(path_to_zip_file, f) for f in listdir(path_to_zip_file)]
for f in zip_files:
if f.endswith(".zip"):
directory_to_extract_to = path_to_zip_file # extracted file itself contains a folder
print(f'extract data {f} to {directory_to_extract_to}')
with zipfile.ZipFile(f, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
os.remove(f)
else: # local data
VIDEO_PATH = 'robotinder-data'
VIDEO_INFO = os.path.join(VIDEO_PATH, 'video_info.json')
def inference(video_path):
# for displaying mp4 with autoplay on Gradio
with open(video_path, "rb") as f:
data = f.read()
b64 = base64.b64encode(data).decode()
html = (
f"""
<video controls autoplay muted loop>
<source src="data:video/mp4;base64,{b64}" type="video/mp4">
</video>
"""
)
return html
def video_identity(video):
return video
def nan():
return None
FORMAT = ['mp4', 'gif'][0]
def get_huggingface_dataset():
try:
import huggingface_hub
except (ImportError, ModuleNotFoundError):
raise ImportError(
"Package `huggingface_hub` not found is needed "
"for HuggingFaceDatasetSaver. Try 'pip install huggingface_hub'."
)
HF_TOKEN = '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' # my HF token
DATASET_NAME = 'crowdsourced-robotinder-demo'
FLAGGING_DIR = 'flag/'
path_to_dataset_repo = huggingface_hub.create_repo(
repo_id=DATASET_NAME,
token=HF_TOKEN,
private=False,
repo_type="dataset",
exist_ok=True,
)
dataset_dir = os.path.join(DATASET_NAME, FLAGGING_DIR)
repo = huggingface_hub.Repository(
local_dir=dataset_dir,
clone_from=path_to_dataset_repo,
use_auth_token=HF_TOKEN,
)
repo.git_pull(lfs=True)
log_file = os.path.join(dataset_dir, "flag_data.csv")
return repo, log_file
def update(user_choice, left, right, choose_env, data_folder=VIDEO_PATH, flag_to_huggingface=True):
global last_left_video_path
global last_right_video_path
global last_infer_left_video_path
global last_infer_right_video_path
if flag_to_huggingface: # log
env_name = str(last_left_video_path).split('/')[1] # 'robotinder-data/ENV_NAME/'
current_time = strftime("%Y-%m-%d-%H-%M-%S", gmtime())
info = [env_name, user_choice, last_left_video_path, last_right_video_path, current_time]
print(info)
repo, log_file = get_huggingface_dataset()
with open(log_file, 'a') as file: # incremental change of the file
writer_object = writer(file)
writer_object.writerow(info)
file.close()
if int(current_time.split('-')[-2]) % 5 == 0: # push only on certain minutes
try:
repo.push_to_hub(commit_message=f"Flagged sample at {current_time}")
except:
repo.git_pull(lfs=True) # sync with remote first
repo.push_to_hub(commit_message=f"Flagged sample at {current_time}")
if choose_env == 'Random' or choose_env == '': # random or no selection
envs = get_env_names()
env_name = envs[random.randint(0, len(envs)-1)]
else:
env_name = choose_env
# choose video
left, right = randomly_select_videos(env_name)
last_left_video_path = left
last_right_video_path = right
last_infer_left_video_path = inference(left)
last_infer_right_video_path = inference(right)
return last_infer_left_video_path, last_infer_right_video_path, env_name
def replay(left, right):
return left, right
def parse_envs(folder=VIDEO_PATH, filter=True, MAX_ITER=20000, DEFAULT_ITER=20000):
"""
return a dict of env_name: video_paths
"""
files = {}
if filter:
df = pd.read_csv('Bidexhands_Video.csv')
# print(df)
for env_name in os.listdir(folder):
env_path = os.path.join(folder, env_name)
if os.path.isdir(env_path):
videos = os.listdir(env_path)
video_files = []
for video in videos: # video name rule: EnvName_Alg_Seed_Timestamp_Checkpoint_video-episode-EpisodeID
if video.endswith(f'.{FORMAT}'):
if filter:
if len(video.split('_')) < 6:
print(f'{video} is wrongly named.')
seed = video.split('_')[2]
checkpoint = video.split('_')[4]
try:
succeed_iteration = df.loc[(df['seed'] == int(seed)) & (df['env_name'] == str(env_name))]['succeed_iteration'].iloc[0]
except:
print(f'Env {env_name} with seed {seed} not found in Bidexhands_Video.csv')
if 'unsolved' in succeed_iteration:
continue
elif pd.isnull(succeed_iteration):
min_iter = DEFAULT_ITER
max_iter = MAX_ITER
elif '-' in succeed_iteration:
[min_iter, max_iter] = succeed_iteration.split('-')
else:
min_iter = succeed_iteration
max_iter = MAX_ITER
# check if the checkpoint is in the valid range
valid_checkpoints = np.arange(int(min_iter), int(max_iter)+1000, 1000)
if int(checkpoint) not in valid_checkpoints:
continue
video_path = os.path.join(folder, env_name, video)
video_files.append(video_path)
# print(video_path)
files[env_name] = video_files
with open(VIDEO_INFO, 'w') as fp:
json.dump(files, fp)
return files
def get_env_names():
with open(VIDEO_INFO, 'r') as fp:
files = json.load(fp)
return list(files.keys())
def randomly_select_videos(env_name):
# load the parsed video info
with open(VIDEO_INFO, 'r') as fp:
files = json.load(fp)
env_files = files[env_name]
# randomly choose two videos
selected_video_ids = np.random.choice(len(env_files), 2, replace=False)
left_video_path = env_files[selected_video_ids[0]]
right_video_path = env_files[selected_video_ids[1]]
return left_video_path, right_video_path
def build_interface(iter=3, data_folder=VIDEO_PATH):
import sys
import csv
csv.field_size_limit(sys.maxsize)
HF_TOKEN = os.getenv('HF_TOKEN')
print(HF_TOKEN)
HF_TOKEN = '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' # my HF token
# hf_writer = gr.HuggingFaceDatasetSaver(HF_TOKEN, "crowdsourced-robotinder-demo") # HuggingFace logger instead of local one: https://github.com/gradio-app/gradio/blob/master/gradio/flagging.py
hf_writer = HuggingFaceDatasetSaver(HF_TOKEN, "crowdsourced-robotinder-demo")
# callback = gr.CSVLogger()
callback = hf_writer
# parse the video folder
files = parse_envs()
# build gradio interface
with gr.Blocks() as demo:
gr.Markdown("## Here is <span style=color:cyan>RoboTinder</span>!")
gr.Markdown("### Select the best robot behaviour in your choice!")
# some initial values
env_name = list(files.keys())[random.randint(0, len(files)-1)] # random pick an env
with gr.Row():
str_env_name = gr.Markdown(f"{env_name}")
# choose video
left_video_path, right_video_path = randomly_select_videos(env_name)
with gr.Row():
if FORMAT == 'mp4':
# left = gr.PlayableVideo(left_video_path, label="left_video")
# right = gr.PlayableVideo(right_video_path, label="right_video")
infer_left_video_path = inference(left_video_path)
infer_right_video_path = inference(right_video_path)
right = gr.HTML(infer_right_video_path, label="right_video")
left = gr.HTML(infer_left_video_path, label="left_video")
else:
left = gr.Image(left_video_path, shape=(1024, 768), label="left_video")
# right = gr.Image(right_video_path).style(height=768, width=1024)
right = gr.Image(right_video_path, label="right_video")
global last_left_video_path
last_left_video_path = left_video_path
global last_right_video_path
last_right_video_path = right_video_path
global last_infer_left_video_path
last_infer_left_video_path = infer_left_video_path
global last_infer_right_video_path
last_infer_right_video_path = infer_right_video_path
# btn1 = gr.Button("Replay")
user_choice = gr.Radio(["Left", "Right", "Not Sure"], label="Which one is your favorite?")
choose_env = gr.Radio(["Random"]+ENVS, label="Choose the next task:")
btn2 = gr.Button("Next")
# This needs to be called at some point prior to the first call to callback.flag()
callback.setup([user_choice, left, right], "flagged_data_points")
# btn1.click(fn=replay, inputs=[left, right], outputs=[left, right])
btn2.click(fn=update, inputs=[user_choice, left, right, choose_env], outputs=[left, right, str_env_name])
# We can choose which components to flag -- in this case, we'll flag all of them
# btn2.click(lambda *args: callback.flag(args), [user_choice, left, right], None, preprocess=False) # not using the gradio flagging anymore
return demo
if __name__ == "__main__":
last_left_video_path = None
last_right_video_path = None
demo = build_interface()
# demo.launch(share=True)
demo.launch(share=False)
|