Last active
October 10, 2021 12:17
-
-
Save ewerybody/0d9f73fa8d75fddf7c1c96d8bc9fe5b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import requests | |
NAME = 'thispersondoesnotexist' | |
URL = f'https://{NAME}.com/image' | |
IMG_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), NAME)) | |
# The file name pattern. `nr` will be replaced with the index of the file to write. | |
IMG_NAME = 'face_{nr}.jpg' | |
# How many face images you want to download. | |
NUM_IMG = 5 | |
# Just to not have it retry endlessly getting a unique image: The script stops after this amount of tries. | |
RETRIES = 5 | |
# Seconds to wait before attempting the next download. | |
TIMEOUT = 0.4 | |
def main(): | |
os.makedirs(IMG_DIR, exist_ok=True) | |
adds = 0 | |
img_data = b'' | |
for i in range(1, NUM_IMG + 1): | |
img_data = _get_img(img_data) | |
# find available number for the next file. | |
try_name = os.path.join(IMG_DIR, IMG_NAME.format(nr=i + adds)) | |
while os.path.isfile(try_name): | |
adds += 1 | |
try_name = os.path.join(IMG_DIR, IMG_NAME.format(nr=i + adds)) | |
with open(try_name, 'wb') as fobj: | |
print('try_name: %s' % try_name) | |
fobj.write(img_data) | |
time.sleep(TIMEOUT) | |
def _get_img(img_before): | |
"""Try to get a new image from `URL` thats different from the 1 before.""" | |
img_new = requests.get(URL).content | |
for try_nr in range(RETRIES): | |
if img_new != img_before: | |
return img_new | |
print('Got the same image. Trying again (%i) ...' % (try_nr + 1)) | |
time.sleep(TIMEOUT) | |
img_new = requests.get(URL).content | |
raise RuntimeError(f'Could not get new image after {RETRIES} retries!') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment