From 230bb4e5e5b0bee5426c0cb07ea162e92bc75639 Mon Sep 17 00:00:00 2001 From: Ye Yuan <10695116+martini9393@users.noreply.github.com> Date: Fri, 12 Feb 2021 16:40:51 -0800 Subject: [PATCH] feat: add sample code for using regional Dialogflow endpoint (#254) * Add sample code for using regional dialogflow endpoint * Update comment * udpate some styles based on last round of reviews * run blacken to reformat files and update remaining string formatting Co-authored-by: Ye Yuan --- samples/snippets/create_document_test.py | 28 ++-- .../snippets/create_knowledge_base_test.py | 12 +- samples/snippets/detect_intent_audio.py | 64 ++++----- samples/snippets/detect_intent_audio_test.py | 14 +- samples/snippets/detect_intent_knowledge.py | 89 +++++++------ .../snippets/detect_intent_knowledge_test.py | 13 +- samples/snippets/detect_intent_stream.py | 79 ++++++----- samples/snippets/detect_intent_stream_test.py | 12 +- samples/snippets/detect_intent_texts.py | 62 ++++----- samples/snippets/detect_intent_texts_test.py | 21 ++- .../detect_intent_texts_with_location.py | 97 ++++++++++++++ .../detect_intent_texts_with_location_test.py | 43 ++++++ .../detect_intent_with_sentiment_analysis.py | 91 +++++++------ ...ect_intent_with_sentiment_analysis_test.py | 25 ++-- ...etect_intent_with_texttospeech_response.py | 70 +++++----- ..._intent_with_texttospeech_response_test.py | 20 +-- samples/snippets/document_management.py | 101 ++++++++------ samples/snippets/intent_management.py | 126 +++++++++--------- samples/snippets/intent_management_test.py | 26 ++-- samples/snippets/knowledge_base_management.py | 40 +++--- samples/snippets/noxfile.py | 34 ++--- 21 files changed, 638 insertions(+), 429 deletions(-) create mode 100644 samples/snippets/detect_intent_texts_with_location.py create mode 100644 samples/snippets/detect_intent_texts_with_location_test.py diff --git a/samples/snippets/create_document_test.py b/samples/snippets/create_document_test.py index 7099eed41..337976c45 100644 --- a/samples/snippets/create_document_test.py +++ b/samples/snippets/create_document_test.py @@ -22,9 +22,9 @@ import document_management -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -KNOWLEDGE_BASE_NAME = 'knowledge_{}'.format(uuid.uuid4()) -DOCUMENT_DISPLAY_NAME = 'test_document_{}'.format(uuid.uuid4()) +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +KNOWLEDGE_BASE_NAME = "knowledge_{}".format(uuid.uuid4()) +DOCUMENT_DISPLAY_NAME = "test_document_{}".format(uuid.uuid4()) pytest.KNOWLEDGE_BASE_ID = None @@ -33,17 +33,18 @@ def setup_teardown(): # Create a knowledge base to use in document management client = dialogflow_v2beta1.KnowledgeBasesClient() project_path = client.common_project_path(PROJECT_ID) - knowledge_base = dialogflow_v2beta1.KnowledgeBase( - display_name=KNOWLEDGE_BASE_NAME) - response = client.create_knowledge_base(parent=project_path, knowledge_base=knowledge_base) - pytest.KNOWLEDGE_BASE_ID = response.name.split( - '/knowledgeBases/')[1].split('\n')[0] + knowledge_base = dialogflow_v2beta1.KnowledgeBase(display_name=KNOWLEDGE_BASE_NAME) + response = client.create_knowledge_base( + parent=project_path, knowledge_base=knowledge_base + ) + pytest.KNOWLEDGE_BASE_ID = response.name.split("/knowledgeBases/")[1].split("\n")[0] yield # Delete the created knowledge base knowledge_base_path = client.knowledge_base_path( - PROJECT_ID, pytest.KNOWLEDGE_BASE_ID) + PROJECT_ID, pytest.KNOWLEDGE_BASE_ID + ) request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest( name=knowledge_base_path, force=True ) @@ -53,7 +54,12 @@ def setup_teardown(): @pytest.mark.flaky(max_runs=3, min_passes=1) def test_create_document(capsys): document_management.create_document( - PROJECT_ID, pytest.KNOWLEDGE_BASE_ID, DOCUMENT_DISPLAY_NAME, - 'text/html', 'FAQ', 'https://cloud.google.com/storage/docs/faq') + PROJECT_ID, + pytest.KNOWLEDGE_BASE_ID, + DOCUMENT_DISPLAY_NAME, + "text/html", + "FAQ", + "https://cloud.google.com/storage/docs/faq", + ) out, _ = capsys.readouterr() assert DOCUMENT_DISPLAY_NAME in out diff --git a/samples/snippets/create_knowledge_base_test.py b/samples/snippets/create_knowledge_base_test.py index 601a62047..39d33d0f3 100644 --- a/samples/snippets/create_knowledge_base_test.py +++ b/samples/snippets/create_knowledge_base_test.py @@ -22,8 +22,8 @@ import knowledge_base_management -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -KNOWLEDGE_BASE_NAME = 'knowledge_{}'.format(uuid.uuid4()) +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +KNOWLEDGE_BASE_NAME = "knowledge_{}".format(uuid.uuid4()) pytest.KNOWLEDGE_BASE_ID = None @@ -35,14 +35,14 @@ def teardown(): client = dialogflow_v2beta1.KnowledgeBasesClient() assert pytest.KNOWLEDGE_BASE_ID is not None knowledge_base_path = client.knowledge_base_path( - PROJECT_ID, pytest.KNOWLEDGE_BASE_ID) + PROJECT_ID, pytest.KNOWLEDGE_BASE_ID + ) client.delete_knowledge_base(name=knowledge_base_path) def test_create_knowledge_base(capsys): - knowledge_base_management.create_knowledge_base(PROJECT_ID, - KNOWLEDGE_BASE_NAME) + knowledge_base_management.create_knowledge_base(PROJECT_ID, KNOWLEDGE_BASE_NAME) out, _ = capsys.readouterr() assert KNOWLEDGE_BASE_NAME in out - pytest.KNOWLEDGE_BASE_ID = out.split('/knowledgeBases/')[1].split('\n')[0] + pytest.KNOWLEDGE_BASE_ID = out.split("/knowledgeBases/")[1].split("\n")[0] diff --git a/samples/snippets/detect_intent_audio.py b/samples/snippets/detect_intent_audio.py index 0e1794334..6c3981687 100644 --- a/samples/snippets/detect_intent_audio.py +++ b/samples/snippets/detect_intent_audio.py @@ -31,8 +31,7 @@ # [START dialogflow_detect_intent_audio] -def detect_intent_audio(project_id, session_id, audio_file_path, - language_code): +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 @@ -46,14 +45,16 @@ def detect_intent_audio(project_id, session_id, audio_file_path, sample_rate_hertz = 16000 session = session_client.session_path(project_id, session_id) - print('Session path: {}\n'.format(session)) + print("Session path: {}\n".format(session)) - with open(audio_file_path, 'rb') as audio_file: + with open(audio_file_path, "rb") as audio_file: input_audio = audio_file.read() audio_config = dialogflow.InputAudioConfig( - audio_encoding=audio_encoding, language_code=language_code, - sample_rate_hertz=sample_rate_hertz) + audio_encoding=audio_encoding, + language_code=language_code, + sample_rate_hertz=sample_rate_hertz, + ) query_input = dialogflow.QueryInput(audio_config=audio_config) request = dialogflow.DetectIntentRequest( @@ -63,40 +64,43 @@ def detect_intent_audio(project_id, session_id, audio_file_path, ) response = session_client.detect_intent(request=request) - 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("=" * 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__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', - help='Project/agent id. Required.', - required=True) + "--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())) + "--session-id", + help="Identifier of the DetectIntent session. " "Defaults to a random UUID.", + default=str(uuid.uuid4()), + ) parser.add_argument( - '--language-code', + "--language-code", help='Language code of the query. Defaults to "en-US".', - default='en-US') + default="en-US", + ) parser.add_argument( - '--audio-file-path', - help='Path to the audio file.', - required=True) + "--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) + args.project_id, args.session_id, args.audio_file_path, args.language_code + ) diff --git a/samples/snippets/detect_intent_audio_test.py b/samples/snippets/detect_intent_audio_test.py index a4814aa9e..43054a8b7 100644 --- a/samples/snippets/detect_intent_audio_test.py +++ b/samples/snippets/detect_intent_audio_test.py @@ -19,18 +19,18 @@ from detect_intent_audio import detect_intent_audio DIRNAME = os.path.realpath(os.path.dirname(__file__)) -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -SESSION_ID = 'test_{}'.format(uuid.uuid4()) +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +SESSION_ID = "test_{}".format(uuid.uuid4()) AUDIOS = [ - '{0}/resources/book_a_room.wav'.format(DIRNAME), - '{0}/resources/mountain_view.wav'.format(DIRNAME), - '{0}/resources/today.wav'.format(DIRNAME), + "{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') + 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 + assert "Fulfillment text: What time will the meeting start?" in out diff --git a/samples/snippets/detect_intent_knowledge.py b/samples/snippets/detect_intent_knowledge.py index 56b9a1e00..8ec6c9cca 100644 --- a/samples/snippets/detect_intent_knowledge.py +++ b/samples/snippets/detect_intent_knowledge.py @@ -28,8 +28,9 @@ # [START dialogflow_detect_intent_knowledge] -def detect_intent_knowledge(project_id, session_id, language_code, - knowledge_base_id, texts): +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: @@ -41,69 +42,79 @@ def detect_intent_knowledge(project_id, session_id, language_code, texts: A list of text queries to send. """ from google.cloud 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)) + print("Session path: {}\n".format(session_path)) for text in texts: - text_input = dialogflow.TextInput( - text=text, language_code=language_code) + text_input = dialogflow.TextInput(text=text, language_code=language_code) query_input = dialogflow.QueryInput(text=text_input) - knowledge_base_path = dialogflow.KnowledgeBasesClient \ - .knowledge_base_path(project_id, knowledge_base_id) + knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path( + project_id, knowledge_base_id + ) query_params = dialogflow.QueryParameters( - knowledge_base_names=[knowledge_base_path]) + knowledge_base_names=[knowledge_base_path] + ) request = dialogflow.DetectIntentRequest( - session=session_path, - query_input=query_input, - query_params=query_params + session=session_path, query_input=query_input, query_params=query_params ) response = session_client.detect_intent(request=request) - 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:') + 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)) + print(" - Answer: {}".format(answers.answer)) + print(" - Confidence: {}".format(answers.match_confidence)) + + # [END dialogflow_detect_intent_knowledge] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', help='Project/agent id. Required.', required=True) + "--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())) + "--session-id", + help="ID of the DetectIntent session. " "Defaults to a random UUID.", + default=str(uuid.uuid4()), + ) parser.add_argument( - '--language-code', + "--language-code", help='Language code of the query. Defaults to "en-US".', - default='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.') + "--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) + detect_intent_knowledge( + args.project_id, + args.session_id, + args.language_code, + args.knowledge_base_id, + args.texts, + ) diff --git a/samples/snippets/detect_intent_knowledge_test.py b/samples/snippets/detect_intent_knowledge_test.py index 63864aec1..1ca999a08 100644 --- a/samples/snippets/detect_intent_knowledge_test.py +++ b/samples/snippets/detect_intent_knowledge_test.py @@ -19,15 +19,16 @@ import detect_intent_knowledge -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -SESSION_ID = 'session_{}'.format(uuid.uuid4()) -KNOWLEDGE_BASE_ID = 'MjEwMjE4MDQ3MDQwMDc0NTQ3Mg' -TEXTS = ['Where is my data stored?'] +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +SESSION_ID = "session_{}".format(uuid.uuid4()) +KNOWLEDGE_BASE_ID = "MjEwMjE4MDQ3MDQwMDc0NTQ3Mg" +TEXTS = ["Where is my data stored?"] def test_detect_intent_knowledge(capsys): detect_intent_knowledge.detect_intent_knowledge( - PROJECT_ID, SESSION_ID, 'en-us', KNOWLEDGE_BASE_ID, TEXTS) + PROJECT_ID, SESSION_ID, "en-us", KNOWLEDGE_BASE_ID, TEXTS + ) out, _ = capsys.readouterr() - assert 'Knowledge results' in out + assert "Knowledge results" in out diff --git a/samples/snippets/detect_intent_stream.py b/samples/snippets/detect_intent_stream.py index df3d33b11..430d4b51f 100644 --- a/samples/snippets/detect_intent_stream.py +++ b/samples/snippets/detect_intent_stream.py @@ -30,13 +30,13 @@ # [START dialogflow_detect_intent_streaming] -def detect_intent_stream(project_id, session_id, audio_file_path, - language_code): +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 conversation.""" from google.cloud import dialogflow + session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. @@ -44,77 +44,84 @@ def detect_intent_stream(project_id, session_id, audio_file_path, sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) - print('Session path: {}\n'.format(session_path)) + print("Session path: {}\n".format(session_path)) def request_generator(audio_config, audio_file_path): query_input = dialogflow.QueryInput(audio_config=audio_config) # The first request contains the configuration. yield dialogflow.StreamingDetectIntentRequest( - session=session_path, query_input=query_input) + 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: + 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.StreamingDetectIntentRequest( - input_audio=chunk) + yield dialogflow.StreamingDetectIntentRequest(input_audio=chunk) audio_config = dialogflow.InputAudioConfig( - audio_encoding=audio_encoding, language_code=language_code, - sample_rate_hertz=sample_rate_hertz) + 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=requests) - print('=' * 20) + print("=" * 20) for response in responses: - print('Intermediate transcript: "{}".'.format( - response.recognition_result.transcript)) + 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)) + 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__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', - help='Project/agent id. Required.', - required=True) + "--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())) + "--session-id", + help="Identifier of the DetectIntent session. " "Defaults to a random UUID.", + default=str(uuid.uuid4()), + ) parser.add_argument( - '--language-code', + "--language-code", help='Language code of the query. Defaults to "en-US".', - default='en-US') + default="en-US", + ) parser.add_argument( - '--audio-file-path', - help='Path to the audio file.', - required=True) + "--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) + args.project_id, args.session_id, args.audio_file_path, args.language_code + ) diff --git a/samples/snippets/detect_intent_stream_test.py b/samples/snippets/detect_intent_stream_test.py index 9659308c3..cd1e29ca0 100644 --- a/samples/snippets/detect_intent_stream_test.py +++ b/samples/snippets/detect_intent_stream_test.py @@ -18,16 +18,16 @@ from detect_intent_stream import detect_intent_stream -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -SESSION_ID = 'test_{}'.format(uuid.uuid4()) -AUDIO_FILE_PATH = '{0}/resources/book_a_room.wav'.format( +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +SESSION_ID = "test_{}".format(uuid.uuid4()) +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') + detect_intent_stream(PROJECT_ID, SESSION_ID, AUDIO_FILE_PATH, "en-US") out, _ = capsys.readouterr() - assert 'Intermediate transcript:' in out - assert 'Fulfillment text:' in out + assert "Intermediate transcript:" in out + assert "Fulfillment text:" in out diff --git a/samples/snippets/detect_intent_texts.py b/samples/snippets/detect_intent_texts.py index 8630b519e..673f8a694 100644 --- a/samples/snippets/detect_intent_texts.py +++ b/samples/snippets/detect_intent_texts.py @@ -37,54 +37,56 @@ def detect_intent_texts(project_id, session_id, texts, language_code): Using the same `session_id` between requests allows continuation of the conversation.""" from google.cloud import dialogflow + session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) - print('Session path: {}\n'.format(session)) + print("Session path: {}\n".format(session)) for text in texts: - text_input = dialogflow.TextInput( - text=text, language_code=language_code) + text_input = dialogflow.TextInput(text=text, language_code=language_code) query_input = dialogflow.QueryInput(text=text_input) response = session_client.detect_intent( - request={'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)) + request={"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__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', - help='Project/agent id. Required.', - required=True) + "--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())) + "--session-id", + help="Identifier of the DetectIntent session. " "Defaults to a random UUID.", + default=str(uuid.uuid4()), + ) parser.add_argument( - '--language-code', + "--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.') + 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) + args.project_id, args.session_id, args.texts, args.language_code + ) diff --git a/samples/snippets/detect_intent_texts_test.py b/samples/snippets/detect_intent_texts_test.py index 45404b667..788c3526d 100644 --- a/samples/snippets/detect_intent_texts_test.py +++ b/samples/snippets/detect_intent_texts_test.py @@ -18,14 +18,23 @@ from detect_intent_texts import detect_intent_texts -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -SESSION_ID = 'test_{}'.format(uuid.uuid4()) -TEXTS = ["hello", "book a meeting room", "Mountain View", - "tomorrow", "10 AM", "2 hours", "10 people", "A", "yes"] +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +SESSION_ID = "test_{}".format(uuid.uuid4()) +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') + detect_intent_texts(PROJECT_ID, SESSION_ID, TEXTS, "en-US") out, _ = capsys.readouterr() - assert 'Fulfillment text: All set!' in out + assert "Fulfillment text: All set!" in out diff --git a/samples/snippets/detect_intent_texts_with_location.py b/samples/snippets/detect_intent_texts_with_location.py new file mode 100644 index 000000000..d52ac178d --- /dev/null +++ b/samples/snippets/detect_intent_texts_with_location.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python + +# Copyright 2021 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 to use regional endpoint. + +Examples: + python detect_intent_texts_with_location.py -h + python detect_intent_texts_with_location.py --project-id PROJECT_ID \ + --location-id LOCATION_ID --session-id SESSION_ID \ + "hello" "book a meeting room" "Mountain View" +""" + +import argparse +import uuid + + +# [START dialogflow_detect_intent_text_with_location] +def detect_intent_texts_with_location( + project_id, location_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 conversation.""" + from google.cloud import dialogflow + + session_client = dialogflow.SessionsClient( + client_options={"api_endpoint": f"{location_id}-dialogflow.googleapis.com"} + ) + + session = ( + f"projects/{project_id}/locations/{location_id}/agent/sessions/{session_id}" + ) + print(f"Session path: {session}\n") + + for text in texts: + text_input = dialogflow.TextInput(text=text, language_code=language_code) + + query_input = dialogflow.QueryInput(text=text_input) + + response = session_client.detect_intent( + request={"session": session, "query_input": query_input} + ) + + print("=" * 20) + print(f"Query text: {response.query_result.query_text}") + print( + f"Detected intent: {response.query_result.intent.display_name} (confidence: {response.query_result.intent_detection_confidence,})\n" + ) + print(f"Fulfillment text: {response.query_result.fulfillment_text}\n") + + +# [END dialogflow_detect_intent_text_with_location] + + +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("--location-id", help="Location 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_with_location( + args.project_id, + args.location_id, + args.session_id, + args.texts, + args.language_code, + ) diff --git a/samples/snippets/detect_intent_texts_with_location_test.py b/samples/snippets/detect_intent_texts_with_location_test.py new file mode 100644 index 000000000..5a9e50e48 --- /dev/null +++ b/samples/snippets/detect_intent_texts_with_location_test.py @@ -0,0 +1,43 @@ +# 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 uuid + +from detect_intent_texts_with_location import detect_intent_texts_with_location + +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +LOCATION_ID = "europe-west2" +SESSION_ID = "test_{}".format(uuid.uuid4()) +TEXTS = [ + "hello", + "book a meeting room", + "Mountain View", + "tomorrow", + "10 AM", + "2 hours", + "10 people", + "A", + "yes", +] + + +def test_detect_intent_texts_with_location(capsys): + detect_intent_texts_with_location( + PROJECT_ID, LOCATION_ID, SESSION_ID, TEXTS, "en-GB" + ) + out, _ = capsys.readouterr() + + assert "Fulfillment text: All set!" in out diff --git a/samples/snippets/detect_intent_with_sentiment_analysis.py b/samples/snippets/detect_intent_with_sentiment_analysis.py index c3a6e3121..c9538327e 100644 --- a/samples/snippets/detect_intent_with_sentiment_analysis.py +++ b/samples/snippets/detect_intent_with_sentiment_analysis.py @@ -28,77 +28,88 @@ # [START dialogflow_detect_intent_with_sentiment_analysis] -def detect_intent_with_sentiment_analysis(project_id, session_id, texts, - language_code): +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 conversation.""" from google.cloud import dialogflow + session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) - print('Session path: {}\n'.format(session_path)) + print("Session path: {}\n".format(session_path)) for text in texts: - text_input = dialogflow.TextInput( - text=text, language_code=language_code) + text_input = dialogflow.TextInput(text=text, language_code=language_code) query_input = dialogflow.QueryInput(text=text_input) # Enable sentiment analysis sentiment_config = dialogflow.SentimentAnalysisRequestConfig( - analyze_query_text_sentiment=True) + analyze_query_text_sentiment=True + ) # Set the query parameters with sentiment analysis query_params = dialogflow.QueryParameters( - sentiment_analysis_request_config=sentiment_config) + sentiment_analysis_request_config=sentiment_config + ) response = session_client.detect_intent( - request={'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)) + request={ + "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)) + 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__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', - help='Project/agent id. Required.', - required=True) + "--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())) + "--session-id", + help="Identifier of the DetectIntent session. " "Defaults to a random UUID.", + default=str(uuid.uuid4()), + ) parser.add_argument( - '--language-code', + "--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.') + 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) + args.project_id, args.session_id, args.texts, args.language_code + ) diff --git a/samples/snippets/detect_intent_with_sentiment_analysis_test.py b/samples/snippets/detect_intent_with_sentiment_analysis_test.py index 71d85ae13..434c84082 100644 --- a/samples/snippets/detect_intent_with_sentiment_analysis_test.py +++ b/samples/snippets/detect_intent_with_sentiment_analysis_test.py @@ -16,18 +16,25 @@ import os import uuid -from detect_intent_with_sentiment_analysis import \ - detect_intent_with_sentiment_analysis +from detect_intent_with_sentiment_analysis import detect_intent_with_sentiment_analysis -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -SESSION_ID = 'test_{}'.format(uuid.uuid4()) -TEXTS = ["hello", "book a meeting room", "Mountain View", - "tomorrow", "10 AM", "2 hours", "10 people", "A", "yes"] +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +SESSION_ID = "test_{}".format(uuid.uuid4()) +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') + detect_intent_with_sentiment_analysis(PROJECT_ID, SESSION_ID, TEXTS, "en-US") out, _ = capsys.readouterr() - assert 'Query Text Sentiment Score' in out + assert "Query Text Sentiment Score" in out diff --git a/samples/snippets/detect_intent_with_texttospeech_response.py b/samples/snippets/detect_intent_with_texttospeech_response.py index 630166d79..ad9ab077b 100644 --- a/samples/snippets/detect_intent_with_texttospeech_response.py +++ b/samples/snippets/detect_intent_with_texttospeech_response.py @@ -27,75 +27,77 @@ # [START dialogflow_detect_intent_with_texttospeech_response] -def detect_intent_with_texttospeech_response(project_id, session_id, texts, - language_code): +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 conversation.""" from google.cloud import dialogflow + session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) - print('Session path: {}\n'.format(session_path)) + print("Session path: {}\n".format(session_path)) for text in texts: - text_input = dialogflow.TextInput( - text=text, language_code=language_code) + text_input = dialogflow.TextInput(text=text, language_code=language_code) query_input = dialogflow.QueryInput(text=text_input) # Set the query parameters with sentiment analysis output_audio_config = dialogflow.OutputAudioConfig( - audio_encoding=dialogflow.OutputAudioEncoding - .OUTPUT_AUDIO_ENCODING_LINEAR_16) + audio_encoding=dialogflow.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16 + ) request = dialogflow.DetectIntentRequest( session=session_path, query_input=query_input, - output_audio_config=output_audio_config + output_audio_config=output_audio_config, ) response = session_client.detect_intent(request=request) - 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("=" * 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: + 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__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', - help='Project/agent id. Required.', - required=True) + "--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())) + "--session-id", + help="Identifier of the DetectIntent session. " "Defaults to a random UUID.", + default=str(uuid.uuid4()), + ) parser.add_argument( - '--language-code', + "--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.') + 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) + args.project_id, args.session_id, args.texts, args.language_code + ) diff --git a/samples/snippets/detect_intent_with_texttospeech_response_test.py b/samples/snippets/detect_intent_with_texttospeech_response_test.py index adb904a6d..29fcf838b 100644 --- a/samples/snippets/detect_intent_with_texttospeech_response_test.py +++ b/samples/snippets/detect_intent_with_texttospeech_response_test.py @@ -16,21 +16,21 @@ import os import uuid -from detect_intent_with_texttospeech_response import \ - detect_intent_with_texttospeech_response +from detect_intent_with_texttospeech_response import ( + detect_intent_with_texttospeech_response, +) -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -SESSION_ID = 'test_{}'.format(uuid.uuid4()) +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +SESSION_ID = "test_{}".format(uuid.uuid4()) TEXTS = ["hello"] def test_detect_intent_with_sentiment_analysis(capsys): - detect_intent_with_texttospeech_response(PROJECT_ID, SESSION_ID, TEXTS, - 'en-US') + 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 "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') + os.remove("output.wav") + assert not os.path.isfile("output.wav") diff --git a/samples/snippets/document_management.py b/samples/snippets/document_management.py index 2823bd495..4cbd8a346 100644 --- a/samples/snippets/document_management.py +++ b/samples/snippets/document_management.py @@ -28,12 +28,13 @@ import argparse -KNOWLEDGE_TYPES = ['KNOWLEDGE_TYPE_UNSPECIFIED', 'FAQ', 'EXTRACTIVE_QA'] +KNOWLEDGE_TYPES = ["KNOWLEDGE_TYPE_UNSPECIFIED", "FAQ", "EXTRACTIVE_QA"] # [START dialogflow_create_document]] -def create_document(project_id, knowledge_base_id, display_name, mime_type, - knowledge_type, content_uri): +def create_document( + project_id, knowledge_base_id, display_name, mime_type, knowledge_type, content_uri +): """Creates a Document. Args: @@ -47,70 +48,84 @@ def create_document(project_id, knowledge_base_id, display_name, mime_type, content_uri: Uri of the document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html.""" from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path( - project_id, knowledge_base_id) + project_id, knowledge_base_id + ) document = dialogflow.Document( - display_name=display_name, mime_type=mime_type, - content_uri=content_uri) + display_name=display_name, mime_type=mime_type, content_uri=content_uri + ) document.knowledge_types.append( getattr(dialogflow.Document.KnowledgeType, knowledge_type) ) response = client.create_document(parent=knowledge_base_path, document=document) - print('Waiting for results...') + print("Waiting for results...") document = response.result(timeout=120) - 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:') + 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)) + print(" - {}".format(KNOWLEDGE_TYPES[knowledge_type])) + print(" - Source: {}\n".format(document.content_uri)) + + # [END dialogflow_create_document]] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument( - '--project-id', help='Project id. Required.', required=True) + 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) + "--knowledge-base-id", + help="The id of the Knowledge Base that the Document belongs to", + required=True, + ) - subparsers = parser.add_subparsers(dest='command') + subparsers = parser.add_subparsers(dest="command") create_parser = subparsers.add_parser( - 'create', help='Create a Document for a certain Knowledge base.') + "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('')) + "--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) + "--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) + "--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) + "--content-uri", + help="The uri of the Document, e.g. gs://path/mydoc.csv, " + "http://mypage.com/faq.html", + required=True, + ) args = parser.parse_args() - if args.command == 'create': - create_document(args.project_id, args.knowledge_base_id, - args.display_name, args.mime_type, args.knowledge_type, - args.content_uri) + if args.command == "create": + create_document( + args.project_id, + args.knowledge_base_id, + args.display_name, + args.mime_type, + args.knowledge_type, + args.content_uri, + ) diff --git a/samples/snippets/intent_management.py b/samples/snippets/intent_management.py index a1a4d0993..30292eced 100644 --- a/samples/snippets/intent_management.py +++ b/samples/snippets/intent_management.py @@ -33,44 +33,44 @@ # [START dialogflow_list_intents] def list_intents(project_id): from google.cloud import dialogflow + intents_client = dialogflow.IntentsClient() parent = dialogflow.AgentsClient.agent_path(project_id) - intents = intents_client.list_intents(request={'parent': parent}) + intents = intents_client.list_intents(request={"parent": 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:') + 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("\tName: {}".format(input_context_name)) - print('Output contexts:') + print("Output contexts:") for output_context in intent.output_contexts: - print('\tName: {}'.format(output_context.name)) + 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): +def create_intent(project_id, display_name, training_phrases_parts, message_texts): """Create an intent of the given intent type.""" from google.cloud import dialogflow + intents_client = dialogflow.IntentsClient() parent = dialogflow.AgentsClient.agent_path(project_id) training_phrases = [] for training_phrases_part in training_phrases_parts: - part = dialogflow.Intent.TrainingPhrase.Part( - text=training_phrases_part) + part = dialogflow.Intent.TrainingPhrase.Part(text=training_phrases_part) # Here we create a new training phrase for each provided part. training_phrase = dialogflow.Intent.TrainingPhrase(parts=[part]) training_phrases.append(training_phrase) @@ -79,13 +79,16 @@ def create_intent(project_id, display_name, training_phrases_parts, message = dialogflow.Intent.Message(text=text) intent = dialogflow.Intent( - display_name=display_name, - training_phrases=training_phrases, - messages=[message]) + display_name=display_name, training_phrases=training_phrases, messages=[message] + ) + + response = intents_client.create_intent( + request={"parent": parent, "intent": intent} + ) + + print("Intent created: {}".format(response)) - response = intents_client.create_intent(request={'parent': parent, 'intent': intent}) - print('Intent created: {}'.format(response)) # [END dialogflow_create_intent] @@ -93,77 +96,76 @@ def create_intent(project_id, display_name, training_phrases_parts, def delete_intent(project_id, intent_id): """Delete intent with the given intent type and intent value.""" from google.cloud import dialogflow + intents_client = dialogflow.IntentsClient() intent_path = intents_client.intent_path(project_id, intent_id) - intents_client.delete_intent(request={'name': intent_path}) + intents_client.delete_intent(request={"name": intent_path}) + + # [END dialogflow_delete_intent] # Helper to get intent from display name. def _get_intent_ids(project_id, display_name): from google.cloud import dialogflow + intents_client = dialogflow.IntentsClient() parent = dialogflow.AgentsClient.agent_path(project_id) - intents = intents_client.list_intents(request={'parent': parent}) + intents = intents_client.list_intents(request={"parent": parent}) intent_names = [ - intent.name for intent in intents - if intent.display_name == display_name] + intent.name for intent in intents if intent.display_name == display_name + ] - intent_ids = [ - intent_name.split('/')[-1] for intent_name - in intent_names] + intent_ids = [intent_name.split("/")[-1] for intent_name in intent_names] return intent_ids -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) parser.add_argument( - '--project-id', - help='Project/agent id. Required.', - required=True) + "--project-id", help="Project/agent id. Required.", required=True + ) - subparsers = parser.add_subparsers(dest='command') + subparsers = parser.add_subparsers(dest="command") - list_parser = subparsers.add_parser( - 'list', help=list_intents.__doc__) + 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 = subparsers.add_parser("create", help=create_intent.__doc__) + create_parser.add_argument("display_name") create_parser.add_argument( - '--training-phrases-parts', - nargs='*', + "--training-phrases-parts", + nargs="*", type=str, - help='Training phrases.', - default=[]) + help="Training phrases.", + default=[], + ) create_parser.add_argument( - '--message-texts', - nargs='*', + "--message-texts", + nargs="*", type=str, - help='Message texts for the agent\'s response when the intent ' - 'is detected.', - default=[]) + 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.') + 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': + if args.command == "list": list_intents(args.project_id) - elif args.command == 'create': + elif args.command == "create": create_intent( - args.project_id, args.display_name, args.training_phrases_parts, - args.message_texts, ) - elif args.command == 'delete': + 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/samples/snippets/intent_management_test.py b/samples/snippets/intent_management_test.py index d47cebc44..0c7ed62bd 100644 --- a/samples/snippets/intent_management_test.py +++ b/samples/snippets/intent_management_test.py @@ -19,24 +19,18 @@ import intent_management -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -INTENT_DISPLAY_NAME = 'test_{}'.format(uuid.uuid4()) -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' -] +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +INTENT_DISPLAY_NAME = "test_{}".format(uuid.uuid4()) +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) + PROJECT_ID, INTENT_DISPLAY_NAME, TRAINING_PHRASE_PARTS, MESSAGE_TEXTS + ) - intent_ids = intent_management._get_intent_ids( - PROJECT_ID, INTENT_DISPLAY_NAME) + intent_ids = intent_management._get_intent_ids(PROJECT_ID, INTENT_DISPLAY_NAME) assert len(intent_ids) == 1 @@ -51,8 +45,7 @@ def test_create_intent(capsys): def test_delete_session_entity_type(capsys): - intent_ids = intent_management._get_intent_ids( - PROJECT_ID, INTENT_DISPLAY_NAME) + 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) @@ -62,7 +55,6 @@ def test_delete_session_entity_type(capsys): assert INTENT_DISPLAY_NAME not in out - intent_ids = intent_management._get_intent_ids( - PROJECT_ID, INTENT_DISPLAY_NAME) + intent_ids = intent_management._get_intent_ids(PROJECT_ID, INTENT_DISPLAY_NAME) assert len(intent_ids) == 0 diff --git a/samples/snippets/knowledge_base_management.py b/samples/snippets/knowledge_base_management.py index 699217d94..644a95f0e 100644 --- a/samples/snippets/knowledge_base_management.py +++ b/samples/snippets/knowledge_base_management.py @@ -33,41 +33,41 @@ def create_knowledge_base(project_id, display_name): project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.""" from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() project_path = client.common_project_path(project_id) - knowledge_base = dialogflow.KnowledgeBase( - display_name=display_name) + knowledge_base = dialogflow.KnowledgeBase(display_name=display_name) response = client.create_knowledge_base( - parent=project_path, - knowledge_base=knowledge_base + parent=project_path, knowledge_base=knowledge_base ) - print('Knowledge Base created:\n') - print('Display Name: {}\n'.format(response.display_name)) - print('Knowledge ID: {}\n'.format(response.name)) + 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] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument( - '--project-id', help='Project/agent id.', required=True) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--project-id", help="Project/agent id.", required=True) - subparsers = parser.add_subparsers(dest='command') + subparsers = parser.add_subparsers(dest="command") - create_parser = subparsers.add_parser( - 'create', help='Create a new Knowledge base.') + 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('')) + "--display-name", + help="A name of the Knowledge base, used for display purpose, " + "can not be used to identify the Knowledge base.", + default=str(""), + ) args = parser.parse_args() - if args.command == 'create': + if args.command == "create": create_knowledge_base(args.project_id, args.display_name) diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index b90eef00f..ab2c49227 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -37,28 +37,25 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], - + "ignored_versions": ["2.7"], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - 'envs': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -73,12 +70,12 @@ def get_pytest_env_vars(): ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -87,7 +84,7 @@ def get_pytest_env_vars(): ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) @@ -136,7 +133,7 @@ def _determine_local_import_names(start_dir): @nox.session def lint(session): - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -145,9 +142,11 @@ def lint(session): args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -160,6 +159,7 @@ def blacken(session): session.run("black", *python_files) + # # Sample Tests # @@ -199,9 +199,9 @@ def py(session): if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) #