import os import sys import argparse import tarfile from constants import * import concurrent.futures def compress_chunk(chunk, chunk_index, output_dir): with tarfile.open(os.path.join(output_dir, f"chunk_{chunk_index}.tar"), "w") as tar: for image_path in chunk: tags_path = os.path.splitext(image_path)[0] + ".txt" if not os.path.isfile(tags_path): continue tar.add(image_path, arcname=os.path.basename(image_path)) tar.add(tags_path, arcname=os.path.basename(tags_path)) def parse_args(): parser = argparse.ArgumentParser(description="Group images into uncompressed tar files.") parser.add_argument("-i", "--input-dir", default=IMAGE_DIR, help="Input directory for the images to chunk into tars") parser.add_argument("-o", "--output-dir", default=COMPRESSED_DIR, help="Output directory for chunked tars") parser.add_argument("-n", "--num-images-per-chunk", type=int, default=1024, help="Number of images per chunk, default to 1024") args = parser.parse_args() if args.num_images_per_chunk < 1: print("Number of images per chunk needs to be a positive integer!") sys.exit(1) return args def main(): args = parse_args() if not os.path.isdir(args.input_dir): print(f"Your input dir \"{args.input_dir}\" doesn't exist or isn't a directory!") sys.exit(1) image_files = [os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir) if not f.endswith(".txt")] image_files.sort() os.makedirs(args.output_dir, exist_ok=True) with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: futures = [] for i in range(0, len(image_files), args.num_images_per_chunk): chunk = image_files[i:i + args.num_images_per_chunk] chunk_index = i // args.num_images_per_chunk future = executor.submit(compress_chunk, chunk, chunk_index, args.output_dir) futures.append(future) concurrent.futures.wait(futures) if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\nScript interrupted by user, exiting...") sys.exit(1)