Skip to content

Commit

Permalink
feat: add sample code for using regional Dialogflow endpoint (#254)
Browse files Browse the repository at this point in the history
* 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 <yuanye@google.com>
  • Loading branch information
martini9393 and Ye Yuan authored Feb 13, 2021
1 parent 0014158 commit b561392
Show file tree
Hide file tree
Showing 21 changed files with 638 additions and 429 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
)
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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]
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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
)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading

0 comments on commit b561392

Please sign in to comment.