-
Notifications
You must be signed in to change notification settings - Fork 2
/
image_search.py
54 lines (49 loc) · 1.52 KB
/
image_search.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
import requests
import threading
import os
import cStringIO
import pygame
REQUESTS = {}
URL_BASE = 'https://api.cognitive.microsoft.com/bing/v5.0/images/search?q={query}&count={count}'
BING_API_KEY = os.environ.get('BING_API_KEY')
MAX_WIDTH = 600
MAX_HEIGHT = 450
def search_image(term):
global REQUESTS
r = requests.post(
URL_BASE.format(query=term, count=3),
headers={
'Ocp-Apim-Subscription-Key': BING_API_KEY
}
).json()
results = r['value']
img_data = None
for result in results:
try:
img_data = requests.get(result['contentUrl']).content
break
except e:
continue
if img_data is not None:
image = pygame.image.load(cStringIO.StringIO(img_data))
# Resize Image
ow, oh = image.get_size()
if ((MAX_WIDTH / MAX_HEIGHT) * ow) > oh:
image = pygame.transform.smoothscale(image, (MAX_WIDTH, int(MAX_HEIGHT*(oh * 1.0 / ow))))
else:
image = pygame.transform.smoothscale(image, (int(MAX_WIDTH * (ow * 1.0/ oh)), MAX_HEIGHT))
REQUESTS[term] = image
def get_image(search_term):
global REQUESTS
if search_term not in REQUESTS:
REQUESTS[search_term] = None
thread = threading.Thread(target=search_image, args=(search_term,))
thread.daemon = True
thread.start()
else:
return REQUESTS[search_term]
if __name__ == 'main':
while True:
img = get_image('Foobar')
if img is not None:
print(img)