| 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: |
| |
| rgb_img = img.convert('RGB') |
| rgb_img.save(output_path, 'JPEG') |
| os.remove(input_path) |
| 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() |
| 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: |
| |
| if not convert_to_jpg(temp_output_file, output_file): |
| print(f"Warning: Could not convert image to JPG for image {image_url}") |
|
|
| |
| with open('dataset.json', 'r') as fp: |
| data = json.load(fp) |
|
|
| |
| verify_and_download_images(data) |
|
|