import os import requests from PIL import Image import json def download_image_with_retries(image_url, output_file): try: response = requests.get(image_url, stream=True, timeout=5) if response.status_code == 200: with open(output_file, 'wb') as out_file: for chunk in response.iter_content(1024): out_file.write(chunk) return True except requests.RequestException as e: print(f"Download failed: {e}") return False def convert_to_jpg(input_path, output_path): try: with Image.open(input_path) as img: # Convert image to RGB to ensure compatibility if original is in a different mode (e.g., RGBA, P) rgb_img = img.convert('RGB') rgb_img.save(output_path, 'JPEG') os.remove(input_path) # Remove the original image file after conversion return True except Exception as e: print(f"Error converting image to JPG: {e}") return False def verify_and_download_images(data): images_directory = './images' os.makedirs(images_directory, exist_ok=True) for key, value in data.items(): image_url = value['imageURL'] ext = os.path.splitext(image_url)[1].lower() # Ensure extension is in lowercase for comparison needs_conversion = ext in ['.gif', '.png'] output_ext = '.jpg' if needs_conversion else ext output_file = f'{images_directory}/{key}{output_ext}' if not os.path.exists(output_file): print(f"Image {key}{output_ext} not found, attempting to download...") temp_output_file = output_file if not needs_conversion else f'{images_directory}/{key}{ext}' if not download_image_with_retries(image_url, temp_output_file): print(f"Warning: Could not download image {image_url}") elif needs_conversion: # Convert image to JPG if not convert_to_jpg(temp_output_file, output_file): print(f"Warning: Could not convert image to JPG for image {image_url}") # Load the dataset JSON file (assuming you have a dataset.json file in the same directory) with open('dataset.json', 'r') as fp: data = json.load(fp) # Check and download images as necessary verify_and_download_images(data)