Skip to content

Instantly share code, notes, and snippets.

@FlorianLatapie
Last active December 30, 2022 17:01
Show Gist options
  • Save FlorianLatapie/60785afb8cd25b8767e14832d19679eb to your computer and use it in GitHub Desktop.
Save FlorianLatapie/60785afb8cd25b8767e14832d19679eb to your computer and use it in GitHub Desktop.
This script creates a zip file with the images asked by the user (two files : golfed and readable)
import os, sys, requests, json, shutil
results = json.loads(requests.request("GET", "https://imsea.herokuapp.com/api/1?q=" + sys.argv[1]).text)["results"]
os.path.exists(sys.argv[1] + "/") or os.makedirs(sys.argv[1] + "/")
[open(sys.argv[1] + "/" + sys.argv[1] + str(i // 2 + 1) + '.png', 'wb').write(requests.get(results[i]).content) for i in
range(0, len(results), 2)]
shutil.make_archive(sys.argv[1], 'zip', sys.argv[1] + "/")
shutil.rmtree(sys.argv[1] + "/")
import os
import sys
import requests
import json
import shutil
# Free API without any key !
api_base_url = "https://imsea.herokuapp.com/api/1?q="
# Try to read arguments from the command line or asks the user to enter the two values
if len(sys.argv) == 3:
user_input = sys.argv[1]
size = int(sys.argv[2])
else:
user_input = input("Enter a search term: ")
size = int(input("Enter a size: "))
print("Searching for: " + user_input)
# Call the API
response = requests.request("GET", api_base_url + user_input)
json_data = json.loads(response.text)
results = json_data["results"]
size = min(size, len(results)//2)
print("Found " + str(len(results)//2) + " results, downloading " + str(size) + " images")
# Create a temporary folder for the images
temp_dir = user_input + "/"
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
# Download the images, the API gives each image twice
for i in range(0, size * 2, 2):
img_data = requests.get(results[i]).content
img_name = user_input + str(i // 2 + 1) + '.png'
with open(temp_dir + img_name, 'wb') as handler:
handler.write(img_data)
print(f"Image {img_name} saved")
# Zip the images and remove the temporary folder
shutil.make_archive(user_input, 'zip', temp_dir)
shutil.rmtree(temp_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment