diff --git a/dialogflow/cloud-client/README.rst b/dialogflow/cloud-client/README.rst new file mode 100644 index 000000000000..bcbe73777cf9 --- /dev/null +++ b/dialogflow/cloud-client/README.rst @@ -0,0 +1,632 @@ +.. This file is automatically generated. Do not edit this file directly. + +Dialogflow Enterprise Edition API Python Samples +=============================================================================== + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/README.rst + + +This directory contains samples for Dialogflow Enterprise Edition API. The `Dialogflow Enterprise Edition API`_ enables you to create conversational experiences across devices and platforms. + + + + +.. _Dialogflow Enterprise Edition API: https://cloud.google.com/dialogflow-enterprise/docs/ + +Setup +------------------------------------------------------------------------------- + + +Authentication +++++++++++++++ + +This sample requires you to have authentication setup. Refer to the +`Authentication Getting Started Guide`_ for instructions on setting up +credentials for applications. + +.. _Authentication Getting Started Guide: + https://cloud.google.com/docs/authentication/getting-started + +Install Dependencies +++++++++++++++++++++ + +#. Clone the repository and change directory to the sample directory. + + .. code-block:: bash + + $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + +#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. + + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup + +#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. + + .. code-block:: bash + + $ virtualenv env + $ source env/bin/activate + +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt + +.. _pip: https://pip.pypa.io/ +.. _virtualenv: https://virtualenv.pypa.io/ + +Samples +------------------------------------------------------------------------------- + +Detect Intent Text ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_texts.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_texts.py + + usage: detect_intent_texts.py [-h] --project-id PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + texts [texts ...] + + DialogFlow API Detect Intent Python sample with text inputs. + + Examples: + python detect_intent_texts.py -h + python detect_intent_texts.py --project-id PROJECT_ID --session-id SESSION_ID "hello" "book a meeting room" "Mountain View" + python detect_intent_texts.py --project-id PROJECT_ID --session-id SESSION_ID "tomorrow" "10 AM" "2 hours" "10 people" "A" "yes" + + positional arguments: + texts Text inputs. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + Identifier of the DetectIntent session. Defaults to a + random UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + + + +Detect Intent Audio ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_audio.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_audio.py + + usage: detect_intent_audio.py [-h] --project-id PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + --audio-file-path AUDIO_FILE_PATH + + DialogFlow API Detect Intent Python sample with audio file. + + Examples: + python detect_intent_audio.py -h + python detect_intent_audio.py --project-id PROJECT_ID --session-id SESSION_ID --audio-file-path resources/book_a_room.wav + python detect_intent_audio.py --project-id PROJECT_ID --session-id SESSION_ID --audio-file-path resources/mountain_view.wav + python detect_intent_audio.py --project-id PROJECT_ID --session-id SESSION_ID --audio-file-path resources/today.wav + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + Identifier of the DetectIntent session. Defaults to a + random UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + --audio-file-path AUDIO_FILE_PATH + Path to the audio file. + + + +Detect Intent Stream ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_stream.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_stream.py + + usage: detect_intent_stream.py [-h] --project-id PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + --audio-file-path AUDIO_FILE_PATH + + DialogFlow API Detect Intent Python sample with audio files processed + as an audio stream. + + Examples: + python detect_intent_stream.py -h + python detect_intent_stream.py --project-id PROJECT_ID --session-id SESSION_ID --audio-file-path resources/book_a_room.wav + python detect_intent_stream.py --project-id PROJECT_ID --session-id SESSION_ID --audio-file-path resources/mountain_view.wav + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + Identifier of the DetectIntent session. Defaults to a + random UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + --audio-file-path AUDIO_FILE_PATH + Path to the audio file. + + + +Detect Intent Knowledge Base ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_knowledge.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_knowledge.py + + usage: detect_intent_knowledge.py [-h] --project-id PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + --knowledge-base-id KNOWLEDGE_ID + texts [texts ...] + + Dialogflow API Detect Intent Python sample with text inputs. + + Examples: + python detect_intent_knowledge.py -h + python detect_intent_knowledge.py --project-id PROJECT_ID --session-id SESSION_ID --knowledge-base-id KNOWLEDGE_ID "hello" "how do I reset my password?" + + positional arguments: + texts Text inputs. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + ID of the DetectIntent session. Defaults to a random + UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + --knowledge-base-id KNOWLEDGE_ID + The id of the Knowledge Base to query against, e.g., OTE5NjYzMTkxNDA2NzI2MzQ4OA + + + +Detect Intent with Model Selection ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_with_model_selection.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_with_model_selection.py + + usage: detect_intent_with_model_selection.py [-h] --project-id PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + --audio-file-path AUDIO_FILE_PATH + + Dialogflow API Beta Detect Intent Python sample with model selection. + + Examples: + python detect_intent_with_model_selection.py -h + python detect_intent_with_model_selection.py --project-id PROJECT_ID --session-id SESSION_ID --audio-file-path resources/book_a_room.wav + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + Identifier of the DetectIntent session. Defaults to a + random UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + --audio-file-path AUDIO_FILE_PATH + Path to the audio file. + + + +Detect Intent with Sentiment Analysis ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_with_sentiment_analysis.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_with_sentiment_analysis.py + + usage: detect_intent_with_sentiment_analysis.py [-h] --project-id PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + texts [texts ...] + + Dialogflow API Beta Detect Intent Python sample with sentiment analysis. + + Examples: + python detect_intent_with_sentiment_analysis.py -h + python detect_intent_with_sentiment_analysis.py --project-id PROJECT_ID --session-id SESSION_ID "hello" "book a meeting room" "Mountain View" + + positional arguments: + texts Text inputs. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + Identifier of the DetectIntent session. Defaults to a + random UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + + + +Detect Intent with Text to Speech Response ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/detect_intent_with_texttospeech_response.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python detect_intent_with_texttospeech_response.py + + usage: detect_intent_with_texttospeech_response.py [-h] --project-id + PROJECT_ID + [--session-id SESSION_ID] + [--language-code LANGUAGE_CODE] + texts [texts ...] + + Dialogflow API Beta Detect Intent Python sample with an audio response. + + Examples: + python detect_intent_with_texttospeech_response.py -h + python detect_intent_with_texttospeech_response.py --project-id PROJECT_ID --session-id SESSION_ID "hello" + + positional arguments: + texts Text inputs. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + --session-id SESSION_ID + Identifier of the DetectIntent session. Defaults to a + random UUID. + --language-code LANGUAGE_CODE + Language code of the query. Defaults to "en-US". + + + +Intent Management ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/intent_management.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python intent_management.py + + usage: intent_management.py [-h] --project-id PROJECT_ID + {list,create,delete} ... + + DialogFlow API Intent Python sample showing how to manage intents. + + Examples: + python intent_management.py -h + python intent_management.py --project-id PROJECT_ID list + python intent_management.py --project-id PROJECT_ID create "room.cancellation - yes" --training-phrases-parts "cancel" "cancellation" --message-texts "Are you sure you want to cancel?" "Cancelled." + python intent_management.py --project-id PROJECT_ID delete 74892d81-7901-496a-bb0a-c769eda5180e + + positional arguments: + {list,create,delete} + list + create Create an intent of the given intent type. + delete Delete intent with the given intent type and intent + value. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + + + +Entity Type Management ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/entity_type_management.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python entity_type_management.py + + usage: entity_type_management.py [-h] --project-id PROJECT_ID + {list,create,delete} ... + + DialogFlow API EntityType Python sample showing how to manage entity types. + + Examples: + python entity_type_management.py -h + python entity_type_management.py --project-id PROJECT_ID list + python entity_type_management.py --project-id PROJECT_ID create employee + python entity_type_management.py --project-id PROJECT_ID delete e57238e2-e692-44ea-9216-6be1b2332e2a + + positional arguments: + {list,create,delete} + list + create Create an entity type with the given display name. + delete Delete entity type with the given entity type name. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + + + +Entity Management ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/entity_management.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python entity_management.py + + usage: entity_management.py [-h] --project-id PROJECT_ID + {list,create,delete} ... + + DialogFlow API Entity Python sample showing how to manage entities. + + Examples: + python entity_management.py -h + python entity_management.py --project-id PROJECT_ID list --entity-type-id e57238e2-e692-44ea-9216-6be1b2332e2a + python entity_management.py --project-id PROJECT_ID create new_room --synonyms basement cellar --entity-type-id e57238e2-e692-44ea-9216-6be1b2332e2a + python entity_management.py --project-id PROJECT_ID delete new_room --entity-type-id e57238e2-e692-44ea-9216-6be1b2332e2a + + positional arguments: + {list,create,delete} + list + create Create an entity of the given entity type. + delete Delete entity with the given entity type and entity + value. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + + + +Session Entity Type Management ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/session_entity_type_management.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python session_entity_type_management.py + + usage: session_entity_type_management.py [-h] --project-id PROJECT_ID + {list,create,delete} ... + + DialogFlow API SessionEntityType Python sample showing how to manage + session entity types. + + Examples: + python session_entity_type_management.py -h + python session_entity_type_management.py --project-id PROJECT_ID list --session-id SESSION_ID + python session_entity_type_management.py --project-id PROJECT_ID create --session-id SESSION_ID --entity-type-display-name room --entity-values C D E F + python session_entity_type_management.py --project-id PROJECT_ID delete --session-id SESSION_ID --entity-type-display-name room + + positional arguments: + {list,create,delete} + list + create Create a session entity type with the given display + name. + delete Delete session entity type with the given entity type + display name. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. Required. + + + +Knowledge Base Management ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/knowledge_base_management.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python knowledge_base_management.py + + usage: knowledge_base_management.py [-h] --project-id PROJECT_ID + {list,create,get,delete} ... + + Dialogflow API Python sample showing how to manage Knowledge bases. + + Examples: + python knowledge_base_management.py -h + python knowledge_base_management.py --project-id PROJECT_ID list + python knowledge_base_management.py --project-id PROJECT_ID create --display-name DISPLAY_NAME + python knowledge_base_management.py --project-id PROJECT_ID get --knowledge-base-id knowledge_base_id + python knowledge_base_management.py --project-id PROJECT_ID delete --knowledge-base-id knowledge_base_id + + positional arguments: + {list,create,get,delete} + list List all Knowledge bases that belong to the project. + create Create a new Knowledge base. + get Get a Knowledge base by its id. + delete Delete a Knowledge base by its id. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project/agent id. + + + +Document Management ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/document_management.py,/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python document_management.py + + usage: document_management.py [-h] --project-id PROJECT_ID --knowledge-base-id + KNOWLEDGE_BASE_ID + {list,create,get,delete} ... + + Dialogflow API Python sample showing how to manage Knowledge Documents. + + Examples: + python document_management.py -h + python document_management.py --project-id PROJECT_ID --knowledge-base-id knowledge_base_id list + python document_management.py --project-id PROJECT_ID --knowledge-base-id knowledge_base_id create --display-name DISPLAY_NAME --mime-type MIME_TYPE --knowledge-type KNOWLEDGE_TYPE --content-uri CONTENT_URI + python document_management.py --project-id PROJECT_ID --knowledge-base-id knowledge_base_id get --document-id DOCUMENT_ID + python document_management.py --project-id PROJECT_ID --knowledge-base-id knowledge_base_id delete --document-id DOCUMENT_ID + + positional arguments: + {list,create,get,delete} + list List all Documents that belong to a certain Knowledge + base. + create Create a Document for a certain Knowledge base. Please note that it will be initially disabled until you enable it. + get Get a Document by its id and the Knowledge base id. + delete Delete a Document by its id and the Knowledge baseid. + + optional arguments: + -h, --help show this help message and exit + --project-id PROJECT_ID + Project id. Required. + --knowledge-base-id KNOWLEDGE_BASE_ID + The id of the Knowledge Base that the Document belongs + to, e.g., OTE5NjYzMTkxNDA2NzI2MzQ4OA + --mime_type The mime_type of the Document. e.g. text/csv, text/html, + text/plain, text/pdf etc. + + --knowledge_type The Knowledge type of the Document. e.g. FAQ, EXTRACTIVE_QA. + + --content_uri Uri of the document, e.g. gs://path/mydoc.csv, + http://mypage.com/faq.html. + + + + + + + + +The client library +------------------------------------------------------------------------------- + +This sample uses the `Google Cloud Client Library for Python`_. +You can read the documentation for more details on API usage and use GitHub +to `browse the source`_ and `report issues`_. + +.. _Google Cloud Client Library for Python: + https://googlecloudplatform.github.io/google-cloud-python/ +.. _browse the source: + https://github.com/GoogleCloudPlatform/google-cloud-python +.. _report issues: + https://github.com/GoogleCloudPlatform/google-cloud-python/issues + + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ diff --git a/dialogflow/cloud-client/README.rst.in b/dialogflow/cloud-client/README.rst.in new file mode 100644 index 000000000000..250055c43d69 --- /dev/null +++ b/dialogflow/cloud-client/README.rst.in @@ -0,0 +1,55 @@ +# This file is used to generate README.rst + +product: + name: Dialogflow Enterprise Edition API + short_name: Dialogflow API + url: https://cloud.google.com/dialogflow-enterprise/docs/ + description: > + The `Dialogflow Enterprise Edition API`_ enables you to create conversational experiences across devices and platforms. + +setup: +- auth +- install_deps + +samples: +- name: Detect Intent Text + file: detect_intent_texts.py + show_help: True +- name: Detect Intent Audio + file: detect_intent_audio.py + show_help: True +- name: Detect Intent Stream + file: detect_intent_stream.py + show_help: True +- name: Detect Intent Knowledge Base + file: detect_intent_knowledge.py + show_help: True +- name: Detect Intent with Model Selection + file: detect_intent_with_model_selection.py + show_help: True +- name: Detect Intent with Sentiment Analysis + file: detect_intent_with_sentiment_analysis.py + show_help: True +- name: Detect Intent with Text to Speech Response + file: detect_intent_with_texttospeech_response.py + show_help: True +- name: Intent Management + file: intent_management.py + show_help: True +- name: Entity Type Management + file: entity_type_management.py + show_help: True +- name: Entity Management + file: entity_management.py + show_help: True +- name: Session Entity Type Management + file: session_entity_type_management.py + show_help: True +- name: Knowledge Base Management + file: knowledge_base_management.py + show_help: True +- name: Document Management + file: document_management.py + show_help: True + +cloud_client_library: true diff --git a/dialogflow/cloud-client/context_management.py b/dialogflow/cloud-client/context_management.py new file mode 100644 index 000000000000..d2a75bd711ad --- /dev/null +++ b/dialogflow/cloud-client/context_management.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API Context Python sample showing how to manage session +contexts. + +Examples: + python context_management.py -h + python context_management.py --project-id PROJECT_ID \ + list --session-id SESSION_ID + python context_management.py --project-id PROJECT_ID \ + create --session-id SESSION_ID --context-id CONTEXT_ID + python context_management.py --project-id PROJECT_ID \ + delete --session-id SESSION_ID --context-id CONTEXT_ID +""" + +import argparse + + +# [START dialogflow_list_contexts] +def list_contexts(project_id, session_id): + import dialogflow_v2 as dialogflow + contexts_client = dialogflow.ContextsClient() + + session_path = contexts_client.session_path(project_id, session_id) + + contexts = contexts_client.list_contexts(session_path) + + print('Contexts for session {}:\n'.format(session_path)) + for context in contexts: + print('Context name: {}'.format(context.name)) + print('Lifespan count: {}'.format(context.lifespan_count)) + print('Fields:') + for field, value in context.parameters.fields.items(): + if value.string_value: + print('\t{}: {}'.format(field, value)) +# [END dialogflow_list_contexts] + + +# [START dialogflow_create_context] +def create_context(project_id, session_id, context_id, lifespan_count): + import dialogflow_v2 as dialogflow + contexts_client = dialogflow.ContextsClient() + + session_path = contexts_client.session_path(project_id, session_id) + context_name = contexts_client.context_path( + project_id, session_id, context_id) + + context = dialogflow.types.Context( + name=context_name, lifespan_count=lifespan_count) + + response = contexts_client.create_context(session_path, context) + + print('Context created: \n{}'.format(response)) +# [END dialogflow_create_context] + + +# [START dialogflow_delete_context] +def delete_context(project_id, session_id, context_id): + import dialogflow_v2 as dialogflow + contexts_client = dialogflow.ContextsClient() + + context_name = contexts_client.context_path( + project_id, session_id, context_id) + + contexts_client.delete_context(context_name) +# [END dialogflow_delete_context] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', help=list_contexts.__doc__) + list_parser.add_argument( + '--session-id', + required=True) + + create_parser = subparsers.add_parser( + 'create', help=create_context.__doc__) + create_parser.add_argument( + '--session-id', + required=True) + create_parser.add_argument( + '--context-id', + help='The id of the context.', + required=True) + create_parser.add_argument( + '--lifespan-count', + help='The lifespan_count of the context. Defaults to 1.', + default=1) + + delete_parser = subparsers.add_parser( + 'delete', help=delete_context.__doc__) + delete_parser.add_argument( + '--session-id', + required=True) + delete_parser.add_argument( + '--context-id', + help='The id of the context.', + required=True) + + args = parser.parse_args() + + if args.command == 'list': + list_contexts(args.project_id, args.session_id, ) + elif args.command == 'create': + create_context( + args.project_id, args.session_id, args.context_id, + args.lifespan_count) + elif args.command == 'delete': + delete_context(args.project_id, args.session_id, args.context_id) diff --git a/dialogflow/cloud-client/context_management_test.py b/dialogflow/cloud-client/context_management_test.py new file mode 100644 index 000000000000..8460a9c65fb3 --- /dev/null +++ b/dialogflow/cloud-client/context_management_test.py @@ -0,0 +1,44 @@ +# Copyright 2017 Google LLC +# +# 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 absolute_import + +import os + +import context_management +import detect_intent_texts + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +CONTEXT_ID = 'fake_context_for_testing' + + +def test_create_context(capsys): + # Calling detect intent to create a session. + detect_intent_texts.detect_intent_texts( + PROJECT_ID, SESSION_ID, ['hi'], 'en-US') + + context_management.create_context(PROJECT_ID, SESSION_ID, CONTEXT_ID, 1) + context_management.list_contexts(PROJECT_ID, SESSION_ID) + + out, _ = capsys.readouterr() + assert CONTEXT_ID in out + + +def test_delete_context(capsys): + context_management.delete_context(PROJECT_ID, SESSION_ID, CONTEXT_ID) + context_management.list_contexts(PROJECT_ID, SESSION_ID) + + out, _ = capsys.readouterr() + assert CONTEXT_ID not in out diff --git a/dialogflow/cloud-client/detect_intent_audio.py b/dialogflow/cloud-client/detect_intent_audio.py new file mode 100644 index 000000000000..7dcef341a8a6 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_audio.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API Detect Intent Python sample with audio file. + +Examples: + python detect_intent_audio.py -h + python detect_intent_audio.py --project-id PROJECT_ID \ + --session-id SESSION_ID --audio-file-path resources/book_a_room.wav + python detect_intent_audio.py --project-id PROJECT_ID \ + --session-id SESSION_ID --audio-file-path resources/mountain_view.wav + python detect_intent_audio.py --project-id PROJECT_ID \ + --session-id SESSION_ID --audio-file-path resources/today.wav +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_audio] +def detect_intent_audio(project_id, session_id, audio_file_path, + language_code): + """Returns the result of detect intent with an audio file as input. + + Using the same `session_id` between requests allows continuation + of the conversaion.""" + import dialogflow_v2 as dialogflow + + session_client = dialogflow.SessionsClient() + + # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. + audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 + sample_rate_hertz = 16000 + + session = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session)) + + with open(audio_file_path, 'rb') as audio_file: + input_audio = audio_file.read() + + audio_config = dialogflow.types.InputAudioConfig( + audio_encoding=audio_encoding, language_code=language_code, + sample_rate_hertz=sample_rate_hertz) + query_input = dialogflow.types.QueryInput(audio_config=audio_config) + + response = session_client.detect_intent( + session=session, query_input=query_input, + input_audio=input_audio) + + print('=' * 20) + print('Query text: {}'.format(response.query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + response.query_result.intent.display_name, + response.query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + response.query_result.fulfillment_text)) +# [END dialogflow_detect_intent_audio] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + parser.add_argument( + '--session-id', + help='Identifier of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + '--audio-file-path', + help='Path to the audio file.', + required=True) + + args = parser.parse_args() + + detect_intent_audio( + args.project_id, args.session_id, args.audio_file_path, + args.language_code) diff --git a/dialogflow/cloud-client/detect_intent_audio_test.py b/dialogflow/cloud-client/detect_intent_audio_test.py new file mode 100644 index 000000000000..5f67f6ef1495 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_audio_test.py @@ -0,0 +1,35 @@ +# Copyright 2017, Google LLC +# 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 absolute_import + +import os + +from detect_intent_audio import detect_intent_audio + +DIRNAME = os.path.realpath(os.path.dirname(__file__)) +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +AUDIOS = [ + '{0}/resources/book_a_room.wav'.format(DIRNAME), + '{0}/resources/mountain_view.wav'.format(DIRNAME), + '{0}/resources/today.wav'.format(DIRNAME), +] + + +def test_detect_intent_audio(capsys): + for audio_file_path in AUDIOS: + detect_intent_audio(PROJECT_ID, SESSION_ID, audio_file_path, 'en-US') + out, _ = capsys.readouterr() + + assert 'Fulfillment text: What time will the meeting start?' in out diff --git a/dialogflow/cloud-client/detect_intent_knowledge.py b/dialogflow/cloud-client/detect_intent_knowledge.py new file mode 100644 index 000000000000..edfd4b517ec8 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_knowledge.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC +# +# 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. + +"""Dialogflow API Detect Knowledge Base Intent Python sample with text inputs. + +Examples: + python detect_intent_knowledge.py -h + python detect_intent_knowledge.py --project-id PROJECT_ID \ + --session-id SESSION_ID --knowledge-base-id KNOWLEDGE_BASE_ID \ + "hello" "how do I reset my password?" +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_knowledge] +def detect_intent_knowledge(project_id, session_id, language_code, + knowledge_base_id, texts): + """Returns the result of detect intent with querying Knowledge Connector. + + Args: + project_id: The GCP project linked with the agent you are going to query. + session_id: Id of the session, using the same `session_id` between requests + allows continuation of the conversation. + language_code: Language of the queries. + knowledge_base_id: The Knowledge base's id to query against. + texts: A list of text queries to send. + """ + import dialogflow_v2beta1 as dialogflow + session_client = dialogflow.SessionsClient() + + session_path = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session_path)) + + for text in texts: + text_input = dialogflow.types.TextInput( + text=text, language_code=language_code) + + query_input = dialogflow.types.QueryInput(text=text_input) + + knowledge_base_path = dialogflow.knowledge_bases_client \ + .KnowledgeBasesClient \ + .knowledge_base_path(project_id, knowledge_base_id) + + query_params = dialogflow.types.QueryParameters( + knowledge_base_names=[knowledge_base_path]) + + response = session_client.detect_intent( + session=session_path, query_input=query_input, + query_params=query_params) + + print('=' * 20) + print('Query text: {}'.format(response.query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + response.query_result.intent.display_name, + response.query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + response.query_result.fulfillment_text)) + print('Knowledge results:') + knowledge_answers = response.query_result.knowledge_answers + for answers in knowledge_answers.answers: + print(' - Answer: {}'.format(answers.answer)) + print(' - Confidence: {}'.format( + answers.match_confidence)) +# [END dialogflow_detect_intent_knowledge] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', help='Project/agent id. Required.', required=True) + parser.add_argument( + '--session-id', + help='ID of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + '--knowledge-base-id', + help='The id of the Knowledge Base to query against', + required=True) + parser.add_argument('texts', nargs='+', type=str, help='Text inputs.') + + args = parser.parse_args() + + detect_intent_knowledge(args.project_id, args.session_id, + args.language_code, args.knowledge_base_id, + args.texts) diff --git a/dialogflow/cloud-client/detect_intent_stream.py b/dialogflow/cloud-client/detect_intent_stream.py new file mode 100644 index 000000000000..e69d46c25bbb --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_stream.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API Detect Intent Python sample with audio files processed +as an audio stream. + +Examples: + python detect_intent_stream.py -h + python detect_intent_stream.py --project-id PROJECT_ID \ + --session-id SESSION_ID --audio-file-path resources/book_a_room.wav + python detect_intent_stream.py --project-id PROJECT_ID \ + --session-id SESSION_ID --audio-file-path resources/mountain_view.wav +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_streaming] +def detect_intent_stream(project_id, session_id, audio_file_path, + language_code): + """Returns the result of detect intent with streaming audio as input. + + Using the same `session_id` between requests allows continuation + of the conversaion.""" + import dialogflow_v2 as dialogflow + session_client = dialogflow.SessionsClient() + + # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. + audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 + sample_rate_hertz = 16000 + + session_path = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session_path)) + + def request_generator(audio_config, audio_file_path): + query_input = dialogflow.types.QueryInput(audio_config=audio_config) + + # The first request contains the configuration. + yield dialogflow.types.StreamingDetectIntentRequest( + session=session_path, query_input=query_input) + + # Here we are reading small chunks of audio data from a local + # audio file. In practice these chunks should come from + # an audio input device. + with open(audio_file_path, 'rb') as audio_file: + while True: + chunk = audio_file.read(4096) + if not chunk: + break + # The later requests contains audio data. + yield dialogflow.types.StreamingDetectIntentRequest( + input_audio=chunk) + + audio_config = dialogflow.types.InputAudioConfig( + audio_encoding=audio_encoding, language_code=language_code, + sample_rate_hertz=sample_rate_hertz) + + requests = request_generator(audio_config, audio_file_path) + responses = session_client.streaming_detect_intent(requests) + + print('=' * 20) + for response in responses: + print('Intermediate transcript: "{}".'.format( + response.recognition_result.transcript)) + + # Note: The result from the last response is the final transcript along + # with the detected content. + query_result = response.query_result + + print('=' * 20) + print('Query text: {}'.format(query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + query_result.intent.display_name, + query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + query_result.fulfillment_text)) +# [END dialogflow_detect_intent_streaming] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + parser.add_argument( + '--session-id', + help='Identifier of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + '--audio-file-path', + help='Path to the audio file.', + required=True) + + args = parser.parse_args() + + detect_intent_stream( + args.project_id, args.session_id, args.audio_file_path, + args.language_code) diff --git a/dialogflow/cloud-client/detect_intent_stream_test.py b/dialogflow/cloud-client/detect_intent_stream_test.py new file mode 100644 index 000000000000..f83ab07b5e67 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_stream_test.py @@ -0,0 +1,32 @@ +# Copyright 2017, Google LLC +# 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 absolute_import + +import os + +from detect_intent_stream import detect_intent_stream + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +AUDIO_FILE_PATH = '{0}/resources/book_a_room.wav'.format( + os.path.realpath(os.path.dirname(__file__)), +) + + +def test_detect_intent_stream(capsys): + detect_intent_stream(PROJECT_ID, SESSION_ID, AUDIO_FILE_PATH, 'en-US') + out, _ = capsys.readouterr() + + assert 'Intermediate transcript: "book"' in out + assert 'Fulfillment text: What time will the meeting start?' in out diff --git a/dialogflow/cloud-client/detect_intent_texts.py b/dialogflow/cloud-client/detect_intent_texts.py new file mode 100644 index 000000000000..c1b8f04dfc59 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_texts.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API Detect Intent Python sample with text inputs. + +Examples: + python detect_intent_texts.py -h + python detect_intent_texts.py --project-id PROJECT_ID \ + --session-id SESSION_ID \ + "hello" "book a meeting room" "Mountain View" + python detect_intent_texts.py --project-id PROJECT_ID \ + --session-id SESSION_ID \ + "tomorrow" "10 AM" "2 hours" "10 people" "A" "yes" +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_text] +def detect_intent_texts(project_id, session_id, texts, language_code): + """Returns the result of detect intent with texts as inputs. + + Using the same `session_id` between requests allows continuation + of the conversaion.""" + import dialogflow_v2 as dialogflow + session_client = dialogflow.SessionsClient() + + session = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session)) + + for text in texts: + text_input = dialogflow.types.TextInput( + text=text, language_code=language_code) + + query_input = dialogflow.types.QueryInput(text=text_input) + + response = session_client.detect_intent( + session=session, query_input=query_input) + + print('=' * 20) + print('Query text: {}'.format(response.query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + response.query_result.intent.display_name, + response.query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + response.query_result.fulfillment_text)) +# [END dialogflow_detect_intent_text] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + parser.add_argument( + '--session-id', + help='Identifier of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + 'texts', + nargs='+', + type=str, + help='Text inputs.') + + args = parser.parse_args() + + detect_intent_texts( + args.project_id, args.session_id, args.texts, args.language_code) diff --git a/dialogflow/cloud-client/detect_intent_texts_test.py b/dialogflow/cloud-client/detect_intent_texts_test.py new file mode 100644 index 000000000000..1995b9b3d26b --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_texts_test.py @@ -0,0 +1,30 @@ +# Copyright 2017, Google LLC +# 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 absolute_import + +import os + +from detect_intent_texts import detect_intent_texts + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +TEXTS = ["hello", "book a meeting room", "Mountain View", + "tomorrow", "10 AM", "2 hours", "10 people", "A", "yes"] + + +def test_detect_intent_texts(capsys): + detect_intent_texts(PROJECT_ID, SESSION_ID, TEXTS, 'en-US') + out, _ = capsys.readouterr() + + assert 'Fulfillment text: All set!' in out diff --git a/dialogflow/cloud-client/detect_intent_with_model_selection.py b/dialogflow/cloud-client/detect_intent_with_model_selection.py new file mode 100644 index 000000000000..723170ee9fe1 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_with_model_selection.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC +# +# 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. + +"""Dialogflow API Beta Detect Intent Python sample with model selection. + +Examples: + python detect_intent_with_model_selection.py -h + python detect_intent_with_model_selection.py --project-id PROJECT_ID \ + --session-id SESSION_ID --audio-file-path resources/book_a_room.wav +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_with_model_selection] +def detect_intent_with_model_selection(project_id, session_id, audio_file_path, + language_code): + """Returns the result of detect intent with model selection on an audio file + as input + + Using the same `session_id` between requests allows continuation + of the conversaion.""" + import dialogflow_v2beta1 as dialogflow + session_client = dialogflow.SessionsClient() + + # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. + audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 + sample_rate_hertz = 16000 + + session_path = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session_path)) + + with open(audio_file_path, 'rb') as audio_file: + input_audio = audio_file.read() + + # Which Speech model to select for the given request. + # Possible models: video, phone_call, command_and_search, default + model = 'phone_call' + + audio_config = dialogflow.types.InputAudioConfig( + audio_encoding=audio_encoding, language_code=language_code, + sample_rate_hertz=sample_rate_hertz, + model=model) + query_input = dialogflow.types.QueryInput(audio_config=audio_config) + + response = session_client.detect_intent( + session=session_path, query_input=query_input, + input_audio=input_audio) + + print('=' * 20) + print('Query text: {}'.format(response.query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + response.query_result.intent.display_name, + response.query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + response.query_result.fulfillment_text)) +# [END dialogflow_detect_intent_with_model_selection] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + parser.add_argument( + '--session-id', + help='Identifier of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + '--audio-file-path', + help='Path to the audio file.', + required=True) + + args = parser.parse_args() + + detect_intent_with_model_selection( + args.project_id, args.session_id, args.audio_file_path, + args.language_code) diff --git a/dialogflow/cloud-client/detect_intent_with_model_selection_test.py b/dialogflow/cloud-client/detect_intent_with_model_selection_test.py new file mode 100644 index 000000000000..127622893312 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_with_model_selection_test.py @@ -0,0 +1,37 @@ +# Copyright 2018, Google LLC +# 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 absolute_import + +import os + +from detect_intent_with_model_selection import \ + detect_intent_with_model_selection + +DIRNAME = os.path.realpath(os.path.dirname(__file__)) +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +AUDIOS = [ + '{0}/resources/book_a_room.wav'.format(DIRNAME), + '{0}/resources/mountain_view.wav'.format(DIRNAME), + '{0}/resources/today.wav'.format(DIRNAME), +] + + +def test_detect_intent_audio_with_model_selection(capsys): + for audio_file_path in AUDIOS: + detect_intent_with_model_selection(PROJECT_ID, SESSION_ID, + audio_file_path, 'en-US') + out, _ = capsys.readouterr() + + assert 'Fulfillment text: What time will the meeting start?' in out diff --git a/dialogflow/cloud-client/detect_intent_with_sentiment_analysis.py b/dialogflow/cloud-client/detect_intent_with_sentiment_analysis.py new file mode 100644 index 000000000000..4eb4babf29f1 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_with_sentiment_analysis.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC +# +# 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. + +"""Dialogflow API Beta Detect Intent Python sample with sentiment analysis. + +Examples: + python detect_intent_with_sentiment_analysis.py -h + python detect_intent_with_sentiment_analysis.py --project-id PROJECT_ID \ + --session-id SESSION_ID \ + "hello" "book a meeting room" "Mountain View" +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_with_sentiment_analysis] +def detect_intent_with_sentiment_analysis(project_id, session_id, texts, + language_code): + """Returns the result of detect intent with texts as inputs and analyzes the + sentiment of the query text. + + Using the same `session_id` between requests allows continuation + of the conversaion.""" + import dialogflow_v2beta1 as dialogflow + session_client = dialogflow.SessionsClient() + + session_path = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session_path)) + + for text in texts: + text_input = dialogflow.types.TextInput( + text=text, language_code=language_code) + + query_input = dialogflow.types.QueryInput(text=text_input) + + # Enable sentiment analysis + sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig( + analyze_query_text_sentiment=True) + + # Set the query parameters with sentiment analysis + query_params = dialogflow.types.QueryParameters( + sentiment_analysis_request_config=sentiment_config) + + response = session_client.detect_intent( + session=session_path, query_input=query_input, + query_params=query_params) + + print('=' * 20) + print('Query text: {}'.format(response.query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + response.query_result.intent.display_name, + response.query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + response.query_result.fulfillment_text)) + # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment). + print('Query Text Sentiment Score: {}\n'.format( + response.query_result.sentiment_analysis_result + .query_text_sentiment.score)) + print('Query Text Sentiment Magnitude: {}\n'.format( + response.query_result.sentiment_analysis_result + .query_text_sentiment.magnitude)) +# [END dialogflow_detect_intent_with_sentiment_analysis] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + parser.add_argument( + '--session-id', + help='Identifier of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + 'texts', + nargs='+', + type=str, + help='Text inputs.') + + args = parser.parse_args() + + detect_intent_with_sentiment_analysis( + args.project_id, args.session_id, args.texts, args.language_code) diff --git a/dialogflow/cloud-client/detect_intent_with_sentiment_analysis_test.py b/dialogflow/cloud-client/detect_intent_with_sentiment_analysis_test.py new file mode 100644 index 000000000000..5e9041b177a1 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_with_sentiment_analysis_test.py @@ -0,0 +1,32 @@ +# Copyright 2018, Google LLC +# 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 absolute_import + +import os + +from detect_intent_with_sentiment_analysis import \ + detect_intent_with_sentiment_analysis + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +TEXTS = ["hello", "book a meeting room", "Mountain View", + "tomorrow", "10 AM", "2 hours", "10 people", "A", "yes"] + + +def test_detect_intent_with_sentiment_analysis(capsys): + detect_intent_with_sentiment_analysis(PROJECT_ID, SESSION_ID, TEXTS, + 'en-US') + out, _ = capsys.readouterr() + + assert 'Query Text Sentiment Score' in out diff --git a/dialogflow/cloud-client/detect_intent_with_texttospeech_response.py b/dialogflow/cloud-client/detect_intent_with_texttospeech_response.py new file mode 100644 index 000000000000..fbbf701da9d7 --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_with_texttospeech_response.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC +# +# 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. + +"""Dialogflow API Beta Detect Intent Python sample with an audio response. + +Examples: + python detect_intent_with_texttospeech_response_test.py -h + python detect_intent_with_texttospeech_response_test.py \ + --project-id PROJECT_ID --session-id SESSION_ID "hello" +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_with_texttospeech_response] +def detect_intent_with_texttospeech_response(project_id, session_id, texts, + language_code): + """Returns the result of detect intent with texts as inputs and includes + the response in an audio format. + + Using the same `session_id` between requests allows continuation + of the conversaion.""" + import dialogflow_v2beta1 as dialogflow + session_client = dialogflow.SessionsClient() + + session_path = session_client.session_path(project_id, session_id) + print('Session path: {}\n'.format(session_path)) + + for text in texts: + text_input = dialogflow.types.TextInput( + text=text, language_code=language_code) + + query_input = dialogflow.types.QueryInput(text=text_input) + + # Set the query parameters with sentiment analysis + output_audio_config = dialogflow.types.OutputAudioConfig( + audio_encoding=dialogflow.enums.OutputAudioEncoding + .OUTPUT_AUDIO_ENCODING_LINEAR_16) + + response = session_client.detect_intent( + session=session_path, query_input=query_input, + output_audio_config=output_audio_config) + + print('=' * 20) + print('Query text: {}'.format(response.query_result.query_text)) + print('Detected intent: {} (confidence: {})\n'.format( + response.query_result.intent.display_name, + response.query_result.intent_detection_confidence)) + print('Fulfillment text: {}\n'.format( + response.query_result.fulfillment_text)) + # The response's audio_content is binary. + with open('output.wav', 'wb') as out: + out.write(response.output_audio) + print('Audio content written to file "output.wav"') +# [END dialogflow_detect_intent_with_texttospeech_response] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + parser.add_argument( + '--session-id', + help='Identifier of the DetectIntent session. ' + 'Defaults to a random UUID.', + default=str(uuid.uuid4())) + parser.add_argument( + '--language-code', + help='Language code of the query. Defaults to "en-US".', + default='en-US') + parser.add_argument( + 'texts', + nargs='+', + type=str, + help='Text inputs.') + + args = parser.parse_args() + + detect_intent_with_texttospeech_response( + args.project_id, args.session_id, args.texts, args.language_code) diff --git a/dialogflow/cloud-client/detect_intent_with_texttospeech_response_test.py b/dialogflow/cloud-client/detect_intent_with_texttospeech_response_test.py new file mode 100644 index 000000000000..96419b2f229d --- /dev/null +++ b/dialogflow/cloud-client/detect_intent_with_texttospeech_response_test.py @@ -0,0 +1,35 @@ +# Copyright 2018, Google LLC +# 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 absolute_import + +import os + +from detect_intent_with_texttospeech_response import \ + detect_intent_with_texttospeech_response + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +TEXTS = ["hello"] + + +def test_detect_intent_with_sentiment_analysis(capsys): + detect_intent_with_texttospeech_response(PROJECT_ID, SESSION_ID, TEXTS, + 'en-US') + out, _ = capsys.readouterr() + + assert 'Audio content written to file' in out + statinfo = os.stat('output.wav') + assert statinfo.st_size > 0 + os.remove('output.wav') + assert not os.path.isfile('output.wav') diff --git a/dialogflow/cloud-client/document_management.py b/dialogflow/cloud-client/document_management.py new file mode 100644 index 000000000000..6145c9df8a6a --- /dev/null +++ b/dialogflow/cloud-client/document_management.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC +# +# 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. + +"""Dialogflow API Python sample showing how to manage Knowledge Documents. + +Examples: + python document_management.py -h + python document_management.py --project-id PROJECT_ID \ + --knowledge-base-id knowledge_base_id \ + list + python document_management.py --project-id PROJECT_ID \ + --knowledge-base-id knowledge_base_id \ + create --display-name DISPLAY_NAME --mime-type MIME_TYPE \ + --knowledge-type KNOWLEDGE_TYPE --content-uri CONTENT_URI + python document_management.py --project-id PROJECT_ID \ + --knowledge-base-id knowledge_base_id \ + get --document-id DOCUMENT_ID + python document_management.py --project-id PROJECT_ID \ + --knowledge-base-id knowledge_base_id \ + delete --document-id DOCUMENT_ID +""" + +import argparse + + +KNOWLEDGE_TYPES = ['KNOWLEDGE_TYPE_UNSPECIFIED', 'FAQ', 'EXTRACTIVE_QA'] + + +# [START dialogflow_list_document] +def list_documents(project_id, knowledge_base_id): + """Lists the Documents belonging to a Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + knowledge_base_path = client.knowledge_base_path(project_id, + knowledge_base_id) + + print('Documents for Knowledge Id: {}'.format(knowledge_base_id)) + for document in client.list_documents(knowledge_base_path): + print(' - Display Name: {}'.format(document.display_name)) + print(' - Knowledge ID: {}'.format(document.name)) + print(' - MIME Type: {}'.format(document.mime_type)) + print(' - Knowledge Types:') + for knowledge_type in document.knowledge_types: + print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) + print(' - Source: {}\n'.format(document.content_uri)) +# [END dialogflow_list_document] + + +# [START dialogflow_create_document]] +def create_document(project_id, knowledge_base_id, display_name, mime_type, + knowledge_type, content_uri): + """Creates a Document. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base. + display_name: The display name of the Document. + mime_type: The mime_type of the Document. e.g. text/csv, text/html, + text/plain, text/pdf etc. + knowledge_type: The Knowledge type of the Document. e.g. FAQ, + EXTRACTIVE_QA. + content_uri: Uri of the document, e.g. gs://path/mydoc.csv, + http://mypage.com/faq.html.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + knowledge_base_path = client.knowledge_base_path(project_id, + knowledge_base_id) + + document = dialogflow.types.Document( + display_name=display_name, mime_type=mime_type, + content_uri=content_uri) + + document.knowledge_types.append( + dialogflow.types.Document.KnowledgeType.Value(knowledge_type)) + + response = client.create_document(knowledge_base_path, document) + print('Waiting for results...') + document = response.result(timeout=90) + print('Created Document:') + print(' - Display Name: {}'.format(document.display_name)) + print(' - Knowledge ID: {}'.format(document.name)) + print(' - MIME Type: {}'.format(document.mime_type)) + print(' - Knowledge Types:') + for knowledge_type in document.knowledge_types: + print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) + print(' - Source: {}\n'.format(document.content_uri)) +# [END dialogflow_create_document]] + + +# [START dialogflow_get_document]] +def get_document(project_id, knowledge_base_id, document_id): + """Gets a Document. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base. + document_id: Id of the Document.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + document_path = client.document_path(project_id, knowledge_base_id, + document_id) + + response = client.get_document(document_path) + print('Got Document:') + print(' - Display Name: {}'.format(response.display_name)) + print(' - Knowledge ID: {}'.format(response.name)) + print(' - MIME Type: {}'.format(response.mime_type)) + print(' - Knowledge Types:') + for knowledge_type in response.knowledge_types: + print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) + print(' - Source: {}\n'.format(response.content_uri)) +# [END dialogflow_get_document]] + + +# [START dialogflow_delete_document]] +def delete_document(project_id, knowledge_base_id, document_id): + """Deletes a Document. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base. + document_id: Id of the Document.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + document_path = client.document_path(project_id, knowledge_base_id, + document_id) + + response = client.delete_document(document_path) + print('operation running:\n {}'.format(response.operation)) + print('Waiting for results...') + print('Done.\n {}'.format(response.result())) +# [END dialogflow_delete_document]] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', help='Project id. Required.', required=True) + parser.add_argument( + '--knowledge-base-id', + help='The id of the Knowledge Base that the Document belongs to', + required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', + help='List all Documents that belong to a certain Knowledge base.') + + create_parser = subparsers.add_parser( + 'create', help='Create a Document for a certain Knowledge base.') + create_parser.add_argument( + '--display-name', + help='A name of the Document, mainly used for display purpose, ' + 'can not be used to identify the Document.', + default=str('')) + create_parser.add_argument( + '--mime-type', + help='The mime-type of the Document, e.g. text/csv, text/html, ' + 'text/plain, text/pdf etc. ', + required=True) + create_parser.add_argument( + '--knowledge-type', + help='The knowledge-type of the Document, e.g. FAQ, EXTRACTIVE_QA.', + required=True) + create_parser.add_argument( + '--content-uri', + help='The uri of the Document, e.g. gs://path/mydoc.csv, ' + 'http://mypage.com/faq.html', + required=True) + + get_parser = subparsers.add_parser( + 'get', help='Get a Document by its id and the Knowledge base id.') + get_parser.add_argument( + '--document-id', help='The id of the Document', required=True) + + delete_parser = subparsers.add_parser( + 'delete', help='Delete a Document by its id and the Knowledge base' + 'id.') + delete_parser.add_argument( + '--document-id', + help='The id of the Document you want to delete', + required=True) + + args = parser.parse_args() + + if args.command == 'list': + list_documents(args.project_id, args.knowledge_base_id) + elif args.command == 'create': + create_document(args.project_id, args.knowledge_base_id, + args.display_name, args.mime_type, args.knowledge_type, + args.content_uri) + elif args.command == 'get': + get_document(args.project_id, args.knowledge_base_id, args.document_id) + elif args.command == 'delete': + delete_document(args.project_id, args.knowledge_base_id, + args.document_id) diff --git a/dialogflow/cloud-client/entity_management.py b/dialogflow/cloud-client/entity_management.py new file mode 100644 index 000000000000..2fff2fe12fe0 --- /dev/null +++ b/dialogflow/cloud-client/entity_management.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API Entity Python sample showing how to manage entities. + +Examples: + python entity_management.py -h + python entity_management.py --project-id PROJECT_ID \ + list --entity-type-id e57238e2-e692-44ea-9216-6be1b2332e2a + python entity_management.py --project-id PROJECT_ID \ + create new_room --synonyms basement cellar \ + --entity-type-id e57238e2-e692-44ea-9216-6be1b2332e2a + python entity_management.py --project-id PROJECT_ID \ + delete new_room \ + --entity-type-id e57238e2-e692-44ea-9216-6be1b2332e2a +""" + +import argparse + + +# [START dialogflow_list_entities] +def list_entities(project_id, entity_type_id): + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + parent = entity_types_client.entity_type_path( + project_id, entity_type_id) + + entities = entity_types_client.get_entity_type(parent).entities + + for entity in entities: + print('Entity value: {}'.format(entity.value)) + print('Entity synonyms: {}\n'.format(entity.synonyms)) +# [END dialogflow_list_entities] + + +# [START dialogflow_create_entity] +def create_entity(project_id, entity_type_id, entity_value, synonyms): + """Create an entity of the given entity type.""" + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + # Note: synonyms must be exactly [entity_value] if the + # entity_type's kind is KIND_LIST + synonyms = synonyms or [entity_value] + + entity_type_path = entity_types_client.entity_type_path( + project_id, entity_type_id) + + entity = dialogflow.types.EntityType.Entity() + entity.value = entity_value + entity.synonyms.extend(synonyms) + + response = entity_types_client.batch_create_entities( + entity_type_path, [entity]) + + print('Entity created: {}'.format(response)) +# [END dialogflow_create_entity] + + +# [START dialogflow_delete_entity] +def delete_entity(project_id, entity_type_id, entity_value): + """Delete entity with the given entity type and entity value.""" + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + entity_type_path = entity_types_client.entity_type_path( + project_id, entity_type_id) + + entity_types_client.batch_delete_entities( + entity_type_path, [entity_value]) +# [END dialogflow_delete_entity] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', help=list_entities.__doc__) + list_parser.add_argument( + '--entity-type-id', + help='The id of the entity_type.') + + create_parser = subparsers.add_parser( + 'create', help=create_entity.__doc__) + create_parser.add_argument( + 'entity_value', + help='The entity value to be added.') + create_parser.add_argument( + '--entity-type-id', + help='The id of the entity_type to which to add an entity.', + required=True) + create_parser.add_argument( + '--synonyms', + nargs='*', + help='The synonyms that will map to the provided entity value.', + default=[]) + + delete_parser = subparsers.add_parser( + 'delete', help=delete_entity.__doc__) + delete_parser.add_argument( + '--entity-type-id', + help='The id of the entity_type.', + required=True) + delete_parser.add_argument( + 'entity_value', + help='The value of the entity to delete.') + + args = parser.parse_args() + + if args.command == 'list': + list_entities(args.project_id, args.entity_type_id) + elif args.command == 'create': + create_entity( + args.project_id, args.entity_type_id, args.entity_value, + args.synonyms) + elif args.command == 'delete': + delete_entity( + args.project_id, args.entity_type_id, args.entity_value) diff --git a/dialogflow/cloud-client/entity_management_test.py b/dialogflow/cloud-client/entity_management_test.py new file mode 100644 index 000000000000..e2433d7a4e9d --- /dev/null +++ b/dialogflow/cloud-client/entity_management_test.py @@ -0,0 +1,90 @@ +# Copyright 2017 Google LLC +# +# 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 absolute_import + +import os + +import entity_management +import entity_type_management + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +ENTITY_TYPE_DISPLAY_NAME = 'fake_entity_type_for_testing' +ENTITY_VALUE_1 = 'fake_entity_for_testing_1' +ENTITY_VALUE_2 = 'fake_entity_for_testing_2' +SYNONYMS = ['fake_synonym_for_testing_1', 'fake_synonym_for_testing_2'] + + +def test_create_entity_type(capsys): + entity_type_ids = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME) + + assert len(entity_type_ids) == 0 + + entity_type_management.create_entity_type( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME, 'KIND_MAP') + out, _ = capsys.readouterr() + + assert 'display_name: "{}"'.format(ENTITY_TYPE_DISPLAY_NAME) in out + + entity_type_ids = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME) + + assert len(entity_type_ids) == 1 + + +def test_create_entity(capsys): + entity_type_id = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME)[0] + + entity_management.create_entity( + PROJECT_ID, entity_type_id, ENTITY_VALUE_1, []) + entity_management.create_entity( + PROJECT_ID, entity_type_id, ENTITY_VALUE_2, SYNONYMS) + + entity_management.list_entities(PROJECT_ID, entity_type_id) + out, _ = capsys.readouterr() + + assert 'Entity value: {}'.format(ENTITY_VALUE_1) in out + assert 'Entity value: {}'.format(ENTITY_VALUE_2) in out + for synonym in SYNONYMS: + assert synonym in out + + +def test_delete_entity(capsys): + entity_type_id = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME)[0] + + entity_management.delete_entity( + PROJECT_ID, entity_type_id, ENTITY_VALUE_1) + entity_management.delete_entity( + PROJECT_ID, entity_type_id, ENTITY_VALUE_2) + + entity_management.list_entities(PROJECT_ID, entity_type_id) + out, _ = capsys.readouterr() + + assert out == '' + + +def test_delete_entity_type(capsys): + entity_type_ids = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME) + + for entity_type_id in entity_type_ids: + entity_type_management.delete_entity_type(PROJECT_ID, entity_type_id) + + entity_type_ids = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME) + + assert len(entity_type_ids) == 0 diff --git a/dialogflow/cloud-client/entity_type_management.py b/dialogflow/cloud-client/entity_type_management.py new file mode 100644 index 000000000000..1f342f3a1b94 --- /dev/null +++ b/dialogflow/cloud-client/entity_type_management.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API EntityType Python sample showing how to manage entity types. + +Examples: + python entity_type_management.py -h + python entity_type_management.py --project-id PROJECT_ID list + python entity_type_management.py --project-id PROJECT_ID create employee + python entity_type_management.py --project-id PROJECT_ID delete \ + e57238e2-e692-44ea-9216-6be1b2332e2a +""" + +import argparse + + +# [START dialogflow_list_entity_types] +def list_entity_types(project_id): + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + parent = entity_types_client.project_agent_path(project_id) + + entity_types = entity_types_client.list_entity_types(parent) + + for entity_type in entity_types: + print('Entity type name: {}'.format(entity_type.name)) + print('Entity type display name: {}'.format(entity_type.display_name)) + print('Number of entities: {}\n'.format(len(entity_type.entities))) +# [END dialogflow_list_entity_types] + + +# [START dialogflow_create_entity_type] +def create_entity_type(project_id, display_name, kind): + """Create an entity type with the given display name.""" + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + parent = entity_types_client.project_agent_path(project_id) + entity_type = dialogflow.types.EntityType( + display_name=display_name, kind=kind) + + response = entity_types_client.create_entity_type(parent, entity_type) + + print('Entity type created: \n{}'.format(response)) +# [END dialogflow_create_entity_type] + + +# [START dialogflow_delete_entity_type] +def delete_entity_type(project_id, entity_type_id): + """Delete entity type with the given entity type name.""" + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + entity_type_path = entity_types_client.entity_type_path( + project_id, entity_type_id) + + entity_types_client.delete_entity_type(entity_type_path) +# [END dialogflow_delete_entity_type] + + +# Helper to get entity_type_id from display name. +def _get_entity_type_ids(project_id, display_name): + import dialogflow_v2 as dialogflow + entity_types_client = dialogflow.EntityTypesClient() + + parent = entity_types_client.project_agent_path(project_id) + entity_types = entity_types_client.list_entity_types(parent) + entity_type_names = [ + entity_type.name for entity_type in entity_types + if entity_type.display_name == display_name] + + entity_type_ids = [ + entity_type_name.split('/')[-1] for entity_type_name + in entity_type_names] + + return entity_type_ids + + +if __name__ == '__main__': + import dialogflow_v2 + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', help=list_entity_types.__doc__) + + create_parser = subparsers.add_parser( + 'create', help=create_entity_type.__doc__) + create_parser.add_argument( + 'display_name', + help='The display name of the entity.') + create_parser.add_argument( + '--kind', + help='The kind of entity. KIND_MAP (default) or KIND_LIST.', + default=dialogflow_v2.enums.EntityType.Kind.KIND_MAP) + + delete_parser = subparsers.add_parser( + 'delete', help=delete_entity_type.__doc__) + delete_parser.add_argument( + 'entity_type_id', + help='The id of the entity_type.') + + args = parser.parse_args() + + if args.command == 'list': + list_entity_types(args.project_id) + elif args.command == 'create': + create_entity_type(args.project_id, args.display_name, args.kind) + elif args.command == 'delete': + delete_entity_type(args.project_id, args.entity_type_id) diff --git a/dialogflow/cloud-client/intent_management.py b/dialogflow/cloud-client/intent_management.py new file mode 100644 index 000000000000..853e191c1a18 --- /dev/null +++ b/dialogflow/cloud-client/intent_management.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API Intent Python sample showing how to manage intents. + +Examples: + python intent_management.py -h + python intent_management.py --project-id PROJECT_ID list + python intent_management.py --project-id PROJECT_ID create \ + "room.cancellation - yes" \ + --training-phrases-parts "cancel" "cancellation" \ + --message-texts "Are you sure you want to cancel?" "Cancelled." + python intent_management.py --project-id PROJECT_ID delete \ + 74892d81-7901-496a-bb0a-c769eda5180e +""" + +import argparse + + +# [START dialogflow_list_intents] +def list_intents(project_id): + import dialogflow_v2 as dialogflow + intents_client = dialogflow.IntentsClient() + + parent = intents_client.project_agent_path(project_id) + + intents = intents_client.list_intents(parent) + + for intent in intents: + print('=' * 20) + print('Intent name: {}'.format(intent.name)) + print('Intent display_name: {}'.format(intent.display_name)) + print('Action: {}\n'.format(intent.action)) + print('Root followup intent: {}'.format( + intent.root_followup_intent_name)) + print('Parent followup intent: {}\n'.format( + intent.parent_followup_intent_name)) + + print('Input contexts:') + for input_context_name in intent.input_context_names: + print('\tName: {}'.format(input_context_name)) + + print('Output contexts:') + for output_context in intent.output_contexts: + print('\tName: {}'.format(output_context.name)) +# [END dialogflow_list_intents] + + +# [START dialogflow_create_intent] +def create_intent(project_id, display_name, training_phrases_parts, + message_texts): + """Create an intent of the given intent type.""" + import dialogflow_v2 as dialogflow + intents_client = dialogflow.IntentsClient() + + parent = intents_client.project_agent_path(project_id) + training_phrases = [] + for training_phrases_part in training_phrases_parts: + part = dialogflow.types.Intent.TrainingPhrase.Part( + text=training_phrases_part) + # Here we create a new training phrase for each provided part. + training_phrase = dialogflow.types.Intent.TrainingPhrase(parts=[part]) + training_phrases.append(training_phrase) + + text = dialogflow.types.Intent.Message.Text(text=message_texts) + message = dialogflow.types.Intent.Message(text=text) + + intent = dialogflow.types.Intent( + display_name=display_name, + training_phrases=training_phrases, + messages=[message]) + + response = intents_client.create_intent(parent, intent) + + print('Intent created: {}'.format(response)) +# [END dialogflow_create_intent] + + +# [START dialogflow_delete_intent] +def delete_intent(project_id, intent_id): + """Delete intent with the given intent type and intent value.""" + import dialogflow_v2 as dialogflow + intents_client = dialogflow.IntentsClient() + + intent_path = intents_client.intent_path(project_id, intent_id) + + intents_client.delete_intent(intent_path) +# [END dialogflow_delete_intent] + + +# Helper to get intent from display name. +def _get_intent_ids(project_id, display_name): + import dialogflow_v2 as dialogflow + intents_client = dialogflow.IntentsClient() + + parent = intents_client.project_agent_path(project_id) + intents = intents_client.list_intents(parent) + intent_names = [ + intent.name for intent in intents + if intent.display_name == display_name] + + intent_ids = [ + intent_name.split('/')[-1] for intent_name + in intent_names] + + return intent_ids + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', help=list_intents.__doc__) + + create_parser = subparsers.add_parser( + 'create', help=create_intent.__doc__) + create_parser.add_argument( + 'display_name') + create_parser.add_argument( + '--training-phrases-parts', + nargs='*', + type=str, + help='Training phrases.', + default=[]) + create_parser.add_argument( + '--message-texts', + nargs='*', + type=str, + help='Message texts for the agent\'s response when the intent ' + 'is detected.', + default=[]) + + delete_parser = subparsers.add_parser( + 'delete', help=delete_intent.__doc__) + delete_parser.add_argument( + 'intent_id', + help='The id of the intent.') + + args = parser.parse_args() + + if args.command == 'list': + list_intents(args.project_id) + elif args.command == 'create': + create_intent( + args.project_id, args.display_name, args.training_phrases_parts, + args.message_texts, ) + elif args.command == 'delete': + delete_intent(args.project_id, args.intent_id) diff --git a/dialogflow/cloud-client/intent_management_test.py b/dialogflow/cloud-client/intent_management_test.py new file mode 100644 index 000000000000..53105fe0002a --- /dev/null +++ b/dialogflow/cloud-client/intent_management_test.py @@ -0,0 +1,68 @@ +# Copyright 2017 Google LLC +# +# 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 absolute_import + +import os + +import intent_management + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +INTENT_DISPLAY_NAME = 'fake_display_name_for_testing' +MESSAGE_TEXTS = [ + 'fake_message_text_for_testing_1', + 'fake_message_text_for_testing_2' +] +TRAINING_PHRASE_PARTS = [ + 'fake_training_phrase_part_1', + 'fake_training_phease_part_2' +] + + +def test_create_intent(capsys): + intent_management.create_intent( + PROJECT_ID, INTENT_DISPLAY_NAME, TRAINING_PHRASE_PARTS, + MESSAGE_TEXTS) + + intent_ids = intent_management._get_intent_ids( + PROJECT_ID, INTENT_DISPLAY_NAME) + + assert len(intent_ids) == 1 + + intent_management.list_intents(PROJECT_ID) + + out, _ = capsys.readouterr() + + assert INTENT_DISPLAY_NAME in out + + for message_text in MESSAGE_TEXTS: + assert message_text in out + + +def test_delete_session_entity_type(capsys): + intent_ids = intent_management._get_intent_ids( + PROJECT_ID, INTENT_DISPLAY_NAME) + + for intent_id in intent_ids: + intent_management.delete_intent(PROJECT_ID, intent_id) + + intent_management.list_intents(PROJECT_ID) + out, _ = capsys.readouterr() + + assert INTENT_DISPLAY_NAME not in out + + intent_ids = intent_management._get_intent_ids( + PROJECT_ID, INTENT_DISPLAY_NAME) + + assert len(intent_ids) == 0 diff --git a/dialogflow/cloud-client/knowledge_base_management.py b/dialogflow/cloud-client/knowledge_base_management.py new file mode 100644 index 000000000000..b5ceab786ccf --- /dev/null +++ b/dialogflow/cloud-client/knowledge_base_management.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC +# +# 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. + +"""Dialogflow API Python sample showing how to manage Knowledge bases. + +Examples: + python knowledge_base_management.py -h + python knowledge_base_management.py --project-id PROJECT_ID \ + list + python knowledge_base_management.py --project-id PROJECT_ID \ + create --display-name DISPLAY_NAME + python knowledge_base_management.py --project-id PROJECT_ID \ + get --knowledge-base-id knowledge_base_id + python knowledge_base_management.py --project-id PROJECT_ID \ + delete --knowledge-base-id knowledge_base_id +""" + +import argparse + + +# [START dialogflow_list_knowledge_base] +def list_knowledge_bases(project_id): + """Lists the Knowledge bases belonging to a project. + + Args: + project_id: The GCP project linked with the agent.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() + project_path = client.project_path(project_id) + + print('Knowledge Bases for: {}'.format(project_id)) + for knowledge_base in client.list_knowledge_bases(project_path): + print(' - Display Name: {}'.format(knowledge_base.display_name)) + print(' - Knowledge ID: {}\n'.format(knowledge_base.name)) +# [END dialogflow_list_knowledge_base] + + +# [START dialogflow_create_knowledge_base] +def create_knowledge_base(project_id, display_name): + """Creates a Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + display_name: The display name of the Knowledge base.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() + project_path = client.project_path(project_id) + + knowledge_base = dialogflow.types.KnowledgeBase( + display_name=display_name) + + response = client.create_knowledge_base(project_path, knowledge_base) + + print('Knowledge Base created:\n') + print('Display Name: {}\n'.format(response.display_name)) + print('Knowledge ID: {}\n'.format(response.name)) +# [END dialogflow_create_knowledge_base] + + +# [START dialogflow_get_knowledge_base] +def get_knowledge_base(project_id, knowledge_base_id): + """Gets a specific Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() + knowledge_base_path = client.knowledge_base_path( + project_id, knowledge_base_id) + + response = client.get_knowledge_base(knowledge_base_path) + + print('Got Knowledge Base:') + print(' - Display Name: {}'.format(response.display_name)) + print(' - Knowledge ID: {}'.format(response.name)) +# [END dialogflow_get_knowledge_base] + + +# [START dialogflow_delete_knowledge_base] +def delete_knowledge_base(project_id, knowledge_base_id): + """Deletes a specific Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base.""" + import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() + knowledge_base_path = client.knowledge_base_path( + project_id, knowledge_base_id) + + response = client.delete_knowledge_base(knowledge_base_path) + + print('Knowledge Base deleted.'.format(response)) +# [END dialogflow_delete_knowledge_base] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', help='Project/agent id.', required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', help='List all Knowledge bases that belong to the project.') + + create_parser = subparsers.add_parser( + 'create', help='Create a new Knowledge base.') + create_parser.add_argument( + '--display-name', + help='A name of the Knowledge base, used for display purpose, ' + 'can not be used to identify the Knowledge base.', + default=str('')) + + get_parser = subparsers.add_parser( + 'get', help='Get a Knowledge base by its id.') + get_parser.add_argument( + '--knowledge-base-id', help='The id of the Knowledge base.', + required=True) + + delete_parser = subparsers.add_parser( + 'delete', help='Delete a Knowledge base by its id.') + delete_parser.add_argument( + '--knowledge-base-id', + help='The id of the Knowledge base you want to delete.', + required=True) + + args = parser.parse_args() + + if args.command == 'list': + list_knowledge_bases(args.project_id) + elif args.command == 'create': + create_knowledge_base(args.project_id, args.display_name) + elif args.command == 'get': + get_knowledge_base(args.project_id, args.knowledge_base_id) + elif args.command == 'delete': + delete_knowledge_base(args.project_id, args.knowledge_base_id) diff --git a/dialogflow/cloud-client/knowledge_base_management_test.py b/dialogflow/cloud-client/knowledge_base_management_test.py new file mode 100644 index 000000000000..d5e6f26cf31e --- /dev/null +++ b/dialogflow/cloud-client/knowledge_base_management_test.py @@ -0,0 +1,107 @@ +# Copyright 2018 Google LLC +# +# 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 absolute_import + +import os + +import detect_intent_knowledge +import document_management +import knowledge_base_management + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +TEXTS = ['Where is my data stored?'] + +KNOWLEDGE_BASE_NAME = 'fake_knowledge_base_name' +DOCUMENT_BASE_NAME = 'fake_document_name' + + +def test_create_knowledge_base(capsys): + # Check the knowledge base does not yet exists + knowledge_base_management.list_knowledge_bases(PROJECT_ID) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(KNOWLEDGE_BASE_NAME) not in out + + # Create a knowledge base + knowledge_base_management.create_knowledge_base(PROJECT_ID, + KNOWLEDGE_BASE_NAME) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(KNOWLEDGE_BASE_NAME) in out + + # List the knowledge base + knowledge_base_management.list_knowledge_bases(PROJECT_ID) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(KNOWLEDGE_BASE_NAME) in out + + knowledge_base_id = out.split('knowledgeBases/')[1].rstrip() + + # Get the knowledge base + knowledge_base_management.get_knowledge_base(PROJECT_ID, knowledge_base_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(KNOWLEDGE_BASE_NAME) in out + + # Create a Document + document_management.create_document( + PROJECT_ID, knowledge_base_id, DOCUMENT_BASE_NAME, 'text/html', 'FAQ', + 'https://cloud.google.com/storage/docs/faq') + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(DOCUMENT_BASE_NAME) in out + + # List the Document + document_management.list_documents(PROJECT_ID, knowledge_base_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(DOCUMENT_BASE_NAME) in out + + document_id = out.split('documents/')[1].split(' - MIME Type:')[0].rstrip() + + # Get the Document + document_management.get_document(PROJECT_ID, knowledge_base_id, + document_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(DOCUMENT_BASE_NAME) in out + + # Detect intent with Knowledge Base + detect_intent_knowledge.detect_intent_knowledge( + PROJECT_ID, SESSION_ID, 'en-us', knowledge_base_id, TEXTS) + + out, _ = capsys.readouterr() + assert 'Knowledge results' in out + + # Delete the Document + document_management.delete_document(PROJECT_ID, knowledge_base_id, + document_id) + + # List the Document + document_management.list_documents(PROJECT_ID, knowledge_base_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(DOCUMENT_BASE_NAME) not in out + + # Delete the Knowledge Base + knowledge_base_management.delete_knowledge_base(PROJECT_ID, + knowledge_base_id) + + # List the knowledge base + knowledge_base_management.list_knowledge_bases(PROJECT_ID) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(KNOWLEDGE_BASE_NAME) not in out diff --git a/dialogflow/cloud-client/requirements.txt b/dialogflow/cloud-client/requirements.txt new file mode 100644 index 000000000000..6b1de5689d25 --- /dev/null +++ b/dialogflow/cloud-client/requirements.txt @@ -0,0 +1 @@ +dialogflow==0.5.1 diff --git a/dialogflow/cloud-client/resources/230pm.wav b/dialogflow/cloud-client/resources/230pm.wav new file mode 100644 index 000000000000..7509eca784dc Binary files /dev/null and b/dialogflow/cloud-client/resources/230pm.wav differ diff --git a/dialogflow/cloud-client/resources/RoomReservation.zip b/dialogflow/cloud-client/resources/RoomReservation.zip new file mode 100644 index 000000000000..7873fb628c89 Binary files /dev/null and b/dialogflow/cloud-client/resources/RoomReservation.zip differ diff --git a/dialogflow/cloud-client/resources/book_a_room.wav b/dialogflow/cloud-client/resources/book_a_room.wav new file mode 100644 index 000000000000..9124e9279460 Binary files /dev/null and b/dialogflow/cloud-client/resources/book_a_room.wav differ diff --git a/dialogflow/cloud-client/resources/half_an_hour.wav b/dialogflow/cloud-client/resources/half_an_hour.wav new file mode 100644 index 000000000000..71010a871bbb Binary files /dev/null and b/dialogflow/cloud-client/resources/half_an_hour.wav differ diff --git a/dialogflow/cloud-client/resources/mountain_view.wav b/dialogflow/cloud-client/resources/mountain_view.wav new file mode 100644 index 000000000000..1c5437f7cb5b Binary files /dev/null and b/dialogflow/cloud-client/resources/mountain_view.wav differ diff --git a/dialogflow/cloud-client/resources/today.wav b/dialogflow/cloud-client/resources/today.wav new file mode 100644 index 000000000000..d47ed78b3516 Binary files /dev/null and b/dialogflow/cloud-client/resources/today.wav differ diff --git a/dialogflow/cloud-client/resources/two_people.wav b/dialogflow/cloud-client/resources/two_people.wav new file mode 100644 index 000000000000..5114ebbd3105 Binary files /dev/null and b/dialogflow/cloud-client/resources/two_people.wav differ diff --git a/dialogflow/cloud-client/session_entity_type_management.py b/dialogflow/cloud-client/session_entity_type_management.py new file mode 100644 index 000000000000..2c8523253382 --- /dev/null +++ b/dialogflow/cloud-client/session_entity_type_management.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python + +# Copyright 2017 Google LLC +# +# 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. + +"""DialogFlow API SessionEntityType Python sample showing how to manage +session entity types. + +Examples: + python session_entity_type_management.py -h + python session_entity_type_management.py --project-id PROJECT_ID list \ + --session-id SESSION_ID + python session_entity_type_management.py --project-id PROJECT_ID create \ + --session-id SESSION_ID \ + --entity-type-display-name room --entity-values C D E F + python session_entity_type_management.py --project-id PROJECT_ID delete \ + --session-id SESSION_ID \ + --entity-type-display-name room +""" + +import argparse + + +# [START dialogflow_list_session_entity_types] +def list_session_entity_types(project_id, session_id): + import dialogflow_v2 as dialogflow + session_entity_types_client = dialogflow.SessionEntityTypesClient() + + session_path = session_entity_types_client.session_path( + project_id, session_id) + + session_entity_types = ( + session_entity_types_client. + list_session_entity_types(session_path)) + + print('SessionEntityTypes for session {}:\n'.format(session_path)) + for session_entity_type in session_entity_types: + print('\tSessionEntityType name: {}'.format(session_entity_type.name)) + print('\tNumber of entities: {}\n'.format( + len(session_entity_type.entities))) +# [END dialogflow_list_session_entity_types] + + +# [START dialogflow_create_session_entity_type] +def create_session_entity_type(project_id, session_id, entity_values, + entity_type_display_name, entity_override_mode): + """Create a session entity type with the given display name.""" + import dialogflow_v2 as dialogflow + session_entity_types_client = dialogflow.SessionEntityTypesClient() + + session_path = session_entity_types_client.session_path( + project_id, session_id) + session_entity_type_name = ( + session_entity_types_client.session_entity_type_path( + project_id, session_id, entity_type_display_name)) + + # Here we use the entity value as the only synonym. + entities = [ + dialogflow.types.EntityType.Entity(value=value, synonyms=[value]) + for value in entity_values] + session_entity_type = dialogflow.types.SessionEntityType( + name=session_entity_type_name, + entity_override_mode=entity_override_mode, + entities=entities) + + response = session_entity_types_client.create_session_entity_type( + session_path, session_entity_type) + + print('SessionEntityType created: \n\n{}'.format(response)) +# [END dialogflow_create_session_entity_type] + + +# [START dialogflow_delete_session_entity_type] +def delete_session_entity_type(project_id, session_id, + entity_type_display_name): + """Delete session entity type with the given entity type display name.""" + import dialogflow_v2 as dialogflow + session_entity_types_client = dialogflow.SessionEntityTypesClient() + + session_entity_type_name = ( + session_entity_types_client.session_entity_type_path( + project_id, session_id, entity_type_display_name)) + + session_entity_types_client.delete_session_entity_type( + session_entity_type_name) +# [END dialogflow_delete_session_entity_type] + + +if __name__ == '__main__': + import dialogflow_v2 + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', + help='Project/agent id. Required.', + required=True) + + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', help=list_session_entity_types.__doc__) + list_parser.add_argument( + '--session-id', + required=True) + + create_parser = subparsers.add_parser( + 'create', help=create_session_entity_type.__doc__) + create_parser.add_argument( + '--session-id', + required=True) + create_parser.add_argument( + '--entity-type-display-name', + help='The DISPLAY NAME of the entity type to be overridden ' + 'in the session.', + required=True) + create_parser.add_argument( + '--entity-values', + nargs='*', + help='The entity values of the session entity type.', + required=True) + create_parser.add_argument( + '--entity-override-mode', + help='ENTITY_OVERRIDE_MODE_OVERRIDE (default) or ' + 'ENTITY_OVERRIDE_MODE_SUPPLEMENT', + default=(dialogflow_v2.enums.SessionEntityType.EntityOverrideMode. + ENTITY_OVERRIDE_MODE_OVERRIDE)) + + delete_parser = subparsers.add_parser( + 'delete', help=delete_session_entity_type.__doc__) + delete_parser.add_argument( + '--session-id', + required=True) + delete_parser.add_argument( + '--entity-type-display-name', + help='The DISPLAY NAME of the entity type.', + required=True) + + args = parser.parse_args() + + if args.command == 'list': + list_session_entity_types(args.project_id, args.session_id) + elif args.command == 'create': + create_session_entity_type( + args.project_id, args.session_id, args.entity_values, + args.entity_type_display_name, args.entity_override_mode) + elif args.command == 'delete': + delete_session_entity_type( + args.project_id, args.session_id, args.entity_type_display_name) diff --git a/dialogflow/cloud-client/session_entity_type_management_test.py b/dialogflow/cloud-client/session_entity_type_management_test.py new file mode 100644 index 000000000000..5931ea2ea81a --- /dev/null +++ b/dialogflow/cloud-client/session_entity_type_management_test.py @@ -0,0 +1,63 @@ +# Copyright 2017 Google LLC +# +# 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 absolute_import + +import os + +import entity_type_management +import session_entity_type_management + +PROJECT_ID = os.getenv('GCLOUD_PROJECT') +SESSION_ID = 'fake_session_for_testing' +ENTITY_TYPE_DISPLAY_NAME = 'fake_display_name_for_testing' +ENTITY_VALUES = ['fake_entity_value_1', 'fake_entity_value_2'] + + +def test_create_session_entity_type(capsys): + # Create an entity type + entity_type_management.create_entity_type( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME, 'KIND_MAP') + + session_entity_type_management.create_session_entity_type( + PROJECT_ID, SESSION_ID, ENTITY_VALUES, ENTITY_TYPE_DISPLAY_NAME, + 'ENTITY_OVERRIDE_MODE_SUPPLEMENT') + session_entity_type_management.list_session_entity_types( + PROJECT_ID, SESSION_ID) + + out, _ = capsys.readouterr() + + assert SESSION_ID in out + assert ENTITY_TYPE_DISPLAY_NAME in out + for entity_value in ENTITY_VALUES: + assert entity_value in out + + +def test_delete_session_entity_type(capsys): + session_entity_type_management.delete_session_entity_type( + PROJECT_ID, SESSION_ID, ENTITY_TYPE_DISPLAY_NAME) + session_entity_type_management.list_session_entity_types( + PROJECT_ID, SESSION_ID) + + out, _ = capsys.readouterr() + assert ENTITY_TYPE_DISPLAY_NAME not in out + for entity_value in ENTITY_VALUES: + assert entity_value not in out + + # Clean up entity type + entity_type_ids = entity_type_management._get_entity_type_ids( + PROJECT_ID, ENTITY_TYPE_DISPLAY_NAME) + for entity_type_id in entity_type_ids: + entity_type_management.delete_entity_type( + PROJECT_ID, entity_type_id)