add make code
Browse files- make_openimages.py +121 -0
make_openimages.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
from datasets import Dataset, load_dataset, Image
|
| 8 |
+
import boto3
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_jsonl(file_path):
|
| 12 |
+
"""
|
| 13 |
+
Loads a JSONL file and returns a list of Python dictionaries.
|
| 14 |
+
Each dictionary represents a JSON object from a line in the file.
|
| 15 |
+
"""
|
| 16 |
+
data = []
|
| 17 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 18 |
+
for line in f:
|
| 19 |
+
try:
|
| 20 |
+
# Parse each line as a JSON object
|
| 21 |
+
json_object = json.loads(line.strip())
|
| 22 |
+
data.append(json_object)
|
| 23 |
+
except json.JSONDecodeError as e:
|
| 24 |
+
print(f"Error decoding JSON on line: {line.strip()} - {e}")
|
| 25 |
+
return data
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
s3 = boto3.client('s3')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def download_file(image_id, split):
|
| 32 |
+
bucket_name = "open-images-dataset"
|
| 33 |
+
object_key = f"{split}/{image_id}.jpg"
|
| 34 |
+
store_name = f"./open_images/images_files/{split}/{image_id}.jpg"
|
| 35 |
+
if os.path.exists(store_name):
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
s3.download_file(bucket_name, object_key, store_name)
|
| 40 |
+
except KeyboardInterrupt:
|
| 41 |
+
raise
|
| 42 |
+
except:
|
| 43 |
+
print(f"Error getting {bucket_name}")
|
| 44 |
+
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def download_split(split):
|
| 49 |
+
workdir = "./open_images"
|
| 50 |
+
|
| 51 |
+
annot_file = os.path.join(workdir, f"{split}-images-with-rotation.csv")
|
| 52 |
+
df = pd.read_csv(annot_file)
|
| 53 |
+
df = pd.DataFrame(df)
|
| 54 |
+
os.makedirs(os.path.join(workdir, "images_files", split), exist_ok=True)
|
| 55 |
+
|
| 56 |
+
# Prepare list of image IDs for multithreading
|
| 57 |
+
image_ids = df["ImageID"].tolist()
|
| 58 |
+
|
| 59 |
+
# Use ThreadPoolExecutor with 6 threads and tqdm for progress
|
| 60 |
+
with ThreadPoolExecutor(max_workers=6) as executor:
|
| 61 |
+
try:
|
| 62 |
+
# Submit all download tasks
|
| 63 |
+
futures = [executor.submit(download_file, image_id, split) for image_id in image_ids]
|
| 64 |
+
|
| 65 |
+
# Use tqdm to show progress
|
| 66 |
+
for future in tqdm(futures, desc=f"Downloading {split} images", unit="image"):
|
| 67 |
+
future.result() # Wait for completion and handle any exceptions
|
| 68 |
+
except KeyboardInterrupt:
|
| 69 |
+
print("\nKeyboardInterrupt received. Shutting down threads...")
|
| 70 |
+
# Cancel all pending futures
|
| 71 |
+
for future in futures:
|
| 72 |
+
future.cancel()
|
| 73 |
+
# Shutdown the executor immediately
|
| 74 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 75 |
+
print("All threads stopped.")
|
| 76 |
+
raise # Re-raise to exit the program
|
| 77 |
+
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_dataset():
|
| 82 |
+
|
| 83 |
+
return
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def prepare_subset(split):
|
| 87 |
+
workdir = "open_images"
|
| 88 |
+
csv_file = os.path.join(workdir, f"{split}-images-with-rotation.csv")
|
| 89 |
+
df = pd.read_csv(csv_file)
|
| 90 |
+
df = pd.DataFrame(df)
|
| 91 |
+
print(df)
|
| 92 |
+
|
| 93 |
+
narratives = load_jsonl(os.path.join(workdir, "narratives", f"open_images_{split}_captions.jsonl"))
|
| 94 |
+
narratives = {x["image_id"]: x for x in narratives}
|
| 95 |
+
|
| 96 |
+
def gen():
|
| 97 |
+
for _, row in df.iterrows():
|
| 98 |
+
item = {
|
| 99 |
+
"image_id": row["ImageID"],
|
| 100 |
+
"original_url": row["OriginalURL"],
|
| 101 |
+
"license": row["License"],
|
| 102 |
+
"author": row["Author"],
|
| 103 |
+
"caption": row["Title"],
|
| 104 |
+
"image_id": row["ImageID"],
|
| 105 |
+
"image": os.path.join(workdir, "images_files", split, row["ImageID"] + ".jpg"),
|
| 106 |
+
"narrative": narratives[row["ImageID"]]["caption"],
|
| 107 |
+
}
|
| 108 |
+
yield item
|
| 109 |
+
|
| 110 |
+
ds = Dataset.from_generator(gen)
|
| 111 |
+
ds = ds.cast_column("image", Image())
|
| 112 |
+
ds.save_to_disk(f"{workdir}/datasets/data/{split}", max_shard_size="400MB")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == "__main__":
|
| 117 |
+
# for split in ["train", "validation", "test"]:
|
| 118 |
+
# download_split(split)
|
| 119 |
+
for split in ["validation"]:
|
| 120 |
+
prepare_subset(split)
|
| 121 |
+
# test_dataset()
|