Skip to content
This repository has been archived by the owner on Jan 6, 2024. It is now read-only.

Commit

Permalink
docs(samples): add initial sample codes (#13)
Browse files Browse the repository at this point in the history
Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly:
- [x] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/python-dialogflow-cx/issues/new/choose) before writing your code!  That way we can discuss the change, evaluate designs, and agree on the general idea
- [x] Ensure the tests and linter pass
- [ ] Code coverage does not decrease (if any source code was changed)
- [ ] Appropriate docs were updated (if necessary)

Fixes #12  🦕
  • Loading branch information
wuyuexin committed Sep 30, 2020
1 parent b4ed732 commit b590308
Show file tree
Hide file tree
Showing 17 changed files with 962 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .github/CODEOWNERS
Validating CODEOWNERS rules …
Expand Up @@ -8,4 +8,4 @@
* @googleapis/yoshi-python

# The python-samples-reviewers team is the default owner for samples changes
/samples/ @googleapis/python-samples-owners
/samples/ @googleapis/python-samples-owners @wuyuexin
Empty file added .github/snippet-bot.yml
Empty file.
1 change: 1 addition & 0 deletions samples/AUTHORING_GUIDE.md
@@ -0,0 +1 @@
See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md
1 change: 1 addition & 0 deletions samples/CONTRIBUTING.md
@@ -0,0 +1 @@
See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md
221 changes: 221 additions & 0 deletions samples/snippets/README.rst
@@ -0,0 +1,221 @@

.. This file is automatically generated. Do not edit this file directly.
Dialogflow CX 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 CX API. The `Dialogflow CX API`_ enables you to create conversational experiences across devices and platforms.




.. _Dialogflow CX API: https://cloud.google.com/dialogflow/cx/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 python-docs-samples and change directory to the sample directory you want to use.

.. 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 3.6+.

.. 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] --agent AGENT [--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 --agent AGENT --session-id SESSION_ID "hello" "book a meeting room" "Mountain View"
python detect_intent_texts.py --agent AGENT --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
--agent AGENT Agent resource name. 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] --agent AGENT [--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 --agent AGENT --session-id SESSION_ID --audio-file-path resources/hello.wav
optional arguments:
-h, --help show this help message and exit
--agent AGENT Agent resource name. 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] --agent AGENT [--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 --agent AGENT --session-id SESSION_ID --audio-file-path resources/hello.wav
optional arguments:
-h, --help show this help message and exit
--agent AGENT Agent resource name. 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.
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/
25 changes: 25 additions & 0 deletions samples/snippets/README.rst.in
@@ -0,0 +1,25 @@
# This file is used to generate README.rst

product:
name: Dialogflow CX API
short_name: Dialogflow CX API
url: https://cloud.google.com/dialogflow/cx/docs/
description: >
The `Dialogflow CX 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

cloud_client_library: true
107 changes: 107 additions & 0 deletions samples/snippets/detect_intent_audio.py
@@ -0,0 +1,107 @@
#!/usr/bin/env python

# Copyright 2020 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 --agent AGENT \
--session-id SESSION_ID --audio-file-path resources/hello.wav
"""

import argparse
import uuid

from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient
from google.cloud.dialogflowcx_v3beta1.types import audio_config
from google.cloud.dialogflowcx_v3beta1.types import session


# [START dialogflow_detect_intent_audio]
def run_sample():
# TODO(developer): Replace these values when running the function
project_id = "YOUR-PROJECT-ID"
location_id = "YOUR-LOCATION-ID"
# For more info on agents see https://cloud.google.com/dialogflow/cx/docs/concept/agent
agent_id = "YOUR-AGENT-ID"
agent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"
# For more information on sessions see https://cloud.google.com/dialogflow/cx/docs/concept/session
session_id = str(uuid.uuid4())
audio_file_path = "YOUR-AUDIO-FILE-PATH"
# For more supported languages see https://cloud.google.com/dialogflow/es/docs/reference/language
language_code = "en-us"

detect_intent_audio(agent, session_id, audio_file_path, language_code)


def detect_intent_audio(agent, 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 conversation."""
session_client = SessionsClient()
session_path = f"{agent}/sessions/{session_id}"
print(f"Session path: {session_path}\n")

input_audio_config = audio_config.InputAudioConfig(
audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,
sample_rate_hertz=24000,
)

with open(audio_file_path, "rb") as audio_file:
input_audio = audio_file.read()

audio_input = session.AudioInput(config=input_audio_config, audio=input_audio)
query_input = session.QueryInput(audio=audio_input, language_code=language_code)
request = session.DetectIntentRequest(session=session_path, query_input=query_input)
response = session_client.detect_intent(request=request)

print("=" * 20)
print(f"Query text: {response.query_result.transcript}")
response_messages = [
" ".join(msg.text.text) for msg in response.query_result.response_messages
]
print(f"Response text: {' '.join(response_messages)}\n")


# [END dialogflow_detect_intent_audio]

if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--agent", help="Agent resource name. 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.agent, args.session_id, args.audio_file_path, args.language_code
)

0 comments on commit b590308

Please sign in to comment.