Datasets:

Modalities:
Text
Formats:
text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
License:
M3VIR / Scripts /extract_track4.py
guluthemonster's picture
Upload folder using huggingface_hub
6f5985d verified
Raw History Blame Contribute Delete
6.76 kB
import webdataset as wds
import os
import json
import glob
import argparse
def extract_webdataset(webdataset_path, output_dir):
"""
Extract all WebDataset tar files back to original directory structure,
handling missing depth.exr (e.g., Metalize).
"""
os.makedirs(output_dir, exist_ok=True)
# Get all tar files in the directory
tar_files = sorted(glob.glob(os.path.join(webdataset_path, "*.tar")))
if not tar_files:
print(f"No tar files found in {webdataset_path}")
return
print(f"Found {len(tar_files)} tar files")
total_sample_count = 0
for tar_file in tar_files:
print(f"\nProcessing {os.path.basename(tar_file)}")
# Initialize WebDataset reader for current tar file
dataset = wds.WebDataset(
tar_file,
shardshuffle=False,
empty_check=False
)
sample_count = 0
for sample in dataset:
try:
# Get path information
path_info = json.loads(sample['path_info.json'])
category = path_info['category']
scene = path_info['scene']
style = path_info['style']
resolution = path_info['resolution']
view = path_info['view']
# Create directories for each image type
depth_dir = os.path.join(output_dir, "TRACK4", category, scene, style,
resolution, "Depth_images", view)
id_dir = os.path.join(output_dir, "TRACK4", category, scene, style,
resolution, "ID_images", view)
rgb_dir = os.path.join(output_dir, "TRACK4", category, scene, style,
resolution, "RGB_images", view)
# Create directories if they don't exist
os.makedirs(depth_dir, exist_ok=True)
os.makedirs(id_dir, exist_ok=True)
os.makedirs(rgb_dir, exist_ok=True)
# Get base filename from key
base_name = sample['__key__'].split('/')[-1]
# Save Depth files
depth_json_path = os.path.join(depth_dir, f"{base_name}.json")
with open(depth_json_path, 'w') as f:
json.dump(json.loads(sample['depth.json']), f, indent=4)
# Only save depth.exr if it exists
if "depth.exr" in sample:
depth_exr_path = os.path.join(depth_dir, f"{base_name}.exr")
with open(depth_exr_path, 'wb') as f:
f.write(sample['depth.exr'])
# Save ID files (handle both Realistic and Cartoon/Metalize cases)
id_json_path = os.path.join(id_dir, f"{base_name}.json")
with open(id_json_path, 'w') as f:
json.dump(json.loads(sample['id.json']), f, indent=4)
if "id.png" in sample:
id_png_path = os.path.join(id_dir, f"{base_name}.png")
with open(id_png_path, 'wb') as f:
f.write(sample['id.png'])
# Save RGB files (handle different extensions)
rgb_json_path = os.path.join(rgb_dir, f"{base_name}.json")
with open(rgb_json_path, 'w') as f:
json.dump(json.loads(sample['rgb.json']), f, indent=4)
if "rgb.jpeg" in sample:
rgb_image_path = os.path.join(rgb_dir, f"{base_name}.jpeg")
with open(rgb_image_path, 'wb') as f:
f.write(sample['rgb.jpeg'])
if "rgb.png" in sample:
rgb_image_path = os.path.join(rgb_dir, f"{base_name}.png")
with open(rgb_image_path, 'wb') as f:
f.write(sample['rgb.png'])
sample_count += 1
if sample_count % 100 == 0:
print(f"Extracted {sample_count} samples from current tar...")
except Exception as e:
print(f"Error extracting sample {sample.get('__key__', 'unknown')}: {str(e)}")
continue
total_sample_count += sample_count
print(f"Completed {os.path.basename(tar_file)}: {sample_count} samples extracted")
print(f"\nExtraction complete. Total samples extracted: {total_sample_count}")
def verify_extraction(extracted_dir):
"""
Verify the extraction by counting files
"""
print("\nVerifying extraction...")
def count_files(directory):
exr_count = 0
png_count = 0
jpeg_count = 0
json_count = 0
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.exr'):
exr_count += 1
elif file.endswith('.png'):
png_count += 1
elif file.endswith('.jpeg'):
jpeg_count += 1
elif file.endswith('.json'):
json_count += 1
return {
'exr': exr_count,
'png': png_count,
'jpeg': jpeg_count,
'json': json_count
}
counts = count_files(extracted_dir)
print("\nExtracted file counts:")
print(f" EXR files: {counts['exr']}")
print(f" PNG files: {counts['png']}")
print(f" JPEG files: {counts['jpeg']}")
print(f" JSON files: {counts['json']}")
if all(count > 0 for count in counts.values()):
print("\nAll file types present in extraction.")
else:
print("\nWARNING: Some file types are missing!")
def parse_arguments():
parser = argparse.ArgumentParser(description='Extract WebDataset tar files')
parser.add_argument('--input_path', '-i', required=True,
help='Input directory containing WebDataset tar files')
parser.add_argument('--output_path', '-o', required=True,
help='Output directory for extracted files')
parser.add_argument('--verify', '-v', action='store_true',
help='Verify the extraction after completion')
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
print(f"Input directory: {args.input_path}")
print(f"Output directory: {args.output_path}")
print("\nStarting extraction...")
extract_webdataset(args.input_path, args.output_path)
if args.verify:
verify_extraction(args.output_path)