Skip to content

Instantly share code, notes, and snippets.

@ewerybody
Last active October 10, 2021 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewerybody/0d9f73fa8d75fddf7c1c96d8bc9fe5b1 to your computer and use it in GitHub Desktop.
Save ewerybody/0d9f73fa8d75fddf7c1c96d8bc9fe5b1 to your computer and use it in GitHub Desktop.
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