Skip to content

Commit be0d0c5

Browse files
committed
Merge pull request AlchemyAPI#3 from lineback/master
added imagetagging call and tests for combined, taxonomy, and image extraction.
2 parents 0a92072 + db90561 commit be0d0c5

File tree

4 files changed

+111
-9
lines changed

4 files changed

+111
-9
lines changed

alchemyapi.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
from __future__ import print_function
1818

19+
import requests
20+
1921
try:
2022
from urllib.request import urlopen
2123
from urllib.parse import urlparse
@@ -117,6 +119,9 @@ class AlchemyAPI:
117119
ENDPOINTS['combined']['text'] = '/text/TextGetCombinedData'
118120
ENDPOINTS['image'] = {}
119121
ENDPOINTS['image']['url'] = '/url/URLGetImage'
122+
ENDPOINTS['imagetagging'] = {}
123+
ENDPOINTS['imagetagging']['url'] = '/url/URLGetRankedImageKeywords'
124+
ENDPOINTS['imagetagging']['image'] = '/image/ImageGetRankedImageKeywords'
120125
ENDPOINTS['taxonomy'] = {}
121126
ENDPOINTS['taxonomy']['url'] = '/url/URLGetRankedTaxonomy'
122127
ENDPOINTS['taxonomy']['html'] = '/html/HTMLGetRankedTaxonomy'
@@ -718,7 +723,26 @@ def combined(self, flavor, data, options={}):
718723
options[flavor] = data
719724
return self.__analyze(AlchemyAPI.ENDPOINTS['combined'][flavor], options)
720725

721-
def __analyze(self, endpoint, params):
726+
def imageTagging(self, flavor, data, options={}):
727+
"""
728+
729+
INPUT:
730+
flavor -> which version of the call only url or image.
731+
data -> the data to analyze, either the the url or path to image.
732+
options -> various parameters that can be used to adjust how the API works, see below for more info on the available options.
733+
"""
734+
if flavor not in AlchemyAPI.ENDPOINTS['imagetagging']:
735+
return { 'status':'ERROR', 'statusInfo':'imagetagging for ' + flavor + ' not available' }
736+
elif 'image' == flavor:
737+
image = open(data, 'rb').read()
738+
options['imagePostMode'] = 'raw'
739+
return self.__analyze(AlchemyAPI.ENDPOINTS['imagetagging'][flavor], options, image)
740+
741+
options[flavor] = data
742+
return self.__analyze(AlchemyAPI.ENDPOINTS['imagetagging'][flavor], options)
743+
744+
745+
def __analyze(self, endpoint, params, post_data=bytearray()):
722746
"""
723747
HTTP Request wrapper that is called by the endpoint functions. This function is not intended to be called through an external interface.
724748
It makes the call, then converts the returned JSON string into a Python object.
@@ -730,17 +754,15 @@ def __analyze(self, endpoint, params):
730754
The response, already converted from JSON to a Python object.
731755
"""
732756

733-
#Insert the base url
734-
url = AlchemyAPI.BASE_URL + endpoint;
735-
736757
#Add the API Key and set the output mode to JSON
737758
params['apikey'] = self.apikey;
738759
params['outputMode'] = 'json';
760+
#Insert the base url
761+
762+
post_url = AlchemyAPI.BASE_URL + endpoint + '?' + urlencode(params).encode('utf-8');
739763

740764
try:
741-
#build the request with uri encoding
742-
page = urlopen(url, data=urlencode(params).encode('utf-8')).read().decode('utf-8')
743-
return json.loads(page)
765+
return requests.post(url=post_url, data=post_data).json()
744766
except Exception as e:
745767
print(e)
746768
return { 'status':'ERROR', 'statusInfo':'network-error' }

example.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
demo_text = 'Yesterday dumb Bob destroyed my fancy iPhone in beautiful Denver, Colorado. I guess I will have to head over to the Apple Store and buy a new one.'
2424
demo_url = 'http://www.npr.org/2013/11/26/247336038/dont-stuff-the-turkey-and-other-tips-from-americas-test-kitchen'
2525
demo_html = '<html><head><title>Python Demo | AlchemyAPI</title></head><body><h1>Did you know that AlchemyAPI works on HTML?</h1><p>Well, you do now.</p></body></html>'
26-
26+
image_url = 'http://demo1.alchemyapi.com/images/vision/football.jpg'
2727

2828
print('')
2929
print('')
@@ -477,6 +477,36 @@
477477
print('')
478478

479479

480+
print('')
481+
print('')
482+
print('')
483+
print('############################################')
484+
print('# Image tagging Example #')
485+
print('############################################')
486+
print('')
487+
print('')
488+
489+
print('Processing url: ', demo_url)
490+
print('')
491+
492+
response = alchemyapi.imageTagging('url',image_url)
493+
494+
if response['status'] == 'OK':
495+
print('## Response Object ##')
496+
print(json.dumps(response, indent=4))
497+
498+
print('')
499+
print('## Keywords ##')
500+
for keyword in response['imageKeywords']:
501+
print(keyword['text'], ' : ', keyword['score'])
502+
print('')
503+
else:
504+
print('Error in image tagging call: ', response['statusInfo'])
505+
506+
print('')
507+
print('')
508+
509+
480510
print('')
481511
print('')
482512
print('')

pigeon.jpg

7.61 KB
Loading

tests.py

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
test_text = 'Bob broke my heart, and then made up this silly sentence to test the PHP SDK'
2424
test_html = '<html><head><title>The best SDK Test | AlchemyAPI</title></head><body><h1>Hello World!</h1><p>My favorite language is PHP</p></body></html>'
2525
test_url = 'http://www.nytimes.com/2013/07/13/us/politics/a-day-of-friction-notable-even-for-a-fractious-congress.html?_r=0'
26-
26+
test_jpg = 'pigeon.jpg'
2727

2828

2929
alchemyapi = AlchemyAPI()
@@ -228,6 +228,56 @@
228228
print('')
229229
print('')
230230

231+
#imagetagging
232+
print('Checking imagetagging . . . ')
233+
response = alchemyapi.imageTagging('text', test_text);
234+
assert(response['status'] == 'ERROR')
235+
response = alchemyapi.imageTagging('html', test_html);
236+
assert(response['status'] == 'ERROR')
237+
response = alchemyapi.imageTagging('url', test_url);
238+
assert(response['status'] == 'OK')
239+
response = alchemyapi.imageTagging('image', test_jpg);
240+
assert(response['status'] == 'OK')
241+
print('Image tagging tests complete!')
242+
print('')
243+
print('')
244+
245+
#combined
246+
print('Checking combined . . . ')
247+
response = alchemyapi.combined('text', test_text);
248+
assert(response['status'] == 'OK')
249+
response = alchemyapi.combined('html', test_html);
250+
assert(response['status'] == 'ERROR')
251+
response = alchemyapi.combined('url', test_url);
252+
assert(response['status'] == 'OK')
253+
print('Combined tests complete!')
254+
print('')
255+
print('')
256+
257+
#taxonomy
258+
print('Checking taxonomy . . . ')
259+
response = alchemyapi.taxonomy('text', test_text);
260+
assert(response['status'] == 'OK')
261+
response = alchemyapi.taxonomy('html', test_html, {'url':'test'});
262+
assert(response['status'] == 'OK')
263+
response = alchemyapi.taxonomy('url', test_url);
264+
assert(response['status'] == 'OK')
265+
print('Taxonomy tests complete!')
266+
print('')
267+
print('')
268+
269+
#image
270+
print('Checking image extraction . . . ')
271+
response = alchemyapi.imageExtraction('text', test_text);
272+
assert(response['status'] == 'ERROR')
273+
response = alchemyapi.imageExtraction('html', test_html);
274+
assert(response['status'] == 'ERROR')
275+
response = alchemyapi.imageExtraction('url', test_url);
276+
assert(response['status'] == 'OK')
277+
print('Image Extraction tests complete!')
278+
print('')
279+
print('')
280+
231281

232282
print('**** All tests complete! ****')
233283

0 commit comments

Comments
 (0)