SciTS / process /process_iNaturalist.py
lwLiu's picture
Add files using upload-large-folder tool
aadeb6f verified
raw
history blame
2.59 kB
import json
import os
import shutil
from tqdm import tqdm
import argparse
def read_jsonl(path):
data_list = []
try:
with open(path, "r", encoding="utf-8") as file:
for line in tqdm(file, desc="Reading JSONL file"):
data = json.loads(line)
data_list.append(data)
return data_list
except FileNotFoundError:
raise FileNotFoundError(f"Error: File {path} not found.")
except json.JSONDecodeError:
raise json.JSONDecodeError(f"Error: Invalid JSON format in file {path}.")
except Exception as e:
raise Exception(f"An unexpected error occurred while reading {path}: {e}")
def main():
"""
Main function to process metadata and copy relevant files from iNaturalist test data.
"""
# Set up argument parser
parser = argparse.ArgumentParser(description="Process iNaturalist data.")
parser.add_argument("--data_folder", type=str, required=True, help="Path to the iNaturalist test folder.")
args = parser.parse_args()
try:
# Define the source folder containing the original files
data_folder = args.data_folder
meta_data = read_jsonl("meta_data.jsonl")
# Copying iNaturalist test data in the metadata
for data in tqdm(meta_data, desc="Copying iNaturalist test data"):
if data["task_id"][0] == "BIU02":
tmp_path = data["input_ts"]["path"]
target_folder = os.path.dirname(tmp_path)
# Create the target folder if it doesn't exist
os.makedirs(target_folder, exist_ok=True)
# Extract the file name and parent folder from the path
data_name = os.path.basename(tmp_path).split("_")[-1]
folder = os.path.basename(tmp_path).replace(data_name, "")[:-1]
# Copy the file if it doesn't exist in the target path
if not os.path.exists(tmp_path):
source_path = os.path.join(data_folder, os.path.join(folder, data_name))
try:
shutil.copy(source_path, tmp_path)
except FileNotFoundError:
print(f"Warning: Source file {source_path} not found. Skipping.")
except Exception as e:
print(f"Warning: Failed to copy {source_path} to {tmp_path}. Error: {e}")
except Exception as e:
print(f"An error occurred during execution: {e}")
if __name__ == "__main__":
main()