File size: 2,328 Bytes
038c5ad
6ce386d
 
 
8377992
6ce386d
 
 
 
 
 
 
8377992
6ce386d
 
8377992
 
f812b4c
6ce386d
 
f812b4c
 
 
 
6ce386d
 
f812b4c
6ce386d
8377992
6ce386d
8377992
 
 
 
 
6ce386d
f812b4c
 
6ce386d
8377992
 
6ce386d
f812b4c
6ce386d
8377992
f812b4c
 
 
 
8377992
6ce386d
038c5ad
8377992
038c5ad
8377992
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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)