Download hf.py from IPEC-COMMUNITY/OpenFly: direct link, hf CLI and curl.
- Browser
- Download file 5.17 kB
-
https://huggingface.co/datasets/IPEC-COMMUNITY/OpenFly/resolve/main/hf.py
- Command line
-
hf download hf://datasets/IPEC-COMMUNITY/OpenFly/hf.py
-
curl -L -o hf.py https://huggingface.co/datasets/IPEC-COMMUNITY/OpenFly/resolve/main/hf.py
5.17 kB
| import glob | |
| import json | |
| import time | |
| from pathlib import Path | |
| import datasets | |
| from datasets.table import embed_table_storage | |
| from tqdm import tqdm | |
| def extract_number(s): | |
| # 移除 `.png` 后缀部分 | |
| if s.endswith(".png"): | |
| s = s.rsplit('.', 1)[0] # 删除文件扩展名 | |
| # 查找最后一个 "_" 后的数字部分 | |
| last_underscore_pos = s.rfind("_") | |
| if last_underscore_pos == -1: | |
| return float("inf") # 没有找到 "_" 时,返回一个较大的值,表示该项排最后 | |
| number_part = s[last_underscore_pos + 1:] | |
| # 尝试将数字部分转换为整数,如果失败则返回 float('inf') | |
| try: | |
| return int(number_part) | |
| except ValueError: | |
| return float("inf") | |
| def sort_strings(strings): | |
| # 使用 sorted 排序,根据数字部分排序 | |
| return sorted(strings, key=extract_number) | |
| def embed_images(dataset: datasets.Dataset) -> datasets.Dataset: | |
| format = dataset.format | |
| dataset = dataset.with_format("arrow") | |
| dataset = dataset.map(embed_table_storage, batched=False) | |
| dataset = dataset.with_format(**format) | |
| return dataset | |
| def read_jsonl(file_path): | |
| with open(file_path, 'r') as f: | |
| content = f.read() | |
| # 用来存储完整的 JSON 对象 | |
| json_objects = [] | |
| # 变量用于跟踪大括号的嵌套层级 | |
| brace_count = 0 | |
| start = 0 | |
| # 遍历文件内容 | |
| for idx, char in enumerate(content): | |
| if char == '{': | |
| # 增加嵌套层级 | |
| if brace_count == 0: | |
| start = idx # 记录开始位置 | |
| brace_count += 1 | |
| elif char == '}': | |
| # 减少嵌套层级 | |
| brace_count -= 1 | |
| if brace_count == 0: | |
| # 当嵌套层级归零时,意味着我们找到了一个完整的 JSON 对象 | |
| json_str = content[start:idx+1] | |
| try: | |
| # 将字符串解析为字典 | |
| json_objects.append(json.loads(json_str)) | |
| except json.JSONDecodeError as e: | |
| print(f"Error parsing JSON: {e}") | |
| continue | |
| action_dicts = [d for d in json_objects if 'action' in d] | |
| return action_dicts | |
| features = datasets.Features( | |
| { | |
| "env_id": datasets.Value("string"), | |
| "traj_id": datasets.Value("string"), | |
| "image_id": datasets.Value("string"), | |
| "frame_index": datasets.Value("int32"), | |
| "image": datasets.Image(), | |
| "pos": datasets.Sequence(length=3, feature=datasets.Value("float64")), | |
| "yaw": datasets.Value("float64"), | |
| "action_type": datasets.Value("string"), | |
| "action_value": datasets.Value("int32"), | |
| } | |
| ) | |
| json_path = '/cpfs01/shared/optimal/Datasets/Openfly/OpenFly/Annotation/unseen.json' | |
| with open(json_path, 'r') as file: | |
| data = json.load(file) | |
| for item in tqdm(data, ncols=100, position=0, desc="Progress"): | |
| path = '/cpfs01/shared/optimal/Datasets/Openfly/OpenFly/Image/'+str(item['image_path']) + '/' | |
| json_path = path + 'pose.jsonl' | |
| path += '*.png' # 假设图片格式为png,可以根据实际情况修改 | |
| print(json_path) | |
| # 获取所有匹配的文件 | |
| png_files = sort_strings(glob.glob(path)) | |
| action_list = read_jsonl(json_path) # 假设read_jsonl函数已经定义,用于读取jsonl文件 | |
| action_list.sort(key=lambda x: int(x['action']['imageid'])) # 根据帧号排序action_list | |
| image_path = Path(item['image_path']) | |
| env_id_item = image_path.parent | |
| traj_id_item = image_path.stem | |
| img_id = [Path(item).stem for item in png_files] | |
| num = len(png_files) | |
| assert num == len(action_list), f"Number of images and actions do not match: {num} != {len(action_list)}" | |
| data_dict = { | |
| "env_id" : [env_id_item] * num, | |
| "traj_id" : [traj_id_item] * num, | |
| "image_id" : img_id, | |
| "frame_index" : [i for i in range(num)], | |
| "image" : ['/cpfs01/shared/optimal/Datasets/Openfly/OpenFly/Image/'+str(image_path) + '/' + img_id[i] + '.png' for i in range(num)], | |
| "pos": [action_list[i]['action']['pos'][:3] for i in range(num)], | |
| "yaw": [action_list[i]['action']['yaw'] for i in range(num)], | |
| "action_type": [action_list[i]['action']['type'] for i in range(num)], | |
| "action_value": [action_list[i]['action']['value'] for i in range(num)] | |
| } | |
| path = Path("./hf") | |
| episode_dict = {key: data_dict[key] for key in features} | |
| ep_dataset = datasets.Dataset.from_dict(episode_dict, features=features, split="train") | |
| ep_dataset = embed_images(ep_dataset) | |
| ep_data_path = (path / data_dict["env_id"][0] / data_dict["traj_id"][0]).with_suffix(".parquet") | |
| ep_data_path.parent.mkdir(parents=True, exist_ok=True) | |
| ep_dataset.to_parquet(ep_data_path) | |
| # break | |
| # data = datasets.load_dataset('parquet', data_files=str(ep_data_path), split='train') | |
| # print(data) | |
| # import datasets | |
| # path = '/cpfs01/shared/optimal/Datasets/Openfly/OpenFly/hf/env_airsim_16/astar_data/high_average/2025-1-9_16-50-28_2007905771.parquet' | |
| # data = datasets.load_dataset('parquet', data_files=path, split='train') | |
| # print(data[1]) | |