import requests
import os
from PIL import Image
from io import BytesIO
from random import shuffle

# Step 1: Fetch JSON data from the URL
url = "https://picsum.photos/v2/list?limit=1000"
try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    data = response.json()
except requests.RequestException as e:
    print(f"Failed to fetch image list: {e}")
    data = []

# Step 2: Extract image download links
image_urls = [item["download_url"] for item in data]

shuffle(image_urls)
# Step 3: Create a directory to save images
os.makedirs("images", exist_ok=True)

# Desired size for resizing
desired_size = (450, 250)

# Step 4: Download and resize each image
for i, image_url in enumerate(image_urls):
    try:
        img_response = requests.get(image_url, timeout=10)
        img_response.raise_for_status()
        # Open image from response content
        img = Image.open(BytesIO(img_response.content))
        # Resize the image
        img = img.resize(desired_size, Image.Resampling.LANCZOS)
        # Save the resized image
        img.save(f"images/image_{17}.jpg")
        print(f"Downloaded and resized: image_{17}.jpg")
    else:
        print(f"Failed to download image from {image_url}")
    if input() !="":
        break 