From 3affdea53feb92ef7d23ca8b4d9155b8716378aa Mon Sep 17 00:00:00 2001 From: Andres Osinski Date: Wed, 26 Mar 2014 07:29:49 -0300 Subject: [PATCH 1/6] Added distutils files --- MANIFEST | 4 ++++ README | 35 +++++++++++++++++++++++++++++++++++ setup.py | 9 +++++++++ 3 files changed, 48 insertions(+) create mode 100644 MANIFEST create mode 100644 README create mode 100644 setup.py diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..5bbe43d --- /dev/null +++ b/MANIFEST @@ -0,0 +1,4 @@ +# file GENERATED by distutils, do NOT edit +README +alchemyapi.py +setup.py diff --git a/README b/README new file mode 100644 index 0000000..0609034 --- /dev/null +++ b/README @@ -0,0 +1,35 @@ +# alchemyapi_python # + +A sdk for AlchemyAPI using Python + + +## AlchemyAPI ## + +AlchemyAPI offers artificial intelligence as a service. We teach computers to learn how to read and see, and apply our technology to text analysis and image recognition through a cloud-based API. Our customers use AlchemyAPI to transform their unstructured content such as blog posts, news articles, social media posts and images into much more useful structured data. + +AlchemyAPI is a tech startup located in downtown Denver, Colorado. As the world’s most popular text analysis service, AlchemyAPI serves over 3.5 billion monthly API requests to over 35,000 developers. To enable our services, we use artificial intelligence, machine learning, neural networks, natural language processing and massive-scale web crawling. Our technology powers use cases in a variety of industry verticals, including social media monitoring, business intelligence, content recommendations, financial trading and targeted advertising. + +More information at: http://www.alchemyapi.com + + + +## API Key ## + +To use AlchemyAPI, you'll need to obtain an API key and attach that key to all requests. If you do not already have a key, please visit: http://www.alchemyapi.com/api/register.html + + + +## Getting Started with the Python SDK ## + +To get started and run the example, simply: + + git clone https://github.com/AlchemyAPI/alchemyapi_python.git + cd alchemyapi_python + python alchemyapi.py YOUR_API_KEY + python example.py + + +Just replace YOUR_API_KEY with your 40 character API key from AlchemyAPI, and you should be good to go. + + + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..3aca77d --- /dev/null +++ b/setup.py @@ -0,0 +1,9 @@ +from distutils.core import setup + +setup(name='AlchemyAPI', + version='1.0', + description='AlchemyAPI Python bindings', + author='AlchemyAPI', + url='https://github.com/AlchemyAPI/alchemyapi_python', + author_email='support@alchemyapi.com', + py_modules=['alchemyapi']) From fb57eb4eff41efb26b4b667049fcaf07f2134ce5 Mon Sep 17 00:00:00 2001 From: Simon Hewitt Date: Thu, 12 Jun 2014 11:52:05 -0700 Subject: [PATCH 2/6] whitespace --- alchemyapi.py | 292 +++++++++++++++++++++++++------------------------- 1 file changed, 146 insertions(+), 146 deletions(-) diff --git a/alchemyapi.py b/alchemyapi.py index 5e91215..a95410d 100644 --- a/alchemyapi.py +++ b/alchemyapi.py @@ -22,7 +22,7 @@ from urllib.request import urlopen from urllib.parse import urlparse from urllib.parse import urlencode -except ImportError: +except ImportError: from urlparse import urlparse from urllib2 import urlopen from urllib import urlencode @@ -39,14 +39,14 @@ Writes the API key to api_key.txt file. It will create the file if it doesn't exist. This function is intended to be called from the Python command line using: python alchemyapi YOUR_API_KEY If you don't have an API key yet, register for one at: http://www.alchemyapi.com/api/register.html - + INPUT: argv[1] -> Your API key from AlchemyAPI. Should be 40 hex characters - + OUTPUT: none """ - + import sys if len(sys.argv) == 2 and sys.argv[1]: if len(sys.argv[1]) == 40: @@ -133,7 +133,7 @@ class AlchemyAPI: s = requests.Session() def __init__(self): - """ + """ Initializes the SDK so it can send requests to AlchemyAPI for analysis. It loads the API key from api_key.txt and configures the endpoints. """ @@ -143,7 +143,7 @@ def __init__(self): # Open the key file and read the key f = open("api_key.txt", "r") key = f.read().strip() - + if key == '': #The key file should't be blank print('The api_key.txt file appears to be blank, please run: python alchemyapi.py YOUR_KEY_HERE') @@ -156,67 +156,67 @@ def __init__(self): else: #setup the key self.apikey = key - + # Close file f.close() except IOError: #The file doesn't exist, so show the message and create the file. print('API Key not found! Please run: python alchemyapi.py YOUR_KEY_HERE') print('If you do not have an API Key from AlchemyAPI, please register for one at: http://www.alchemyapi.com/api/register.html') - + #create a blank key file open('api_key.txt', 'a').close() sys.exit(0) except Exception as e: print(e) - + def entities(self, flavor, data, options={}): """ Extracts the entities for text, a URL or HTML. - For an overview, please refer to: http://www.alchemyapi.com/products/features/entity-extraction/ + For an overview, please refer to: http://www.alchemyapi.com/products/features/entity-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/entity-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: disambiguate -> disambiguate entities (i.e. Apple the company vs. apple the fruit). 0: disabled, 1: enabled (default) - linkedData -> include linked data on disambiguated entities. 0: disabled, 1: enabled (default) + linkedData -> include linked data on disambiguated entities. 0: disabled, 1: enabled (default) coreference -> resolve coreferences (i.e. the pronouns that correspond to named entities). 0: disabled, 1: enabled (default) quotations -> extract quotations by entities. 0: disabled (default), 1: enabled. sentiment -> analyze sentiment for each entity. 0: disabled (default), 1: enabled. Requires 1 additional API transction if enabled. - showSourceText -> 0: disabled (default), 1: enabled + showSourceText -> 0: disabled (default), 1: enabled maxRetrieve -> the maximum number of entities to retrieve (default: 50) OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['entities']: return { 'status':'ERROR', 'statusInfo':'entity extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['entities'][flavor], {}, options) - - + + def keywords(self, flavor, data, options={}): """ Extracts the keywords from text, a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/keyword-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/keyword-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: keywordExtractMode -> normal (default), strict sentiment -> analyze sentiment for each keyword. 0: disabled (default), 1: enabled. Requires 1 additional API transaction if enabled. @@ -224,14 +224,14 @@ def keywords(self, flavor, data, options={}): maxRetrieve -> the max number of keywords returned (default: 50) OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['keywords']: return { 'status':'ERROR', 'statusInfo':'keyword extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['keywords'][flavor], {}, options) @@ -241,22 +241,22 @@ def concepts(self, flavor, data, options={}): """ Tags the concepts for text, a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/concept-tagging/ - For the docs, please refer to: http://www.alchemyapi.com/api/concept-tagging/ - + For the docs, please refer to: http://www.alchemyapi.com/api/concept-tagging/ + Available Options: maxRetrieve -> the maximum number of concepts to retrieve (default: 8) linkedData -> include linked data, 0: disabled, 1: enabled (default) showSourceText -> 0:disabled (default), 1: enabled OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['concepts']: return { 'status':'ERROR', 'statusInfo':'concept tagging for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['concepts'][flavor], {}, options) @@ -267,24 +267,24 @@ def sentiment(self, flavor, data, options={}): Calculates the sentiment for text, a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/sentiment-analysis/ For the docs, please refer to: http://www.alchemyapi.com/api/sentiment-analysis/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: showSourceText -> 0: disabled (default), 1: enabled OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['sentiment']: return { 'status':'ERROR', 'statusInfo':'sentiment analysis for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['sentiment'][flavor], {}, options) @@ -295,18 +295,18 @@ def sentiment_targeted(self, flavor, data, target, options={}): Calculates the targeted sentiment for text, a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/sentiment-analysis/ For the docs, please refer to: http://www.alchemyapi.com/api/sentiment-analysis/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. target -> the word or phrase to run sentiment analysis on. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: showSourceText -> 0: disabled, 1: enabled OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ #Make sure the target is valid @@ -316,38 +316,38 @@ def sentiment_targeted(self, flavor, data, target, options={}): #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['sentiment_targeted']: return { 'status':'ERROR', 'statusInfo':'targeted sentiment analysis for ' + flavor + ' not available' } - - #add the URL encoded data and target to the options and analyze + + #add the URL encoded data and target to the options and analyze options[flavor] = data options['target'] = target return self.__analyze(AlchemyAPI.ENDPOINTS['sentiment_targeted'][flavor], {}, options) - + def text(self, flavor, data, options={}): """ Extracts the cleaned text (removes ads, navigation, etc.) for text, a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/text-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/text-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: useMetadata -> utilize meta description data, 0: disabled, 1: enabled (default) extractLinks -> include links, 0: disabled (default), 1: enabled. OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['text']: return { 'status':'ERROR', 'statusInfo':'clean text extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['text'][flavor], options) @@ -356,26 +356,26 @@ def text(self, flavor, data, options={}): def text_raw(self, flavor, data, options={}): """ Extracts the raw text (includes ads, navigation, etc.) for a URL or HTML. - For an overview, please refer to: http://www.alchemyapi.com/products/features/text-extraction/ + For an overview, please refer to: http://www.alchemyapi.com/products/features/text-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/text-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: none OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['text_raw']: return { 'status':'ERROR', 'statusInfo':'raw text extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['text_raw'][flavor], {}, options) @@ -386,7 +386,7 @@ def author(self, flavor, data, options={}): Extracts the author from a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/author-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/author-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. @@ -396,25 +396,25 @@ def author(self, flavor, data, options={}): none OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['author']: return { 'status':'ERROR', 'statusInfo':'author extraction for ' + flavor + ' not available' } - #add the data to the options and analyze + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['author'][flavor], {}, options) - + def language(self, flavor, data, options={}): """ Detects the language for text, a URL or HTML. - For an overview, please refer to: http://www.alchemyapi.com/api/language-detection/ + For an overview, please refer to: http://www.alchemyapi.com/api/language-detection/ For the docs, please refer to: http://www.alchemyapi.com/products/features/language-detection/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. @@ -424,14 +424,14 @@ def language(self, flavor, data, options={}): none OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['language']: return { 'status':'ERROR', 'statusInfo':'language detection for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['language'][flavor], {}, options) @@ -440,26 +440,26 @@ def language(self, flavor, data, options={}): def title(self, flavor, data, options={}): """ Extracts the title for a URL or HTML. - For an overview, please refer to: http://www.alchemyapi.com/products/features/text-extraction/ + For an overview, please refer to: http://www.alchemyapi.com/products/features/text-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/text-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: - useMetadata -> utilize title info embedded in meta data, 0: disabled, 1: enabled (default) + useMetadata -> utilize title info embedded in meta data, 0: disabled, 1: enabled (default) OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['title']: return { 'status':'ERROR', 'statusInfo':'title extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['title'][flavor], {}, options) @@ -468,14 +468,14 @@ def title(self, flavor, data, options={}): def relations(self, flavor, data, options={}): """ Extracts the relations for text, a URL or HTML. - For an overview, please refer to: http://www.alchemyapi.com/products/features/relation-extraction/ + For an overview, please refer to: http://www.alchemyapi.com/products/features/relation-extraction/ For the docs, please refer to: http://www.alchemyapi.com/api/relation-extraction/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: sentiment -> 0: disabled (default), 1: enabled. Requires one additional API transaction if enabled. keywords -> extract keywords from the subject and object. 0: disabled (default), 1: enabled. Requires one additional API transaction if enabled. @@ -484,19 +484,19 @@ def relations(self, flavor, data, options={}): sentimentExcludeEntities -> exclude full entity name in sentiment analysis. 0: disabled, 1: enabled (default) disambiguate -> disambiguate entities (i.e. Apple the company vs. apple the fruit). 0: disabled, 1: enabled (default) linkedData -> include linked data with disambiguated entities. 0: disabled, 1: enabled (default). - coreference -> resolve entity coreferences. 0: disabled, 1: enabled (default) + coreference -> resolve entity coreferences. 0: disabled, 1: enabled (default) showSourceText -> 0: disabled (default), 1: enabled. maxRetrieve -> the maximum number of relations to extract (default: 50, max: 100) OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['relations']: return { 'status':'ERROR', 'statusInfo':'relation extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['relations'][flavor], {}, options) @@ -507,26 +507,26 @@ def category(self, flavor, data, options={}): Categorizes the text for text, a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/text-categorization/ For the docs, please refer to: http://www.alchemyapi.com/api/text-categorization/ - + INPUT: flavor -> which version of the call, i.e. text, url or html. data -> the data to analyze, either the text, the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: showSourceText -> 0: disabled (default), 1: enabled OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['category']: return { 'status':'ERROR', 'statusInfo':'text categorization for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data - + return self.__analyze(AlchemyAPI.ENDPOINTS['category'][flavor], {}, options) @@ -534,9 +534,9 @@ def category(self, flavor, data, options={}): def feeds(self, flavor, data, options={}): """ Detects the RSS/ATOM feeds for a URL or HTML. - For an overview, please refer to: http://www.alchemyapi.com/products/features/feed-detection/ + For an overview, please refer to: http://www.alchemyapi.com/products/features/feed-detection/ For the docs, please refer to: http://www.alchemyapi.com/api/feed-detection/ - + INPUT: flavor -> which version of the call, i.e. url or html. data -> the data to analyze, either the the url or html code. @@ -546,14 +546,14 @@ def feeds(self, flavor, data, options={}): none OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['feeds']: return { 'status':'ERROR', 'statusInfo':'feed detection for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['feeds'][flavor], {}, options) @@ -564,46 +564,46 @@ def microformats(self, flavor, data, options={}): Parses the microformats for a URL or HTML. For an overview, please refer to: http://www.alchemyapi.com/products/features/microformats-parsing/ For the docs, please refer to: http://www.alchemyapi.com/api/microformats-parsing/ - + INPUT: flavor -> which version of the call, i.e. url or html. data -> the data to analyze, either the the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: none OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ - + #Make sure this request supports this flavor if flavor not in AlchemyAPI.ENDPOINTS['microformats']: return { 'status':'ERROR', 'statusInfo':'microformat extraction for ' + flavor + ' not available' } - - #add the data to the options and analyze + + #add the data to the options and analyze options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['microformats'][flavor], {}, options) def imageExtraction(self, flavor, data, options={}): """ Extracts main image from a URL - + INPUT: flavor -> which version of the call (url only currently). data -> URL to analyze - options -> various parameters that can be used to adjust how the API works, + options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: - extractMode -> + extractMode -> trust-metadata : (less CPU intensive, less accurate) always-infer : (more CPU intensive, more accurate) OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ if flavor not in AlchemyAPI.ENDPOINTS['image']: - return { 'status':'ERROR', 'statusInfo':'image extraction for ' + flavor + ' not available' } + return { 'status':'ERROR', 'statusInfo':'image extraction for ' + flavor + ' not available' } options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['image'][flavor], {}, options) @@ -616,33 +616,33 @@ def taxonomy(self, flavor, data, options={}): data -> the data to analyze, either the the url or html code. options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. - + Available Options: - showSourceText -> + showSourceText -> include the original 'source text' the taxonomy categories were extracted from within the API response Possible values: 1 - enabled - 0 - disabled (default) + 0 - disabled (default) sourceText -> where to obtain the text that will be processed by this API call. - + AlchemyAPI supports multiple modes of text extraction: - web page cleaning (removes ads, navigation links, etc.), raw text extraction - (processes all web page text, including ads / nav links), visual constraint queries, and XPath queries. + web page cleaning (removes ads, navigation links, etc.), raw text extraction + (processes all web page text, including ads / nav links), visual constraint queries, and XPath queries. Possible values: cleaned_or_raw : cleaning enabled, fallback to raw when cleaning produces no text (default) cleaned : operate on 'cleaned' web page text (web page cleaning enabled) raw : operate on raw web page text (web page cleaning disabled) - cquery : operate on the results of a visual constraints query + cquery : operate on the results of a visual constraints query Note: The 'cquery' http argument must also be set to a valid visual constraints query. - xpath : operate on the results of an XPath query + xpath : operate on the results of an XPath query Note: The 'xpath' http argument must also be set to a valid XPath query. cquery -> a visual constraints query to apply to the web page. - + xpath -> an XPath query to apply to the web page. @@ -650,11 +650,11 @@ def taxonomy(self, flavor, data, options={}): rel-tag output base http url (must be uri-argument encoded) OUTPUT: - The response, already converted from JSON to a Python object. - + The response, already converted from JSON to a Python object. + """ if flavor not in AlchemyAPI.ENDPOINTS['taxonomy']: - return { 'status':'ERROR', 'statusInfo':'taxonomy for ' + flavor + ' not available' } + return { 'status':'ERROR', 'statusInfo':'taxonomy for ' + flavor + ' not available' } options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['taxonomy'][flavor], {}, options) @@ -668,16 +668,16 @@ def combined(self, flavor, data, options={}): options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. Available Options: - extract -> + extract -> Possible values: page-image, entity, keyword, title, author, taxonomy, concept default : entity, keyword, taxonomy, concept - - disambiguate -> + + disambiguate -> disambiguate detected entities Possible values: 1 : enabled (default) 0 : disabled - + linkedData -> include Linked Data content links with disambiguated entities Possible values : @@ -689,44 +689,44 @@ def combined(self, flavor, data, options={}): Possible values: 1 : enabled (default) 0 : disabled - - quotations -> + + quotations -> enable quotations extraction Possible values: 1 : enabled 0 : disabled (default) - + sentiment -> enable entity-level sentiment analysis Possible values: 1 : enabled 0 : disabled (default) - - showSourceText -> + + showSourceText -> include the original 'source text' the entities were extracted from within the API response Possible values: 1 : enabled 0 : disabled (default) - + maxRetrieve -> maximum number of named entities to extract default : 50 - baseUrl -> + baseUrl -> rel-tag output base http url - - + + OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ if flavor not in AlchemyAPI.ENDPOINTS['combined']: - return { 'status':'ERROR', 'statusInfo':'combined for ' + flavor + ' not available' } + return { 'status':'ERROR', 'statusInfo':'combined for ' + flavor + ' not available' } options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['combined'][flavor], {}, options) def imageTagging(self, flavor, data, options={}): """ - + INPUT: flavor -> which version of the call only url or image. data -> the data to analyze, either the the url or path to image. @@ -738,31 +738,31 @@ def imageTagging(self, flavor, data, options={}): image = open(data, 'rb').read() options['imagePostMode'] = 'raw' return self.__analyze(AlchemyAPI.ENDPOINTS['imagetagging'][flavor], options, image) - + options[flavor] = data return self.__analyze(AlchemyAPI.ENDPOINTS['imagetagging'][flavor], {}, options) - - + + def __analyze(self, endpoint, params, post_data=bytearray()): """ - HTTP Request wrapper that is called by the endpoint functions. This function is not intended to be called through an external interface. - It makes the call, then converts the returned JSON string into a Python object. - + HTTP Request wrapper that is called by the endpoint functions. This function is not intended to be called through an external interface. + It makes the call, then converts the returned JSON string into a Python object. + INPUT: url -> the full URI encoded url OUTPUT: - The response, already converted from JSON to a Python object. + The response, already converted from JSON to a Python object. """ #Add the API Key and set the output mode to JSON params['apikey'] = self.apikey; params['outputMode'] = 'json'; #Insert the base url - + post_url = AlchemyAPI.BASE_URL + endpoint + '?' + urlencode(params).encode('utf-8'); - - try: + + try: results = self.s.post(url=post_url, data=post_data) return results.json() except Exception as e: From ffc1e132e4b9332e0e7654757b31259994df2911 Mon Sep 17 00:00:00 2001 From: Simon Hewitt Date: Thu, 12 Jun 2014 11:55:39 -0700 Subject: [PATCH 3/6] allow the api key to be passed into the constructor --- alchemyapi.py | 64 ++++++++++++++++++++------------------------------- 1 file changed, 25 insertions(+), 39 deletions(-) diff --git a/alchemyapi.py b/alchemyapi.py index a95410d..65067a4 100644 --- a/alchemyapi.py +++ b/alchemyapi.py @@ -17,6 +17,7 @@ from __future__ import print_function import requests +import sys try: from urllib.request import urlopen @@ -46,8 +47,6 @@ OUTPUT: none """ - - import sys if len(sys.argv) == 2 and sys.argv[1]: if len(sys.argv[1]) == 40: #write the key to the file @@ -60,6 +59,9 @@ print('The key appears to invalid. Please make sure to use the 40 character key assigned by AlchemyAPI') +class APIKeyException(Exception): + pass + class AlchemyAPI: #Setup the endpoints @@ -132,45 +134,29 @@ class AlchemyAPI: s = requests.Session() - def __init__(self): + def __init__(self, apikey=None): """ Initializes the SDK so it can send requests to AlchemyAPI for analysis. - It loads the API key from api_key.txt and configures the endpoints. - """ - - import sys - try: - # Open the key file and read the key - f = open("api_key.txt", "r") - key = f.read().strip() - - if key == '': - #The key file should't be blank - print('The api_key.txt file appears to be blank, please run: python alchemyapi.py YOUR_KEY_HERE') - print('If you do not have an API Key from AlchemyAPI, please register for one at: http://www.alchemyapi.com/api/register.html') - sys.exit(0) - elif len(key) != 40: - #Keys should be exactly 40 characters long - print('It appears that the key in api_key.txt is invalid. Please make sure the file only includes the API key, and it is the correct one.') - sys.exit(0) - else: - #setup the key - self.apikey = key - - # Close file - f.close() - except IOError: - #The file doesn't exist, so show the message and create the file. - print('API Key not found! Please run: python alchemyapi.py YOUR_KEY_HERE') - print('If you do not have an API Key from AlchemyAPI, please register for one at: http://www.alchemyapi.com/api/register.html') - - #create a blank key file - open('api_key.txt', 'a').close() - sys.exit(0) - except Exception as e: - print(e) - - + If the apikey is not supplied, is is loaded from api_key.txt. + """ + if not apikey: + try: + # Open the key file and read the key + with open("api_key.txt", "r"): + apikey = f.read().strip() + except IOError: + raise APIKeyException( + 'The api_key.txt file could not be read. To create one, ' + 'please run: python alchemyapi.py YOUR_KEY_HERE') + if not apikey: + raise APIKeyException( + 'No apikey key found. If you want to use the api_key.txt file ' + 'to store the key, please run: python alchemyapi.py YOUR_KEY_HERE') + elif len(apikey) != 40: + raise APIKeyException( + 'It appears that the api key is invalid. It should be exactly ' + '40 characters in length') + self.apikey = apikey def entities(self, flavor, data, options={}): """ From 5eaa127647ac863a47ce6cf912507b9b5e59058f Mon Sep 17 00:00:00 2001 From: Simon Hewitt Date: Thu, 12 Jun 2014 11:57:05 -0700 Subject: [PATCH 4/6] update version --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 3aca77d..df3ce2a 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from distutils.core import setup setup(name='AlchemyAPI', - version='1.0', + version='1.1', description='AlchemyAPI Python bindings', author='AlchemyAPI', url='https://github.com/AlchemyAPI/alchemyapi_python', From 5c7447bc14bef6af979e28d302cfb85485648a52 Mon Sep 17 00:00:00 2001 From: Simon Hewitt Date: Thu, 12 Jun 2014 12:01:16 -0700 Subject: [PATCH 5/6] update readme --- README | 7 +++++-- README.md | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/README b/README index 0609034..2153593 100644 --- a/README +++ b/README @@ -31,5 +31,8 @@ To get started and run the example, simply: Just replace YOUR_API_KEY with your 40 character API key from AlchemyAPI, and you should be good to go. - - +It is also possible to pass the API key into the constructor: + + from alchemyapi import AlchemyAPI + client = AlchemyAPI(YOUR_API_KEY) + response = client.entities('text', demo_text, { 'sentiment':1 }) \ No newline at end of file diff --git a/README.md b/README.md index 0609034..2153593 100644 --- a/README.md +++ b/README.md @@ -31,5 +31,8 @@ To get started and run the example, simply: Just replace YOUR_API_KEY with your 40 character API key from AlchemyAPI, and you should be good to go. - - +It is also possible to pass the API key into the constructor: + + from alchemyapi import AlchemyAPI + client = AlchemyAPI(YOUR_API_KEY) + response = client.entities('text', demo_text, { 'sentiment':1 }) \ No newline at end of file From 16a2a796ee2f7229633f179a3cfb1d81239fc245 Mon Sep 17 00:00:00 2001 From: Simon Hewitt Date: Thu, 26 Nov 2015 17:24:20 -0800 Subject: [PATCH 6/6] update to latest --- alchemyapi.py | 75 +++++++++++++++++---------------------------------- 1 file changed, 24 insertions(+), 51 deletions(-) diff --git a/alchemyapi.py b/alchemyapi.py index 4a7845d..a8a9878 100644 --- a/alchemyapi.py +++ b/alchemyapi.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2013 AlchemyAPI +# Copyright 2013 AlchemyAPI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,20 +20,10 @@ import sys try: - from urllib.request import urlopen - from urllib.parse import urlparse from urllib.parse import urlencode except ImportError: - from urlparse import urlparse - from urllib2 import urlopen from urllib import urlencode -try: - import json -except ImportError: - # Older versions of Python (i.e. 2.4) require simplejson instead of json - import simplejson as json - if __name__ == '__main__': """ @@ -48,7 +38,6 @@ none """ - import sys if len(sys.argv) == 2 and sys.argv[1]: if len(sys.argv[1]) == 40: # write the key to the file @@ -62,8 +51,9 @@ print( 'The key appears to invalid. Please make sure to use the 40 character key assigned by AlchemyAPI') + class APIKeyException(Exception): - pass + pass class AlchemyAPI: @@ -140,48 +130,31 @@ class AlchemyAPI: s = requests.Session() - def __init__(self): + def __init__(self, apikey=None): """ Initializes the SDK so it can send requests to AlchemyAPI for analysis. It loads the API key from api_key.txt and configures the endpoints. """ - import sys - try: - # Open the key file and read the key - f = open("api_key.txt", "r") - key = f.read().strip() - - if key == '': - # The key file should't be blank - print( - 'The api_key.txt file appears to be blank, please run: python alchemyapi.py YOUR_KEY_HERE') - print( - 'If you do not have an API Key from AlchemyAPI, please register for one at: http://www.alchemyapi.com/api/register.html') - sys.exit(0) - elif len(key) != 40: - # Keys should be exactly 40 characters long - print( - 'It appears that the key in api_key.txt is invalid. Please make sure the file only includes the API key, and it is the correct one.') - sys.exit(0) - else: - # setup the key - self.apikey = key - - # Close file - f.close() - except IOError: - # The file doesn't exist, so show the message and create the file. - print( - 'API Key not found! Please run: python alchemyapi.py YOUR_KEY_HERE') - print( - 'If you do not have an API Key from AlchemyAPI, please register for one at: http://www.alchemyapi.com/api/register.html') - - # create a blank key file - open('api_key.txt', 'a').close() - sys.exit(0) - except Exception as e: - print(e) + if not apikey: + try: + # Open the key file and read the key + with open("api_key.txt", "r"): + apikey = f.read().strip() + except IOError: + # The file doesn't exist, so show the message and create the file. + raise APIKeyException( + 'The api_key.txt file could not be read. To create one, ' + 'please run: python alchemyapi.py YOUR_KEY_HERE') + if not apikey: + raise APIKeyException( + 'No apikey key found. If you want to use the api_key.txt file ' + 'to store the key, please run: python alchemyapi.py YOUR_KEY_HERE') + elif len(apikey) != 40: + raise APIKeyException( + 'It appears that the api key is invalid. It should be exactly ' + '40 characters in length') + self.apikey = apikey def entities(self, flavor, data, options={}): """ @@ -306,7 +279,7 @@ def sentiment_targeted(self, flavor, data, target, options={}): options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. Available Options: - showSourceText -> 0: disabled, 1: enabled + showSourceText -> 0: disabled, 1: enabled OUTPUT: The response, already converted from JSON to a Python object.