Datasets:
Tasks:
Question Answering
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
1K - 10K
License:
weizhen
Refactor the images into subdirectories for compatibilities per HF Dataset. Updated VQA records to reflect the change
fae6778
| import json | |
| import os | |
| import tqdm | |
| def preprocess(): | |
| all_train = json.load(open('trainval.json', 'r')) | |
| im_ids = set() | |
| for vqa_id, vqa in all_train.items(): | |
| im_ids.add(vqa['obs'][0]) | |
| move_to_mapping = dict() | |
| subfolder_id = 0 | |
| subfolder_num_items = 0 | |
| max_items = 5000 | |
| for im_id in im_ids: | |
| move_to_mapping[im_id] = subfolder_id | |
| subfolder_num_items += 1 | |
| if subfolder_num_items >= max_items: | |
| subfolder_id += 1 | |
| subfolder_num_items = 0 | |
| json.dump(move_to_mapping, open('move_to_mapping.json', 'w'), indent=2) | |
| print(len(im_ids)) | |
| def refactor(): | |
| new_root_folder = 'trainval_obs' | |
| if not os.path.exists(new_root_folder): | |
| os.makedirs(new_root_folder) | |
| move_to_mapping = json.load(open('move_to_mapping.json', 'r')) | |
| all_train = json.load(open('trainval.json', 'r')) | |
| for vqa_id, vqa in tqdm.tqdm(all_train.items(), total=len(all_train)): | |
| im_id = vqa['obs'][0] | |
| im_file_name = os.path.basename(im_id) | |
| subfolder_id = move_to_mapping[im_id] | |
| subfolder_path = os.path.join(new_root_folder, str(subfolder_id)) | |
| new_im_path = os.path.join(subfolder_path, im_file_name) | |
| if not os.path.exists(subfolder_path): | |
| os.makedirs(subfolder_path) | |
| if not os.path.exists(new_im_path): | |
| #print(f'Moving {im_id} to {new_im_path}') | |
| os.rename(im_id, new_im_path) | |
| vqa['obs'] = [new_im_path] | |
| json.dump(all_train, open('updated_trainval.json', 'w'), indent=2) | |
| def sanity_check(): | |
| prev_vqas = json.load(open('trainval.json', 'r')) | |
| now_vqas = json.load(open('updated_trainval.json', 'r')) | |
| assert len(prev_vqas) == len(now_vqas), 'Number of VQAs should be the same after refactoring.' | |
| for vqa_id, vqa in now_vqas.items(): | |
| assert prev_vqas[vqa_id]['obs'][0] != vqa['obs'][0], 'VQA obs should be updated after refactoring.' | |
| old_im_name = os.path.basename(prev_vqas[vqa_id]['obs'][0]) | |
| new_im_name = os.path.basename(vqa['obs'][0]) | |
| assert old_im_name == new_im_name, 'Image file names should be the same' | |
| if __name__ == '__main__': | |
| pass | |