import os cur_dir = os.path.dirname(os.path.realpath(__file__)) # mkdir jsonl jsonl_dir = os.path.join(cur_dir, 'jsonl') if not os.path.exists(jsonl_dir): os.makedirs(jsonl_dir) # list files in jsonl-all directory jsonl_all_dir = os.path.join(cur_dir, 'jsonl-all') file_sizes = {} for file in os.listdir(jsonl_all_dir): file_path = os.path.join(jsonl_all_dir, file) file_size = os.path.getsize(file_path) file_sizes[file] = file_size # sort files by size (keep dictionary) sorted_files = sorted(file_sizes.items(), key=lambda x: x[1], reverse=True) def widen_variance(file_sizes, reduction_factor): sorted_files = sorted(file_sizes.items(), key=lambda x: x[1], reverse=True) print(sorted_files) for i, (file, size) in enumerate(sorted_files): if i == 0: continue sorted_files[i] = (file, round(size * (reduction_factor / (i/10)))) return sorted_files # increase the file size distribution targeted_file_sizes = widen_variance(file_sizes, 0.00005) print("Sorted files by size:") for file, size in sorted_files: print(f"{file}: {size}") print("Targeted file sizes:") for file, size in targeted_file_sizes: print(f"{file}: {size}") # targeted to dict targeted_file_sizes = dict(targeted_file_sizes) for file in targeted_file_sizes: size = targeted_file_sizes[file] file_path = os.path.join(jsonl_all_dir, file) file_path_target = os.path.join(jsonl_dir, file) os.system(f"head -c {size} {file_path} > {file_path_target}") print(f"Created {file_path_target} with size {size} bytes") with open(file_path_target, 'rb+') as file: # Open the file in read-write binary mode file.seek(0, 2) # Move to the end of the file file_size = file.tell() # Get the total file size for i in range(file_size - 1, -1, -1): # Start from the last byte and move backwards file.seek(i) # Move the cursor to the ith position from the start if file.read(1) == b'\n': # If a newline character is found file.truncate(i + 1) # Truncate the file from this point break # Exit the loop after truncating print("Done!")