tsbpp commited on
Commit
6ce386d
·
verified ·
1 Parent(s): 34a8267

Upload load.py

Browse files
Files changed (1) hide show
  1. load.py +34 -33
load.py CHANGED
@@ -1,51 +1,52 @@
1
- import json
2
  import os
3
- import time
4
- import urllib.request as ureq
5
-
6
- def download_image_with_retries(url, output_file, max_retries=3, backoff_factor=1):
7
- """Attempt to download an image with retries upon failure.
8
 
9
- Args:
10
- url (str): The URL of the image to download.
11
- output_file (str): The local file path to save the downloaded image.
12
- max_retries (int): The maximum number of retry attempts.
13
- backoff_factor (float): The factor to calculate the delay between retries.
14
- """
15
- attempt = 0
16
- while attempt < max_retries:
17
- try:
18
- ureq.urlretrieve(url, output_file)
19
- print(f"Successfully downloaded: {output_file}")
20
  return True
21
- except Exception as e:
22
- print(f"Attempt {attempt + 1} failed for {url}: {e}")
23
- time.sleep(backoff_factor * (2 ** attempt))
24
- attempt += 1
25
- print(f"Failed to download {url} after {max_retries} attempts.")
26
  return False
27
 
28
- def verify_and_download_images(data):
29
- """Verify if images are downloaded; if not, download them.
 
 
 
 
 
 
 
30
 
31
- Args:
32
- data (dict): The dataset containing image URLs and additional information.
33
- """
34
  images_directory = './images'
35
  os.makedirs(images_directory, exist_ok=True)
36
 
37
  for key, value in data.items():
38
  image_url = value['imageURL']
39
- ext = os.path.splitext(image_url)[1]
40
- output_file = f'{images_directory}/{key}{ext}'
 
 
41
 
42
  if not os.path.exists(output_file):
43
- print(f"Image {key}{ext} not found, attempting to download...")
44
- if not download_image_with_retries(image_url, output_file):
 
45
  print(f"Warning: Could not download image {image_url}")
46
-
 
 
 
47
 
48
- # Load the dataset JSON file
49
  with open('dataset.json', 'r') as fp:
50
  data = json.load(fp)
51
 
 
 
1
  import os
2
+ import requests
3
+ from PIL import Image
4
+ import json
 
 
5
 
6
+ def download_image_with_retries(image_url, output_file):
7
+ try:
8
+ response = requests.get(image_url, stream=True, timeout=5)
9
+ if response.status_code == 200:
10
+ with open(output_file, 'wb') as out_file:
11
+ for chunk in response.iter_content(1024):
12
+ out_file.write(chunk)
 
 
 
 
13
  return True
14
+ except requests.RequestException as e:
15
+ print(f"Download failed: {e}")
 
 
 
16
  return False
17
 
18
+ def convert_gif_to_jpg(input_path, output_path):
19
+ try:
20
+ with Image.open(input_path) as img:
21
+ img.convert('RGB').save(output_path, 'JPEG')
22
+ os.remove(input_path) # Remove the original GIF after conversion
23
+ return True
24
+ except Exception as e:
25
+ print(f"Error converting GIF to JPG: {e}")
26
+ return False
27
 
28
+ def verify_and_download_images(data):
 
 
29
  images_directory = './images'
30
  os.makedirs(images_directory, exist_ok=True)
31
 
32
  for key, value in data.items():
33
  image_url = value['imageURL']
34
+ ext = os.path.splitext(image_url)[1].lower() # Ensure extension is in lowercase for comparison
35
+ is_gif = ext == '.gif'
36
+ output_ext = '.jpg' if is_gif else ext
37
+ output_file = f'{images_directory}/{key}{output_ext}'
38
 
39
  if not os.path.exists(output_file):
40
+ print(f"Image {key}{output_ext} not found, attempting to download...")
41
+ temp_output_file = output_file if not is_gif else f'{images_directory}/{key}{ext}'
42
+ if not download_image_with_retries(image_url, temp_output_file):
43
  print(f"Warning: Could not download image {image_url}")
44
+ elif is_gif:
45
+ # Convert GIF to JPG
46
+ if not convert_gif_to_jpg(temp_output_file, output_file):
47
+ print(f"Warning: Could not convert GIF to JPG for image {image_url}")
48
 
49
+ # Load the dataset JSON file (assuming you have a dataset.json file in the same directory)
50
  with open('dataset.json', 'r') as fp:
51
  data = json.load(fp)
52