File size: 9,624 Bytes
fcc02a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import os
import requests
import tqdm
from typing import List, Optional, TYPE_CHECKING


def img_root_path(img_id: str):
    return os.path.dirname(os.path.dirname(img_id))


if TYPE_CHECKING:
    from .dataset_tools_config_modules import DatasetSyncCollectionConfig

img_exts = ['.jpg', '.jpeg', '.webp', '.png']

class Photo:
    def __init__(
            self,
            id,
            host,
            width,
            height,
            url,
            filename
    ):
        self.id = str(id)
        self.host = host
        self.width = width
        self.height = height
        self.url = url
        self.filename = filename


def get_desired_size(img_width: int, img_height: int, min_width: int, min_height: int):
    if img_width > img_height:
        scale = min_height / img_height
    else:
        scale = min_width / img_width

    new_width = int(img_width * scale)
    new_height = int(img_height * scale)

    return new_width, new_height


def get_pexels_images(config: 'DatasetSyncCollectionConfig') -> List[Photo]:
    all_images = []
    next_page = f"https://api.pexels.com/v1/collections/{config.collection_id}?page=1&per_page=80&type=photos"

    while True:
        response = requests.get(next_page, headers={
            "Authorization": f"{config.api_key}"
        })
        response.raise_for_status()
        data = response.json()
        all_images.extend(data['media'])
        if 'next_page' in data and data['next_page']:
            next_page = data['next_page']
        else:
            break

    photos = []
    for image in all_images:
        new_width, new_height = get_desired_size(image['width'], image['height'], config.min_width, config.min_height)
        url = f"{image['src']['original']}?auto=compress&cs=tinysrgb&h={new_height}&w={new_width}"
        filename = os.path.basename(image['src']['original'])

        photos.append(Photo(
            id=image['id'],
            host="pexels",
            width=image['width'],
            height=image['height'],
            url=url,
            filename=filename
        ))

    return photos


def get_unsplash_images(config: 'DatasetSyncCollectionConfig') -> List[Photo]:
    headers = {
        # "Authorization": f"Client-ID {UNSPLASH_ACCESS_KEY}"
        "Authorization": f"Client-ID {config.api_key}"
    }
    # headers['Authorization'] = f"Bearer {token}"

    url = f"https://api.unsplash.com/collections/{config.collection_id}/photos?page=1&per_page=30"
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    res_headers = response.headers
    # parse the link header to get the next page
    # 'Link': '<https://api.unsplash.com/collections/mIPWwLdfct8/photos?page=82>; rel="last", <https://api.unsplash.com/collections/mIPWwLdfct8/photos?page=2>; rel="next"'
    has_next_page = False
    if 'Link' in res_headers:
        has_next_page = True
        link_header = res_headers['Link']
        link_header = link_header.split(',')
        link_header = [link.strip() for link in link_header]
        link_header = [link.split(';') for link in link_header]
        link_header = [[link[0].strip('<>'), link[1].strip().strip('"')] for link in link_header]
        link_header = {link[1]: link[0] for link in link_header}

        # get page number from last url
        last_page = link_header['rel="last']
        last_page = last_page.split('?')[1]
        last_page = last_page.split('&')
        last_page = [param.split('=') for param in last_page]
        last_page = {param[0]: param[1] for param in last_page}
        last_page = int(last_page['page'])

    all_images = response.json()

    if has_next_page:
        # assume we start on page 1, so we don't need to get it again
        for page in tqdm.tqdm(range(2, last_page + 1)):
            url = f"https://api.unsplash.com/collections/{config.collection_id}/photos?page={page}&per_page=30"
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            all_images.extend(response.json())

    photos = []
    for image in all_images:
        new_width, new_height = get_desired_size(image['width'], image['height'], config.min_width, config.min_height)
        url = f"{image['urls']['raw']}&w={new_width}"
        filename = f"{image['id']}.jpg"

        photos.append(Photo(
            id=image['id'],
            host="unsplash",
            width=image['width'],
            height=image['height'],
            url=url,
            filename=filename
        ))

    return photos


def get_img_paths(dir_path: str):
    os.makedirs(dir_path, exist_ok=True)
    local_files = os.listdir(dir_path)
    # remove non image files
    local_files = [file for file in local_files if os.path.splitext(file)[1].lower() in img_exts]
    # make full path
    local_files = [os.path.join(dir_path, file) for file in local_files]
    return local_files


def get_local_image_ids(dir_path: str):
    os.makedirs(dir_path, exist_ok=True)
    local_files = get_img_paths(dir_path)
    # assuming local files are named after Unsplash IDs, e.g., 'abc123.jpg'
    return set([os.path.basename(file).split('.')[0] for file in local_files])


def get_local_image_file_names(dir_path: str):
    os.makedirs(dir_path, exist_ok=True)
    local_files = get_img_paths(dir_path)
    # assuming local files are named after Unsplash IDs, e.g., 'abc123.jpg'
    return set([os.path.basename(file) for file in local_files])


def download_image(photo: Photo, dir_path: str, min_width: int = 1024, min_height: int = 1024):
    img_width = photo.width
    img_height = photo.height

    if img_width < min_width or img_height < min_height:
        raise ValueError(f"Skipping {photo.id} because it is too small: {img_width}x{img_height}")

    img_response = requests.get(photo.url)
    img_response.raise_for_status()
    os.makedirs(dir_path, exist_ok=True)

    filename = os.path.join(dir_path, photo.filename)
    with open(filename, 'wb') as file:
        file.write(img_response.content)


def update_caption(img_path: str):
    # if the caption is a txt file, convert it to a json file
    filename_no_ext = os.path.splitext(os.path.basename(img_path))[0]
    # see if it exists
    if os.path.exists(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.json")):
        # todo add poi and what not
        return  # we have a json file
    caption = ""
    # see if txt file exists
    if os.path.exists(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.txt")):
        # read it
        with open(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.txt"), 'r') as file:
            caption = file.read()
    # write json file
    with open(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.json"), 'w') as file:
        file.write(f'{{"caption": "{caption}"}}')

    # delete txt file
    os.remove(os.path.join(os.path.dirname(img_path), f"{filename_no_ext}.txt"))


# def equalize_img(img_path: str):
#     input_path = img_path
#     output_path = os.path.join(img_root_path(img_path), COLOR_CORRECTED_DIR, os.path.basename(img_path))
#     os.makedirs(os.path.dirname(output_path), exist_ok=True)
#     process_img(
#         img_path=input_path,
#         output_path=output_path,
#         equalize=True,
#         max_size=2056,
#         white_balance=False,
#         gamma_correction=False,
#         strength=0.6,
#     )


# def annotate_depth(img_path: str):
#     # make fake args
#     args = argparse.Namespace()
#     args.annotator = "midas"
#     args.res = 1024
#
#     img = cv2.imread(img_path)
#     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#
#     output = annotate(img, args)
#
#     output = output.astype('uint8')
#     output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
#
#     os.makedirs(os.path.dirname(img_path), exist_ok=True)
#     output_path = os.path.join(img_root_path(img_path), DEPTH_DIR, os.path.basename(img_path))
#
#     cv2.imwrite(output_path, output)


# def invert_depth(img_path: str):
#     img = cv2.imread(img_path)
#     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#     # invert the colors
#     img = cv2.bitwise_not(img)
#
#     os.makedirs(os.path.dirname(img_path), exist_ok=True)
#     output_path = os.path.join(img_root_path(img_path), INVERTED_DEPTH_DIR, os.path.basename(img_path))
#     cv2.imwrite(output_path, img)


    #
    # # update our list of raw images
    # raw_images = get_img_paths(raw_dir)
    #
    # # update raw captions
    # for image_id in tqdm.tqdm(raw_images, desc="Updating raw captions"):
    #     update_caption(image_id)
    #
    # # equalize images
    # for img_path in tqdm.tqdm(raw_images, desc="Equalizing images"):
    #     if img_path not in eq_images:
    #         equalize_img(img_path)
    #
    # # update our list of eq images
    # eq_images = get_img_paths(eq_dir)
    # # update eq captions
    # for image_id in tqdm.tqdm(eq_images, desc="Updating eq captions"):
    #     update_caption(image_id)
    #
    # # annotate depth
    # depth_dir = os.path.join(root_dir, DEPTH_DIR)
    # depth_images = get_img_paths(depth_dir)
    # for img_path in tqdm.tqdm(eq_images, desc="Annotating depth"):
    #     if img_path not in depth_images:
    #         annotate_depth(img_path)
    #
    # depth_images = get_img_paths(depth_dir)
    #
    # # invert depth
    # inv_depth_dir = os.path.join(root_dir, INVERTED_DEPTH_DIR)
    # inv_depth_images = get_img_paths(inv_depth_dir)
    # for img_path in tqdm.tqdm(depth_images, desc="Inverting depth"):
    #     if img_path not in inv_depth_images:
    #         invert_depth(img_path)