watson-developer-cloud-0.22.0/0000755000076500000240000000000013006647576017230 5ustar jsstylosstaff00000000000000watson-developer-cloud-0.22.0/examples/0000755000076500000240000000000013006647576021046 5ustar jsstylosstaff00000000000000watson-developer-cloud-0.22.0/examples/__init__.py0000644000076500000240000000113212673061735023150 0ustar jsstylosstaff00000000000000# Copyright 2015 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. watson-developer-cloud-0.22.0/examples/alchemy_data_news_v1.py0000644000076500000240000000122212671632556025471 0ustar jsstylosstaff00000000000000import json from watson_developer_cloud import AlchemyDataNewsV1 alchemy_data_news = AlchemyDataNewsV1(api_key='YOUR API KEY') results = alchemy_data_news.get_news_documents(start='now-7d', end='now', time_slice='12h') print(json.dumps(results, indent=2)) results = alchemy_data_news.get_news_documents( start='1453334400', end='1454022000', return_fields=['enriched.url.title', 'enriched.url.url', 'enriched.url.author', 'enriched.url.publicationDate'], query_fields={'q.enriched.url.enrichedTitle.entities.entity': '|text=IBM,type=company|'}) print(json.dumps(results, indent=2)) watson-developer-cloud-0.22.0/examples/alchemy_language_v1.py0000644000076500000240000000454213006422620025275 0ustar jsstylosstaff00000000000000import json from os.path import join, dirname from watson_developer_cloud import AlchemyLanguageV1 alchemy_language = AlchemyLanguageV1(api_key='YOUR API KEY') url = 'https://developer.ibm.com/watson/blog/2015/11/03/price-reduction-for-watson-personality-insights/' print(json.dumps(alchemy_language.targeted_sentiment(text='I love cats! Dogs are smelly.', targets=['cats', 'dogs'], language='english'), indent=2)) # print(json.dumps(alchemy_language.targeted_emotion(text='I love apples. I hate bananas', # targets=['apples', 'bananas'], language='english'), indent=2)) # print(json.dumps(alchemy_language.author(url=url), indent=2)) # print(json.dumps(alchemy_language.concepts(max_items=2, url=url), indent=2)) # print(json.dumps(alchemy_language.dates(url=url, anchor_date='2016-03-22 00:00:00'), indent=2)) # print(json.dumps(alchemy_language.emotion(url=url), indent=2)) # print(json.dumps(alchemy_language.entities(url=url), indent=2)) # print(json.dumps(alchemy_language.keywords(max_items=5, url=url), indent=2)) # print(json.dumps(alchemy_language.category(url=url), indent=2)) # print(json.dumps(alchemy_language.typed_relations(url=url), indent=2)) # print(json.dumps(alchemy_language.relations(url=url), indent=2)) # print(json.dumps(alchemy_language.language(url=url), indent=2)) # print(json.dumps(alchemy_language.text(url=url), indent=2)) # print(json.dumps(alchemy_language.raw_text(url=url), indent=2)) # print(json.dumps(alchemy_language.title(url=url), indent=2)) # print(json.dumps(alchemy_language.feeds(url=url), indent=2)) # print(json.dumps(alchemy_language.microformats(url='http://microformats.org/wiki/hcard-examples'), indent=2)) # print(json.dumps(alchemy_language.publication_date(url=url), indent=2)) # print(json.dumps(alchemy_language.taxonomy(url=url), indent=2)) combined_operations = ['page-image', 'entity', 'keyword', 'title', 'author', 'taxonomy', 'concept', 'doc-emotion'] print(json.dumps(alchemy_language.combined(url=url, extract=combined_operations), indent=2)) # Get sentiment and emotion information results for detected entities/keywords: # print(json.dumps(alchemy_language.entities(url=url, sentiment=True, emotion=True), indent=2)) # print(json.dumps(alchemy_language.keywords(max_items=5, url=url, sentiment=True, emotion=True), indent=2)) watson-developer-cloud-0.22.0/examples/authorization_v1.py0000644000076500000240000000046512671632556024732 0ustar jsstylosstaff00000000000000import json from watson_developer_cloud import AuthorizationV1 from watson_developer_cloud import SpeechToTextV1 authorization = AuthorizationV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') print(json.dumps(authorization.get_token(url=SpeechToTextV1.default_url), indent=2)) watson-developer-cloud-0.22.0/examples/conversation_tone_analyzer_integration/0000755000076500000240000000000013006647576031115 5ustar jsstylosstaff00000000000000watson-developer-cloud-0.22.0/examples/conversation_tone_analyzer_integration/__init__.py0000644000076500000240000000161712777740445033236 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .watson_developer_cloud_service import WatsonDeveloperCloudService from .watson_developer_cloud_service import WatsonException from .watson_developer_cloud_service import WatsonInvalidArgument from .conversation_v1 import ConversationV1 from .tone_analyzer_v3 import ToneAnalyzerV3 from .version import __version__watson-developer-cloud-0.22.0/examples/conversation_tone_analyzer_integration/README.md0000644000076500000240000000373412777740445032406 0ustar jsstylosstaff00000000000000# Conversation and Tone Analyzer Integration Example This example provides sample code for integrating [Tone Analyzer][tone_analyzer] and [Conversation][conversation]. * [tone_detection.py][tone_conversation_integration_example_tone_detection] - sample code to initialize a user object in the conversation payload's context (initUser), to call Tone Analyzer to retrieve tone for a user's input (invokeToneAsync), and to update tone in the user object in the conversation payload's context (updateUserTone). * [tone_conversation_integration.v1.py][tone_conversation_integration_example] - sample code to use tone_detection.py to get and add tone to the payload and send a request to the Conversation Service's message endpoint both in a synchronous and asynchronous manner. Requirements to run the sample code * [Tone Analyzer Service credentials][bluemix_tone_analyzer_service] * [Conversation Service credentials][bluemix_conversation_service] * [Conversation Workspace ID][conversation_simple_workspace] Credentials & the Workspace ID can be set in environment properties, a .env file, or directly in the code. Dependencies provided in `init.py` Command to run the sample code `python tone_conversation_integration.v1.py` [conversation]: https://www.ibm.com/watson/developercloud/conversation.html [tone_analyzer]: http://www.ibm.com/watson/developercloud/tone-analyzer.html [bluemix_conversation_service]: https://console.ng.bluemix.net/catalog/services/conversation/ [bluemix_tone_analyzer_service]: https://console.ng.bluemix.net/catalog/services/tone-analyzer/ [conversation_simple_workspace]: https://github.com/watson-developer-cloud/conversation-simple#workspace [tone_conversation_integration_example]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples/tone_conversation_integration.v1.py [tone_conversation_integration_example_tone_detection]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples/conversation_addons/tone_detection.py././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000watson-developer-cloud-0.22.0/examples/conversation_tone_analyzer_integration/tone_conversation_integration.v1.pywatson-developer-cloud-0.22.0/examples/conversation_tone_analyzer_integration/tone_conversation_inte0000644000076500000240000000650612777740445035630 0ustar jsstylosstaff00000000000000import json import os from dotenv import load_dotenv, find_dotenv import asyncio from watson_developer_cloud import ConversationV1 from watson_developer_cloud import ToneAnalyzerV3 # import tone detection import tone_detection # load the .env file containing your environment variables for the required services (conversation and tone) load_dotenv(find_dotenv()) # replace with your own conversation credentials or put them in a .env file conversation = ConversationV1( username=os.environ.get('CONVERSATION_USERNAME') or 'YOUR SERVICE NAME', password=os.environ.get('CONVERSATION_PASSWORD') or 'YOUR PASSWORD', version='2016-09-20') # replace with your own tone analyzer credentials tone_analyzer = ToneAnalyzerV3( username=os.environ.get('TONE_ANALYZER_USERNAME') or 'YOUR SERVICE NAME', password=os.environ.get('TONE_ANALYZER_PASSWORD') or 'YOUR SERVICE NAME', version='2016-02-11') # replace with your own workspace_id workspace_id = os.environ.get('WORKSPACE_ID') or 'YOUR WORKSPACE ID' # This example stores tone for each user utterance in conversation context. # Change this to false, if you do not want to maintain history maintainToneHistoryInContext = True # Payload for the Watson Conversation Service # user input text required - replace "I am happy" with user input text. payload = { 'workspace_id':workspace_id, 'input': { 'text': "I am happy" } } def invokeToneConversation (payload, maintainToneHistoryInContext): ''' invokeToneConversation calls the the Tone Analyzer service to get the tone information for the user's input text (input['text'] in the payload json object), adds/updates the user's tone in the payload's context, and sends the payload to the conversation service to get a response which is printed to screen. :param payload: a json object containing the basic information needed to converse with the Conversation Service's message endpoint. :param maintainHistoryInContext: Note: as indicated below, the console.log statements can be replaced with application-specific code to process the err or data object returned by the Conversation Service. ''' tone = tone_analyzer.tone(text=payload['input']['text']) conversation_payload = tone_detection.updateUserTone(payload, tone, maintainToneHistoryInContext) response = conversation.message(workspace_id=workspace_id, message_input=conversation_payload['input'], context=conversation_payload['context']) print(json.dumps(response, indent=2)) async def invokeToneConversationAsync (payload, maintainToneHistoryInContext): tone = await tone_detection.invokeToneAsync(payload,tone_analyzer) conversation_payload = tone_detection.updateUserTone(payload, tone, maintainToneHistoryInContext) response = conversation.message(workspace_id=workspace_id, message_input=conversation_payload['input'], context=conversation_payload['context']) print(json.dumps(response, indent=2)) # invoke tone aware calls to conversation - either synchronously or asynchronously # synchronous call to conversation with tone included in the context invokeToneConversation(payload,maintainToneHistoryInContext) # asynchronous call to conversation with tone included in the context loop = asyncio.get_event_loop() loop.run_until_complete(invokeToneConversationAsync(payload,maintainToneHistoryInContext)) loop.close() watson-developer-cloud-0.22.0/examples/conversation_tone_analyzer_integration/tone_detection.py0000644000076500000240000002056712777740445034507 0ustar jsstylosstaff00000000000000""" * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. """ """ * Thresholds for identifying meaningful tones returned by the Watson Tone Analyzer. Current values are * based on the recommendations made by the Watson Tone Analyzer at * https://www.ibm.com/watson/developercloud/doc/tone-analyzer/understanding-tone.shtml * These thresholds can be adjusted to client/domain requirements. """ import json import asyncio PRIMARY_EMOTION_SCORE_THRESHOLD = 0.5 WRITING_HIGH_SCORE_THRESHOLD = 0.75 WRITING_NO_SCORE_THRESHOLD = 0.0 SOCIAL_HIGH_SCORE_THRESHOLD = 0.75 SOCIAL_LOW_SCORE_THRESHOLD = 0.25 # Labels for the tone categories returned by the Watson Tone Analyzer EMOTION_TONE_LABEL = 'emotion_tone' WRITING_TONE_LABEL = 'writing_tone' SOCIAL_TONE_LABEL = 'social_tone' ''' * updateUserTone processes the Tone Analyzer payload to pull out the emotion, writing and social * tones, and identify the meaningful tones (i.e., those tones that meet the specified thresholds). * The conversationPayload json object is updated to include these tones. * @param conversationPayload json object returned by the Watson Conversation Service * @param toneAnalyzerPayload json object returned by the Watson Tone Analyzer Service * @returns conversationPayload where the user object has been updated with tone information from the toneAnalyzerPayload ''' def updateUserTone (conversationPayload, toneAnalyzerPayload, maintainHistory): emotionTone = None writingTone = None socialTone = None # if there is no context in a if 'context' not in conversationPayload: conversationPayload['context'] = {}; if 'user' not in conversationPayload['context']: conversationPayload['context'] = initUser() # For convenience sake, define a variable for the user object user = conversationPayload['context']['user']; # Extract the tones - emotion, writing and social if toneAnalyzerPayload and toneAnalyzerPayload['document_tone']: for toneCategory in toneAnalyzerPayload['document_tone']['tone_categories']: if toneCategory['category_id'] == EMOTION_TONE_LABEL: emotionTone = toneCategory if toneCategory['category_id'] == WRITING_TONE_LABEL: writingTone = toneCategory if toneCategory['category_id'] == SOCIAL_TONE_LABEL: socialTone = toneCategory updateEmotionTone(user, emotionTone, maintainHistory) updateWritingTone(user, writingTone, maintainHistory) updateSocialTone(user, socialTone, maintainHistory) conversationPayload['context']['user'] = user return conversationPayload; ''' initToneContext initializes a user object containing tone data (from the Watson Tone Analyzer) @returns user json object with the emotion, writing and social tones. The current tone identifies the tone for a specific conversation turn, and the history provides the conversation for all tones up to the current tone for a conversation instance with a user. ''' def initUser(): return { 'user': { 'tone': { 'emotion': { 'current': None }, 'writing': { 'current': None }, 'social': { 'current': None } } } } ''' invokeToneAsync is an asynchronous function that calls the Tone Analyzer service @param conversationPayload json object returned by the Watson Conversation Service @param tone_analyzer an instance of the Watson Tone Analyzer service @returns the result of calling the tone_analyzer with the conversationPayload (which contains the user's input text) ''' async def invokeToneAsync(conversationPayload, tone_analyzer): return tone_analyzer.tone(text=conversationPayload['input']['text']) ''' updateEmotionTone updates the user emotion tone with the primary emotion - the emotion tone that has a score greater than or equal to the EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral' @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param emotionTone a json object containing the emotion tones in the payload returned by the Tone Analyzer ''' def updateEmotionTone(user, emotionTone, maintainHistory): maxScore = 0.0 primaryEmotion = None primaryEmotionScore = None for tone in emotionTone['tones']: if tone['score'] > maxScore: maxScore = tone['score'] primaryEmotion = tone['tone_name'].lower() primaryEmotionScore = tone['score'] if maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD: primaryEmotion = 'neutral' primaryEmotionScore = None # update user emotion tone user['tone']['emotion']['current'] = primaryEmotion; if maintainHistory: if 'history' not in user['tone']['emotion']: user['tone']['emotion']['history'] = [] user['tone']['emotion']['history'].append({ 'tone_name': primaryEmotion, 'score': primaryEmotionScore }) ''' updateWritingTone updates the user with the writing tones interpreted based on the specified thresholds @param: user a json object representing user information (tone) to be used in conversing with the Conversation Service @param: writingTone a json object containing the writing tones in the payload returned by the Tone Analyzer ''' def updateWritingTone (user, writingTone, maintainHistory): currentWriting = []; currentWritingObject = []; # Process each writing tone and determine if it is high or low for tone in writingTone['tones']: if tone['score'] >= WRITING_HIGH_SCORE_THRESHOLD: currentWriting.append(tone['tone_name'].lower() + '_high') currentWritingObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely high' }) elif tone['score'] <= WRITING_NO_SCORE_THRESHOLD: currentWritingObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'no evidence' }) else: currentWritingObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely medium' }) # update user writing tone user['tone']['writing']['current'] = currentWriting if maintainHistory: if 'history' not in user['tone']['writing']: user['tone']['writing']['history'] = [] user['tone']['writing']['history'].append(currentWritingObject) #TODO - is this the correct location??? AW ''' updateSocialTone updates the user with the social tones interpreted based on the specified thresholds @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param socialTone a json object containing the social tones in the payload returned by the Tone Analyzer ''' def updateSocialTone (user, socialTone, maintainHistory): currentSocial = [] currentSocialObject = [] # Process each social tone and determine if it is high or low for tone in socialTone['tones']: if tone['score'] >= SOCIAL_HIGH_SCORE_THRESHOLD: currentSocial.append(tone['tone_name'].lower() + '_high') currentSocialObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely high' }) elif tone['score'] <= SOCIAL_LOW_SCORE_THRESHOLD: currentSocial.append(tone['tone_name'].lower() + '_low'); currentSocialObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely low' }) else: currentSocialObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely medium' }) # update user social tone user['tone']['social']['current'] = currentSocial if maintainHistory: if not user['tone']['social']['current']: user['tone']['social']['current'] = []; user['tone']['social']['current'].append(currentSocialObject); watson-developer-cloud-0.22.0/examples/conversation_v1.py0000644000076500000240000000137512777740445024551 0ustar jsstylosstaff00000000000000import json from watson_developer_cloud import ConversationV1 conversation = ConversationV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', version='2016-09-20') # replace with your own workspace_id workspace_id = 'b42ee794-c019-4a0d-acd2-9e4d1d016767' response = conversation.message(workspace_id=workspace_id, message_input={'text': 'What\'s the weather like?'}) print(json.dumps(response, indent=2)) # When you send multiple requests for the same conversation, include the context object from the previous response. # response = conversation.message(workspace_id=workspace_id, message_input={'text': 'turn the wipers on'}, # context=response['context']) # print(json.dumps(response, indent=2)) watson-developer-cloud-0.22.0/examples/dialog_v1.py0000644000076500000240000000317512672054205023260 0ustar jsstylosstaff00000000000000# coding=utf-8 import json from os.path import join, dirname from watson_developer_cloud import DialogV1 dialog = DialogV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') print(json.dumps(dialog.get_dialogs(), indent=2)) # print(json.dumps(dialog.get_dialog('6250d170-41d6-468a-a697-5675578c8012'), indent=2)) # CREATE A DIALOG # with open(join(dirname(__file__), '../resources/dialog.xml') as dialog_file: # print(json.dumps(dialog.create_dialog( # dialog_file=dialog_file, name='pizza_test_9'), indent=2)) # dialog_id = '98734721-8952-4a1c-bb72-ef9957d4be93' # with open(join(dirname(__file__), '../resources/dialog.xml') as dialog_file: # print(json.dumps(dialog.update_dialog(dialog_file=dialog_file, dialog_id=dialog_id), indent=2)) # print(json.dumps(dialog.get_content(dialog_id), indent=2)) # # initial_response = dialog.conversation(dialog_id) # # print(json.dumps(initial_response, indent=2)) # # print(json.dumps(dialog.conversation(dialog_id=dialog_id, # dialog_input='What type of toppings do you have?', # conversation_id=initial_response['conversation_id'], # client_id=initial_response['client_id']), indent=2)) # print(json.dumps(dialog.delete_dialog(dialog_id='63b0489c-cd97-45ef-8800-4e7c310eeb19'), indent=2)) # print(json.dumps(dialog.update_profile( # dialog_id='6250d170-41d6-468a-a697-5675578c8012', client_id=123, name_values=[{'name': 'test', 'value': 'v1'}]), # indent=2)) # # print(json.dumps(dialog.get_profile( # dialog_id='6250d170-41d6-468a-a697-5675578c8012', client_id=123), indent=2)) watson-developer-cloud-0.22.0/examples/document_conversion_v1.py0000644000076500000240000000716013003737016026077 0ustar jsstylosstaff00000000000000# coding=utf-8 import json from os.path import join, dirname from watson_developer_cloud import DocumentConversionV1 document_conversion = DocumentConversionV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', version='2016-02-09') # Example of retrieving html or plain text with open(join(dirname(__file__), '../resources/example.html'), 'r') as document: config = {'conversion_target': DocumentConversionV1.NORMALIZED_HTML} print(document_conversion.convert_document(document=document, config=config, media_type='text/html') .content) # Example with JSON with open(join(dirname(__file__), '../resources/example.html'), 'r') as document: config['conversion_target'] = DocumentConversionV1.ANSWER_UNITS print(json.dumps(document_conversion.convert_document(document=document, config=config), indent=2)) # Examples of index_document API print("########## Example of a dry run of index_document with only a document ##########") with open(join(dirname(__file__), '../resources/example.html'), 'r') as document: config = { 'retrieve_and_rank': { 'dry_run': 'true' } } print(json.dumps(document_conversion.index_document(config=config, document=document), indent=2)) print("########## Example of a dry run of index_document with only metadata ##########") config = { 'retrieve_and_rank': { 'dry_run': 'true' } } metadata = { 'metadata': [ {'name': 'id', 'value': '12345'} ] } print(json.dumps(document_conversion.index_document(config=config, metadata=metadata), indent=2)) print("########## Example of a dry run of index_document with document and metadata ##########") with open(join(dirname(__file__), '../resources/example.html'), 'r') as document: config = { 'retrieve_and_rank': { 'dry_run': 'true' } } metadata = { 'metadata': [ {'name': 'id', 'value': '12345'} ] } print(json.dumps(document_conversion.index_document(config=config, document=document, metadata=metadata), indent=2)) print("########## Example of a dry run of index_document with document, metadata, and additional config for conversion" "##########") with open(join(dirname(__file__), '../resources/example.html'), 'r') as document: config = { 'convert_document': { 'normalized_html': { 'exclude_content': {"xpaths": ["//body/div"]} } }, 'retrieve_and_rank': { 'dry_run': 'true' } } metadata = { 'metadata': [ {'name': 'id', 'value': '12345'} ] } print(json.dumps(document_conversion.index_document(config=config, document=document, metadata=metadata), indent=2)) # print("########## Example of index_document with document, metadata (A service instance id, SOLR cluster id, and " # "a SOLR collection name must be provided from the Retrieve and Rank service in order to index) ##########") # with open(join(dirname(__file__), '../resources/example.html'), 'r') as document: # config = { # 'retrieve_and_rank': { # 'dry_run': 'false', # 'service_instance_id': 'YOUR RETRIEVE AND RANK SERVICE INSTANCE ID', # 'cluster_id': 'YOUR RETRIEVE AND RANK SERVICE SOLR CLUSTER ID', # 'search_collection': 'YOUR RETRIEVE AND RANK SERVICE SOLR SEARCH COLLECTION NAME' # } # } # metadata = { # 'metadata': [ # {'name': 'id', 'value': '12345'} # ] # } # print(json.dumps(document_conversion.index_document(config=config, document=document, metadata=metadata), indent=2)) watson-developer-cloud-0.22.0/examples/language_translation_v2.py0000644000076500000240000000233212777740445026233 0ustar jsstylosstaff00000000000000# coding=utf-8 import json from watson_developer_cloud import LanguageTranslationV2 # Language translation was deprecated use Language Translator. language_translation = LanguageTranslationV2( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') # create new custom model # with open('../resources/language_translator_model.tmx', 'rb') as custom_model: # print(json.dumps(language_translator.create_model( # base_model_id='en-fr', name='test_glossary', forced_glossary=custom_model), indent=2)) print(json.dumps(language_translation.get_models(), indent=2)) print(json.dumps(language_translation.get_model('en-es-conversational'), indent=2)) # delete custom model # print(json.dumps(language_translator.delete_model('13860c86-ec3f-4e60-8cbe-3ef0048f92af'), indent=2)) print(json.dumps(language_translation.translate('Hola, cómo estás? €', source='es', target='en'), indent=2, ensure_ascii=False)) print(json.dumps(language_translation.translate('Messi is the best ever', model_id='en-es-conversational'), indent=2)) print(json.dumps(language_translation.identify('Hello how are you?'), indent=2)) print(json.dumps(language_translation.get_identifiable_languages(), indent=2)) watson-developer-cloud-0.22.0/examples/language_translator_v2.py0000644000076500000240000000222112777740445026063 0ustar jsstylosstaff00000000000000# coding=utf-8 import json from watson_developer_cloud import LanguageTranslatorV2 language_translator = LanguageTranslatorV2( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') # create new custom model # with open('../resources/language_translator_model.tmx', 'rb') as custom_model: # print(json.dumps(language_translator.create_model( # base_model_id='en-fr', name='test_glossary', forced_glossary=custom_model), indent=2)) print(json.dumps(language_translator.get_models(), indent=2)) print(json.dumps(language_translator.get_model('en-es-conversational'), indent=2)) # delete custom model # print(json.dumps(language_translator.delete_model('13860c86-ec3f-4e60-8cbe-3ef0048f92af'), indent=2)) print(json.dumps(language_translator.translate('Hola, cómo estás? €', source='es', target='en'), indent=2, ensure_ascii=False)) print(json.dumps(language_translator.translate('Messi is the best ever', model_id='en-es-conversational'), indent=2)) print(json.dumps(language_translator.identify('Hello how are you?'), indent=2)) print(json.dumps(language_translator.get_identifiable_languages(), indent=2)) watson-developer-cloud-0.22.0/examples/natural_language_classifier_v1.py0000644000076500000240000000216312777757707027561 0ustar jsstylosstaff00000000000000import json # from os.path import join, dirname from watson_developer_cloud import NaturalLanguageClassifierV1 natural_language_classifier = NaturalLanguageClassifierV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') classifiers = natural_language_classifier.list() print(json.dumps(classifiers, indent=2)) # create a classifier # with open('../resources/weather_data_train.csv', 'rb') as training_data: # print(json.dumps(natural_language_classifier.create(training_data=training_data, name='weather'), indent=2)) # replace 2374f9x68-nlc-2697 with your classifier id status = natural_language_classifier.status('2374f9x68-nlc-2697') print(json.dumps(status, indent=2)) if status['status'] == 'Available': classes = natural_language_classifier.classify('2374f9x68-nlc-2697', 'How hot will it be tomorrow?') print(json.dumps(classes, indent=2)) # delete = natural_language_classifier.remove('2374f9x68-nlc-2697') # print(json.dumps(delete, indent=2)) # example of raising a WatsonException # print(json.dumps(natural_language_classifier.create(training_data='', name='weather3'), indent=2)) watson-developer-cloud-0.22.0/examples/personality_insights_v2.py0000755000076500000240000000221713003413561026273 0ustar jsstylosstaff00000000000000import json from os.path import join, dirname from watson_developer_cloud import PersonalityInsightsV2 personality_insights = PersonalityInsightsV2( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') with open(join(dirname(__file__), '../resources/personality.txt')) as personality_text: print(json.dumps(personality_insights.profile( text=personality_text.read()), indent=2)) # with open(join(dirname(__file__), '../resources/personality.txt') as personality_text: # personality_insights_json = {"contentItems": [ # {"id": "245160944223793152", "userid": "bob", "sourceid": "twitter", "created": 1427720427, # "updated": 1427720427, "contenttype": "text/plain", "charset": "UTF-8", "language": "en-us", # "content": personality_text.read(), "parentid": "", "reply": "false", "forward": "false"}]} # print(json.dumps(personality_insights.profile(text=personality_insights_json), indent=2)) # with open(join(dirname(__file__), '../resources/personality.es.txt') as personality_text: # print(json.dumps(personality_insights.profile(text=personality_text.read(), language='es'), indent=2)) watson-developer-cloud-0.22.0/examples/personality_insights_v3.py0000755000076500000240000000123513003460541026273 0ustar jsstylosstaff00000000000000import json from os.path import join, dirname from watson_developer_cloud import PersonalityInsightsV3 """ The example returns a JSON response whose content is the same as that in ../resources/personality-v3-expect2.txt """ personality_insights = PersonalityInsightsV3( version='2016-10-20', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') with open(join(dirname(__file__), '../resources/personality-v3.json')) as profile_json: profile = personality_insights.profile( profile_json.read(), content_type='application/json', raw_scores=True, consumption_preferences=True) print(json.dumps(profile, indent=2)) watson-developer-cloud-0.22.0/examples/README.md0000644000076500000240000000132412676511107022315 0ustar jsstylosstaff00000000000000## Examples To run the examples, you will need the `username` and `password` credentials. To get your service credentials, follow these steps: 1. Log in to Bluemix at https://bluemix.net. 1. Create an instance of the service: 1. In the Bluemix **Catalog**, select the Natural Language Classifier service. 1. Under **Add Service**, type a unique name for the service instance in the Service name field. For example, type `my-service-name`. Leave the default values for the other options. 1. Click **Use**. 1. Copy your credentials: 1. On the left side of the page, click **Service Credentials** to view your service credentials. 1. Copy `username` and `password` from these service credentials. watson-developer-cloud-0.22.0/examples/retrieve_and_rank_v1.py0000644000076500000240000000471512777762477025533 0ustar jsstylosstaff00000000000000import json from watson_developer_cloud import RetrieveAndRankV1 retrieve_and_rank = RetrieveAndRankV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') # Solr clusters solr_clusters = retrieve_and_rank.list_solr_clusters() print(json.dumps(solr_clusters, indent=2)) # created_cluster = retrieve_and_rank.create_solr_cluster(cluster_name='Test Cluster', cluster_size='1') # print(json.dumps(created_cluster, indent=2)) # Replace with your own solr_cluster_id solr_cluster_id = 'sc573c955c_4bb3_46b2_bada_d8040c8c058d' status = retrieve_and_rank.get_solr_cluster_status(solr_cluster_id=solr_cluster_id) print(json.dumps(status, indent=2)) # Solr cluster config # with open('../resources/solr_config.zip', 'rb') as config: # config_status = retrieve_and_rank.create_config(solr_cluster_id, 'test-config', config) # print(json.dumps(config_status, indent=2)) # deleted_response = retrieve_and_rank.delete_config(solr_cluster_id, 'test-config') # print(json.dumps(deleted_response, indent=2)) configs = retrieve_and_rank.list_configs(solr_cluster_id=solr_cluster_id) print(json.dumps(configs, indent=2)) # collection = retrieve_and_rank.create_collection(solr_cluster_id, 'test-collection', 'test-config') # print(json.dumps(collection, indent=2)) if len(configs['solr_configs']) > 0: collections = retrieve_and_rank.list_collections(solr_cluster_id=solr_cluster_id) print(json.dumps(collections, indent=2)) pysolr_client = retrieve_and_rank.get_pysolr_client(solr_cluster_id, collections['collections'][0]) # Can also refer to config by name results = pysolr_client.search('bananas') print('{0} documents found'.format(len(results.docs))) # Rankers # rankers = retrieve_and_rank.list_rankers() # print(json.dumps(rankers, indent=2)) # create a ranker # with open('../resources/ranker_training_data.csv', 'rb') as training_data: # print(json.dumps(retrieve_and_rank.create_ranker(training_data=training_data, name='Ranker Test'), indent=2)) # replace YOUR RANKER ID # status = retrieve_and_rank.get_ranker_status('42AF7Ex10-rank-47') # print(json.dumps(status, indent=2)) # delete_results = retrieve_and_rank.delete_ranker('YOUR RANKER ID') # print(json.dumps(delete_results)) # replace '42AF7Ex10-rank-47' with your ranker_id # with open('../resources/ranker_answer_data.csv', 'rb') as answer_data: # ranker_results = retrieve_and_rank.rank('42AF7Ex10-rank-47', answer_data) # print(json.dumps(ranker_results, indent=2)) watson-developer-cloud-0.22.0/examples/speech_to_text_v1.py0000644000076500000240000000113612777763760025054 0ustar jsstylosstaff00000000000000import json from os.path import join, dirname from watson_developer_cloud import SpeechToTextV1 speech_to_text = SpeechToTextV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', x_watson_learning_opt_out=False ) print(json.dumps(speech_to_text.models(), indent=2)) print(json.dumps(speech_to_text.get_model('en-US_BroadbandModel'), indent=2)) with open(join(dirname(__file__), '../resources/speech.wav'), 'rb') as audio_file: print(json.dumps(speech_to_text.recognize( audio_file, content_type='audio/wav', timestamps=True, word_confidence=True), indent=2)) watson-developer-cloud-0.22.0/examples/text_to_speech_v1.py0000644000076500000240000000315212741751531025034 0ustar jsstylosstaff00000000000000# coding=utf-8 import json from os.path import join, dirname from watson_developer_cloud import TextToSpeechV1 text_to_speech = TextToSpeechV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', x_watson_learning_opt_out=True) # Optional flag print(json.dumps(text_to_speech.voices(), indent=2)) with open(join(dirname(__file__), '../resources/output.wav'), 'wb') as audio_file: audio_file.write(text_to_speech.synthesize('Hello world!', accept='audio/wav', voice="en-US_AllisonVoice")) print(json.dumps(text_to_speech.pronunciation('Watson', pronunciation_format='spr'), indent=2)) print(json.dumps(text_to_speech.customizations(), indent=2)) # print(json.dumps(text_to_speech.create_customization('test-customization'), indent=2)) # print(text_to_speech.update_customization('YOUR CUSTOMIZATION ID', name='new name')) # print(json.dumps(text_to_speech.get_customization('YOUR CUSTOMIZATION ID'), indent=2)) # print(json.dumps(text_to_speech.get_customization_words('YOUR CUSTOMIZATION ID'), indent=2)) # print(text_to_speech.add_customization_words('YOUR CUSTOMIZATION ID', # [{'word': 'resume', 'translation': 'rɛzʊmeɪ'}])) # print(text_to_speech.set_customization_word('YOUR CUSTOMIZATION ID', word='resume', # translation='rɛzʊmeɪ')) # print(json.dumps(text_to_speech.get_customization_word('YOUR CUSTOMIZATION ID', 'resume'), indent=2)) # print(text_to_speech.delete_customization_word('YOUR CUSTOMIZATION ID', 'resume')) # print(text_to_speech.delete_customization('YOUR CUSTOMIZATION ID')) watson-developer-cloud-0.22.0/examples/tone_analyzer_v3.py0000644000076500000240000000041712723355615024677 0ustar jsstylosstaff00000000000000import json from watson_developer_cloud import ToneAnalyzerV3 tone_analyzer = ToneAnalyzerV3( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', version='2016-02-11') print(json.dumps(tone_analyzer.tone(text='I am very happy'), indent=2)) watson-developer-cloud-0.22.0/examples/tradeoff_analytics_v1.py0000755000076500000240000000071713006647105025663 0ustar jsstylosstaff00000000000000import json import os from os.path import join, dirname from watson_developer_cloud import TradeoffAnalyticsV1 tradeoff_analytics = TradeoffAnalyticsV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') with open(os.path.join(os.path.dirname(__file__), '../resources/problem.json')) as problem_json: dilemma = tradeoff_analytics.dilemmas(json.load(problem_json), generate_visualization=False) print(json.dumps(dilemma, indent=2)) watson-developer-cloud-0.22.0/examples/visual_recognition_v3.py0000644000076500000240000000370213003465473025724 0ustar jsstylosstaff00000000000000import json from os.path import join, dirname from os import environ from watson_developer_cloud import VisualRecognitionV3 test_url = 'https://www.ibm.com/ibm/ginni/images/ginni_bio_780x981_v4_03162016.jpg' visual_recognition = VisualRecognitionV3('2016-05-20', api_key='YOUR API KEY') # with open(join(dirname(__file__), '../resources/cars.zip'), 'rb') as cars, \ # open(join(dirname(__file__), '../resources/trucks.zip'), 'rb') as trucks: # print(json.dumps(visual_recognition.create_classifier('Cars vs Trucks', cars_positive_examples=cars, # negative_examples=trucks), indent=2)) with open(join(dirname(__file__), '../resources/car.jpg'), 'rb') as image_file: print(json.dumps(visual_recognition.classify(images_file=image_file, threshold=0.1, classifier_ids=['CarsvsTrucks_1675727418', 'default']), indent=2)) # print(json.dumps(visual_recognition.get_classifier('YOUR CLASSIFIER ID'), indent=2)) # with open(join(dirname(__file__), '../resources/car.jpg'), 'rb') as image_file: # print(json.dumps(visual_recognition.update_classifier('CarsvsTrucks_1479118188', # cars_positive_examples=image_file), indent=2)) print(json.dumps(visual_recognition.classify(images_url=test_url), indent=2)) print(json.dumps(visual_recognition.detect_faces(images_url=test_url), indent=2)) # print(json.dumps(visual_recognition.delete_classifier(classifier_id='YOUR CLASSIFIER ID'), indent=2)) print(json.dumps(visual_recognition.list_classifiers(), indent=2)) with open(join(dirname(__file__), '../resources/text.png'), 'rb') as image_file: print(json.dumps(visual_recognition.recognize_text(images_file=image_file), indent=2)) with open(join(dirname(__file__), '../resources/face.jpg'), 'rb') as image_file: print(json.dumps(visual_recognition.detect_faces(images_file=image_file), indent=2)) watson-developer-cloud-0.22.0/LICENSE0000644000076500000240000007242412605473757020250 0ustar jsstylosstaff00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. APACHE HTTP SERVER SUBCOMPONENTS: The Apache HTTP Server includes a number of subcomponents with separate copyright notices and license terms. Your use of the source code for the these subcomponents is subject to the terms and conditions of the following licenses. For the mod_mime_magic component: /* * mod_mime_magic: MIME type lookup via file magic numbers * Copyright (c) 1996-1997 Cisco Systems, Inc. * * This software was submitted by Cisco Systems to the Apache Group in July * 1997. Future revisions and derivatives of this source code must * acknowledge Cisco Systems as the original contributor of this module. * All other licensing and usage conditions are those of the Apache Group. * * Some of this code is derived from the free version of the file command * originally posted to comp.sources.unix. Copyright info for that program * is included below as required. * --------------------------------------------------------------------------- * - Copyright (c) Ian F. Darwin, 1987. Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone and * Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on any * computer system, and to alter it and redistribute it freely, subject to * the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, credits * must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users ever read * sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. * ------------------------------------------------------------------------- * */ For the modules\mappers\mod_imap.c component: "macmartinized" polygon code copyright 1992 by Eric Haines, erich@eye.com For the server\util_md5.c component: /************************************************************************ * NCSA HTTPd Server * Software Development Group * National Center for Supercomputing Applications * University of Illinois at Urbana-Champaign * 605 E. Springfield, Champaign, IL 61820 * httpd@ncsa.uiuc.edu * * Copyright (C) 1995, Board of Trustees of the University of Illinois * ************************************************************************ * * md5.c: NCSA HTTPd code which uses the md5c.c RSA Code * * Original Code Copyright (C) 1994, Jeff Hostetler, Spyglass, Inc. * Portions of Content-MD5 code Copyright (C) 1993, 1994 by Carnegie Mellon * University (see Copyright below). * Portions of Content-MD5 code Copyright (C) 1991 Bell Communications * Research, Inc. (Bellcore) (see Copyright below). * Portions extracted from mpack, John G. Myers - jgm+@cmu.edu * Content-MD5 Code contributed by Martin Hamilton (martin@net.lut.ac.uk) * */ /* these portions extracted from mpack, John G. Myers - jgm+@cmu.edu */ /* (C) Copyright 1993,1994 by Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without * fee, provided that the above copyright notice appear in all copies * and that both that copyright notice and this permission notice * appear in supporting documentation, and that the name of Carnegie * Mellon University not be used in advertising or publicity * pertaining to distribution of the software without specific, * written prior permission. Carnegie Mellon University makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied * warranty. * * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ /* * Copyright (c) 1991 Bell Communications Research, Inc. (Bellcore) * * Permission to use, copy, modify, and distribute this material * for any purpose and without fee is hereby granted, provided * that the above copyright notice and this permission notice * appear in all copies, and that the name of Bellcore not be * used in advertising or publicity pertaining to this * material without the specific, prior written permission * of an authorized representative of Bellcore. BELLCORE * MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY * OF THIS MATERIAL FOR ANY PURPOSE. IT IS PROVIDED "AS IS", * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. */ For the srclib\apr\include\apr_md5.h component: /* * This is work is derived from material Copyright RSA Data Security, Inc. * * The RSA copyright statement and Licence for that original material is * included below. This is followed by the Apache copyright statement and * licence for the modifications made to that material. */ /* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. These notices must be retained in any copies of any part of this documentation and/or software. */ For the srclib\apr\passwd\apr_md5.c component: /* * This is work is derived from material Copyright RSA Data Security, Inc. * * The RSA copyright statement and Licence for that original material is * included below. This is followed by the Apache copyright statement and * licence for the modifications made to that material. */ /* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm */ /* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. These notices must be retained in any copies of any part of this documentation and/or software. */ /* * The apr_md5_encode() routine uses much code obtained from the FreeBSD 3.0 * MD5 crypt() function, which is licenced as follows: * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp * ---------------------------------------------------------------------------- */ For the srclib\apr-util\crypto\apr_md4.c component: * This is derived from material copyright RSA Data Security, Inc. * Their notice is reproduced below in its entirety. * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD4 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD4 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ For the srclib\apr-util\include\apr_md4.h component: * * This is derived from material copyright RSA Data Security, Inc. * Their notice is reproduced below in its entirety. * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD4 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD4 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ For the srclib\apr-util\test\testdbm.c component: /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * This file came from the SDBM package (written by oz@nexus.yorku.ca). * That package was under public domain. This file has been ported to * APR, updated to ANSI C and other, newer idioms, and added to the Apache * codebase under the above copyright and license. */ For the srclib\apr-util\test\testmd4.c component: * * This is derived from material copyright RSA Data Security, Inc. * Their notice is reproduced below in its entirety. * * Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All * rights reserved. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ For the srclib\apr-util\xml\expat\conftools\install-sh component: # # install - install a program, script, or datafile # This comes from X11R5 (mit/util/scripts/install.sh). # # Copyright 1991 by the Massachusetts Institute of Technology # # Permission to use, copy, modify, distribute, and sell this software and its # documentation for any purpose is hereby granted without fee, provided that # the above copyright notice appear in all copies and that both that # copyright notice and this permission notice appear in supporting # documentation, and that the name of M.I.T. not be used in advertising or # publicity pertaining to distribution of the software without specific, # written prior permission. M.I.T. makes no representations about the # suitability of this software for any purpose. It is provided "as is" # without express or implied warranty. # For the srclib\pcre\install-sh component: # # Copyright 1991 by the Massachusetts Institute of Technology # # Permission to use, copy, modify, distribute, and sell this software and its # documentation for any purpose is hereby granted without fee, provided that # the above copyright notice appear in all copies and that both that # copyright notice and this permission notice appear in supporting # documentation, and that the name of M.I.T. not be used in advertising or # publicity pertaining to distribution of the software without specific, # written prior permission. M.I.T. makes no representations about the # suitability of this software for any purpose. It is provided "as is" # without express or implied warranty. For the pcre component: PCRE LICENCE ------------ PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by: Philip Hazel University of Cambridge Computing Service, Cambridge, England. Phone: +44 1223 334714. Copyright (c) 1997-2001 University of Cambridge Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. In practice, this means that if you use PCRE in software which you distribute to others, commercially or otherwise, you must put a sentence like this Regular expression support is provided by the PCRE library package, which is open source software, written by Philip Hazel, and copyright by the University of Cambridge, England. somewhere reasonably visible in your documentation and in any relevant files or online help data or similar. A reference to the ftp site for the source, that is, to ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ should also be given in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), or Lesser General Purpose Licence (LGPL), then the terms of that licence shall supersede any condition above with which it is incompatible. The documentation for PCRE, supplied in the "doc" directory, is distributed under the same terms as the software itself. End PCRE LICENCE For the test\zb.c component: /* ZeusBench V1.01 =============== This program is Copyright (C) Zeus Technology Limited 1996. This program may be used and copied freely providing this copyright notice is not removed. This software is provided "as is" and any express or implied waranties, including but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall Zeus Technology Ltd. be liable for any direct, indirect, incidental, special, exemplary, or consequential damaged (including, but not limited to, procurement of substitute good or services; loss of use, data, or profits; or business interruption) however caused and on theory of liability. Whether in contract, strict liability or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. Written by Adam Twiss (adam@zeus.co.uk). March 1996 Thanks to the following people for their input: Mike Belshe (mbelshe@netscape.com) Michael Campanella (campanella@stevms.enet.dec.com) */ For the expat xml parser component: Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd and Clark Cooper 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. ==================================================================== watson-developer-cloud-0.22.0/MANIFEST.in0000644000076500000240000000016612607731772020767 0ustar jsstylosstaff00000000000000include README.md include LICENSE recursive-include examples *.py *.md global-exclude .DS_Store global-exclude *.pyc watson-developer-cloud-0.22.0/PKG-INFO0000644000076500000240000001200013006647576020316 0ustar jsstylosstaff00000000000000Metadata-Version: 1.1 Name: watson-developer-cloud Version: 0.22.0 Summary: Client library to use the IBM Watson Services Home-page: https://github.com/watson-developer-cloud/python-sdk Author: Jeffrey Stylos Author-email: jsstylos@us.ibm.com License: Apache 2.0 Description: Watson Developer Cloud Python SDK --------------------------------- |Build Status| |codecov.io| |Latest Stable Version| |Download Times| Python client library to quickly get started with the various `Watson Developer Cloud `__ services. Installation ------------ To install, use ``pip`` or ``easy_install``: .. code:: bash $ pip install --upgrade watson-developer-cloud or .. code:: bash $ easy_install --upgrade watson-developer-cloud Examples -------- The `examples `__ folder has basic and advanced examples. Getting the Service Credentials ------------------------------- You will need the ``username`` and ``password`` credentials for each service. Service credentials are different from your Bluemix account username and password. To get your service credentials, follow these steps: 1. Log in to Bluemix at https://bluemix.net. 1. Create an instance of the service: 1. In the Bluemix **Catalog**, select the Watson service you want to use. For example, select the Natural Language Classifier service. 2. Under **Add Service**, type a unique name for the service instance in the Service name field. For example, type ``my-service-name``. Leave the default values for the other options. 3. Click **Use**. 2. Copy your credentials: 1. On the left side of the page, click **Service Credentials** to view your service credentials. 2. Copy ``username`` and ``password`` from these service credentials. Python Version -------------- Tested 👌 (lightly) on: Python from 2.7 to 3.5-dev (development branch). Python 2.6 is partially supported but generates InsecurePlatformWarnings (and other warnings), which can be ignored. CHANGELOG --------- See `CHANGELOG `__. Known Issues ------------ There is a known incompatibility with this module with Python versions 3.x with Korean systems. Dependencies ------------ - `requests `__ - `responses `__ for testing Contributing ------------ See `CONTRIBUTING.md `__. License ------- This library is licensed under the `Apache 2.0 license `__. .. |Build Status| image:: https://travis-ci.org/watson-developer-cloud/python-sdk.svg :target: https://travis-ci.org/watson-developer-cloud/python-sdk .. |codecov.io| image:: https://codecov.io/github/watson-developer-cloud/python-sdk/coverage.svg?branch=master :target: https://codecov.io/github/watson-developer-cloud/python-sdk?branch=master .. |Latest Stable Version| image:: https://img.shields.io/pypi/v/watson-developer-cloud.svg :target: https://pypi.python.org/pypi/watson-developer-cloud .. |Download Times| image:: https://img.shields.io/pypi/dm/watson-developer-cloud.svg :target: https://pypi.python.org/pypi/watson-developer-cloud Keywords: alchemy datanews,language,vision,question and answer tone_analyzer,natural language classifier,retrieve and rank,tradeoff analytics,text to speech,language translation,language identification,concept expansion,machine translation,personality insights,message resonance,watson developer cloud,wdc,watson,ibm,dialog,user modeling,alchemyapi,alchemy,tone analyzer,speech to text,visual recognition Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Software Development :: Libraries :: Application Frameworks watson-developer-cloud-0.22.0/README.md0000644000076500000240000000602612750146665020511 0ustar jsstylosstaff00000000000000## Watson Developer Cloud Python SDK [![Build Status](https://travis-ci.org/watson-developer-cloud/python-sdk.svg)](https://travis-ci.org/watson-developer-cloud/python-sdk) [![codecov.io](https://codecov.io/github/watson-developer-cloud/python-sdk/coverage.svg?branch=master)](https://codecov.io/github/watson-developer-cloud/python-sdk?branch=master) [![Latest Stable Version](https://img.shields.io/pypi/v/watson-developer-cloud.svg)](https://pypi.python.org/pypi/watson-developer-cloud) [![Download Times](https://img.shields.io/pypi/dm/watson-developer-cloud.svg)](https://pypi.python.org/pypi/watson-developer-cloud) Python client library to quickly get started with the various [Watson Developer Cloud][wdc] services. ## Installation To install, use `pip` or `easy_install`: ```bash $ pip install --upgrade watson-developer-cloud ``` or ```bash $ easy_install --upgrade watson-developer-cloud ``` ## Examples The [examples][examples] folder has basic and advanced examples. ## Getting the Service Credentials You will need the `username` and `password` credentials for each service. Service credentials are different from your Bluemix account username and password. To get your service credentials, follow these steps: 1. Log in to Bluemix at https://bluemix.net. 1. Create an instance of the service: 1. In the Bluemix **Catalog**, select the Watson service you want to use. For example, select the Natural Language Classifier service. 1. Under **Add Service**, type a unique name for the service instance in the Service name field. For example, type `my-service-name`. Leave the default values for the other options. 1. Click **Use**. 1. Copy your credentials: 1. On the left side of the page, click **Service Credentials** to view your service credentials. 1. Copy `username` and `password` from these service credentials. ## Python Version Tested 👌 (lightly) on: Python from 2.7 to 3.5-dev (development branch). Python 2.6 is partially supported but generates InsecurePlatformWarnings (and other warnings), which can be ignored. ## CHANGELOG See [CHANGELOG][CHANGELOG.md]. ## Known Issues There is a known incompatibility with this module with Python versions 3.x with Korean systems. ## Dependencies * [requests] * [responses] for testing ## Contributing See [CONTRIBUTING.md][CONTRIBUTING]. ## License This library is licensed under the [Apache 2.0 license][license]. [wdc]: http://www.ibm.com/watson/developercloud/ [vcap_environment]: http://www.ibm.com/watson/developercloud/doc/getting_started/gs-variables.shtml [bluemix]: https://console.ng.bluemix.net [pytest]: http://pytest.org/latest/ [responses]: https://github.com/getsentry/responses [requests]: http://docs.python-requests.org/en/latest/ [examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples [CONTRIBUTING]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md [CHANGELOG.md]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CHANGELOG.md [license]: http://www.apache.org/licenses/LICENSE-2.0 watson-developer-cloud-0.22.0/setup.cfg0000644000076500000240000000007313006647576021051 0ustar jsstylosstaff00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 watson-developer-cloud-0.22.0/setup.py0000644000076500000240000000645413006647511020740 0ustar jsstylosstaff00000000000000#!/usr/bin/env python # Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from setuptools import setup from setuptools.command.test import test as TestCommand import os import sys __version__ = '0.22.0' if sys.argv[-1] == 'publish': # test server os.system('python setup.py register -r pypitest') os.system('python setup.py sdist upload -r pypitest') # production server os.system('python setup.py register -r pypi') os.system('python setup.py sdist upload -r pypi') sys.exit() # Convert README.md to README.rst for pypi try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print('warning: pypandoc module not found, could not convert Markdown to RST') read_md = lambda f: open(f, 'r').read() class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['--strict', '--verbose', '--tb=long', 'test'] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(self.test_args) sys.exit(errcode) setup(name='watson-developer-cloud', version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', install_requires=['requests>=2.0, <3.0', 'pysolr>= 3.3, <4.0'], tests_require=['responses', 'pytest', 'python_dotenv'], cmdclass={'test': PyTest}, author='Jeffrey Stylos', author_email='jsstylos@us.ibm.com', long_description=read_md('README.md'), url='https://github.com/watson-developer-cloud/python-sdk', packages=['watson_developer_cloud'], keywords='alchemy datanews, language, vision, question and answer' + ' tone_analyzer, natural language classifier, retrieve and rank,' + ' tradeoff analytics, text to speech,' + ' language translation, language identification,' + ' concept expansion, machine translation, personality insights,' + ' message resonance, watson developer cloud, wdc, watson, ibm,' + ' dialog, user modeling, alchemyapi, alchemy, tone analyzer,' + 'speech to text, visual recognition', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], zip_safe=True ) watson-developer-cloud-0.22.0/test/0000755000076500000240000000000013006647576020207 5ustar jsstylosstaff00000000000000watson-developer-cloud-0.22.0/test/test_conversation_v1.py0000644000076500000240000000360312777740445024745 0ustar jsstylosstaff00000000000000import responses import watson_developer_cloud @responses.activate def test_message(): # Ranker endpoints conversation = watson_developer_cloud.ConversationV1(username="username", password="password", version='2016-09-20') workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' message_url = 'https://gateway.watsonplatform.net/conversation/api/v1/workspaces/%s/message' % workspace_id message_url1 = 'https://gateway.watsonplatform.net/conversation/api/v1/workspaces/%s/message?version=2016-09-20' % workspace_id message_response = '{"context":{"conversation_id":"1b7b67c0-90ed-45dc-8508-9488bc483d5b","system":{"dialog_stack":["root"],"dialog_turn_counter":1,"dialog_request_counter":1}},"intents":[],"entities":[],"input":{}}' responses.add(responses.POST, message_url, body=message_response, status=200, content_type='application/json') message = conversation.message(workspace_id=workspace_id, message_input={'text': 'Turn on the lights'}, context=None) assert message is not None assert responses.calls[0].request.url == message_url1 assert responses.calls[0].response.text == message_response # test context responses.add(responses.POST, message_url, body=message_response, status=200, content_type='application/json') message = conversation.message(workspace_id=workspace_id, message_input={'text': 'Turn on the lights'}, context={'context': {'conversation_id':'1b7b67c0-90ed-45dc-8508-9488bc483d5b', 'system': {'dialog_stack':['root'], 'dialog_turn_counter':2, 'dialog_request_counter':1}}}) assert message is not None assert responses.calls[1].request.url == message_url1 assert responses.calls[1].response.text == message_response assert len(responses.calls) == 2 watson-developer-cloud-0.22.0/test/test_document_conversion_v1.py0000644000076500000240000000414012737236674026313 0ustar jsstylosstaff00000000000000# coding=utf-8 import os import responses import watson_developer_cloud @responses.activate def test_success(): convert_url = 'https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document' convert_response = '' \ 'Simple HTML Page' \ '

Chapter 1

The content of the first chapter.

' document_conversion = watson_developer_cloud.DocumentConversionV1( username="username", password="password", version='2015-12-15') responses.add(responses.POST, convert_url, body=convert_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/simple.html'), 'r') as document: convertConfig = {'conversion_target': watson_developer_cloud.DocumentConversionV1.NORMALIZED_HTML} document_conversion.convert_document(document=document, config=convertConfig, media_type='text/html') assert responses.calls[0].request.url.startswith(convert_url) assert responses.calls[0].response.text == convert_response index_url = 'https://gateway.watsonplatform.net/document-conversion/api/v1/index_document' index_response = '{"status": "success"}' responses.add(responses.POST, index_url, body=index_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/example.html'), 'r') as document: indexConfig = { 'retrieve_and_rank': { 'dry_run':'false', 'service_instance_id':'serviceInstanceId', 'cluster_id':'clusterId', 'search_collection':'searchCollectionName' } } document_conversion.index_document(config=indexConfig, document=document) assert responses.calls[1].request.url.startswith(index_url) assert responses.calls[1].response.text == index_response assert len(responses.calls) == 2 watson-developer-cloud-0.22.0/test/test_examples.py0000644000076500000240000000206112777751152023435 0ustar jsstylosstaff00000000000000# coding=utf-8 import os import pytest from os.path import join, dirname from glob import glob # tests to exclude excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py'] # examples path. /examples examples_path = join(dirname(__file__), '../', 'examples', '*.py') # environment variables try: from dotenv import load_dotenv except: print('warning: dotenv module could not be imported') try: dotenv_path = join(dirname(__file__), '../', '.env') load_dotenv(dotenv_path) except: print('warning: no .env file loaded') @pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') def test_examples(): examples = glob(examples_path) for example in examples: name = example.split('/')[-1] # exclude some tests cases like authorization if name in excludes: continue try: exec(open(example).read(), globals()) except Exception as e: assert False, 'example in file ' + name + ' failed with error: ' + str(e) watson-developer-cloud-0.22.0/test/test_natural_language_classifier_v1.py0000644000076500000240000000775012605473757027756 0ustar jsstylosstaff00000000000000import os import responses import watson_developer_cloud @responses.activate def test_success(): natural_language_classifier = watson_developer_cloud.NaturalLanguageClassifierV1(username="username", password="password") list_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' list_response = '{"classifiers": [{"url": "https://gateway.watsonplatform.net/natural-language-classifier-' \ 'experimental/api/v1/classifiers/497EF2-nlc-00", "classifier_id": "497EF2-nlc-00"}]}' responses.add(responses.GET, list_url, body=list_response, status=200, content_type='application/json') natural_language_classifier.list() assert responses.calls[0].request.url == list_url assert responses.calls[0].response.text == list_response status_url = ('https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' '497EF2-nlc-00') status_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \ 'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \ 'instance is now available and is ready to take classifier requests.", "classifier_id": ' \ '"497EF2-nlc-00"}' responses.add(responses.GET, status_url, body=status_response, status=200, content_type='application/json') natural_language_classifier.status('497EF2-nlc-00') assert responses.calls[1].request.url == status_url assert responses.calls[1].response.text == status_response classify_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' \ '497EF2-nlc-00/classify' classify_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/' \ 'v1", "text": "test", "classes": [{"class_name": "conditions", "confidence": ' \ '0.6575315710901418}, {"class_name": "temperature", "confidence": 0.3424684289098582}], ' \ '"classifier_id": "497EF2-nlc-00", "top_class": "conditions"}' responses.add(responses.POST, classify_url, body=classify_response, status=200, content_type='application/json') natural_language_classifier.classify('497EF2-nlc-00', 'test') assert responses.calls[2].request.url == classify_url assert responses.calls[2].response.text == classify_response create_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' create_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \ 'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \ 'instance is now available and is ready to take classifier requests.", "classifier_id": ' \ '"497EF2-nlc-00"}' responses.add(responses.POST, create_url, body=create_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/weather_data_train.csv'), 'rb') as training_data: natural_language_classifier.create( training_data=training_data, language='en') assert responses.calls[3].request.url == create_url assert responses.calls[3].response.text == create_response remove_url = status_url remove_response = '{}' responses.add(responses.DELETE, remove_url, body=remove_response, status=200, content_type='application/json') natural_language_classifier.remove('497EF2-nlc-00') assert responses.calls[4].request.url == remove_url assert responses.calls[4].response.text == remove_response assert len(responses.calls) == 5 watson-developer-cloud-0.22.0/test/test_personality_insights_v2.py0000644000076500000240000000245312605473757026516 0ustar jsstylosstaff00000000000000import responses import watson_developer_cloud import os @responses.activate def test_success(): profile_url = 'https://gateway.watsonplatform.net/personality-insights/api/v2/profile' profile_response = '{"tree":{"children":[{"children":[{"category":"personality","percentage":0.9493716242287923,' \ '"children":[{"category":"personality","name":"Openness","sampling_error":0.14430105599999998,' \ '"id":"Openness","percentage":0.9493716242287923,"children":[{"category":"personality",' \ '"percentage":0.7224550516937974,"id":"Adventurousness","sampling_error":0.11646272,"name":' \ '"Adventurousness"}]}]}]}]}}' responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/personality.txt')) as personality_text: personality_insights = watson_developer_cloud.PersonalityInsightsV2( username="username", password="password") personality_insights.profile(personality_text) assert responses.calls[0].request.url == profile_url assert responses.calls[0].response.text == profile_response assert len(responses.calls) == 1 watson-developer-cloud-0.22.0/test/test_personality_insights_v3.py0000755000076500000240000001124413003413561026474 0ustar jsstylosstaff00000000000000import responses import watson_developer_cloud import os import json profile_url = 'https://gateway.watsonplatform.net/personality-insights/api/v3/profile' """ Input: Plain text (English) Output: JSON, no raw scores or preferences (English) """ @responses.activate def test_plain_to_json(): personality_insights = watson_developer_cloud.PersonalityInsightsV3( '2016-10-20', username="username", password="password") with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3-expect1.txt')) as expect_file: profile_response = json.dumps(expect_file.read()) responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3.txt')) as personality_text: personality_insights.profile( personality_text, content_type='text/plain;charset=utf-8') assert 'version=2016-10-20' in responses.calls[0].request.url assert responses.calls[0].response.text == profile_response assert len(responses.calls) == 1 """ Input: JSON (English) Output: JSON with raw scores and preferences (English) """ @responses.activate def test_json_to_json(): personality_insights = watson_developer_cloud.PersonalityInsightsV3( '2016-10-20', username="username", password="password") with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3-expect2.txt')) as expect_file: profile_response = json.dumps(expect_file.read()) responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3.json')) as personality_text: personality_insights.profile( personality_text, content_type='application/json', raw_scores=True, consumption_preferences=True) assert 'version=2016-10-20' in responses.calls[0].request.url assert 'raw_scores=true' in responses.calls[0].request.url assert 'consumption_preferences=true' in responses.calls[0].request.url assert responses.calls[0].response.text == profile_response assert len(responses.calls) == 1 """ Input: JSON (English) Output: CSV with raw scores, preferences, and headers (English) """ @responses.activate def test_json_to_csv(): personality_insights = watson_developer_cloud.PersonalityInsightsV3( '2016-10-20', username="username", password="password") with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3-expect3.txt')) as expect_file: profile_response = json.dumps(expect_file.read()) responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='text/csv') with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3.json')) as personality_text: personality_insights.profile( personality_text, content_type='application/json', accept='text/csv', csv_headers=True, raw_scores=True, consumption_preferences=True) assert 'version=2016-10-20' in responses.calls[0].request.url assert 'raw_scores=true' in responses.calls[0].request.url assert 'consumption_preferences=true' in responses.calls[0].request.url assert 'csv_headers=true' in responses.calls[0].request.url assert responses.calls[0].response.text == profile_response assert len(responses.calls) == 1 """ Input: Plain text (Spanish) Output: JSON, no raw scores or preferences (Spanish) """ @responses.activate def test_plain_to_json_es(): personality_insights = watson_developer_cloud.PersonalityInsightsV3( '2016-10-20', username="username", password="password") with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3-expect4.txt')) as expect_file: profile_response = json.dumps(expect_file.read()) responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/personality-v3-es.txt')) as personality_text: personality_insights.profile( personality_text, content_type='text/plain;charset=utf-8', content_language='es', accept_language='es') assert 'version=2016-10-20' in responses.calls[0].request.url assert responses.calls[0].response.text == profile_response assert len(responses.calls) == 1 watson-developer-cloud-0.22.0/test/test_retrieve_and_rank_v1.py0000644000076500000240000002572412750146665025720 0ustar jsstylosstaff00000000000000import os import responses import watson_developer_cloud CLUSTER_ID = 'sc0747112c_f978_4e1f_b97e_0e3a8101ac5b' URL_CLUSTERS = 'https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters' URL_CLUSTER = URL_CLUSTERS + '/' + CLUSTER_ID RANKER_ID = '3b140ax14-rank-10383' URL_RANKERS = 'https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers' URL_RANKER = URL_RANKERS + '/' + RANKER_ID retrieve_and_rank = watson_developer_cloud.RetrieveAndRankV1(username="username", password="password") @responses.activate def test_list_rankers(): listrank_response = '{"rankers":[{"ranker_id":"3b140ax14-rank-10383","name":"pythonRank"}]}' responses.add(responses.GET, URL_RANKERS, match_querystring=True, body=listrank_response, status=200, content_type='application/json') ranker_list = retrieve_and_rank.list_rankers() assert ranker_list is not None assert len(ranker_list['rankers']) == 1 assert responses.calls[0].request.url == URL_RANKERS assert responses.calls[0].response.text == listrank_response @responses.activate def test_ranker_status(): statusrank_response = '{"ranker_id":"3b140ax14-rank-10383","name":"pythonRank","status":"Available"}' responses.add(responses.GET, URL_RANKER, match_querystring=True, body=statusrank_response, status=200, content_type='application/json') ranker_status = retrieve_and_rank.get_ranker_status(RANKER_ID) assert ranker_status is not None assert ranker_status['status'] is not None assert responses.calls[0].request.url == URL_RANKER assert responses.calls[0].response.text == statusrank_response @responses.activate def test_rank(): rank_url = URL_RANKER + '/rank' rank_response = '{"ranker_id":"3b140ax14-rank-10383",' \ '"top_answer":"30965a00-5415-4ef5-8e4a-bb21a7aeab44", "answers":[' \ '{"answer_id":"30965a00-5415-4ef5-8e4a-bb21a7aeab44","score":180.0,"confidence":0.2636349925008873},' \ '{"answer_id":"30965a00-5415-4ef5-8e4a-bb21a7aeab44","score":178.0,"confidence":0.25972667610243827}]}' responses.add(responses.POST, rank_url, match_querystring=True, body=rank_response, status=200, content_type='application/json') ranker_answer = None with open(os.path.join(os.path.dirname(__file__), '../resources/ranker_answer_data.csv'), 'rb') as answer_data: ranker_answer = retrieve_and_rank.rank('3b140ax14-rank-10383', answer_data=answer_data, top_answers=3) assert ranker_answer is not None assert responses.calls[0].request.url == rank_url assert responses.calls[0].response.text == rank_response @responses.activate def test_create_ranker(): createrank_response = '{"ranker_id":"3b140ax14-rank-10383","name":"pythonRank","status":"Training"}' responses.add(responses.POST, URL_RANKERS, match_querystring=True, body=createrank_response, status=200, content_type='application/json') ranker = None with open(os.path.join(os.path.dirname(__file__), '../resources/ranker_training_data.csv'), 'rb') as training_data: ranker = retrieve_and_rank.create_ranker(training_data=training_data, name='pythonRank') assert ranker is not None assert ranker['ranker_id'] == RANKER_ID assert ranker['name'] == 'pythonRank' assert responses.calls[0].request.url == URL_RANKERS assert responses.calls[0].response.text == createrank_response @responses.activate def test_delete_ranker(): removerank_response = '{}' responses.add(responses.DELETE, URL_RANKER, match_querystring=True, body=removerank_response, status=200, content_type='application/json') retrieve_and_rank.delete_ranker(RANKER_ID) assert responses.calls[0].request.url == URL_RANKER assert responses.calls[0].response.text == removerank_response @responses.activate def test_list_cluster(): listcluster_response = '{"clusters":[{"solr_cluster_id":"sc0747112c_f978_4e1f_b97e_0e3a8101ac5b","cluster_name":"","cluster_size":"","solr_cluster_status":"READY"}]}' responses.add(responses.GET, URL_CLUSTERS, match_querystring=True, body=listcluster_response, status=200, content_type='application/json') clusters = retrieve_and_rank.list_solr_clusters() assert clusters is not None assert responses.calls[0].request.url == URL_CLUSTERS assert responses.calls[0].response.text == listcluster_response @responses.activate def test_create_cluster(): createcluster_response = '{"solr_cluster_id":"sc0747112c_f978_4e1f_b97e_0e3a8101ac5b","cluster_name":"","cluster_size":"","solr_cluster_status":"NOT_AVAILABLE"}' responses.add(responses.POST, URL_CLUSTERS, match_querystring=True, body=createcluster_response, status=200, content_type='application/json') retrieve_and_rank.create_solr_cluster(cluster_name='pythonCluster', cluster_size=None) assert responses.calls[0].request.url == URL_CLUSTERS assert responses.calls[0].response.text == createcluster_response @responses.activate def test_delete_cluster(): removecluster_response = '{"message":"WRRCSR023: Successfully deleted Solr cluster [sc0747112c_f978_4e1f_b97e_0e3a8101ac5b].","statusCode":200}' responses.add(responses.DELETE, URL_CLUSTER, body=removecluster_response, status=200, match_querystring=True, content_type='application/json') retrieve_and_rank.delete_solr_cluster(CLUSTER_ID) assert responses.calls[0].request.url == URL_CLUSTER assert responses.calls[0].response.text == removecluster_response @responses.activate def test_cluster_status(): statuscluster_response = '{"solr_cluster_id":"sc0747112c_f978_4e1f_b97e_0e3a8101ac5b","cluster_name":"","cluster_size":"","solr_cluster_status":"READY"}' responses.add(responses.GET, URL_CLUSTER, body=statuscluster_response, status=200, match_querystring=True, content_type='application/json') cluster_status = retrieve_and_rank.get_solr_cluster_status(CLUSTER_ID) assert cluster_status is not None assert responses.calls[0].request.url == URL_CLUSTER assert responses.calls[0].response.text == statuscluster_response @responses.activate def test_list_config(): listconfigs_url = URL_CLUSTER + '/config' listconfigs_response = '{"solr_configs":[]}' responses.add(responses.GET, listconfigs_url, body=listconfigs_response, status=200, match_querystring=True, content_type='application/json') config_list = retrieve_and_rank.list_configs(CLUSTER_ID) assert config_list is not None assert responses.calls[0].request.url == listconfigs_url assert responses.calls[0].response.text == listconfigs_response @responses.activate def test_create_config(): createconfig_url = URL_CLUSTER + '/config/exampleconfig' createconfig_response = '{"message":"WRRCSR026: Successfully uploaded named config [example-config] for Solr cluster [sc0747112c_f978_4e1f_b97e_0e3a8101ac5b].","statusCode":200}' responses.add(responses.POST, createconfig_url, body=createconfig_response, status=200, match_querystring=True, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/solr_config.zip'), 'rb') as config_data: config = retrieve_and_rank.create_config(CLUSTER_ID, 'exampleconfig', config=config_data) assert config is not None assert responses.calls[00].request.url == createconfig_url assert responses.calls[00].response.text == createconfig_response @responses.activate def test_delete_config(): removeconfig_url = URL_CLUSTER + '/config/exampleconfig' removeconfig_response = '{"message":"WRRCSR025: Successfully deleted named config [example-config] for Solr cluster [sc0747112c_f978_4e1f_b97e_0e3a8101ac5b]].","statusCode":200}' responses.add(responses.DELETE, removeconfig_url, body=removeconfig_response, status=200, match_querystring=True, content_type='application/json') response = retrieve_and_rank.delete_config(CLUSTER_ID, 'exampleconfig') assert response is not None assert responses.calls[0].request.url == removeconfig_url assert responses.calls[0].response.text == removeconfig_response @responses.activate def test_get_config(): getconfig_url = URL_CLUSTER + '/config/exampleconfig' getconfig_response = '{}' responses.add(responses.GET, getconfig_url, match_querystring=True, body=getconfig_response, status=200) retrieve_and_rank.get_config(CLUSTER_ID, 'exampleconfig') assert responses.calls[0].request.url == getconfig_url assert responses.calls[0].response.text == getconfig_response @responses.activate def test_list_collections(): listcollection_url = URL_CLUSTER + '/solr/admin/collections?action=LIST&wt=json' listcollection_response = '{"responseHeader":{"status":0,"QTime":0},"collections":["examplecollection"]}' responses.add(responses.GET, listcollection_url, match_querystring=True, body=listcollection_response, status=200, content_type='application/json') retrieve_and_rank.list_collections(CLUSTER_ID) assert responses.calls[0].response.text == listcollection_response @responses.activate def test_create_collection(): createcollection_url = URL_CLUSTER + '/solr/admin/collections?action=CREATE&wt=json&collection.configName=exampleconfig&name=examplecollection' createcollection_response = '{}' responses.add(responses.POST, createcollection_url, match_querystring=True, body=createcollection_response, status=200, content_type='application/json') collection = retrieve_and_rank.create_collection(CLUSTER_ID, 'examplecollection', 'exampleconfig') assert collection is not None assert responses.calls[0].response.text == createcollection_response @responses.activate def test_delete_collection(): deletecollection_url = URL_CLUSTER + '/solr/admin/collections?action=DELETE&wt=json&name=examplecollection' deletecollection_response = '{}' responses.add(responses.POST, deletecollection_url, body=deletecollection_response, status=200, match_querystring=True, content_type='application/json') retrieve_and_rank.delete_collection(CLUSTER_ID, 'examplecollection', None) assert responses.calls[0].response.text == deletecollection_response @responses.activate def test_get_solr_client(): solr_client = retrieve_and_rank.get_pysolr_client(CLUSTER_ID, 'examplecollection') assert solr_client is not None watson-developer-cloud-0.22.0/test/test_speech_to_text_v1.py0000755000076500000240000000334613004675571025246 0ustar jsstylosstaff00000000000000# coding=utf-8 import os import responses import watson_developer_cloud @responses.activate def test_success(): models_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models' models_response = '{"models": [{"url": "https://stream.watsonplatform.net/speech-to-text/api/v1/models/' \ 'WatsonModel", "rate": 16000, "name": "WatsonModel", "language": "en-US", "description": ' \ '"Watson model \'v7w_134k.3\' for Attila 2-5 reco engine."}]}' responses.add(responses.GET, models_url, body=models_response, status=200, content_type='application/json') speech_to_text = watson_developer_cloud.SpeechToTextV1( username="username", password="password") speech_to_text.models() assert responses.calls[0].request.url == models_url assert responses.calls[0].response.text == models_response recognize_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize' recognize_response = '{"results":[{"alternatives":[{"transcript":"thunderstorms could produce large hail ' \ 'isolated tornadoes and heavy rain "}],"final":true}],"result_index":0}' responses.add(responses.POST, recognize_url, body=recognize_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/speech.wav'), 'rb') as audio_file: speech_to_text.recognize( audio_file, content_type='audio/l16; rate=44100') assert responses.calls[ 1].request.url == recognize_url + '?continuous=false' assert responses.calls[1].response.text == recognize_response assert len(responses.calls) == 2 watson-developer-cloud-0.22.0/test/test_text_to_speech_v1.py0000644000076500000240000000373512711512541025234 0ustar jsstylosstaff00000000000000# coding=utf-8 import responses import watson_developer_cloud @responses.activate def test_success(): voices_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices' voices_response = '{"voices": [{"url": "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/' \ 'VoiceEnUsLisa", "gender": "female", "name": "VoiceEnUsLisa", "language": "en-US"}, {"url": ' \ '"https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEsEsEnrique", ' \ '"gender": "male", "name": "VoiceEsEsEnrique", "language": "es-ES"}, {"url": ' \ '"https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsMichael", ' \ '"gender": "male", "name": "VoiceEnUsMichael", "language": "en-US"}, {"url": ' \ '"https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsAllison", ' \ '"gender": "female", "name": "VoiceEnUsAllison", "language": "en-US"}]}' responses.add(responses.GET, voices_url, body=voices_response, status=200, content_type='application/json') text_to_speech = watson_developer_cloud.TextToSpeechV1( username="username", password="password") text_to_speech.voices() assert responses.calls[0].request.url == voices_url assert responses.calls[0].response.text == voices_response synthesize_text = 'hello' synthesize_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize' synthesize_response_body = '' responses.add(responses.POST, synthesize_url, body=synthesize_response_body, status=200, content_type='application/json', match_querystring=True) text_to_speech.synthesize(synthesize_text) assert responses.calls[1].request.url == synthesize_url assert responses.calls[1].response.text == synthesize_response_body assert len(responses.calls) == 2 watson-developer-cloud-0.22.0/test/test_tone_analyzer_v3.py0000644000076500000240000000451612734554371025105 0ustar jsstylosstaff00000000000000import responses import watson_developer_cloud import os @responses.activate ## Simple test, just calling tone() with some text def test_success(): tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' tone_args = '?version=2016-05-19' tone_response = None with open(os.path.join(os.path.dirname(__file__), '../resources/tone_response.json')) as response_json: tone_response = response_json.read() responses.add(responses.POST, tone_url, body=tone_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/personality.txt')) as tone_text: tone_analyzer = watson_developer_cloud.ToneAnalyzerV3("2016-05-19", username="username", password="password") tone_analyzer.tone(tone_text.read()) assert responses.calls[0].request.url == tone_url + tone_args assert responses.calls[0].response.text == tone_response assert len(responses.calls) == 1 @responses.activate ## Invoking tone() with some modifiers given in 'params': specific tones requested, and sentences skipped def test_with_args(): tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' tone_args = { 'version': '2016-05-19', 'tones': 'social', 'sentences': 'false' } tone_response = None with open(os.path.join(os.path.dirname(__file__), '../resources/tone_response.json')) as response_json: tone_response = response_json.read() responses.add(responses.POST, tone_url, body=tone_response, status=200, content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../resources/personality.txt')) as tone_text: tone_analyzer = watson_developer_cloud.ToneAnalyzerV3("2016-05-19", username="username", password="password") tone_analyzer.tone(tone_text.read(), tones="social", sentences=False) assert responses.calls[0].request.url.split('?')[0] == tone_url # Compare args. Order is not deterministic! actualArgs = {} for arg in responses.calls[0].request.url.split('?')[1].split('&'): actualArgs[arg.split('=')[0]] = arg.split('=')[1] assert actualArgs == tone_args assert responses.calls[0].response.text == tone_response assert len(responses.calls) == 1 watson-developer-cloud-0.22.0/test/test_tradeoff_analytics_v1.py0000755000076500000240000000344613006647105026065 0ustar jsstylosstaff00000000000000# coding=utf-8 import json import os import responses import watson_developer_cloud dilemmas_url = 'https://gateway.watsonplatform.net/tradeoff-analytics/api/v1/dilemmas' @responses.activate def test_visualization(): with open(os.path.join(os.path.dirname(__file__), '../resources/tradeoff-expect1.txt')) as expect_file: dilemmas_response = expect_file.read() responses.add(responses.POST, dilemmas_url, body=dilemmas_response, status=200, content_type='application/json') tradeoff_analytics = watson_developer_cloud.TradeoffAnalyticsV1( username="username", password="password") with open(os.path.join(os.path.dirname(__file__), '../resources/problem.json')) as data_file: tradeoff_analytics.dilemmas(json.load(data_file)) assert 'generate_visualization=true' in responses.calls[0].request.url assert responses.calls[0].response.text == dilemmas_response assert len(responses.calls) == 1 @responses.activate def test_no_visualization(): with open(os.path.join(os.path.dirname(__file__), '../resources/tradeoff-expect2.txt')) as expect_file: dilemmas_response = expect_file.read() responses.add(responses.POST, dilemmas_url, body=dilemmas_response, status=200, content_type='application/json') tradeoff_analytics = watson_developer_cloud.TradeoffAnalyticsV1( username="username", password="password") with open(os.path.join(os.path.dirname(__file__), '../resources/problem.json')) as data_file: tradeoff_analytics.dilemmas(json.load(data_file), generate_visualization=False) assert 'generate_visualization=false' in responses.calls[0].request.url assert responses.calls[0].response.text == dilemmas_response assert len(responses.calls) == 1 watson-developer-cloud-0.22.0/watson_developer_cloud/0000755000076500000240000000000013006647576023776 5ustar jsstylosstaff00000000000000watson-developer-cloud-0.22.0/watson_developer_cloud/__init__.py0000755000076500000240000000337713003413561026102 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .watson_developer_cloud_service import WatsonDeveloperCloudService from .watson_developer_cloud_service import WatsonException from .watson_developer_cloud_service import WatsonInvalidArgument from .alchemy_data_news_v1 import AlchemyDataNewsV1 from .alchemy_language_v1 import AlchemyLanguageV1 from .alchemy_vision_v1 import AlchemyVisionV1 from .authorization_v1 import AuthorizationV1 from .conversation_v1 import ConversationV1 from .document_conversion_v1 import DocumentConversionV1 from .dialog_v1 import DialogV1 from .language_translation_v2 import LanguageTranslationV2 from .language_translator_v2 import LanguageTranslatorV2 from .natural_language_classifier_v1 import NaturalLanguageClassifierV1 from .personality_insights_v2 import PersonalityInsightsV2 from .personality_insights_v3 import PersonalityInsightsV3 from .retrieve_and_rank_v1 import RetrieveAndRankV1 from .speech_to_text_v1 import SpeechToTextV1 from .text_to_speech_v1 import TextToSpeechV1 from .tone_analyzer_v3 import ToneAnalyzerV3 from .tradeoff_analytics_v1 import TradeoffAnalyticsV1 from .visual_recognition_v3 import VisualRecognitionV3 from .version import __version__ watson-developer-cloud-0.22.0/watson_developer_cloud/alchemy_data_news_v1.py0000644000076500000240000000362312737221464030423 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The AlchemyData News service (https://www.ibm.com/watson/developercloud/alchemy-data-news.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService class AlchemyDataNewsV1(WatsonDeveloperCloudService): default_url = 'https://gateway-a.watsonplatform.net/calls' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'alchemy_api', url, **kwargs) def get_news_documents(self, start, end, max_results=10, query_fields=None, return_fields=None, time_slice=None, next_page=None, dedup=None, dedup_threshold=None, rank=None): if isinstance(return_fields, list): return_fields = ','.join(return_fields) params = {'start': start, 'end': end, 'maxResults': max_results, 'return': return_fields, 'timeSlice': time_slice, 'next': next_page, 'dedup': dedup, 'dedupThreshold': dedup_threshold, 'rank': rank} if isinstance(query_fields, dict): for key in query_fields: params[key if key.startswith('q.') else 'q.' + key] = query_fields[key] return self._alchemy_html_request(method_url='/data/GetNews', method='GET', params=params) watson-developer-cloud-0.22.0/watson_developer_cloud/alchemy_language_v1.py0000644000076500000240000003224713003736506030240 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The AlchemyAPI Language service (https://www.ibm.com/watson/developercloud/alchemy-language.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService class AlchemyLanguageV1(WatsonDeveloperCloudService): default_url = 'https://gateway-a.watsonplatform.net/calls' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'alchemy_api', url, **kwargs) def author(self, html=None, url=None, language=None): params = {'language': language} return self._alchemy_html_request('GetAuthor', html=html, url=url, params=params) def authors(self, html=None, url=None, language=None): params = {'language': language} return self._alchemy_html_request('GetAuthors', html=html, url=url, params=params) def keywords(self, html=None, text=None, url=None, strict_extract_mode=False, sentiment=False, emotion=False, show_source_text=False, max_items=None, language=None, max_keywords=50): """ :param html: HTML input :param text: Text input :param url: URL input :param max_items: The number of results to return (default 50) :param max_keywords: deprecated, use max_items instead :return: A JSON object with extracted keywords from the source document """ if not max_items: max_items = max_keywords params = {'keywordExtractMode': 'strict' if strict_extract_mode else 'normal', 'sentiment': sentiment, 'emotion': emotion, 'showSourceText': show_source_text, 'maxRetrieve': max_items, 'language': language} return self._alchemy_html_request('GetRankedKeywords', html=html, text=text, url=url, params=params) def concepts(self, html=None, text=None, url=None, max_items=8, linked_data=True, show_source_text=False, language=None): params = {'maxRetrieve': max_items, 'linkedData': linked_data, 'showSourceText': show_source_text, 'language': language} return self._alchemy_html_request('GetRankedConcepts', html=html, text=text, url=url, params=params) def dates(self, html=None, text=None, url=None, anchor_date=None, show_source_text=False, language=None): params = {'anchorDate': anchor_date, 'showSourceText': show_source_text, 'language': language} return self._alchemy_html_request('ExtractDates', html=html, text=text, url=url, params=params) def entities(self, html=None, text=None, url=None, disambiguate=True, linked_data=True, coreference=True, quotations=False, sentiment=False, emotion=False, show_source_text=False, max_items=50, language=None, model=None): params = {'disambiguate': disambiguate, 'linkedData': linked_data, 'coreference': coreference, 'quotations': quotations, 'sentiment': sentiment, 'emotion': emotion, 'showSourceText': show_source_text, 'maxRetrieve': max_items, 'language': language, 'model': model} return self._alchemy_html_request('GetRankedNamedEntities', html=html, text=text, url=url, params=params) def emotion(self, html=None, text=None, url=None, show_source_text=False, source_text_type=None, constraint_query=None, xpath_query=None, language=None): params = {'showSourceText': show_source_text, 'sourceText': source_text_type, 'cquery': constraint_query, 'xpath': xpath_query, 'language': language} return self._alchemy_html_request('GetEmotion', html=html, text=text, url=url, params=params) def targeted_emotion(self, targets, html=None, text=None, url=None, language=None, constraint_query=None, xpath_query=None, show_source_text=False, source_text_type=None): if isinstance(targets, list): targets = '|'.join(targets) params = {'targets': targets, 'language': language, 'cquery': constraint_query, 'xpath': xpath_query, 'showSourceText': show_source_text, 'sourceText': source_text_type} return self._alchemy_html_request('GetTargetedEmotion', html=html, text=text, url=url, params=params) def typed_relations(self, html=None, text=None, url=None, model=None, show_source_text=False): params = {'model': model, 'showSourceText': show_source_text} return self._alchemy_html_request('GetTypedRelations', html=html, text=text, url=url, params=params) def relations(self, html=None, text=None, url=None, sentiment=False, keywords=False, entities=False, require_entities=False, sentiment_excludes_entities=True, disambiguate=True, linked_data=True, coreference=True, show_source_text=False, max_items=50, language=None): params = {'sentiment': sentiment, 'keywords': keywords, 'entities': entities, 'requireEntities': require_entities, 'sentimentExcludesEntities': sentiment_excludes_entities, 'disambiguate': disambiguate, 'linkedData': linked_data, 'coreference': coreference, 'showSourceText': show_source_text, 'maxRetrieve': max_items, 'language': language} return self._alchemy_html_request('GetRelations', html=html, text=text, url=url, params=params) def language(self, html=None, text=None, url=None): return self._alchemy_html_request('GetLanguage', html=html, text=text, url=url) def text(self, html=None, url=None, use_metadata=True, extract_links=False): params = {'useMetadata': use_metadata, 'extractLinks': extract_links} return self._alchemy_html_request('GetText', html=html, url=url, params=params) def raw_text(self, html=None, url=None): return self._alchemy_html_request('GetRawText', html=html, url=url) def category(self, html=None, text=None, url=None, show_source_text=False, language=None): params = {'showSourceText': show_source_text, 'language': language} return self._alchemy_html_request('GetCategory', html=html, text=text, url=url, params=params) def title(self, html=None, url=None, use_metadata=True, language=None): params = {'useMetadata': use_metadata, 'language': language} return self._alchemy_html_request('GetTitle', html=html, url=url, params=params) def feeds(self, html=None, url=None): return self._alchemy_html_request('GetFeedLinks', html=html, url=url) def microformats(self, html=None, url=None): return self._alchemy_html_request('GetMicroformatData', html=html, url=url) def publication_date(self, html=None, url=None): return self._alchemy_html_request('GetPubDate', html=html, url=url) def taxonomy(self, html=None, text=None, url=None, show_source_text=False, source_text_type=None, constraint_query=None, xpath_query=None, base_url=None, language=None): """ source_text_type -> 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. 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 Note: The 'constraint_query' argument must also be set to a valid visual constraints query. xpath : operate on the results of an XPath query Note: The 'xpath' http argument must also be set to a valid XPath query. constraint_query -> a visual constraints query to apply to the web page. xpath -> an XPath query to apply to the web page. base_url -> rel-tag output base http url (must be uri-argument encoded) """ params = {'showSourceText': show_source_text, 'sourceText': source_text_type, 'cquery': constraint_query, 'xpath': xpath_query, 'baseUrl': base_url, 'language': language} return self._alchemy_html_request('GetRankedTaxonomy', html=html, text=text, url=url, params=params) # Some of these options don't appear in the API documentation but are supported by the previous AlchemyAPI SDK def combined(self, html=None, text=None, url=None, extract=None, disambiguate=True, linked_data=True, coreference=True, quotations=False, sentiment=False, show_source_text=False, max_items=50, base_url=None, language=None): """ Combined call for page-image, entity, keyword, title, author, taxonomy, concept, doc-emotion. INPUT: extract -> List or comma separated string Possible values: page-image, entity, keyword, title, author, taxonomy, concept default : entity, keyword, taxonomy, concept disambiguate -> disambiguate detected entities Possible values: True : enabled (default) False : disabled linked_data -> include Linked Data content links with disambiguated entities Possible values : True : enabled (default) False : disabled coreference -> resolve he/she/etc coreferences into detected entities Possible values: True : enabled (default) False : disabled quotations -> enable quotations extraction Possible values: True : enabled False : disabled (default) sentiment -> enable entity-level sentiment analysis Possible values: True : enabled False : disabled (default) show_source_text -> include the original 'source text' the entities were extracted from within the API response Possible values: True : enabled False : disabled (default) max_items -> maximum number of named entities to extract default : 50 base_url -> rel-tag output base http url OUTPUT: The response, already converted from JSON to a Python object. """ if isinstance(extract, list): extract = ','.join(extract) params = {'extract': extract, 'disambiguate': disambiguate, 'linkedData': linked_data, 'coreference': coreference, 'quotations': quotations, 'sentiment': sentiment, 'showSourceText': show_source_text, 'maxRetrieve': max_items, 'baseUrl': base_url, 'language': language} return self._alchemy_html_request('GetCombinedData', html=html, text=text, url=url, params=params) def sentiment(self, html=None, text=None, url=None, language=None): params = {'language': language} return self._alchemy_html_request('GetTextSentiment', html=html, text=text, url=url, params=params) def targeted_sentiment(self, targets, html=None, text=None, url=None, language=None, constraint_query=None, xpath_query=None, show_source_text=False, source_text_type=None): if isinstance(targets, list): targets = '|'.join(targets) params = {'targets': targets, 'language': language, 'cquery': constraint_query, 'xpath': xpath_query, 'showSourceText': show_source_text, 'sourceText': source_text_type} return self._alchemy_html_request('GetTargetedSentiment', html=html, text=text, url=url, params=params) watson-developer-cloud-0.22.0/watson_developer_cloud/alchemy_vision_v1.py0000644000076500000240000000426612777740445030002 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The AlchemyAPI Vision service (https://www.ibm.com/watson/developercloud/visual-recognition.html) """ from __future__ import print_function from .watson_developer_cloud_service import WatsonDeveloperCloudService class AlchemyVisionV1(WatsonDeveloperCloudService): """AlchemyVision was deprecated, migrate your application to use VisualRecognition.""" default_url = 'https://gateway-a.watsonplatform.net/calls' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'alchemy_api', url, **kwargs) print('WARNING: The AlchemyVision service was deprecated, use VisualRecognitionV3 instead') def get_image_keywords(self, image_file=None, image_url=None, knowledge_graph=False, force_show_all=False): method_name = 'GetRankedImageKeywords' params = {'knowledgeGraph': knowledge_graph, 'forceShowAll': force_show_all} return self._alchemy_image_request(method_name, image_file, image_url, params) def recognize_faces(self, image_file=None, image_url=None, knowledge_graph=False): method_name = 'GetRankedImageFaceTags' params = {'knowledgeGraph': knowledge_graph} return self._alchemy_image_request(method_name, image_file, image_url, params) def get_image_scene_text(self, image_file=None, image_url=None): method_name = 'GetRankedImageSceneText' return self._alchemy_image_request(method_name, image_file, image_url) def get_image_links(self, url=None, html=None): method_name = 'GetImage' return self._alchemy_html_request(method_name, url=url, html=html) watson-developer-cloud-0.22.0/watson_developer_cloud/authorization_v1.py0000644000076500000240000000364512737221525027656 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Authorization "service" that enables developers to retrieve a temporary access token """ from watson_developer_cloud.watson_developer_cloud_service import WatsonDeveloperCloudService try: import urllib.parse as urlparse # Python 3 except ImportError: import urlparse # Python 2 class AuthorizationV1(WatsonDeveloperCloudService): """ Generates tokens, which can be used client-side to avoid exposing the service credentials. Tokens are valid for 1 hour and are sent using the `X-Watson-Authorization-Token` header. """ default_url = "https://stream.watsonplatform.net/authorization/api" def __init__(self, url=default_url, username=None, password=None, use_vcap_services=True): WatsonDeveloperCloudService.__init__( self, 'authorization', url, username, password, use_vcap_services) def get_token(self, url): """ Retrieves a temporary access token """ # A hack to avoid url-encoding the url, since the authorization service # doesn't work with correctly encoded urls parsed_url = urlparse.urlsplit(url) parsed_url = parsed_url._replace(path='/authorization/api') self.url = urlparse.urlunsplit(parsed_url) response = self.request(method='GET', url='/v1/token?url=' + url) return response.text watson-developer-cloud-0.22.0/watson_developer_cloud/conversation_v1.py0000644000076500000240000000425712777740445027503 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The Conversation v1 service (https://www.ibm.com/watson/developercloud/conversation.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService class ConversationV1(WatsonDeveloperCloudService): """Client for the Conversation service""" default_url = 'https://gateway.watsonplatform.net/conversation/api' latest_version = '2016-09-20' def __init__(self, version, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'conversation', url, **kwargs) self.version = version def message(self, workspace_id, message_input=None, context=None, entities=None, intents=None, output=None, alternate_intents=False): """ Retrieves information about a specific classifier. :param workspace_id: The workspace to use :param message_input: The input, usually containing a text field :param context: The optional context object :param entities: The optional entities :param intents: The optional intents :param alternate_intents: Whether to return more than one intent. :param output: The optional output object """ params = {'version': self.version} data = {'input': message_input, 'context': context, 'entities': entities, 'intents': intents, 'alternate_intents': alternate_intents, 'output': output} return self.request(method='POST', url='/v1/workspaces/{0}/message'.format(workspace_id), params=params, json=data, accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/dialog_v1.py0000644000076500000240000001143513003736306026204 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Dialog service (https://www.ibm.com/watson/developercloud/dialog.html) """ from __future__ import print_function from .watson_developer_cloud_service import WatsonDeveloperCloudService class DialogV1(WatsonDeveloperCloudService): default_url = 'https://gateway.watsonplatform.net/dialog/api' dialog_json_format = 'application/wds+json' dialog_xml_format = 'application/wds+xml' dialog_binary_format = 'application/octet-stream' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'dialog', url, **kwargs) print('WARNING: The Dialog service was deprecated, existing instances of the service will continue to function' 'until August 9, 2017. See https://www.ibm.com/watson/developercloud/doc/conversation/migration.shtml') def get_dialogs(self): return self.request(method='GET', url='/v1/dialogs', accept_json=True) def get_dialog(self, dialog_id, accept='application/wds+json'): accept_json = accept == self.dialog_json_format headers = {'accept': accept} return self.request(method='GET', url='/v1/dialogs/{0}'.format(dialog_id), headers=headers, accept_json=accept_json) def create_dialog(self, dialog_file, name): return self.request(method='POST', url='/v1/dialogs', files={'file': dialog_file}, accept_json=True, data={'name': name}) def update_dialog(self, dialog_id, dialog_file): dialog_id = self.unpack_id(dialog_id, 'dialog_id') return self.request(method='PUT', url='/v1/dialogs/{0}'.format(dialog_id), files={'file': dialog_file}, accept_json=True) def get_content(self, dialog_id): dialog_id = self.unpack_id(dialog_id, 'dialog_id') return self.request(method='GET', url='/v1/dialogs/{0}/content'.format(dialog_id), accept_json=True) def update_content(self, dialog_id, content): dialog_id = self.unpack_id(dialog_id, 'dialog_id') return self.request(method='PUT', url='/v1/dialogs/{0}/content'.format(dialog_id), json=content, accept_json=True) def conversation(self, dialog_id, dialog_input=None, client_id=None, conversation_id=None): dialog_id = self.unpack_id(dialog_id, 'dialog_id') data = {'input': dialog_input, 'client_id': client_id, 'conversation_id': conversation_id} return self.request(method='POST', url='/v1/dialogs/{0}/conversation'.format(dialog_id), data=data, accept_json=True) @staticmethod def _format_date(date): if date: return date.strftime('%Y-%m-%d %H:%M:%S') def get_conversation(self, dialog_id, date_from, date_to): dialog_id = self.unpack_id(dialog_id, 'dialog_id') params = {'date_from': self._format_date( date_from), 'date_to': self._format_date(date_to)} return self.request(method='GET', url='/v1/dialogs/{0}/conversation'.format(dialog_id), params=params, accept_json=True) def get_profile(self, dialog_id, client_id, name=None): dialog_id = self.unpack_id(dialog_id, 'dialog_id') client_id = self.unpack_id(client_id, 'client_id') params = {'client_id': client_id, 'name': name} return self.request(method='GET', url='/v1/dialogs/{0}/profile'.format(dialog_id), params=params, accept_json=True) def update_profile(self, dialog_id, name_values, client_id=None): dialog_id = self.unpack_id(dialog_id, 'dialog_id') client_id = self.unpack_id(client_id, 'client_id') if isinstance(name_values, dict): name_values = list({'name': item[0], 'value': item[1]} for item in name_values.items()) params = { 'client_id': client_id, 'name_values': name_values } return self.request(method='PUT', url='/v1/dialogs/{0}/profile'.format(dialog_id), json=params, accept_json=True) def delete_dialog(self, dialog_id): dialog_id = self.unpack_id(dialog_id, 'dialog_id') return self.request(method='DELETE', url='/v1/dialogs/{0}'.format(dialog_id), accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/document_conversion_v1.py0000644000076500000240000000543313003736547031040 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Document Conversion service (https://www.ibm.com/watson/developercloud/document-conversion.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService import os import json class DocumentConversionV1(WatsonDeveloperCloudService): DEFAULT_URL = 'https://gateway.watsonplatform.net/document-conversion/api' ANSWER_UNITS = 'answer_units' NORMALIZED_HTML = 'normalized_html' NORMALIZED_TEXT = 'normalized_text' latest_version = '2016-02-10' def __init__(self, version, url=DEFAULT_URL, **kwargs): WatsonDeveloperCloudService.__init__(self, 'document_conversion', url, **kwargs) self.version = version def convert_document(self, document, config, media_type=None): params = {'version': self.version} filename = os.path.basename(document.name) file_tuple = (filename, document, media_type) if media_type else (filename, document) files = [('file', file_tuple), ('config', ('config.json', json.dumps(config), 'application/json'))] accept_json = config['conversion_target'] == DocumentConversionV1.ANSWER_UNITS return self.request(method='POST', url='/v1/convert_document', files=files, params=params, accept_json=accept_json) def index_document(self, config, document=None, metadata=None, media_type=None): if document is None and metadata is None: raise AssertionError('Missing required parameters: document or metadata. At least one of those is' 'required.') params = {'version': self.version} files = [('config', ('config.json', json.dumps(config), 'application/json'))] if document is not None: filename = os.path.basename(document.name) file_tuple = (filename, document, media_type) if media_type else (filename, document) files.append(('file', file_tuple)) if metadata is not None: files.append(('metadata', ('metadata.json', json.dumps(metadata), 'application/json'))) return self.request(method='POST', url='/v1/index_document', files=files, params=params, accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/language_translation_v2.py0000644000076500000240000000662213003736564031157 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v2 Language Translation service (https://www.ibm.com/watson/developercloud/language-translation.html) """ from __future__ import print_function from .watson_developer_cloud_service import WatsonDeveloperCloudService from .watson_developer_cloud_service import WatsonInvalidArgument class LanguageTranslationV2(WatsonDeveloperCloudService): default_url = "https://gateway.watsonplatform.net/language-translation/api" def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'language_translation', url, **kwargs) print('WARNING: The Language Translation service was deprecated, please migrate to Language Translator.') def identify(self, text): """ Identifies the language of given source text """ return self.request(method='POST', url='/v2/identify', data=text, headers={'content-type': 'text/plain'}, accept_json=True) def get_identifiable_languages(self): return self.request(method='GET', url='/v2/identifiable_languages', accept_json=True) def get_models(self, default=None, source=None, target=None): """ Get the available models for translation """ params = {'default': default, 'source': source, 'target': target} return self.request(method='GET', url='/v2/models', params=params, accept_json=True) def create_model(self, base_model_id, name=None, forced_glossary=None, parallel_corpus=None, monolingual_corpus=None): if forced_glossary is None and parallel_corpus is None and monolingual_corpus is None: raise WatsonInvalidArgument('A glossary or corpus must be provided') params = {'name': name, 'base_model_id': base_model_id} files = {'forced_glossary': forced_glossary, 'parallel_corpus': parallel_corpus, 'monolingual_corpus': monolingual_corpus} return self.request(method='POST', url='/v2/models', params=params, files=files, accept_json=True) def get_model(self, model_id): return self.request(method='GET', url='/v2/models/{0}'.format(model_id), accept_json=True) def delete_model(self, model_id): return self.request(method='DELETE', url='/v2/models/{0}'.format(model_id), accept_json=True) def translate(self, text, source=None, target=None, model_id=None): """ Translates text from a source language to a target language """ if model_id is None and (source is None or target is None): raise WatsonInvalidArgument('Either model_id or source and target must be specified') data = {'text': text, 'source': source, 'target': target, 'model_id': model_id} # data=data or json=data return self.request(method='POST', url='/v2/translate', json=data).text watson-developer-cloud-0.22.0/watson_developer_cloud/language_translator_v2.py0000644000076500000240000000636512777740445031030 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v2 Language Translator service (https://www.ibm.com/watson/developercloud/language-translator.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService from .watson_developer_cloud_service import WatsonInvalidArgument class LanguageTranslatorV2(WatsonDeveloperCloudService): default_url = "https://gateway.watsonplatform.net/language-translator/api" def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'language_translator', url, **kwargs) def identify(self, text): """ Identifies the language of given source text """ return self.request(method='POST', url='/v2/identify', data=text, headers={'content-type': 'text/plain'}, accept_json=True) def get_identifiable_languages(self): return self.request(method='GET', url='/v2/identifiable_languages', accept_json=True) def get_models(self, default=None, source=None, target=None): """ Get the available models for translation """ params = {'default': default, 'source': source, 'target': target} return self.request(method='GET', url='/v2/models', params=params, accept_json=True) def create_model(self, base_model_id, name=None, forced_glossary=None, parallel_corpus=None, monolingual_corpus=None): if forced_glossary is None and parallel_corpus is None and monolingual_corpus is None: raise WatsonInvalidArgument('A glossary or corpus must be provided') params = {'name': name, 'base_model_id': base_model_id} files = {'forced_glossary': forced_glossary, 'parallel_corpus': parallel_corpus, 'monolingual_corpus': monolingual_corpus} return self.request(method='POST', url='/v2/models', params=params, files=files, accept_json=True) def get_model(self, model_id): return self.request(method='GET', url='/v2/models/{0}'.format(model_id), accept_json=True) def delete_model(self, model_id): return self.request(method='DELETE', url='/v2/models/{0}'.format(model_id), accept_json=True) def translate(self, text, source=None, target=None, model_id=None): """ Translates text from a source language to a target language """ if model_id is None and (source is None or target is None): raise WatsonInvalidArgument('Either model_id or source and target must be specified') data = {'text': text, 'source': source, 'target': target, 'model_id': model_id} # data=data or json=data return self.request(method='POST', url='/v2/translate', json=data).text watson-developer-cloud-0.22.0/watson_developer_cloud/natural_language_classifier_v1.py0000644000076500000240000000522012741730646032466 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Natural Language Classifier service (https://www.ibm.com/watson/developercloud/nl-classifier.html) """ import json from watson_developer_cloud.watson_developer_cloud_service import WatsonDeveloperCloudService class NaturalLanguageClassifierV1(WatsonDeveloperCloudService): default_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'natural_language_classifier', url, **kwargs) def create(self, training_data, name=None, language='en'): """ :param training_data: A csv file representing the training data :param name: The optional descriptive name for the classifier :param language: The language of the input data, i.e. 'en' :return: A JSON object with the classifier_id of the newly created classifier, still in training """ params = {'language': language, 'name': name} return self.request(method='POST', url='/v1/classifiers', accept_json=True, files=[('training_metadata', ('training.json', json.dumps(params))), ('training_data', training_data)]) def list(self): return self.request(method='GET', url='/v1/classifiers', accept_json=True) def status(self, classifier_id): classifier_id = self.unpack_id(classifier_id, 'classifier_id') return self.request(method='GET', url='/v1/classifiers/{0}'.format(classifier_id), accept_json=True) def classify(self, classifier_id, text): classifier_id = self.unpack_id(classifier_id, 'classifier_id') return self.request(method='POST', url='/v1/classifiers/{0}/classify'.format(classifier_id), accept_json=True, json={'text': text}) def remove(self, classifier_id): classifier_id = self.unpack_id(classifier_id, 'classifier_id') return self.request(method='DELETE', url='/v1/classifiers/{0}'.format(classifier_id), accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/personality_insights_v2.py0000644000076500000240000000443412741730673031241 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v2 Personality Insights service (https://www.ibm.com/watson/developercloud/personality-insights.html) """ import json from .watson_developer_cloud_service import WatsonDeveloperCloudService class PersonalityInsightsV2(WatsonDeveloperCloudService): """Wrapper of the Personality Insights service""" default_url = 'https://gateway.watsonplatform.net/personality-insights/api' def __init__(self, url=default_url, **kwargs): """ Construct an instance. Fetches service parameters from VCAP_SERVICES runtime variable for Bluemix, or it defaults to local URLs. """ WatsonDeveloperCloudService.__init__( self, 'personality_insights', url, **kwargs) def profile(self, text, content_type='text/plain', accept='application/json', language=None, csv_headers=False): """ Returns a personality profile given input text (at least 100 unique words) content_type can be 'text/plain', 'application/json' or 'text/html' if accept is set to 'text/csv', returns csv output (with a header row if csv_headers is set to True) """ if isinstance(text, dict): text = json.dumps(text) content_type = 'application/json' headers = {'content-type': content_type, 'accept': accept} if language: headers['content-language'] = language params = {} if accept == 'text/csv' and csv_headers: params['headers'] = 'true' response = self.request( method='POST', url='/v2/profile', data=text, params=params, headers=headers) if accept == 'application/json': return response.json() else: return response.text watson-developer-cloud-0.22.0/watson_developer_cloud/personality_insights_v3.py0000755000076500000240000000674513005721570031242 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v3 Personality Insights service (https://www.ibm.com/watson/developercloud/personality-insights.html) """ import json from .watson_developer_cloud_service import WatsonDeveloperCloudService class PersonalityInsightsV3(WatsonDeveloperCloudService): """Wrapper for the Personality Insights service""" default_url = 'https://gateway.watsonplatform.net/personality-insights/api' default_version = '2016-10-20' def __init__(self, version=default_version, url=default_url, **kwargs): """ Constructs an instance of the service. Fetches service parameters from VCAP_SERVICES runtime variable for \ Bluemix or defaults to local URLs. :param version: The version of the API to be used in YYYY-MM-DD format (for example, '2016-10-20') """ WatsonDeveloperCloudService.__init__(self, 'personality_insights', url, **kwargs) self.version = version def profile(self, text, content_type='text/plain', content_language=None, accept='application/json', accept_language=None, raw_scores=False, consumption_preferences=False, csv_headers=False): """ :param text: The input text to be analyzed; provide a minimum of 100 words and a maximum of 20 MB of content :param content_type: Type of the input text: 'text/plain' (default), 'text/html', or 'application/json'; for \ plain text or HTML, include the charset parameter to indicate the character encoding :param content_language: Language of the input text: 'ar', 'en' (default), 'es', or 'ja' :param accept: Type of the response: 'application/json' (default) or 'text/csv' :param accept_language: Language of the response: 'ar', 'de', 'en' (default), 'es', 'fr', 'it', 'ja', 'ko', \ 'pt-br', 'zh-cn', or 'zh-tw' :param raw_scores: If True, returns percentage scores not compared with a sample population in addition to \ normalized scores :param consumption_preferences: If True, returns consumption preferences in addition to normalized scores :param csv_headers: If True, returns a row of headers for CSV output :return: A personality profile with normalized percentile scores in JSON or CSV format """ if content_type == 'application/json' and isinstance(text, dict): text = json.dumps(text) headers = { 'content-type': content_type, 'content-language': content_language, 'accept': accept, 'accept-language': accept_language } params = { 'version': self.version, 'raw_scores': raw_scores, 'consumption_preferences': consumption_preferences, 'csv_headers': csv_headers } return self.request(method='POST', url='/v3/profile', data=text, params=params, headers=headers, accept_json=(accept is None or accept == 'application/json')) watson-developer-cloud-0.22.0/watson_developer_cloud/retrieve_and_rank_v1.py0000644000076500000240000001215713003736672030437 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Retrieve and Rank service (https://www.ibm.com/watson/developercloud/retrieve-rank.html) """ import json import pysolr from watson_developer_cloud.watson_developer_cloud_service import WatsonDeveloperCloudService class RetrieveAndRankV1(WatsonDeveloperCloudService): default_url = 'https://gateway.watsonplatform.net/retrieve-and-rank/api' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'retrieve_and_rank', url, **kwargs) def list_solr_clusters(self): return self.request(method='GET', url='/v1/solr_clusters', accept_json=True) def create_solr_cluster(self, cluster_name=None, cluster_size=None): if cluster_size: cluster_size = str(cluster_size) params = {'cluster_name': cluster_name, 'cluster_size': cluster_size} return self.request(method='POST', url='/v1/solr_clusters', accept_json=True, json=params) def delete_solr_cluster(self, solr_cluster_id): return self.request(method='DELETE', url='/v1/solr_clusters/{0}'.format(solr_cluster_id), accept_json=True) def get_solr_cluster_status(self, solr_cluster_id): return self.request(method='GET', url='/v1/solr_clusters/{0}'.format(solr_cluster_id), accept_json=True) def list_configs(self, solr_cluster_id): return self.request(method='GET', url='/v1/solr_clusters/{0}/config'.format(solr_cluster_id), accept_json=True) # Need to test def create_config(self, solr_cluster_id, config_name, config): return self.request(method='POST', url='/v1/solr_clusters/{0}/config/{1}'.format(solr_cluster_id, config_name), files={'body': config}, headers={'content-type': 'application/zip'}, accept_json=True) def delete_config(self, solr_cluster_id, config_name): return self.request(method='DELETE', url='/v1/solr_clusters/{0}/config/{1}'.format(solr_cluster_id, config_name), accept_json=True) def get_config(self, solr_cluster_id, config_name): return self.request(method='GET', url='/v1/solr_clusters/{0}/config/{1}'.format(solr_cluster_id, config_name)) def list_collections(self, solr_cluster_id): params = {'action': 'LIST', 'wt': 'json'} return self.request(method='GET', url='/v1/solr_clusters/{0}/solr/admin/collections'.format(solr_cluster_id), params=params, accept_json=True) def create_collection(self, solr_cluster_id, collection_name, config_name): params = {'collection.configName': config_name, 'name': collection_name, 'action': 'CREATE', 'wt': 'json'} return self.request(method='POST', url='/v1/solr_clusters/{0}/solr/admin/collections'.format(solr_cluster_id), params=params, accept_json=True) def delete_collection(self, solr_cluster_id, collection_name, config_name=None): params = {'name': collection_name, 'action': 'DELETE', 'wt': 'json'} return self.request(method='POST', url='/v1/solr_clusters/{0}/solr/admin/collections'.format(solr_cluster_id), params=params, accept_json=True) def get_pysolr_client(self, solr_cluster_id, collection_name): base_url = self.url.replace('https://', 'https://' + self.username + ':' + self.password + '@') url = base_url + '/v1/solr_clusters/{0}/solr/{1}'.format(solr_cluster_id, collection_name) return pysolr.Solr(url) def create_ranker(self, training_data, name=None): data = None if name: data = {'training_metadata': json.dumps({'name': name})} return self.request(method='POST', url='/v1/rankers', accept_json=True, files=[('training_data', training_data)], data=data) def list_rankers(self): return self.request(method='GET', url='/v1/rankers', accept_json=True) def get_ranker_status(self, ranker_id): return self.request(method='GET', url='/v1/rankers/{0}'.format(ranker_id), accept_json=True) def rank(self, ranker_id, answer_data, top_answers=10): data = {'answer_metadata': json.dumps({'answers': + top_answers})} return self.request(method='POST', url='/v1/rankers/{0}/rank'.format(ranker_id), files=[('answer_data', answer_data)], data=data, accept_json=True) def delete_ranker(self, ranker_id): return self.request(method='DELETE', url='/v1/rankers/{0}'.format(ranker_id), accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/speech_to_text_v1.py0000644000076500000240000000541012777754654030005 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Speech to Text service (https://www.ibm.com/watson/developercloud/speech-to-text.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService class SpeechToTextV1(WatsonDeveloperCloudService): default_url = "https://stream.watsonplatform.net/speech-to-text/api" def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'speech_to_text', url, **kwargs) def recognize(self, audio, content_type, continuous=False, model=None, inactivity_timeout=None, keywords=None, keywords_threshold=None, max_alternatives=None, word_alternatives_threshold=None, word_confidence=None, timestamps=None, interim_results=None, profanity_filter=None, smart_formatting=None): """ Returns the recognized text from the audio input """ headers = {'content-type': content_type} params = {'continuous': continuous, 'inactivity_timeout': inactivity_timeout, 'keywords': keywords, 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, 'model': model, 'word_alternatives_threshold': word_alternatives_threshold, 'word_confidence': word_confidence, 'timestamps': timestamps, 'interim_results': interim_results, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting} return self.request(method='POST', url='/v1/recognize', headers=headers, data=audio, params=params, stream=True, accept_json=True) def models(self): """ Returns the list of available models to use with recognize """ return self.request(method='GET', url='/v1/models', accept_json=True) def get_model(self, model_id): """ :param model_id: The identifier of the desired model :return: A single instance of a Model object with results for the specified model. """ return self.request(method='GET', url='/v1/models/{0}'.format(model_id), accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/text_to_speech_v1.py0000644000076500000240000001165612741730744027777 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Text to Speech service (https://www.ibm.com/watson/developercloud/text-to-speech.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService class TextToSpeechV1(WatsonDeveloperCloudService): """Client for the Text to Speech service""" default_url = "https://stream.watsonplatform.net/text-to-speech/api" def __init__(self, url=default_url, **kwargs): """ Construct an instance. Fetches service parameters from VCAP_SERVICES runtime variable for Bluemix, or it defaults to local URLs. """ WatsonDeveloperCloudService.__init__(self, 'text_to_speech', url, **kwargs) def synthesize(self, text, voice=None, accept=None, customization_id=None): """ Returns the get HTTP response by doing a POST to /synthesize with text, voice, accept """ params = {'voice': voice, 'accept': accept, 'customization_id': customization_id} data = {'text': text} response = self.request( method='POST', url='/v1/synthesize', stream=True, params=params, json=data) return response.content def voices(self): """ Returns the list of available voices to use with synthesize """ return self.request(method='GET', url='/v1/voices', accept_json=True) def pronunciation(self, text, voice=None, pronunciation_format='ipa'): params = { 'text': text, 'voice': voice, 'format': pronunciation_format } return self.request(method='GET', url='/v1/pronunciation', params=params, accept_json=True) def customizations(self, language=None): params = { 'language': language } return self.request(method='GET', url='/v1/customizations', params=params, accept_json=True) def get_customization(self, customization_id): customization_id = self.unpack_id(customization_id, 'customization_id') return self.request(method='GET', url='/v1/customizations/{0}'.format(customization_id), accept_json=True) def create_customization(self, name, language=None, description=None): body = { 'name': name, 'language': language, 'description': description } return self.request(method='POST', url='/v1/customizations', json=body, accept_json=True) def update_customization(self, customization_id, name=None, description=None, words=None): body = { 'name': name, 'description': description, 'words': words } return self.request(method='POST', url='/v1/customizations/{0}'.format(customization_id), json=body) def delete_customization(self, customization_id): customization_id = self.unpack_id(customization_id, 'customization_id') return self.request(method='DELETE', url='/v1/customizations/{0}'.format(customization_id)) def get_customization_words(self, customization_id): customization_id = self.unpack_id(customization_id, 'customization_id') return self.request(method='GET', url='/v1/customizations/{0}/words'.format(customization_id), accept_json=True) def add_customization_words(self, customization_id, words): customization_id = self.unpack_id(customization_id, 'customization_id') body = { 'words': words } return self.request(method='POST', url='/v1/customizations/{0}/words'.format(customization_id), json=body) def get_customization_word(self, customization_id, word): customization_id = self.unpack_id(customization_id, 'customization_id') return self.request(method='GET', url='/v1/customizations/{0}/words/{1}'.format(customization_id, word), accept_json=True) def set_customization_word(self, customization_id, word, translation): customization_id = self.unpack_id(customization_id, 'customization_id') body = { 'translation': translation } return self.request(method='PUT', url='/v1/customizations/{0}/words/{1}'.format(customization_id, word), json=body) def delete_customization_word(self, customization_id, word): customization_id = self.unpack_id(customization_id, 'customization_id') return self.request(method='DELETE', url='/v1/customizations/{0}/words/{1}'.format(customization_id, word)) watson-developer-cloud-0.22.0/watson_developer_cloud/tone_analyzer_v3.py0000644000076500000240000000404112741730773027626 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v3 Tone Analyzer service (https://www.ibm.com/watson/developercloud/tone-analyzer.html) """ from watson_developer_cloud.watson_developer_cloud_service import WatsonDeveloperCloudService class ToneAnalyzerV3(WatsonDeveloperCloudService): default_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' latest_version = '2016-05-19' def __init__(self, version, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'tone_analyzer', url, **kwargs) self.version = version def tone(self, text, tones=None, sentences=None): """ The tone API is the main API call: it analyzes the "tone" of a piece of text. The message is analyzed from several tones (social tone, emotional tone, writing tone), and for each of them various traits are derived (such as conscientiousness, agreeableness, openness). :param text: Text to analyze :param sentences: If "false", sentence-level analysis is omitted :param tones: Can be one or more of 'social', 'language', 'emotion'; comma-separated. """ params = {} params['version'] = self.version if tones is not None: params['tones'] = tones if sentences is not None: params['sentences'] = str(sentences).lower() # Cast boolean to "false" / "true" data = {'text': text} return self.request(method='POST', url='/v3/tone', params=params, json=data, accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/tradeoff_analytics_v1.py0000755000076500000240000000316313006647105030611 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Tradeoff Analytics service (https://www.ibm.com/watson/developercloud/tradeoff-analytics.html) """ from .watson_developer_cloud_service import WatsonDeveloperCloudService class TradeoffAnalyticsV1(WatsonDeveloperCloudService): """Wrapper for the Tradeoff Analytics service""" default_url = 'https://gateway.watsonplatform.net/tradeoff-analytics/api' def __init__(self, url=default_url, **kwargs): WatsonDeveloperCloudService.__init__(self, 'tradeoff_analytics', url, **kwargs) def dilemmas(self, params, generate_visualization=True): """ :param params: The JSON problem (subject, columns, and options) :param generate_visualization: If True, returns the map visualization used by the Tradeoff Analytics widget :return: A dilemma that contains the problem and its resolution """ parameters = { 'generate_visualization': generate_visualization } return self.request(method='POST', url='/v1/dilemmas', json=params, params=parameters, accept_json=True) watson-developer-cloud-0.22.0/watson_developer_cloud/version.py0000644000076500000240000000002713006647511026021 0ustar jsstylosstaff00000000000000__version__ = '0.22.0' watson-developer-cloud-0.22.0/watson_developer_cloud/visual_recognition_v3.py0000644000076500000240000001515513003465473030661 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v3 Visual Recognition service (https://www.ibm.com/watson/developercloud/visual-recognition.html) """ import mimetypes from .watson_developer_cloud_service import WatsonDeveloperCloudService class VisualRecognitionV3(WatsonDeveloperCloudService): """Client for the Visual Recognition service""" default_url = 'https://gateway-a.watsonplatform.net/visual-recognition/api' latest_version = '2016-05-20' def __init__(self, version, url=default_url, **kwargs): """ Construct an instance. Fetches service parameters from VCAP_SERVICES runtime variable for Bluemix, or it defaults to local URLs. :param version: specifies the specific version-date of the service to use, for example '2016-05-20' :param api_key: specifies the credentials for the service (doesn't use username and password) """ WatsonDeveloperCloudService.__init__(self, 'watson_vision_combined', url, **kwargs) self.version = version def get_classifier(self, classifier_id): """ Retrieves information about a specific classifier. :param classifier_id: The classifier id """ params = {'version': self.version} return self.request(method='GET', url='/v3/classifiers/{0}'.format(classifier_id), params=params, accept_json=True) def delete_classifier(self, classifier_id): """ Deletes a custom classifier with the specified classifier id. :param classifier_id: The classifier id """ params = {'version': self.version} return self.request(method='DELETE', url='/v3/classifiers/{0}'.format(classifier_id), params=params, accept_json=True) def list_classifiers(self, verbose=False): """ Returns a list of user-created and built-in classifiers. (May change in the future to only user-created.) :param verbose: Specifies whether to return more information about each classifier, such as the author """ params = {'verbose': verbose, 'version': self.version} return self.request(method='GET', url='/v3/classifiers', params=params, accept_json=True) def create_classifier(self, name, **kwargs): """ Train a new classifier from example images which are uploaded. :param name: The desired short name of the new classifier. :param _positive_examples: zip files of images that depict the subject of the new classifier. :param negative_examples: A zip file of images that do not depict the subject of the new classifier. :return: """ params = {'version': self.version} data = {'name': name} # Params sent as url parameters here return self.request(method='POST', url='/v3/classifiers', files=kwargs, data=data, params=params, accept_json=True) def update_classifier(self, classifier_id, **kwargs): """ Updates an existing classifier by adding images to existing or new classes. :param classifier_id: The id of the classifier to update. :param _positive_examples: zip files of images that depict the subject of the class. :param negative_examples: A zip file of images that do not depict the subject of any of the classes. :return: """ params = {'version': self.version} # Params sent as url parameters here return self.request(method='POST', url='/v3/classifiers/{0}'.format(classifier_id), files=kwargs, params=params, accept_json=True) def _image_call(self, url, images_file=None, images_url=None, params=None): if images_file is None and images_url is None: raise AssertionError('You must specify either a file or a url') if images_url: params['url'] = images_url return self.request(method='GET', url=url, params=params, accept_json=True) else: filename = images_file.name mime_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream' return self.request(method='POST', url=url, files={'images_file': (filename, images_file, mime_type)}, params=params, accept_json=True) def classify(self, images_file=None, images_url=None, classifier_ids=None, owners=None, threshold=None): """ Returns a list of classification scores for one or more input images. :param images_file: An image file or zip file of image files to analyze. :param images_url: The url for an image file or zip file of images to analyze. :param classifier_ids: The ids of classifiers to consider. When absent, considers all classifiers. :return: """ if isinstance(classifier_ids, list): classifier_ids = ','.join(classifier_ids) if isinstance(owners, list): owners = ','.join(owners) params = {'version': self.version, 'classifier_ids': classifier_ids, 'owners': owners, 'threshold': threshold} return self._image_call('/v3/classify', images_file, images_url, params) def detect_faces(self, images_file=None, images_url=None): """ Returns a list of faces detected. This includes identities for famous people. :param images_file: An image file or zip file of image files to analyze. :param images_url: The url for an image file or zip file of images to analyze. :return: """ params = {'version': self.version} return self._image_call('/v3/detect_faces', images_file, images_url, params) def recognize_text(self, images_file=None, images_url=None): """ Returns a list of recognized text :param images_file: An image file or zip file of image files to analyze. :param images_url: The url for an image file or zip file of images to analyze. :return: """ params = {'version': self.version} return self._image_call('/v3/recognize_text', images_file, images_url, params) watson-developer-cloud-0.22.0/watson_developer_cloud/watson_developer_cloud_service.py0000755000076500000240000002560313006375714032637 0ustar jsstylosstaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json as json_import import os import requests from requests.structures import CaseInsensitiveDict try: from http.cookiejar import CookieJar # Python 3 except ImportError: from cookielib import CookieJar # Python 2 from .version import __version__ # Uncomment this to enable http debugging # try: # import http.client as http_client # except ImportError: # # Python 2 # import httplib as http_client # http_client.HTTPConnection.debuglevel = 1 def load_from_vcap_services(service_name): vcap_services = os.getenv("VCAP_SERVICES") if vcap_services is not None: services = json_import.loads(vcap_services) if service_name in services: return services[service_name][0]["credentials"] else: return None class WatsonException(Exception): pass class WatsonInvalidArgument(WatsonException): pass def _cleanup_param_value(value): if isinstance(value, bool): return 'true' if value else 'false' return value def _cleanup_param_values(dictionary): if isinstance(dictionary, dict): return dict([(k, _cleanup_param_value(v)) for k, v in dictionary.items()]) return dictionary def _remove_null_values(dictionary): if isinstance(dictionary, dict): return dict([(k, v) for k, v in dictionary.items() if v is not None]) return dictionary def _convert_boolean_value(value): if isinstance(value, bool): return 1 if value else 0 return value def _convert_boolean_values(dictionary): if isinstance(dictionary, dict): return dict([(k, _convert_boolean_value(v)) for k, v in dictionary.items()]) return dictionary class WatsonDeveloperCloudService(object): def __init__(self, vcap_services_name, url, username=None, password=None, use_vcap_services=True, api_key=None, x_watson_learning_opt_out=False): """ Loads credentials from the VCAP_SERVICES environment variable if available, preferring credentials explicitly set in the request. If VCAP_SERVICES is not found (or use_vcap_services is set to False), username and password credentials must be specified. """ self.url = url self.jar = None self.api_key = None self.username = None self.password = None self.x_watson_learning_opt_out = x_watson_learning_opt_out if api_key is not None: if username is not None or password is not None: raise WatsonInvalidArgument('Cannot set api_key and username and password together') self.set_api_key(api_key) else: self.set_username_and_password(username, password) if use_vcap_services and not self.username and not self.api_key: self.vcap_service_credentials = load_from_vcap_services(vcap_services_name) if self.vcap_service_credentials is not None and isinstance(self.vcap_service_credentials, dict): self.url = self.vcap_service_credentials['url'] if 'username' in self.vcap_service_credentials: self.username = self.vcap_service_credentials['username'] if 'password' in self.vcap_service_credentials: self.password = self.vcap_service_credentials['password'] if 'apikey' in self.vcap_service_credentials: self.api_key = self.vcap_service_credentials['apikey'] if 'api_key' in self.vcap_service_credentials: self.api_key = self.vcap_service_credentials['api_key'] if (self.username is None or self.password is None) and self.api_key is None: raise WatsonException('You must specify your username and password service credentials ' + '(Note: these are different from your Bluemix id)') def set_username_and_password(self, username=None, password=None): if username == 'YOUR SERVICE USERNAME': username = None if password == 'YOUR SERVICE PASSWORD': password = None self.username = username self.password = password self.jar = CookieJar() def set_api_key(self, api_key): if api_key == 'YOUR API KEY': api_key = None self.api_key = api_key self.jar = CookieJar() def set_url(self, url): self.url = url # Could make this compute the label_id based on the variable name of the dictionary passed in (using **kwargs), but # this might be confusing to understand. @staticmethod def unpack_id(dictionary, label_id): if isinstance(dictionary, dict) and label_id in dictionary: return dictionary[label_id] return dictionary @staticmethod def _get_error_message(response): """ Gets the error message from a JSON response. { code: 400 error: 'Bad request' } """ error_message = 'Unknown error' try: error_json = response.json() if 'error' in error_json: if isinstance(error_json['error'], dict) and 'description' in error_json['error']: error_message = 'Error: ' + error_json['error']['description'] else: error_message = 'Error: ' + error_json['error'] elif 'error_message' in error_json: error_message = 'Error: ' + error_json['error_message'] elif 'msg' in error_json: error_message = 'Error: ' + error_json['msg'] if 'description' in error_json: error_message += ', Description: ' + error_json['description'] error_message += ', Code: ' + str(response.status_code) except: pass return error_message def _alchemy_html_request(self, method_name=None, url=None, html=None, text=None, params=None, method='POST', method_url=None): if params is None: params = {} params['outputMode'] = 'json' headers = {'content-type': 'application/x-www-form-urlencoded'} params = _convert_boolean_values(params) url_encoded_params = {} if method.upper() is 'POST': url_encoded_params = params params = {} url_encoded_params['html'] = html url_encoded_params['text'] = text if method_url is None: if url: params['url'] = url method_url = '/url/URL' + method_name elif html: method_url = '/html/HTML' + method_name elif text: method_url = '/text/Text' + method_name else: raise WatsonInvalidArgument('url, html or text must be specified') return self.request(method=method, url=method_url, params=params, data=url_encoded_params, headers=headers, accept_json=True) def _alchemy_image_request(self, method_name, image_file=None, image_url=None, params=None): if params is None: params = {} params['outputMode'] = 'json' params = _convert_boolean_values(params) headers = {} image_contents = None if image_file: params['imagePostMode'] = 'raw' image_contents = image_file.read() # headers['content-length'] = sys.getsizeof(image_contents) url = '/image/Image' + method_name elif image_url: params['imagePostMode'] = 'not-raw' params['url'] = image_url url = '/url/URL' + method_name else: raise WatsonInvalidArgument('image_file or image_url must be specified') return self.request(method='POST', url=url, params=params, data=image_contents, headers=headers, accept_json=True) def request(self, method, url, accept_json=False, headers=None, params=None, json=None, data=None, files=None, **kwargs): full_url = self.url + url input_headers = _remove_null_values(headers) if headers else {} headers = CaseInsensitiveDict({'user-agent': 'watson-developer-cloud-python-' + __version__}) if accept_json: headers['accept'] = 'application/json' headers.update(input_headers) # Remove keys with None values params = _remove_null_values(params) params = _cleanup_param_values(params) json = _remove_null_values(json) data = _remove_null_values(data) files = _remove_null_values(files) # Support versions of requests older than 2.4.2 without the json input if not data and json is not None: data = json_import.dumps(json) headers.update({'content-type': 'application/json'}) auth = None if self.username and self.password: auth = (self.username, self.password) if self.api_key is not None: if params is None: params = {} if url.startswith('https://gateway-a.watsonplatform.net/calls'): params['apikey'] = self.api_key else: params['api_key'] = self.api_key if self.x_watson_learning_opt_out: headers['x-watson-learning-opt-out'] = 'true' response = requests.request(method=method, url=full_url, cookies=self.jar, auth=auth, headers=headers, params=params, data=data, files=files, **kwargs) if 200 <= response.status_code <= 299: if accept_json: response_json = response.json() if 'status' in response_json and response_json['status'] == 'ERROR': response.status_code = 400 error_message = 'Unknown error' if 'statusInfo' in response_json: error_message = response_json['statusInfo'] if error_message == 'invalid-api-key': response.status_code = 401 raise WatsonException('Error: ' + error_message) return response_json return response else: if response.status_code == 401: error_message = 'Unauthorized: Access is denied due to invalid credentials' else: error_message = self._get_error_message(response) raise WatsonException(error_message) watson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/0000755000076500000240000000000013006647576025470 5ustar jsstylosstaff00000000000000watson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/dependency_links.txt0000644000076500000240000000000113006647575031535 0ustar jsstylosstaff00000000000000 watson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/PKG-INFO0000644000076500000240000001200013006647575026555 0ustar jsstylosstaff00000000000000Metadata-Version: 1.1 Name: watson-developer-cloud Version: 0.22.0 Summary: Client library to use the IBM Watson Services Home-page: https://github.com/watson-developer-cloud/python-sdk Author: Jeffrey Stylos Author-email: jsstylos@us.ibm.com License: Apache 2.0 Description: Watson Developer Cloud Python SDK --------------------------------- |Build Status| |codecov.io| |Latest Stable Version| |Download Times| Python client library to quickly get started with the various `Watson Developer Cloud `__ services. Installation ------------ To install, use ``pip`` or ``easy_install``: .. code:: bash $ pip install --upgrade watson-developer-cloud or .. code:: bash $ easy_install --upgrade watson-developer-cloud Examples -------- The `examples `__ folder has basic and advanced examples. Getting the Service Credentials ------------------------------- You will need the ``username`` and ``password`` credentials for each service. Service credentials are different from your Bluemix account username and password. To get your service credentials, follow these steps: 1. Log in to Bluemix at https://bluemix.net. 1. Create an instance of the service: 1. In the Bluemix **Catalog**, select the Watson service you want to use. For example, select the Natural Language Classifier service. 2. Under **Add Service**, type a unique name for the service instance in the Service name field. For example, type ``my-service-name``. Leave the default values for the other options. 3. Click **Use**. 2. Copy your credentials: 1. On the left side of the page, click **Service Credentials** to view your service credentials. 2. Copy ``username`` and ``password`` from these service credentials. Python Version -------------- Tested 👌 (lightly) on: Python from 2.7 to 3.5-dev (development branch). Python 2.6 is partially supported but generates InsecurePlatformWarnings (and other warnings), which can be ignored. CHANGELOG --------- See `CHANGELOG `__. Known Issues ------------ There is a known incompatibility with this module with Python versions 3.x with Korean systems. Dependencies ------------ - `requests `__ - `responses `__ for testing Contributing ------------ See `CONTRIBUTING.md `__. License ------- This library is licensed under the `Apache 2.0 license `__. .. |Build Status| image:: https://travis-ci.org/watson-developer-cloud/python-sdk.svg :target: https://travis-ci.org/watson-developer-cloud/python-sdk .. |codecov.io| image:: https://codecov.io/github/watson-developer-cloud/python-sdk/coverage.svg?branch=master :target: https://codecov.io/github/watson-developer-cloud/python-sdk?branch=master .. |Latest Stable Version| image:: https://img.shields.io/pypi/v/watson-developer-cloud.svg :target: https://pypi.python.org/pypi/watson-developer-cloud .. |Download Times| image:: https://img.shields.io/pypi/dm/watson-developer-cloud.svg :target: https://pypi.python.org/pypi/watson-developer-cloud Keywords: alchemy datanews,language,vision,question and answer tone_analyzer,natural language classifier,retrieve and rank,tradeoff analytics,text to speech,language translation,language identification,concept expansion,machine translation,personality insights,message resonance,watson developer cloud,wdc,watson,ibm,dialog,user modeling,alchemyapi,alchemy,tone analyzer,speech to text,visual recognition Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Software Development :: Libraries :: Application Frameworks watson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/requires.txt0000644000076500000240000000004713006647575030070 0ustar jsstylosstaff00000000000000requests>=2.0, <3.0 pysolr>= 3.3, <4.0 watson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/SOURCES.txt0000644000076500000240000000470413006647576027361 0ustar jsstylosstaff00000000000000LICENSE MANIFEST.in README.md setup.py examples/README.md examples/__init__.py examples/alchemy_data_news_v1.py examples/alchemy_language_v1.py examples/authorization_v1.py examples/conversation_v1.py examples/dialog_v1.py examples/document_conversion_v1.py examples/language_translation_v2.py examples/language_translator_v2.py examples/natural_language_classifier_v1.py examples/personality_insights_v2.py examples/personality_insights_v3.py examples/retrieve_and_rank_v1.py examples/speech_to_text_v1.py examples/text_to_speech_v1.py examples/tone_analyzer_v3.py examples/tradeoff_analytics_v1.py examples/visual_recognition_v3.py examples/conversation_tone_analyzer_integration/README.md examples/conversation_tone_analyzer_integration/__init__.py examples/conversation_tone_analyzer_integration/tone_conversation_integration.v1.py examples/conversation_tone_analyzer_integration/tone_detection.py test/test_conversation_v1.py test/test_document_conversion_v1.py test/test_examples.py test/test_natural_language_classifier_v1.py test/test_personality_insights_v2.py test/test_personality_insights_v3.py test/test_retrieve_and_rank_v1.py test/test_speech_to_text_v1.py test/test_text_to_speech_v1.py test/test_tone_analyzer_v3.py test/test_tradeoff_analytics_v1.py watson_developer_cloud/__init__.py watson_developer_cloud/alchemy_data_news_v1.py watson_developer_cloud/alchemy_language_v1.py watson_developer_cloud/alchemy_vision_v1.py watson_developer_cloud/authorization_v1.py watson_developer_cloud/conversation_v1.py watson_developer_cloud/dialog_v1.py watson_developer_cloud/document_conversion_v1.py watson_developer_cloud/language_translation_v2.py watson_developer_cloud/language_translator_v2.py watson_developer_cloud/natural_language_classifier_v1.py watson_developer_cloud/personality_insights_v2.py watson_developer_cloud/personality_insights_v3.py watson_developer_cloud/retrieve_and_rank_v1.py watson_developer_cloud/speech_to_text_v1.py watson_developer_cloud/text_to_speech_v1.py watson_developer_cloud/tone_analyzer_v3.py watson_developer_cloud/tradeoff_analytics_v1.py watson_developer_cloud/version.py watson_developer_cloud/visual_recognition_v3.py watson_developer_cloud/watson_developer_cloud_service.py watson_developer_cloud.egg-info/PKG-INFO watson_developer_cloud.egg-info/SOURCES.txt watson_developer_cloud.egg-info/dependency_links.txt watson_developer_cloud.egg-info/requires.txt watson_developer_cloud.egg-info/top_level.txt watson_developer_cloud.egg-info/zip-safewatson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/top_level.txt0000644000076500000240000000002713006647575030220 0ustar jsstylosstaff00000000000000watson_developer_cloud watson-developer-cloud-0.22.0/watson_developer_cloud.egg-info/zip-safe0000644000076500000240000000000112605477705027117 0ustar jsstylosstaff00000000000000