| 1 |
# Copyright (c), ETH Zurich and UNC Chapel Hill. |
| 2 |
# All rights reserved. |
| 3 |
# |
| 4 |
# Redistribution and use in source and binary forms, with or without |
| 5 |
# modification, are permitted provided that the following conditions are met: |
| 6 |
# |
| 7 |
# * Redistributions of source code must retain the above copyright |
| 8 |
# notice, this list of conditions and the following disclaimer. |
| 9 |
# |
| 10 |
# * Redistributions in binary form must reproduce the above copyright |
| 11 |
# notice, this list of conditions and the following disclaimer in the |
| 12 |
# documentation and/or other materials provided with the distribution. |
| 13 |
# |
| 14 |
# * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of |
| 15 |
# its contributors may be used to endorse or promote products derived |
| 16 |
# from this software without specific prior written permission. |
| 17 |
# |
| 18 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 19 |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 20 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 21 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE |
| 22 |
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 23 |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 24 |
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 26 |
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 27 |
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 28 |
# POSSIBILITY OF SUCH DAMAGE. |
| 29 |
|
| 30 |
|
| 31 |
import argparse |
| 32 |
import datetime |
| 33 |
import multiprocessing |
| 34 |
import os |
| 35 |
import time |
| 36 |
import urllib.error |
| 37 |
import urllib.request |
| 38 |
import xml.etree.ElementTree as ElementTree |
| 39 |
from typing import Final |
| 40 |
|
| 41 |
import urllib2 |
| 42 |
import urlparse |
| 43 |
|
| 44 |
PER_PAGE: Final[int] = 500 |
| 45 |
SORT: Final[str] = "date-posted-desc" |
| 46 |
URL: Final[str] = ( |
| 47 |
"https://api.flickr.com/services/rest/?method=flickr.photos.search&" |
| 48 |
"api_key=%s&text=%s&sort=%s&per_page=%d&page=%d&min_upload_date=%s&" |
| 49 |
"max_upload_date=%s&format=rest&extras=url_o,url_l,url_c,url_z,url_n" |
| 50 |
) |
| 51 |
MAX_PAGE_REQUESTS: Final[int] = 5 |
| 52 |
MAX_PAGE_TIMEOUT: Final[int] = 20 |
| 53 |
MAX_IMAGE_REQUESTS: Final[int] = 3 |
| 54 |
TIME_SKIP: Final[int] = 24 * 60 * 60 |
| 55 |
MAX_DATE: Final[float] = time.time() |
| 56 |
MIN_DATE: Final[float] = MAX_DATE - TIME_SKIP |
| 57 |
|
| 58 |
|
| 59 |
def parse_args() -> argparse.Namespace: |
| 60 |
parser = argparse.ArgumentParser() |
| 61 |
parser.add_argument("--search_text", required=True) |
| 62 |
parser.add_argument("--api_key", required=True) |
| 63 |
parser.add_argument("--image_path", required=True) |
| 64 |
parser.add_argument("--num_procs", type=int, default=10) |
| 65 |
parser.add_argument("--max_days_without_image", type=int, default=365) |
| 66 |
args = parser.parse_args() |
| 67 |
return args |
| 68 |
|
| 69 |
|
| 70 |
def compose_url( |
| 71 |
page: int, api_key: str, text: str, min_date: float, max_date: float |
| 72 |
) -> str: |
| 73 |
return URL % ( |
| 74 |
api_key, |
| 75 |
text, |
| 76 |
SORT, |
| 77 |
PER_PAGE, |
| 78 |
page, |
| 79 |
str(min_date), |
| 80 |
str(max_date), |
| 81 |
) |
| 82 |
|
| 83 |
|
| 84 |
def parse_page( |
| 85 |
page: int, api_key: str, text: str, min_date: float, max_date: float |
| 86 |
) -> tuple[dict[str, str], tuple[dict[str, str], ...]]: |
| 87 |
f: urllib2.urlopen | None = None |
| 88 |
for _ in range(MAX_PAGE_REQUESTS): |
| 89 |
try: |
| 90 |
f = urllib2.urlopen( |
| 91 |
compose_url(page, api_key, text, min_date, max_date), |
| 92 |
timeout=MAX_PAGE_TIMEOUT, |
| 93 |
) |
| 94 |
except TimeoutError: |
| 95 |
continue |
| 96 |
else: |
| 97 |
break |
| 98 |
|
| 99 |
if f is None: |
| 100 |
return { |
| 101 |
"pages": "0", |
| 102 |
"total": "0", |
| 103 |
"page": "0", |
| 104 |
"perpage": "0", |
| 105 |
}, tuple() |
| 106 |
|
| 107 |
response = f.read() |
| 108 |
root = ElementTree.fromstring(response) |
| 109 |
|
| 110 |
if root.attrib["stat"] != "ok": |
| 111 |
raise OSError |
| 112 |
|
| 113 |
metadata = root.find("photos") |
| 114 |
assert metadata is not None |
| 115 |
|
| 116 |
photos = tuple(photo.attrib for photo in root.iter("photo")) |
| 117 |
|
| 118 |
return metadata.attrib, photos |
| 119 |
|
| 120 |
|
| 121 |
class PhotoDownloader: |
| 122 |
def __init__(self, image_path: str) -> None: |
| 123 |
self.image_path: str = image_path |
| 124 |
|
| 125 |
def __call__(self, photo: dict[str, str]) -> None: |
| 126 |
# Find the URL corresponding to the highest image resolution. We will |
| 127 |
# need this URL here to determine the image extension (typically .jpg, |
| 128 |
# but could be .png, .gif, etc). |
| 129 |
url: str | None = None |
| 130 |
for url_suffix in ("o", "l", "k", "h", "b", "c", "z"): |
| 131 |
url_attr = f"url_{url_suffix}" |
| 132 |
if photo.get(url_attr) is not None: |
| 133 |
url = photo.get(url_attr) |
| 134 |
break |
| 135 |
|
| 136 |
if url is not None: |
| 137 |
# Note that the following statement may fail in Python 3. urlparse |
| 138 |
# may need to be replaced with urllib.parse. |
| 139 |
url_filename = urlparse.urlparse(url).path |
| 140 |
image_ext = os.path.splitext(url_filename)[1] |
| 141 |
|
| 142 |
image_name = f"{photo['id']}_{photo['secret']}{image_ext}" |
| 143 |
path = os.path.join(self.image_path, image_name) |
| 144 |
if not os.path.exists(path): |
| 145 |
print(url) |
| 146 |
for _ in range(MAX_IMAGE_REQUESTS): |
| 147 |
try: |
| 148 |
urllib.request.urlretrieve(url, path) |
| 149 |
except urllib.error.ContentTooShortError: |
| 150 |
continue |
| 151 |
else: |
| 152 |
break |
| 153 |
|
| 154 |
|
| 155 |
def main() -> None: |
| 156 |
args = parse_args() |
| 157 |
|
| 158 |
downloader = PhotoDownloader(args.image_path) |
| 159 |
pool = multiprocessing.Pool(processes=args.num_procs) |
| 160 |
|
| 161 |
num_pages = float("inf") |
| 162 |
page = 0 |
| 163 |
|
| 164 |
min_date = MIN_DATE |
| 165 |
max_date = MAX_DATE |
| 166 |
|
| 167 |
days_in_row = 0 |
| 168 |
|
| 169 |
search_text = args.search_text.replace(" ", "-") |
| 170 |
|
| 171 |
while num_pages > page: |
| 172 |
page += 1 |
| 173 |
|
| 174 |
metadata, photos = parse_page( |
| 175 |
page, args.api_key, search_text, min_date, max_date |
| 176 |
) |
| 177 |
|
| 178 |
num_pages = int(metadata["pages"]) |
| 179 |
|
| 180 |
print(78 * "=") |
| 181 |
print("Page:\t\t", page, "of", num_pages) |
| 182 |
print("Min-Date:\t", datetime.datetime.fromtimestamp(min_date)) |
| 183 |
print("Max-Date:\t", datetime.datetime.fromtimestamp(max_date)) |
| 184 |
print("Num-Photos:\t", len(photos)) |
| 185 |
print(78 * "=") |
| 186 |
|
| 187 |
try: |
| 188 |
pool.map_async(downloader, photos).get(1e10) |
| 189 |
except KeyboardInterrupt: |
| 190 |
pool.close() |
| 191 |
pool.join() |
| 192 |
break |
| 193 |
|
| 194 |
if page >= num_pages: |
| 195 |
max_date -= TIME_SKIP |
| 196 |
min_date -= TIME_SKIP |
| 197 |
page = 0 |
| 198 |
|
| 199 |
if num_pages == 0: |
| 200 |
days_in_row = days_in_row + 1 |
| 201 |
num_pages = float("inf") |
| 202 |
|
| 203 |
print(" No images in", days_in_row, "days in a row") |
| 204 |
|
| 205 |
if days_in_row == args.max_days_without_image: |
| 206 |
break |
| 207 |
else: |
| 208 |
days_in_row = 0 |
| 209 |
|
| 210 |
|
| 211 |
if __name__ == "__main__": |
| 212 |
main() |