Added Python2 and Python3 SDKs, gitignore, License, and Contributing files, and modified Readme file

This commit is contained in:
Ahmed Elhinidy 2016-09-04 16:13:54 +02:00
Родитель dfb4b92c53
Коммит 6f564a69e7
31 изменённых файлов: 2507 добавлений и 2 удалений

22
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,22 @@
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
# Installer logs
pip-log.txt

46
CONTRIBUTING.md Normal file
Просмотреть файл

@ -0,0 +1,46 @@
Contributing to Microsoft Cognitive Services Client Libraries & Samples
===============================================
So, you want to contribute on a client library or sample for one of the Microsoft Cognitive Services.
Here's what you need to know.
1. Each SDK should include both a client library and a sample showing the API in
action
2. When working on an SDK, it's important that we are consistent from project to project, so we ask you to follow the coding guidelines below:
- Windows [(Coding guidelines for C#)](https://msdn.microsoft.com/en-us/library/ff926074.aspx) -- also reference our [common Windows code](https://github.com/Microsoft/Cognitive-common-windows) for building samples
- Android [(Coding guidelines for
Java)](<http://source.android.com/source/code-style.html>)
- iOS Objective-C [(Coding guidelines for
Cocoa)](<https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html>)
- Optional: Client Javascript ([Coding guidelines for
npm](<https://docs.npmjs.com/misc/coding-style>))
3. Samples are important for illustrating how to actually call into the API.
Samples should be as visual and reusable as possible.
- Do:
- Create a UI sample when possible.
- Make your sample user friendly. Expect that developers will want to try
different mainline scenarios and key APIs.
- Create code that's easy for other developers to copy/paste into their
own solutions
- Consider:
- Adding UI to allow devs to quickly copy/paste subscription keys, instead
of updating them in the code or using a config file. The
FaceAPI-WPF-Samples.sln provides an example.
- Don't:
- Leave your subscription key in the source of samples. You do not want your key to be abused by others.
Happy coding!

14
LICENSE.md Normal file
Просмотреть файл

@ -0,0 +1,14 @@
Microsoft Cognitive Services SDK
Copyright (c) Microsoft Corporation
All rights reserved.
*This license applies only to the SDK and the sample applications code.
MIT License
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.

Просмотреть файл

@ -0,0 +1,34 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_client import LUISClient

Просмотреть файл

@ -0,0 +1,72 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_parameter import LUISParameter
class LUISAction(object):
'''
LUIS Action Class.
Describes the LUIS Action structure.
'''
def __init__(self, action):
'''
A constructor for the LUISAction class.
:param action: A dictionary containing the action data.
'''
self._name = action[u'name']
self._triggered = action[u'triggered']
self._parameters = []
for parameter in action[u'parameters']:
self._parameters.append(LUISParameter(parameter))
def get_name(self):
'''
A getter for the action's name.
:return: Actions's name.
'''
return self._name
def get_triggered(self):
'''
A getter for the action's triggered flag.
:return: A boolean that expresses whether the action was trigerred or not.
'''
return self._triggered
def get_parameters(self):
'''
A getter for the action's parameters.
:return: A list of parameter.
'''
return self._parameters

Просмотреть файл

@ -0,0 +1,241 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
import threading
from urllib import quote
import httplib
from .luis_response import LUISResponse
class LUISClient(object):
'''
This is the interface of the LUIS
Constructs a LUISClient with the corresponding user's App Id and Subscription Keys
Starts the prediction procedure for the user's text, and accepts a callback function
'''
_LUISURL = u'api.projectoxford.ai'
_PredictMask = u'/luis/v1/application%s?id=%s&subscription-key=%s&verbose=%s&q=%s'
_ReplyMask = u'/luis/v1/application%s?id=%s&subscription-key=%s&contextid=%s&verbose=%s&q=%s'
def __init__(self, app_id, app_key, preview=False, verbose=False):
'''
A constructor for the LUISClient class.
:param app_id: A string containing the application id.
:param app_key: A string containing the subscription key.
:param preview: A boolean to indicate whether the preview version should used or not.
:param verbose: A boolean to indicate whether the verbose version should used or not.
'''
if app_id is None:
raise TypeError(u'NULL App Id')
if not app_id:
raise ValueError(u'Empty App Id')
if u' ' in app_id:
raise ValueError(u'Invalid App Id')
if app_key is None:
raise TypeError(u'NULL Subscription Key')
if not app_key:
raise ValueError(u'Empty Subscription Key')
if u' ' in app_key:
raise ValueError(u'Invalid Subscription Key')
self._app_id = app_id
self._app_key = app_key
self._preview = True if preview else False
self._preview_url = u'/preview' if preview else u''
self._verbose_url = u'true' if verbose else u'false'
def predict(self, text, response_handlers=None, daemon=False):
'''
Routes the prediction routine to either sync or async
based on the presence or absence of a callback fucntion.
:param text: the text to be analysed and predicted.
:param response_handlers: a dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:param daemon: defines whether the new thread used for async will be daemon or not.
:return: LUISResponse if sync, thread object to give control over the thread if async.
'''
if text is None:
raise TypeError(u'NULL text to predict')
text = text.strip()
if not text:
raise ValueError(u'Empty text to predict')
if response_handlers is None:
return self.predict_sync(text)
else:
return self.predict_async(text, response_handlers, daemon)
def predict_sync(self, text):
'''
Predicts synchronously and returns a LUISResponse.
:param text: The text to be analysed and predicted.
:return: A LUISResponse object containing the response data.
'''
try:
conn = httplib.HTTPSConnection(self._LUISURL)
conn.request(u'GET', self._predict_url_gen(text))
res = conn.getresponse()
return LUISResponse(res.read().decode(u'UTF-8'))
except Exception:
raise
def predict_async(self, text, response_handlers, daemon):
'''
Predicts asynchronously and executes a callback function at the end.
:param text: The text to be analysed and predicted.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:param daemon: Defines whether the new thread will be daemon or not.
:return: A thread object to give control over the thread.
'''
if u'on_success' not in response_handlers:
raise KeyError(u'You have to specify the success handler with key: "on_success"')
if u'on_failure' not in response_handlers:
raise KeyError(u'You have to specify the failure handler with key: "on_failure"')
predict_thread = threading.Thread(target=self._predict_async_helper
, args=(text, response_handlers))
predict_thread.daemon = daemon
predict_thread.start()
return predict_thread
def _predict_url_gen(self, text):
'''
Returns the suitable LUIS API predict url.
:param text: The text to be analysed and predicted.
:return: LUIS API predicton url.
'''
return self._PredictMask%(self._preview_url, self._app_id, self._app_key
, self._verbose_url, quote(text))
def _predict_async_helper(self, text, response_handlers):
'''
A wrapper function to be executed asynchronously in an external thread.
It executes the predict routine and then executes a callback function.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse that contains the context Id.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:return: None.
'''
res = None
try:
res = self.predict(text)
except Exception, exc:
response_handlers[u'on_failure'](exc)
return
response_handlers[u'on_success'](res)
def reply(self, text, response, response_handlers=None, daemon=False):
'''
Routes the reply routine to either sync or async
based on the presence or absence of a callback fucntion.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse that contains the context Id.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions
to be executed if async.
:param daemon: Defines whether the new thread used for async will be daemon or not.
:return: A LUISResponse object if sync, a thread object to control the thread if async.
'''
if text is None:
raise TypeError(u'NULL text to predict')
text = text.strip()
if not text:
raise ValueError(u'Empty text to predict')
if not self._preview:
raise Exception(u"Can't use reply unless in the preview mode")
if response_handlers is None:
return self.reply_sync(text, response)
else:
return self.reply_async(text, response, response_handlers, daemon)
def reply_sync(self, text, response):
'''
Replies synchronously and returns a LUISResponse object.
:param text: The text to be analysed and predicted.
:return: A LUISResponse object containg the response data.
'''
try:
conn = httplib.HTTPSConnection(self._LUISURL)
conn.request(u'GET', self._reply_url_gen(text, response))
res = conn.getresponse()
return LUISResponse(res.read().decode(u'UTF-8'))
except Exception:
raise
def reply_async(self, text, response, response_handlers, daemon):
'''
Predicts asynchronously and executes a callback function at the end.
:param text: The text to be analysed and predicted.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions
to be executed if async.
:param daemon: Defines whether the new thread used will be daemon or not.
:return: A thread object to give control over the thread.
'''
if u'on_success' not in response_handlers:
raise KeyError(u'You have to specify the success handler with key: "on_success"')
if u'on_failure' not in response_handlers:
raise KeyError(u'You have to specify the failure handler with key: "on_failure"')
reply_thread = threading.Thread(target=self._reply_async_helper
, args=(text, response, response_handlers))
reply_thread.daemon = daemon
reply_thread.start()
return reply_thread
def _reply_url_gen(self, text, response):
'''
Generates the suitable LUIS API reply url.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse object that contains the context Id.
:return: LUIS API reply url.
'''
return self._ReplyMask%(self._preview_url, self._app_id, self._app_key
, response.get_dialog().get_context_id()
, self._verbose_url, quote(text))
def _reply_async_helper(self, text, response, response_handlers):
'''
A wrapper function to be executed asynchronously in an external thread.
It executes the reply routine and then executes a callback function.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse object that contains the context Id.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:return: None.
'''
res = None
try:
res = self.reply(text, response)
except Exception, exc:
response_handlers[u'on_failure'](exc)
return
response_handlers[u'on_success'](res)

Просмотреть файл

@ -0,0 +1,72 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_composite_entity_child import LUISCompositeEntityChild
class LUISCompositeEntity:
'''
LUIS Composite Entity Class.
Describes the LUIS Composite Entity structure.
'''
def __init__(self, composite_entity):
'''
A constructor for the LUISCompositeEntity class.
:param composite_entity: A dictionary containing the composite entity data.
'''
self._parent_type = composite_entity['parentType']
self._value = composite_entity['value']
self._composite_entity_children = []
for composite_entity_child in composite_entity['children']:
self._composite_entity_children.append(LUISCompositeEntityChild(composite_entity_child))
def get_parent_type(self):
'''
A getter for the composite entity's parent type.
:return: Composite Entity's parent type.
'''
return self._parent_type
def get_value(self):
'''
A getter for the composite entity's value.
:return: Composite Entity's value.
'''
return self._value
def get_children(self):
'''
A getter for the composite entity's children.
:return: Composite_Entity's children.
'''
return self._composite_entity_children

Просмотреть файл

@ -0,0 +1,60 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISCompositeEntityChild:
'''
LUIS Composite Entity Child Class.
Describes the LUIS Composite Entity Child structure.
'''
def __init__(self, composite_entity_child):
'''
A constructor for the LUISCompositeEntityChild class.
:param composite_entity: A dictionary containing the composite entity child data.
'''
self._type = composite_entity_child['type']
self._value = composite_entity_child['value']
def get_type(self):
'''
A getter for the composite entity child's type.
:return: Composite Entity Child's type.
'''
return self._type
def get_value(self):
'''
A getter for the composite entity child's value.
:return: Composite Entity Child's value.
'''
return self._value

Просмотреть файл

@ -0,0 +1,92 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISDialog(object):
'''
LUIS Dialog Class.
Describes the LUIS Action structure.
'''
def __init__(self, dialog):
'''
A constructor for the LUISDialog class.
:param action: A dictionary containing the dialog data.
'''
if u'prompt' in dialog:
self._prompt = dialog[u'prompt']
else:
self._prompt = None
if u'parameterName' in dialog:
self._parameter_name = dialog[u'parameterName']
else:
self._parameter_name = None
self._context_id = dialog[u'contextId']
self._status = dialog[u'status']
self._finished = self._status == u'Finished'
def get_prompt(self):
'''
A getter for the dialog's prompt.
:return: Dialog's prompt.
'''
return self._prompt
def get_parameter_name(self):
'''
A getter for the dialog's parameter name.
:return: Dialog's parameter name.
'''
return self._parameter_name
def get_context_id(self):
'''
A getter for the dialog's context Id.
:return: Dialog's prompt.
'''
return self._context_id
def get_status(self):
'''
A getter for the dialog's status.
:return: Dialog's status.
'''
return self._status
def is_finished(self):
'''
Checks whether the dialog has finished or not.
:return: A boolean that expresses whether the dialog has finished or not.
'''
return self._finished

Просмотреть файл

@ -0,0 +1,105 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISEntity(object):
'''
LUIS Entity Class.
Describes the LUIS Entity structure.
'''
def __init__(self, entity):
'''
A constructor for the LUISEntity class.
:param entity: A dictionary containing the entity data.
'''
self._name = entity[u'entity']
self._type = entity[u'type']
if u'startIndex' in entity:
self._start_idx = entity[u'startIndex']
else:
self._start_idx = None
if u'endIndex' in entity:
self._end_idx = entity[u'endIndex']
else:
self._end_idx = None
if u'score' in entity:
self._score = entity[u'score']
else:
self._score = None
if u'resolution' in entity:
self._resolution = entity[u'resolution']
else:
self._resolution = None
def get_name(self):
'''
A getter for the entity's name.
:return: Entity's name.
'''
return self._name
def get_type(self):
'''
A getter for the entity's type.
:return: Entity's type.
'''
return self._type
def get_start_idx(self):
'''
A getter for the entity's start index.
:return: Entity's start index.
'''
return self._start_idx
def get_end_idx(self):
'''
A getter for the entity's end index.
:return: Entity's end index.
'''
return self._end_idx
def get_score(self):
'''
A getter for the entity's score.
:return: Entity's score.
'''
return self._score
def get_resolution(self):
'''
A getter for the entity's resolution.
:return: Entity's resolution.
'''
return self._resolution

Просмотреть файл

@ -0,0 +1,75 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_action import LUISAction
class LUISIntent(object):
'''
LUIS Intent Class.
Describes the LUIS Intent structure.
'''
def __init__(self, intent):
'''
A constructor for the LUISIntent class.
:param intent: A dictionary containing the intent data.
'''
self._name = intent[u'intent']
self._score = intent[u'score']
self._actions = []
if u'actions' in intent:
for action in intent[u'actions']:
self._actions.append(LUISAction(action))
def get_name(self):
'''
A getter for the intent's name.
:return: Intent's name.
'''
return self._name
def get_score(self):
'''
A getter for the intent's score.
:return: Intent's score.
'''
return self._score
def get_actions(self):
'''
A getter for the entity's actions.
:return: A list of actions.
'''
return self._actions

Просмотреть файл

@ -0,0 +1,74 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_parametervalue import LUISParameterValue
import luis_parametervalue
class LUISParameter(object):
'''
LUIS Parameter Class.
Describes the LUIS Parameter structure.
'''
def __init__(self, parameter):
'''
A constructor for the LUISParameter class.
:param parameter: A dictionary containing the parameter data.
'''
self._name = parameter[u'name']
self._required = parameter[u'required']
self._parameter_values = []
if parameter[u'value']:
for parameter_value in parameter[u'value']:
self._parameter_values.append(LUISParameterValue(parameter_value))
def get_name(self):
'''
A getter for the parameter's name.
:return: Parameter's name.
'''
return self._name
def get_required(self):
'''
A getter for the parameter's required flag.
:return: A boolean that expresses whether the parameter is required or not.
'''
return self._required
def get_parameter_values(self):
'''
A getter for the parameters's values.
:return: A list of parameter values.
'''
return self._parameter_values

Просмотреть файл

@ -0,0 +1,82 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISParameterValue(object):
'''
LUIS Paramater Value Class.
Describes the LUIS Paramter Value structure.
'''
def __init__(self, parameter_value):
'''
A constructor for the LUISAction class.
:param parameter_value: A dictionary containing the parameter value data.
'''
self._name = parameter_value[u'entity']
self._type = parameter_value[u'type']
if u'score' in parameter_value:
self._score = parameter_value[u'score']
else:
self._score = None
if u'resolution' in parameter_value:
self._resolution = parameter_value[u'resolution']
else:
self._resolution = None
def get_name(self):
'''
A getter for the parameter value's name.
:return: Parameter value's name.
'''
return self._name
def get_type(self):
'''
A getter for the parameter value's type.
:return: Parameter values's type.
'''
return self._type
def get_score(self):
'''
A getter for the parameter value's score.
:return: Parameter values's score.
'''
return self._score
def get_resolution(self):
'''
A getter for the parameter value's resolution.
:return: Parameter value's resolution.
'''
return self._resolution

Просмотреть файл

@ -0,0 +1,132 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
import json
from .luis_intent import LUISIntent
from .luis_entity import LUISEntity
from .luis_composite_entity import LUISCompositeEntity
from .luis_dialog import LUISDialog
class LUISResponse(object):
'''
LUIS Response Class.
Describes the response structure, and is the main point
to access the response sent by LUIS after prediction.
'''
def __init__(self, JSONResponse):
'''
A constructor for the LUISResponse class.
:param JSONResponse: A string containing the incoming JSON.
'''
if JSONResponse is None:
raise TypeError(u'NULL JSON response')
if not JSONResponse:
raise ValueError(u'Invalid App Id')
if isinstance(JSONResponse, unicode):
try:
response = json.loads(JSONResponse)
except Exception:
raise Exception(u'Error in parsing json')
else:
response = JSONResponse
if u'statusCode' in response:
raise Exception(u'Invalid Subscription Key')
self._query = response[u'query']
if u'dialog' in response:
self._dialog = LUISDialog(response[u'dialog'])
else:
self._dialog = None
self._intents = []
self._entities = []
self._composite_entities = []
if u'topScoringIntent' in JSONResponse:
self._intents.append(LUISIntent(response[u'topScoringIntent']))
else:
for intent in response[u'intents']:
self._intents.append(LUISIntent(intent))
for entity in response[u'entities']:
self._entities.append(LUISEntity(entity))
if u'compositeEntities' in response:
for composite_entity in response[u'compositeEntities']:
self._composite_entities.append(LUISCompositeEntity(composite_entity))
def get_query(self):
'''
A getter for the response's query.
:return: Response's query.
'''
return self._query
def get_top_intent(self):
'''
A getter for the response's top scoring intent.
:return: Response's top scoring intent.
'''
return self._intents[0]
def get_intents(self):
'''
A getter for the response's intents.
:return: A list of intents.
'''
return self._intents
def get_entities(self):
'''
A getter for the response's entities.
:return: A list of entities.
'''
return self._entities
def get_composite_entities(self):
'''
A getter for the response's composite entities.
:return: A list of composite entities.
'''
return self._composite_entities
def get_dialog(self):
'''
A getter for the response's dialog.
:return: Response's dialog.
'''
return self._dialog

72
Python2/test_app.py Normal file
Просмотреть файл

@ -0,0 +1,72 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from luis_sdk import LUISClient
def process_res(res):
'''
A function that processes the luis_response object and prints info from it.
:param res: A LUISResponse object containing the response data.
:return: None
'''
print(u'---------------------------------------------')
print(u'LUIS Response: ')
print(u'Query: ' + res.get_query())
print(u'Top Scoring Intent: ' + res.get_top_intent().get_name())
if res.get_dialog() is not None:
if res.get_dialog().get_prompt() is None:
print(u'Dialog Prompt: None')
else:
print(u'Dialog Prompt: ' + res.get_dialog().get_prompt())
if res.get_dialog().get_parameter_name() is None:
print(u'Dialog Parameter: None')
else:
print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name())
print(u'Dialog Status: ' + res.get_dialog().get_status())
print(u'Entities:')
for entity in res.get_entities():
print(u'"%s":' % entity.get_name())
print(u'Type: %s, Score: %s' % (entity.get_type(), entity.get_score()))
try:
APPID = raw_input(u'Please enter your app Id:\n')
APPKEY = raw_input(u'Please input your subscription key:\n')
TEXT = raw_input(u'Please input the text to predict:\n')
CLIENT = LUISClient(APPID, APPKEY, True, True)
res = CLIENT.predict(TEXT)
while res.get_dialog() is not None and not res.get_dialog().is_finished():
TEXT = raw_input(u'%s\n'%res.get_dialog().get_prompt())
res = CLIENT.reply(TEXT,res)
process_res(res)
except Exception, exc:
print(exc)

79
Python2/test_app_async.py Normal file
Просмотреть файл

@ -0,0 +1,79 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from luis_sdk import LUISClient
def on_success(res):
'''
A callback function that processes the luis_response object
if the prediction succeeds.
:param res: a luis_response object containing the response data.
:return: None
'''
print(u'---------------------------------------------')
print(u'LUIS Response: ')
print(u'Query: ' + res.get_query())
print(u'Top Scoring Intent: ' + res.get_top_intent().get_name())
if res.get_dialog() is not None:
if res.get_dialog().get_prompt() is None:
print(u'Dialog Prompt: None')
else:
print(u'Dialog Prompt: ' + res.get_dialog().get_prompt())
if res.get_dialog().get_parameter_name() is None:
print(u'Dialog Parameter: None')
else:
print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name())
print(u'Dialog Status: ' + res.get_dialog().get_status())
print(u'Entities:')
for entity in res.get_entities():
print(u'"%s":' % entity.get_name())
print(u'Type: %s, Score: %s' % (entity.get_type(), entity.get_score()))
def on_failure(err):
'''
A callback function that processes the error object
if the prediction fails.
:param err: An Exception object.
:return: None
'''
print err
try:
APPID = raw_input(u'Please enter your app Id:\n')
APPKEY = raw_input(u'Please input your subscription key:\n')
TEXT = raw_input(u'Please input the text to predict:\n')
CLIENT = LUISClient(APPID, APPKEY, True, True)
CLIENT.predict(TEXT, {u'on_success': on_success, u'on_failure': on_failure})
print u'-------\nMain thread finishing!!\n-------'
except Exception, exc:
print exc

Просмотреть файл

@ -0,0 +1,34 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_client import LUISClient

Просмотреть файл

@ -0,0 +1,72 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_parameter import LUISParameter
class LUISAction:
'''
LUIS Action Class.
Describes the LUIS Action structure.
'''
def __init__(self, action):
'''
A constructor for the LUISAction class.
:param action: A dictionary containing the action data.
'''
self._name = action['name']
self._triggered = action['triggered']
self._parameters = []
for parameter in action['parameters']:
self._parameters.append(LUISParameter(parameter))
def get_name(self):
'''
A getter for the action's name.
:return: Actions's name.
'''
return self._name
def get_triggered(self):
'''
A getter for the action's triggered flag.
:return: A boolean that expresses whether the action was trigerred or not.
'''
return self._triggered
def get_parameters(self):
'''
A getter for the action's parameters.
:return: A list of parameter.
'''
return self._parameters

Просмотреть файл

@ -0,0 +1,241 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
import threading
from urllib.parse import quote
import http.client
from .luis_response import LUISResponse
class LUISClient:
'''
This is the interface of the LUIS
Constructs a LUISClient with the corresponding user's App Id and Subscription Keys
Starts the prediction procedure for the user's text, and accepts a callback function
'''
_LUISURL = 'api.projectoxford.ai'
_PredictMask = '/luis/v1/application%s?id=%s&subscription-key=%s&verbose=%s&q=%s'
_ReplyMask = '/luis/v1/application%s?id=%s&subscription-key=%s&contextid=%s&verbose=%s&q=%s'
def __init__(self, app_id, app_key, preview=False, verbose=False):
'''
A constructor for the LUISClient class.
:param app_id: A string containing the application id.
:param app_key: A string containing the subscription key.
:param preview: A boolean to indicate whether the preview version should used or not.
:param verbose: A boolean to indicate whether the verbose version should used or not.
'''
if app_id is None:
raise TypeError('NULL App Id')
if not app_id:
raise ValueError('Empty App Id')
if ' ' in app_id:
raise ValueError('Invalid App Id')
if app_key is None:
raise TypeError('NULL Subscription Key')
if not app_key:
raise ValueError('Empty Subscription Key')
if ' ' in app_key:
raise ValueError('Invalid Subscription Key')
self._app_id = app_id
self._app_key = app_key
self._preview = True if preview else False
self._preview_url = '/preview' if preview else ''
self._verbose_url = 'true' if verbose else 'false'
def predict(self, text, response_handlers=None, daemon=False):
'''
Routes the prediction routine to either sync or async
based on the presence or absence of a callback fucntion.
:param text: the text to be analysed and predicted.
:param response_handlers: a dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:param daemon: defines whether the new thread used for async will be daemon or not.
:return: LUISResponse if sync, thread object to give control over the thread if async.
'''
if text is None:
raise TypeError('NULL text to predict')
text = text.strip()
if not text:
raise ValueError('Empty text to predict')
if response_handlers is None:
return self.predict_sync(text)
else:
return self.predict_async(text, response_handlers, daemon)
def predict_sync(self, text):
'''
Predicts synchronously and returns a LUISResponse.
:param text: The text to be analysed and predicted.
:return: A LUISResponse object containing the response data.
'''
try:
conn = http.client.HTTPSConnection(self._LUISURL)
conn.request('GET', self._predict_url_gen(text))
res = conn.getresponse()
return LUISResponse(res.read().decode('UTF-8'))
except Exception:
raise
def predict_async(self, text, response_handlers, daemon):
'''
Predicts asynchronously and executes a callback function at the end.
:param text: The text to be analysed and predicted.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:param daemon: Defines whether the new thread will be daemon or not.
:return: A thread object to give control over the thread.
'''
if 'on_success' not in response_handlers:
raise KeyError('You have to specify the success handler with key: "on_success"')
if 'on_failure' not in response_handlers:
raise KeyError('You have to specify the failure handler with key: "on_failure"')
predict_thread = threading.Thread(target=self._predict_async_helper
, args=(text, response_handlers))
predict_thread.daemon = daemon
predict_thread.start()
return predict_thread
def _predict_url_gen(self, text):
'''
Returns the suitable LUIS API predict url.
:param text: The text to be analysed and predicted.
:return: LUIS API predicton url.
'''
return self._PredictMask%(self._preview_url, self._app_id, self._app_key
, self._verbose_url, quote(text))
def _predict_async_helper(self, text, response_handlers):
'''
A wrapper function to be executed asynchronously in an external thread.
It executes the predict routine and then executes a callback function.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse that contains the context Id.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:return: None.
'''
res = None
try:
res = self.predict_sync(text)
except Exception as exc:
response_handlers['on_failure'](exc)
return
response_handlers['on_success'](res)
def reply(self, text, response, response_handlers=None, daemon=False):
'''
Routes the reply routine to either sync or async
based on the presence or absence of a callback fucntion.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse that contains the context Id.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions
to be executed if async.
:param daemon: Defines whether the new thread used for async will be daemon or not.
:return: A LUISResponse object if sync, a thread object to control the thread if async.
'''
if text is None:
raise TypeError('NULL text to predict')
text = text.strip()
if not text:
raise ValueError('Empty text to predict')
if not self._preview:
raise Exception("Can't use reply unless in the preview mode")
if response_handlers is None:
return self.reply_sync(text, response)
else:
return self.reply_async(text, response, response_handlers, daemon)
def reply_sync(self, text, response):
'''
Replies synchronously and returns a LUISResponse object.
:param text: The text to be analysed and predicted.
:return: A LUISResponse object containg the response data.
'''
try:
conn = http.client.HTTPSConnection(self._LUISURL)
conn.request('GET', self._reply_url_gen(text, response))
res = conn.getresponse()
return LUISResponse(res.read().decode('UTF-8'))
except Exception:
raise
def reply_async(self, text, response, response_handlers, daemon):
'''
Predicts asynchronously and executes a callback function at the end.
:param text: The text to be analysed and predicted.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions
to be executed if async.
:param daemon: Defines whether the new thread used will be daemon or not.
:return: A thread object to give control over the thread.
'''
if 'on_success' not in response_handlers:
raise KeyError('You have to specify the success handler with key: "on_success"')
if 'on_failure' not in response_handlers:
raise KeyError('You have to specify the failure handler with key: "on_failure"')
reply_thread = threading.Thread(target=self._reply_async_helper
, args=(text, response, response_handlers))
reply_thread.daemon = daemon
reply_thread.start()
return reply_thread
def _reply_url_gen(self, text, response):
'''
Generates the suitable LUIS API reply url.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse object that contains the context Id.
:return: LUIS API reply url.
'''
return self._ReplyMask%(self._preview_url, self._app_id, self._app_key
, response.get_dialog().get_context_id()
, self._verbose_url, quote(text))
def _reply_async_helper(self, text, response, response_handlers):
'''
A wrapper function to be executed asynchronously in an external thread.
It executes the reply routine and then executes a callback function.
:param text: The text to be analysed and predicted.
:param response: A LUISResponse object that contains the context Id.
:param response_handlers: A dictionary that contains two keys on_success and on_failure,
whose values are two functions to be executed if async.
:return: None.
'''
res = None
try:
res = self.reply_sync(text, response)
except Exception as exc:
response_handlers['on_failure'](exc)
return
response_handlers['on_success'](res)

Просмотреть файл

@ -0,0 +1,72 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_composite_entity_child import LUISCompositeEntityChild
class LUISCompositeEntity:
'''
LUIS Composite Entity Class.
Describes the LUIS Composite Entity structure.
'''
def __init__(self, composite_entity):
'''
A constructor for the LUISCompositeEntity class.
:param composite_entity: A dictionary containing the composite entity data.
'''
self._parent_type = composite_entity['parentType']
self._value = composite_entity['value']
self._composite_entity_children = []
for composite_entity_child in composite_entity['children']:
self._composite_entity_children.append(LUISCompositeEntityChild(composite_entity_child))
def get_parent_type(self):
'''
A getter for the composite entity's parent type.
:return: Composite Entity's parent type.
'''
return self._parent_type
def get_value(self):
'''
A getter for the composite entity's value.
:return: Composite Entity's value.
'''
return self._value
def get_children(self):
'''
A getter for the composite entity's children.
:return: Composite_Entity's children.
'''
return self._composite_entity_children

Просмотреть файл

@ -0,0 +1,60 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISCompositeEntityChild:
'''
LUIS Composite Entity Child Class.
Describes the LUIS Composite Entity Child structure.
'''
def __init__(self, composite_entity_child):
'''
A constructor for the LUISCompositeEntityChild class.
:param composite_entity: A dictionary containing the composite entity child data.
'''
self._type = composite_entity_child['type']
self._value = composite_entity_child['value']
def get_type(self):
'''
A getter for the composite entity child's type.
:return: Composite Entity Child's type.
'''
return self._type
def get_value(self):
'''
A getter for the composite entity child's value.
:return: Composite Entity Child's value.
'''
return self._value

Просмотреть файл

@ -0,0 +1,92 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISDialog:
'''
LUIS Dialog Class.
Describes the LUIS Action structure.
'''
def __init__(self, dialog):
'''
A constructor for the LUISDialog class.
:param action: A dictionary containing the dialog data.
'''
if 'prompt' in dialog:
self._prompt = dialog['prompt']
else:
self._prompt = None
if 'parameterName' in dialog:
self._parameter_name = dialog['parameterName']
else:
self._parameter_name = None
self._context_id = dialog['contextId']
self._status = dialog['status']
self._finished = self._status == 'Finished'
def get_prompt(self):
'''
A getter for the dialog's prompt.
:return: Dialog's prompt.
'''
return self._prompt
def get_parameter_name(self):
'''
A getter for the dialog's parameter name.
:return: Dialog's parameter name.
'''
return self._parameter_name
def get_context_id(self):
'''
A getter for the dialog's context Id.
:return: Dialog's prompt.
'''
return self._context_id
def get_status(self):
'''
A getter for the dialog's status.
:return: Dialog's status.
'''
return self._status
def is_finished(self):
'''
Checks whether the dialog has finished or not.
:return: A boolean that expresses whether the dialog has finished or not.
'''
return self._finished

Просмотреть файл

@ -0,0 +1,104 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISEntity:
'''
LUIS Entity Class.
Describes the LUIS Entity structure.
'''
def __init__(self, entity):
'''
A constructor for the LUISEntity class.
:param entity: A dictionary containing the entity data.
'''
self._name = entity['entity']
self._type = entity['type']
if 'startIndex' in entity:
self._start_idx = entity['startIndex']
else:
self._start_idx = None
if 'endIndex' in entity:
self._end_idx = entity['endIndex']
else:
self._end_idx = None
if 'score' in entity:
self._score = entity['score']
else:
self._score = None
if 'resolution' in entity:
self._resolution = entity['resolution']
else:
self._resolution = None
def get_name(self):
'''
A getter for the entity's name.
:return: Entity's name.
'''
return self._name
def get_type(self):
'''
A getter for the entity's type.
:return: Entity's type.
'''
return self._type
def get_start_idx(self):
'''
A getter for the entity's start index.
:return: Entity's start index.
'''
return self._start_idx
def get_end_idx(self):
'''
A getter for the entity's end index.
:return: Entity's end index.
'''
return self._end_idx
def get_score(self):
'''
A getter for the entity's score.
:return: Entity's score.
'''
return self._score
def get_resolution(self):
'''
A getter for the entity's resolution.
:return: Entity's resolution.
'''
return self._resolution

Просмотреть файл

@ -0,0 +1,75 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_action import LUISAction
class LUISIntent:
'''
LUIS Intent Class.
Describes the LUIS Intent structure.
'''
def __init__(self, intent):
'''
LUIS Intent Class.
Describes the LUIS Intent structure.
'''
self._name = intent['intent']
self._score = intent['score']
self._actions = []
if 'actions' in intent:
for action in intent['actions']:
self._actions.append(LUISAction(action))
def get_name(self):
'''
A getter for the intent's name.
:return: Intent's name.
'''
return self._name
def get_score(self):
'''
A getter for the intent's score.
:return: Intent's score.
'''
return self._score
def get_actions(self):
'''
A getter for the entity's actions.
:return: A list of actions.
'''
return self._actions

Просмотреть файл

@ -0,0 +1,73 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from .luis_parametervalue import LUISParameterValue
class LUISParameter:
'''
LUIS Parameter Class.
Describes the LUIS Parameter structure.
'''
def __init__(self, parameter):
'''
A constructor for the LUISParameter class.
:param parameter: A dictionary containing the parameter data.
'''
self._name = parameter['name']
self._required = parameter['required']
self._parameter_values = []
if parameter['value']:
for parameter_value in parameter['value']:
self._parameter_values.append(LUISParameterValue(parameter_value))
def get_name(self):
'''
A getter for the parameter's name.
:return: Parameter's name.
'''
return self._name
def get_required(self):
'''
A getter for the parameter's required flag.
:return: A boolean that expresses whether the parameter is required or not.
'''
return self._required
def get_parameter_values(self):
'''
A getter for the parameters's values.
:return: A list of parameter values.
'''
return self._parameter_values

Просмотреть файл

@ -0,0 +1,83 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
class LUISParameterValue:
'''
LUIS Paramater Value Class.
Describes the LUIS Paramter Value structure.
'''
def __init__(self, parameter_value):
'''
A constructor for the LUISAction class.
:param parameter_value: A dictionary containing the parameter value data.
'''
self._name = parameter_value['entity']
self._type = parameter_value['type']
if 'score' in parameter_value:
self._score = parameter_value['score']
else:
self._score = None
if 'resolution' in parameter_value:
self._resolution = parameter_value['resolution']
else:
self._resolution = None
def get_name(self):
'''
A getter for the parameter value's name.
:return: Parameter value's name.
'''
return self._name
def get_type(self):
'''
A getter for the parameter value's type.
:return: Parameter value's type.
'''
return self._type
def get_score(self):
'''
A getter for the parameter value's score.
:return: Parameter value's score.
'''
return self._score
def get_resolution(self):
'''
A getter for the parameter value's resolution.
:return: Parameter value's resolution.
'''
return self._resolution

Просмотреть файл

@ -0,0 +1,132 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
import json
from .luis_intent import LUISIntent
from .luis_entity import LUISEntity
from .luis_composite_entity import LUISCompositeEntity
from .luis_dialog import LUISDialog
class LUISResponse:
'''
LUIS Response Class.
Describes the response structure, and is the main point
to access the response sent by LUIS after prediction.
'''
def __init__(self, JSONResponse):
'''
A constructor for the LUISResponse class.
:param JSONResponse: A string containing the incoming JSON.
'''
if JSONResponse is None:
raise TypeError('NULL JSON response')
if not JSONResponse:
raise ValueError('Invalid App Id')
if isinstance(JSONResponse, str):
try:
response = json.loads(JSONResponse)
except Exception:
raise Exception('Error in parsing json')
else:
response = JSONResponse
if 'statusCode' in response:
raise Exception(u'Invalid Subscription Key')
self._query = response['query']
if 'dialog' in response:
self._dialog = LUISDialog(response['dialog'])
else:
self._dialog = None
self._intents = []
self._entities = []
self._composite_entities = []
if 'topScoringIntent' in response:
self._intents.append(LUISIntent(response['topScoringIntent']))
else:
for intent in response['intents']:
self._intents.append(LUISIntent(intent))
for entity in response['entities']:
self._entities.append(LUISEntity(entity))
if 'compositeEntities' in response:
for composite_entity in response['compositeEntities']:
self._composite_entities.append(LUISCompositeEntity(composite_entity))
def get_query(self):
'''
A getter for the response's query.
:return: Response's query.
'''
return self._query
def get_top_intent(self):
'''
A getter for the response's top scoring intent.
:return: Response's top scoring intent.
'''
return self._intents[0]
def get_intents(self):
'''
A getter for the response's intents.
:return: A list of intents.
'''
return self._intents
def get_entities(self):
'''
A getter for the response's entities.
:return: A list of entities.
'''
return self._entities
def get_composite_entities(self):
'''
A getter for the response's composite entities.
:return: A list of composite entities.
'''
return self._composite_entities
def get_dialog(self):
'''
A getter for the response's dialog.
:return: Response's dialog.
'''
return self._dialog

72
Python3/test_app.py Normal file
Просмотреть файл

@ -0,0 +1,72 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from luis_sdk import LUISClient
def process_res(res):
'''
A function that processes the luis_response object and prints info from it.
:param res: A LUISResponse object containing the response data.
:return: None
'''
print('---------------------------------------------')
print('LUIS Response: ')
print('Query: ' + res.get_query())
print('Top Scoring Intent: ' + res.get_top_intent().get_name())
if res.get_dialog() is not None:
if res.get_dialog().get_prompt() is None:
print('Dialog Prompt: None')
else:
print('Dialog Prompt: ' + res.get_dialog().get_prompt())
if res.get_dialog().get_parameter_name() is None:
print('Dialog Parameter: None')
else:
print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name())
print('Dialog Status: ' + res.get_dialog().get_status())
print('Entities:')
for entity in res.get_entities():
print('"%s":' % entity.get_name())
print('Type: %s, Score: %s' % (entity.get_type(), entity.get_score()))
try:
APPID = input('Please enter your app Id:\n')
APPKEY = input('Please input your subscription key:\n')
TEXT = input('Please input the text to predict:\n')
CLIENT = LUISClient(APPID, APPKEY, True, True)
res = CLIENT.predict(TEXT)
while res.get_dialog() is not None and not res.get_dialog().is_finished():
TEXT = input('%s\n'%res.get_dialog().get_prompt())
res = CLIENT.reply(TEXT,res)
process_res(res)
except Exception as exc:
raise exc

79
Python3/test_app_async.py Normal file
Просмотреть файл

@ -0,0 +1,79 @@
'''
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license.
Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
Microsoft Cognitive Services (formerly Project Oxford) GitHub:
https://github.com/Microsoft/ProjectOxford-ClientSDK
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
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.
'''
from luis_sdk import LUISClient
def on_success(res):
'''
A callback function that processes the luis_response object
if the prediction succeeds.
:param res: a luis_response object containing the response data.
:return: None
'''
print('---------------------------------------------')
print('LUIS Response: ')
print('Query: ' + res.get_query())
print('Top Scoring Intent: ' + res.get_top_intent().get_name())
if res.get_dialog() is not None:
if res.get_dialog().get_prompt() is None:
print('Dialog Prompt: None')
else:
print('Dialog Prompt: ' + res.get_dialog().get_prompt())
if res.get_dialog().get_parameter_name() is None:
print('Dialog Parameter: None')
else:
print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name())
print('Dialog Status: ' + res.get_dialog().get_status())
print('Entities:')
for entity in res.get_entities():
print('"%s":' % entity.get_name())
print('Type: %s, Score: %s' % (entity.get_type(), entity.get_score()))
def on_failure(err):
'''
A callback function that processes the error object
if the prediction fails.
:param err: An Exception object.
:return: None
'''
print(err)
try:
APPID = input('Please enter your app Id:\n')
APPKEY = input('Please input your subscription key:\n')
TEXT = input('Please input the text to predict:\n')
CLIENT = LUISClient(APPID, APPKEY, True, True)
CLIENT.predict(TEXT, {'on_success': on_success, 'on_failure': on_failure})
print('-------\nMain thread finishing!!\n-------')
except Exception as exc:
print(exc)

Просмотреть файл

@ -1,2 +1,26 @@
# Cognitive-LUIS-Python
Python SDK for the Microsoft Language Understanding Intelligent Service API, part of Congitive Services
LUIS
==============
LUIS is a service for language understanding that provides intent classification and entity extraction.
In order to use the SDK you first need to create and publish an app on www.luis.ai where you will get your appID and appKey and input their values when prompted by the sample applications.
The SDK
--------------
The SDK can be used in 2 different ways with a separate sample for each way.
- One way to use it is synchronously by calling the functions "predict" and "reply" that are present in the "LUISClient" and receiving the response as a returned object from the class "LUISResponse".
- Another way is asynchronously by creating 2 callback functions "on_success" and "on_failure" and passing them to the "predict" and "reply" functions to be called asynchronously in the cases of the request success or failure.
Sample Application
--------------
The sample application allows you to perform the Predict and Reply operations and to view the following parts of the parsed response:
- Query
- Top Intent
- Dialog prompt, parameter name, and status
- Entities
License
=======
All Microsoft Cognitive Services SDKs and samples are licensed with the MIT License. For more details, see
[LICENSE](</LICENSE.md>).

20
setup.py Normal file
Просмотреть файл

@ -0,0 +1,20 @@
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
pkgdir = {'': 'python%s' % sys.version_info[0]}
VERSION = '0.1'
setup(name='cognitive_luis',
version=VERSION,
description='LUIS SDK for python',
url='https://github.com/Microsoft/Cognitive-LUIS-Python',
author='Ahmed El-Hinidy',
author_email='t-ahelhi@microsoft.com',
license='MIT',
package_dir=pkgdir,
packages=['luis_sdk'],
zip_safe=False
)