Valentin Tunev commited on
Commit
a43e23c
·
1 Parent(s): bdc78b6

Add image downloader

Browse files
Files changed (1) hide show
  1. image_downloader.py +139 -0
image_downloader.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Thanks to Claude!
2
+
3
+ import os
4
+ import sys
5
+ import argparse
6
+ import requests
7
+ import time
8
+ from PIL import Image
9
+ from io import BytesIO
10
+ import matplotlib.pyplot as plt
11
+ from duckduckgo_search import DDGS
12
+
13
+ def download_images(query, save_dir, max_images=50):
14
+ """
15
+ Download images based on search query with interactive approval using DuckDuckGo.
16
+
17
+ Args:
18
+ query (str): Search query for images
19
+ save_dir (str): Directory to save approved images
20
+ max_images (int): Maximum number of images to download
21
+ """
22
+ # Create save directory if it doesn't exist
23
+ if not os.path.exists(save_dir):
24
+ os.makedirs(save_dir)
25
+ print(f"Created directory: {save_dir}")
26
+
27
+ # Search for images using duckduckgo-search
28
+ print(f"Searching for '{query}' on DuckDuckGo...")
29
+
30
+ try:
31
+ # Initialize DDGS
32
+ ddgs = DDGS()
33
+
34
+ # Get image results
35
+ image_results = list(ddgs.images(
36
+ query,
37
+ region="wt-wt", # Worldwide
38
+ safesearch="off",
39
+ size=None, # Any size
40
+ color=None, # Any color
41
+ type_image=None, # Any type
42
+ layout=None, # Any layout
43
+ license_image=None, # Any license
44
+ max_results=max_images
45
+ ))
46
+
47
+ except Exception as e:
48
+ print(f"Error searching for images: {e}")
49
+ sys.exit(1)
50
+
51
+ if not image_results:
52
+ print("No images found for the query.")
53
+ return
54
+
55
+ print(f"Found {len(image_results)} images. Starting download process...")
56
+
57
+ # Download and display images one by one
58
+ for i, image_data in enumerate(image_results, 1):
59
+ try:
60
+ # Get image URL
61
+ image_url = image_data.get("image")
62
+ if not image_url:
63
+ print(f"Image {i}: No URL found, skipping")
64
+ continue
65
+
66
+ # Create filename from query
67
+ filename = f"{query.replace(' ', '_')}_{i}.jpg"
68
+ filepath = os.path.join(save_dir, filename)
69
+
70
+ # Download image
71
+ try:
72
+ headers = {
73
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
74
+ }
75
+ response = requests.get(image_url, headers=headers, timeout=10)
76
+ response.raise_for_status() # Raise exception for HTTP errors
77
+
78
+ # Open image
79
+ img = Image.open(BytesIO(response.content))
80
+
81
+ # Display image and metadata
82
+ plt.figure(figsize=(10, 8))
83
+ plt.imshow(img)
84
+ image_title = image_data.get('title', 'Unknown title')
85
+ plt.title(f"File: {filename}\nSize: {img.width}x{img.height}\nTitle: {image_title}")
86
+ plt.axis('off')
87
+ plt.tight_layout()
88
+ plt.show(block=False)
89
+
90
+ # Ask user if they want to keep the image
91
+ while True:
92
+ choice = input(f"Keep image '{filename}'? (y/n/q to quit): ").lower()
93
+ if choice == 'y':
94
+ # Save the image
95
+ img.save(filepath)
96
+ print(f"Saved: {filepath}")
97
+ break
98
+ elif choice == 'n':
99
+ print(f"Skipped: {filename}")
100
+ break
101
+ elif choice == 'q':
102
+ print("Quitting...")
103
+ return
104
+ else:
105
+ print("Please enter 'y' to keep, 'n' to skip, or 'q' to quit.")
106
+
107
+ # Close the figure
108
+ plt.close()
109
+
110
+ # Add a small delay to avoid being blocked
111
+ time.sleep(0.5)
112
+
113
+ except requests.exceptions.RequestException as e:
114
+ print(f"Failed to download image {i}: {e}")
115
+ continue
116
+ except Exception as e:
117
+ print(f"Failed to process image {i}: {e}")
118
+ continue
119
+
120
+ except Exception as e:
121
+ print(f"Error processing image {i}: {e}")
122
+
123
+ print(f"\nFinished downloading images for '{query}'")
124
+
125
+ def main():
126
+ # Set up argument parser
127
+ parser = argparse.ArgumentParser(description='Interactive image downloader using DuckDuckGo')
128
+ parser.add_argument('query', help='Search query for images (e.g., "concorde pear photos")')
129
+ parser.add_argument('--save-dir', default='downloaded_images', help='Directory to save approved images')
130
+ parser.add_argument('--max-images', type=int, default=50, help='Maximum number of images to download')
131
+
132
+ # Parse arguments
133
+ args = parser.parse_args()
134
+
135
+ # Download images
136
+ download_images(args.query, args.save_dir, args.max_images)
137
+
138
+ if __name__ == "__main__":
139
+ main()