-
Notifications
You must be signed in to change notification settings - Fork 0
/
imagescoop.py
152 lines (120 loc) · 5.9 KB
/
imagescoop.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# encoding: utf-8
# Copyright (c) 2016 Kenneth Blomqvist
# modified by Alban PRATS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
############################
## How to use
############################
# To scrape images run e.g. python image-search.py <csv file> --count 200 --label <label>
# The images will be saved in ./images/label/ItemCategory/itemId
# you passed in as the label parameter. This enables you to easily scrape a bunch of different searches while still
# keeping the images organized. The image files will be saved as jpeg images and named by the image contents sha1 hash.
#############################
## Note for the csv
#############################
# Separator : ";"
# 1 row : item id
# 2 row : item name
# 3 row : item category
import os
import re
import time
import argparse
import requests
import io
import hashlib
import itertools
import base64
from PIL import Image
from multiprocessing import Pool
from selenium import webdriver
import numpy as np
argument_parser = argparse.ArgumentParser(description='Download images using google image search')
argument_parser.add_argument('tableau', metavar='tableau', type=str, help="The csv file where list of product is")
argument_parser.add_argument('--count', metavar='count', default=100, type=int, help='How many images to fetch')
argument_parser.add_argument('--label', metavar='label', type=str, help="The directory in which to store the images (images/<label>)", required=True)
def ensure_directory(path):
if not os.path.exists(path):
os.mkdir(path)
def largest_file(dir_path):
def parse_num(filename):
match = re.search('\d+', filename)
if match:
return int(match.group(0))
files = os.listdir(dir_path)
if len(files) != 0:
return max(filter(lambda x: x, map(parse_num, files)))
else:
return 0
def fetch_image_urls(query, images_to_download):
image_urls = set()
search_url = "https://www.google.com/search?safe=off&site=&tbm=isch&source=hp&q={q}&oq={q}&gs_l=img"
browser = webdriver.Firefox()
browser.get(search_url.format(q=query))
def scroll_to_bottom():
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
image_count = len(image_urls)
delta = 0
while image_count < images_to_download:
print("Found:", len(image_urls), "images")
scroll_to_bottom()
images = browser.find_elements_by_css_selector("img.rg_ic")
for img in images:
image_urls.add(img.get_attribute('src'))
delta = len(image_urls) - image_count
image_count = len(image_urls)
if image_count > images_to_download:
image_urls = list(image_urls)[:images_to_download]
break
if delta <= 0:
print("Can't find more images")
break
fetch_more_button = browser.find_element_by_css_selector(".ksb._kvc")
if fetch_more_button:
browser.execute_script("document.querySelector('.ksb._kvc').click();")
scroll_to_bottom()
browser.quit()
return image_urls
def persist_image(dir_image_src):
label_directory = dir_image_src[0]
image_src = dir_image_src[1]
size = (150, 150)
try:
image_content = requests.get(image_src).content
except requests.exceptions.InvalidSchema:
# image is probably base64 encoded
image_data = re.sub('^data:image/.+;base64,', '', image_src)
image_content = base64.b64decode(image_data)
except Exception as e:
print("could not read", e, image_src)
return False
image_file = io.BytesIO(image_content)
image = Image.open(image_file).convert('RGB')
resized = image.resize(size)
with open(label_directory + hashlib.sha1(image_content).hexdigest() + ".jpg", 'wb') as f:
resized.save(f, "JPEG", quality=85)
return True
if __name__ == '__main__':
args = argument_parser.parse_args()
id_produit, name_produit, type_produit = np.loadtxt(args.tableau, dtype="bytes", delimiter=';', unpack=True)
for name, type, idp in zip(name_produit, type_produit, id_produit):
name=name.decode("utf-8")
type=type.decode("utf-8")
idp=idp.decode("utf-8")
ensure_directory('./images/')
ensure_directory('./images/' + args.label + "/")
ensure_directory('./images/' + args.label + "/" + type + "/")
query_directory = './images/' + args.label + "/" + type + "/"+ idp + "/"
ensure_directory(query_directory)
image_urls = fetch_image_urls(name, args.count)
values = [item for item in zip(itertools.cycle([query_directory]), image_urls)]
print("image count", len(image_urls))
pool = Pool(12)
results = pool.map(persist_image, values)
print("Images downloaded: ", len([r for r in results if r]))