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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import tqdm
|
| 4 |
+
from typing import List, Optional, TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def img_root_path(img_id: str):
|
| 8 |
+
return os.path.dirname(os.path.dirname(img_id))
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from .dataset_tools_config_modules import DatasetSyncCollectionConfig
|
| 13 |
+
|
| 14 |
+
img_exts = ['.jpg', '.jpeg', '.webp', '.png']
|
| 15 |
+
|
| 16 |
+
class Photo:
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
id,
|
| 20 |
+
host,
|
| 21 |
+
width,
|
| 22 |
+
height,
|
| 23 |
+
url,
|
| 24 |
+
filename
|
| 25 |
+
):
|
| 26 |
+
self.id = str(id)
|
| 27 |
+
self.host = host
|
| 28 |
+
self.width = width
|
| 29 |
+
self.height = height
|
| 30 |
+
self.url = url
|
| 31 |
+
self.filename = filename
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_desired_size(img_width: int, img_height: int, min_width: int, min_height: int):
|
| 35 |
+
if img_width > img_height:
|
| 36 |
+
scale = min_height / img_height
|
| 37 |
+
else:
|
| 38 |
+
scale = min_width / img_width
|
| 39 |
+
|
| 40 |
+
new_width = int(img_width * scale)
|
| 41 |
+
new_height = int(img_height * scale)
|
| 42 |
+
|
| 43 |
+
return new_width, new_height
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_pexels_images(config: 'DatasetSyncCollectionConfig') -> List[Photo]:
|
| 47 |
+
all_images = []
|
| 48 |
+
next_page = f"https://api.pexels.com/v1/collections/{config.collection_id}?page=1&per_page=80&type=photos"
|
| 49 |
+
|
| 50 |
+
while True:
|
| 51 |
+
response = requests.get(next_page, headers={
|
| 52 |
+
"Authorization": f"{config.api_key}"
|
| 53 |
+
})
|
| 54 |
+
response.raise_for_status()
|
| 55 |
+
data = response.json()
|
| 56 |
+
all_images.extend(data['media'])
|
| 57 |
+
if 'next_page' in data and data['next_page']:
|
| 58 |
+
next_page = data['next_page']
|
| 59 |
+
else:
|
| 60 |
+
break
|
| 61 |
+
|
| 62 |
+
photos = []
|
| 63 |
+
for image in all_images:
|
| 64 |
+
new_width, new_height = get_desired_size(image['width'], image['height'], config.min_width, config.min_height)
|
| 65 |
+
url = f"{image['src']['original']}?auto=compress&cs=tinysrgb&h={new_height}&w={new_width}"
|
| 66 |
+
filename = os.path.basename(image['src']['original'])
|
| 67 |
+
|
| 68 |
+
photos.append(Photo(
|
| 69 |
+
id=image['id'],
|
| 70 |
+
host="pexels",
|
| 71 |
+
width=image['width'],
|
| 72 |
+
height=image['height'],
|
| 73 |
+
url=url,
|
| 74 |
+
filename=filename
|
| 75 |
+
))
|
| 76 |
+
|
| 77 |
+
return photos
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_unsplash_images(config: 'DatasetSyncCollectionConfig') -> List[Photo]:
|
| 81 |
+
headers = {
|
| 82 |
+
# "Authorization": f"Client-ID {UNSPLASH_ACCESS_KEY}"
|
| 83 |
+
"Authorization": f"Client-ID {config.api_key}"
|
| 84 |
+
}
|
| 85 |
+
# headers['Authorization'] = f"Bearer {token}"
|
| 86 |
+
|
| 87 |
+
url = f"https://api.unsplash.com/collections/{config.collection_id}/photos?page=1&per_page=30"
|
| 88 |
+
response = requests.get(url, headers=headers)
|
| 89 |
+
response.raise_for_status()
|
| 90 |
+
res_headers = response.headers
|
| 91 |
+
# parse the link header to get the next page
|
| 92 |
+
# 'Link': '<https://api.unsplash.com/collections/mIPWwLdfct8/photos?page=82>; rel="last", <https://api.unsplash.com/collections/mIPWwLdfct8/photos?page=2>; rel="next"'
|
| 93 |
+
has_next_page = False
|
| 94 |
+
if 'Link' in res_headers:
|
| 95 |
+
has_next_page = True
|
| 96 |
+
link_header = res_headers['Link']
|
| 97 |
+
link_header = link_header.split(',')
|
| 98 |
+
link_header = [link.strip() for link in link_header]
|
| 99 |
+
link_header = [link.split(';') for link in link_header]
|
| 100 |
+
link_header = [[link[0].strip('<>'), link[1].strip().strip('"')] for link in link_header]
|
| 101 |
+
link_header = {link[1]: link[0] for link in link_header}
|
| 102 |
+
|
| 103 |
+
# get page number from last url
|
| 104 |
+
last_page = link_header['rel="last']
|
| 105 |
+
last_page = last_page.split('?')[1]
|
| 106 |
+
last_page = last_page.split('&')
|
| 107 |
+
last_page = [param.split('=') for param in last_page]
|
| 108 |
+
last_page = {param[0]: param[1] for param in last_page}
|
| 109 |
+
last_page = int(last_page['page'])
|
| 110 |
+
|
| 111 |
+
all_images = response.json()
|
| 112 |
+
|
| 113 |
+
if has_next_page:
|
| 114 |
+
# assume we start on page 1, so we don't need to get it again
|
| 115 |
+
for page in tqdm.tqdm(range(2, last_page + 1)):
|
| 116 |
+
url = f"https://api.unsplash.com/collections/{config.collection_id}/photos?page={page}&per_page=30"
|
| 117 |
+
response = requests.get(url, headers=headers)
|
| 118 |
+
response.raise_for_status()
|
| 119 |
+
all_images.extend(response.json())
|
| 120 |
+
|
| 121 |
+
photos = []
|
| 122 |
+
for image in all_images:
|
| 123 |
+
new_width, new_height = get_desired_size(image['width'], image['height'], config.min_width, config.min_height)
|
| 124 |
+
url = f"{image['urls']['raw']}&w={new_width}"
|
| 125 |
+
filename = f"{image['id']}.jpg"
|
| 126 |
+
|
| 127 |
+
photos.append(Photo(
|
| 128 |
+
id=image['id'],
|
| 129 |
+
host="unsplash",
|
| 130 |
+
width=image['width'],
|
| 131 |
+
height=image['height'],
|
| 132 |
+
url=url,
|
| 133 |
+
filename=filename
|
| 134 |
+
))
|
| 135 |
+
|
| 136 |
+
return photos
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def get_img_paths(dir_path: str):
|
| 140 |
+
os.makedirs(dir_path, exist_ok=True)
|
| 141 |
+
local_files = os.listdir(dir_path)
|
| 142 |
+
# remove non image files
|
| 143 |
+
local_files = [file for file in local_files if os.path.splitext(file)[1].lower() in img_exts]
|
| 144 |
+
# make full path
|
| 145 |
+
local_files = [os.path.join(dir_path, file) for file in local_files]
|
| 146 |
+
return local_files
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def get_local_image_ids(dir_path: str):
|
| 150 |
+
os.makedirs(dir_path, exist_ok=True)
|
| 151 |
+
local_files = get_img_paths(dir_path)
|
| 152 |
+
# assuming local files are named after Unsplash IDs, e.g., 'abc123.jpg'
|
| 153 |
+
return set([os.path.basename(file).split('.')[0] for file in local_files])
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def get_local_image_file_names(dir_path: str):
|
| 157 |
+
os.makedirs(dir_path, exist_ok=True)
|
| 158 |
+
local_files = get_img_paths(dir_path)
|
| 159 |
+
# assuming local files are named after Unsplash IDs, e.g., 'abc123.jpg'
|
| 160 |
+
return set([os.path.basename(file) for file in local_files])
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def download_image(photo: Photo, dir_path: str, min_width: int = 1024, min_height: int = 1024):
|
| 164 |
+
img_width = photo.width
|
| 165 |
+
img_height = photo.height
|
| 166 |
+
|
| 167 |
+
if img_width < min_width or img_height < min_height:
|
| 168 |
+
raise ValueError(f"Skipping {photo.id} because it is too small: {img_width}x{img_height}")
|
| 169 |
+
|
| 170 |
+
img_response = requests.get(photo.url)
|
| 171 |
+
img_response.raise_for_status()
|
| 172 |
+
os.makedirs(dir_path, exist_ok=True)
|
| 173 |
+
|
| 174 |
+
filename = os.path.join(dir_path, photo.filename)
|
| 175 |
+
with open(filename, 'wb') as file:
|
| 176 |
+
file.write(img_response.content)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def update_caption(img_path: str):
|
| 180 |
+
# if the caption is a txt file, convert it to a json file
|
| 181 |
+
filename_no_ext = os.path.splitext(os.path.basename(img_path))[0]
|
| 182 |
+
# see if it exists
|
| 183 |
+
if os.path.exists(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.json")):
|
| 184 |
+
# todo add poi and what not
|
| 185 |
+
return # we have a json file
|
| 186 |
+
caption = ""
|
| 187 |
+
# see if txt file exists
|
| 188 |
+
if os.path.exists(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.txt")):
|
| 189 |
+
# read it
|
| 190 |
+
with open(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.txt"), 'r') as file:
|
| 191 |
+
caption = file.read()
|
| 192 |
+
# write json file
|
| 193 |
+
with open(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.json"), 'w') as file:
|
| 194 |
+
file.write(f'{{"caption": "{caption}"}}')
|
| 195 |
+
|
| 196 |
+
# delete txt file
|
| 197 |
+
os.remove(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.txt"))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# def equalize_img(img_path: str):
|
| 201 |
+
# input_path = img_path
|
| 202 |
+
# output_path = os.path.join(img_root_path(img_path), COLOR_CORRECTED_DIR, os.path.basename(img_path))
|
| 203 |
+
# os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 204 |
+
# process_img(
|
| 205 |
+
# img_path=input_path,
|
| 206 |
+
# output_path=output_path,
|
| 207 |
+
# equalize=True,
|
| 208 |
+
# max_size=2056,
|
| 209 |
+
# white_balance=False,
|
| 210 |
+
# gamma_correction=False,
|
| 211 |
+
# strength=0.6,
|
| 212 |
+
# )
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# def annotate_depth(img_path: str):
|
| 216 |
+
# # make fake args
|
| 217 |
+
# args = argparse.Namespace()
|
| 218 |
+
# args.annotator = "midas"
|
| 219 |
+
# args.res = 1024
|
| 220 |
+
#
|
| 221 |
+
# img = cv2.imread(img_path)
|
| 222 |
+
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 223 |
+
#
|
| 224 |
+
# output = annotate(img, args)
|
| 225 |
+
#
|
| 226 |
+
# output = output.astype('uint8')
|
| 227 |
+
# output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
|
| 228 |
+
#
|
| 229 |
+
# os.makedirs(os.path.dirname(img_path), exist_ok=True)
|
| 230 |
+
# output_path = os.path.join(img_root_path(img_path), DEPTH_DIR, os.path.basename(img_path))
|
| 231 |
+
#
|
| 232 |
+
# cv2.imwrite(output_path, output)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# def invert_depth(img_path: str):
|
| 236 |
+
# img = cv2.imread(img_path)
|
| 237 |
+
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 238 |
+
# # invert the colors
|
| 239 |
+
# img = cv2.bitwise_not(img)
|
| 240 |
+
#
|
| 241 |
+
# os.makedirs(os.path.dirname(img_path), exist_ok=True)
|
| 242 |
+
# output_path = os.path.join(img_root_path(img_path), INVERTED_DEPTH_DIR, os.path.basename(img_path))
|
| 243 |
+
# cv2.imwrite(output_path, img)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
#
|
| 247 |
+
# # update our list of raw images
|
| 248 |
+
# raw_images = get_img_paths(raw_dir)
|
| 249 |
+
#
|
| 250 |
+
# # update raw captions
|
| 251 |
+
# for image_id in tqdm.tqdm(raw_images, desc="Updating raw captions"):
|
| 252 |
+
# update_caption(image_id)
|
| 253 |
+
#
|
| 254 |
+
# # equalize images
|
| 255 |
+
# for img_path in tqdm.tqdm(raw_images, desc="Equalizing images"):
|
| 256 |
+
# if img_path not in eq_images:
|
| 257 |
+
# equalize_img(img_path)
|
| 258 |
+
#
|
| 259 |
+
# # update our list of eq images
|
| 260 |
+
# eq_images = get_img_paths(eq_dir)
|
| 261 |
+
# # update eq captions
|
| 262 |
+
# for image_id in tqdm.tqdm(eq_images, desc="Updating eq captions"):
|
| 263 |
+
# update_caption(image_id)
|
| 264 |
+
#
|
| 265 |
+
# # annotate depth
|
| 266 |
+
# depth_dir = os.path.join(root_dir, DEPTH_DIR)
|
| 267 |
+
# depth_images = get_img_paths(depth_dir)
|
| 268 |
+
# for img_path in tqdm.tqdm(eq_images, desc="Annotating depth"):
|
| 269 |
+
# if img_path not in depth_images:
|
| 270 |
+
# annotate_depth(img_path)
|
| 271 |
+
#
|
| 272 |
+
# depth_images = get_img_paths(depth_dir)
|
| 273 |
+
#
|
| 274 |
+
# # invert depth
|
| 275 |
+
# inv_depth_dir = os.path.join(root_dir, INVERTED_DEPTH_DIR)
|
| 276 |
+
# inv_depth_images = get_img_paths(inv_depth_dir)
|
| 277 |
+
# for img_path in tqdm.tqdm(depth_images, desc="Inverting depth"):
|
| 278 |
+
# if img_path not in inv_depth_images:
|
| 279 |
+
# invert_depth(img_path)
|