diff --git a/contact-center-insights/snippets/create_analysis.py b/contact-center-insights/snippets/create_analysis.py new file mode 100644 index 000000000000..2377ec227940 --- /dev/null +++ b/contact-center-insights/snippets/create_analysis.py @@ -0,0 +1,44 @@ +# 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. +# +# [START contactcenterinsights_create_analysis] +from google.cloud import contact_center_insights_v1 + + +def create_analysis(conversation_name: str) -> contact_center_insights_v1.Analysis: + """Creates an analysis. + + Args: + conversation_name: + The parent resource of the analysis. + Format is 'projects/{project_id}/locations/{location_id}/conversations/{conversation_id}'. + For example, 'projects/my-project/locations/us-central1/conversations/123456789'. + + Returns: + An analysis. + """ + # Construct an analysis. + analysis = contact_center_insights_v1.Analysis() + + # Call the Insights client to create an analysis. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + analysis_operation = insights_client.create_analysis( + parent=conversation_name, analysis=analysis + ) + analysis = analysis_operation.result(timeout=86400) + print(f"Created {analysis.name}") + return analysis + + +# [END contactcenterinsights_create_analysis] diff --git a/contact-center-insights/snippets/create_conversation.py b/contact-center-insights/snippets/create_conversation.py new file mode 100644 index 000000000000..2450ad465635 --- /dev/null +++ b/contact-center-insights/snippets/create_conversation.py @@ -0,0 +1,64 @@ +# 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. +# +# [START contactcenterinsights_create_conversation] +from google.cloud import contact_center_insights_v1 + + +def create_conversation( + project_id: str, + transcript_uri: str = "gs://cloud-samples-data/ccai/chat_sample.json", + audio_uri: str = "gs://cloud-samples-data/ccai/voice_6912.txt", +) -> contact_center_insights_v1.Conversation: + """Creates a conversation. + + Args: + project_id: + The project identifier. For example, 'my-project'. + transcript_uri: + The Cloud Storage URI that points to a file that contains the + conversation transcript. Format is 'gs://{bucket_name}/{file.json}'. + For example, 'gs://cloud-samples-data/ccai/chat_sample.json'. + audio_uri: + The Cloud Storage URI that points to a file that contains the + conversation audio. Format is 'gs://{bucket_name}/{file.json}'. + For example, 'gs://cloud-samples-data/ccai/voice_6912.txt'. + + Returns: + A conversation. + """ + # Construct a parent resource. + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + # Construct a conversation. + conversation = contact_center_insights_v1.Conversation() + conversation.data_source.gcs_source.transcript_uri = transcript_uri + conversation.data_source.gcs_source.audio_uri = audio_uri + conversation.medium = contact_center_insights_v1.Conversation.Medium.CHAT + + # Call the Insights client to create a conversation. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + conversation = insights_client.create_conversation( + parent=parent, conversation=conversation + ) + + print(f"Created {conversation.name}") + return conversation + + +# [END contactcenterinsights_create_conversation] diff --git a/contact-center-insights/snippets/create_conversation_with_ttl.py b/contact-center-insights/snippets/create_conversation_with_ttl.py new file mode 100644 index 000000000000..fba2dd0e76e6 --- /dev/null +++ b/contact-center-insights/snippets/create_conversation_with_ttl.py @@ -0,0 +1,71 @@ +# 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. +# +# Create a conversation with a TTL. +# [START contactcenterinsights_create_conversation_with_ttl] +from google.cloud import contact_center_insights_v1 +from google.protobuf import duration_pb2 + + +def create_conversation_with_ttl( + project_id: str, + transcript_uri: str = "gs://cloud-samples-data/ccai/chat_sample.json", + audio_uri: str = "gs://cloud-samples-data/ccai/voice_6912.txt", +) -> contact_center_insights_v1.Conversation: + """Creates a conversation with a TTL value. + + Args: + project_id: + The project identifier. For example, 'my-project'. + transcript_uri: + The Cloud Storage URI that points to a file that contains the + conversation transcript. Format is 'gs://{bucket_name}/{file.json}'. + For example, 'gs://cloud-samples-data/ccai/chat_sample.json'. + audio_uri: + The Cloud Storage URI that points to a file that contains the + conversation audio. Format is 'gs://{bucket_name}/{file.json}'. + For example, 'gs://cloud-samples-data/ccai/voice_6912.txt'. + + Returns: + A conversation. + """ + # Construct a parent resource. + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + # Construct a conversation. + conversation = contact_center_insights_v1.Conversation() + conversation.data_source.gcs_source.transcript_uri = transcript_uri + conversation.data_source.gcs_source.audio_uri = audio_uri + conversation.medium = contact_center_insights_v1.Conversation.Medium.CHAT + + # Construct a TTL. + ttl = duration_pb2.Duration() + ttl.seconds = 86400 + conversation.ttl = ttl + + # Call the Insights client to create a conversation. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + conversation = insights_client.create_conversation( + parent=parent, conversation=conversation + ) + + print(f"Created {conversation.name}") + return conversation + + +# [END contactcenterinsights_create_conversation_with_ttl] diff --git a/contact-center-insights/snippets/create_issue_model.py b/contact-center-insights/snippets/create_issue_model.py new file mode 100644 index 000000000000..9d677a17f56c --- /dev/null +++ b/contact-center-insights/snippets/create_issue_model.py @@ -0,0 +1,52 @@ +# 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. +# +# [START contactcenterinsights_create_issue_model] +from google.cloud import contact_center_insights_v1 + + +def create_issue_model(project_id: str) -> contact_center_insights_v1.IssueModel: + """Creates an issue model. + + Args: + project_id: + The project identifier. For example, 'my-project'. + + Returns: + An issue model. + """ + # Construct a parent resource. + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + # Construct an issue model. + issue_model = contact_center_insights_v1.IssueModel() + issue_model.display_name = "my-model" + issue_model.input_data_config.filter = 'medium="CHAT"' + + # Call the Insights client to create an issue model. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + issue_model_operation = insights_client.create_issue_model( + parent=parent, issue_model=issue_model + ) + + issue_model = issue_model_operation.result(timeout=86400) + print(f"Created an issue model named {issue_model.name}") + return issue_model + + +# [END contactcenterinsights_create_issue_model] diff --git a/contact-center-insights/snippets/create_phrase_matcher_all_of.py b/contact-center-insights/snippets/create_phrase_matcher_all_of.py new file mode 100644 index 000000000000..0175f1f2b079 --- /dev/null +++ b/contact-center-insights/snippets/create_phrase_matcher_all_of.py @@ -0,0 +1,85 @@ +# 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. +# +# [START contactcenterinsights_create_phrase_matcher_all_of] +from google.cloud import contact_center_insights_v1 + + +def create_phrase_matcher_all_of( + project_id: str, +) -> contact_center_insights_v1.PhraseMatcher: + """Creates a phrase matcher that matches all specified queries. + + Args: + project_id: + The project identifier. For example, 'my-project'. + + Returns: + A phrase matcher. + """ + # Construct a parent resource. + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + # Construct a phrase matcher that matches all of its rule groups. + phrase_matcher = contact_center_insights_v1.PhraseMatcher() + phrase_matcher.display_name = "NON_SHIPPING_PHONE_SERVICE" + phrase_matcher.type_ = ( + contact_center_insights_v1.PhraseMatcher.PhraseMatcherType.ALL_OF + ) + phrase_matcher.active = True + + # Construct a rule group to match the word "PHONE" or "CELLPHONE", ignoring case sensitivity. + rule_group_phone_or_cellphone = contact_center_insights_v1.PhraseMatchRuleGroup() + rule_group_phone_or_cellphone.type_ = ( + contact_center_insights_v1.PhraseMatchRuleGroup.PhraseMatchRuleGroupType.ANY_OF + ) + + for word in ["PHONE", "CELLPHONE"]: + rule = contact_center_insights_v1.PhraseMatchRule() + rule.query = word + rule.config.exact_match_config = contact_center_insights_v1.ExactMatchConfig() + rule_group_phone_or_cellphone.phrase_match_rules.append(rule) + phrase_matcher.phrase_match_rule_groups.append(rule_group_phone_or_cellphone) + + # Construct another rule group to not match the word "SHIPPING" or "DELIVERY", ignoring case sensitivity. + rule_group_not_shipping_or_delivery = ( + contact_center_insights_v1.PhraseMatchRuleGroup() + ) + rule_group_not_shipping_or_delivery.type_ = ( + contact_center_insights_v1.PhraseMatchRuleGroup.PhraseMatchRuleGroupType.ALL_OF + ) + + for word in ["SHIPPING", "DELIVERY"]: + rule = contact_center_insights_v1.PhraseMatchRule() + rule.query = word + rule.negated = True + rule.config.exact_match_config = contact_center_insights_v1.ExactMatchConfig() + rule_group_not_shipping_or_delivery.phrase_match_rules.append(rule) + phrase_matcher.phrase_match_rule_groups.append(rule_group_not_shipping_or_delivery) + + # Call the Insights client to create a phrase matcher. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + phrase_matcher = insights_client.create_phrase_matcher( + parent=parent, phrase_matcher=phrase_matcher + ) + + print(f"Created {phrase_matcher.name}") + return phrase_matcher + + +# [END contactcenterinsights_create_phrase_matcher_all_of] diff --git a/contact-center-insights/snippets/create_phrase_matcher_any_of.py b/contact-center-insights/snippets/create_phrase_matcher_any_of.py new file mode 100644 index 000000000000..e55fc4af84cc --- /dev/null +++ b/contact-center-insights/snippets/create_phrase_matcher_any_of.py @@ -0,0 +1,69 @@ +# 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. +# +# [START contactcenterinsights_create_phrase_matcher_any_of] +from google.cloud import contact_center_insights_v1 + + +def create_phrase_matcher_any_of( + project_id: str, +) -> contact_center_insights_v1.PhraseMatcher: + """Creates a phrase matcher that matches any of the specified queries. + + Args: + project_id: + The project identifier. For example, 'my-project'. + + Returns: + A phrase matcher. + """ + # Construct a parent resource. + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + # Construct a phrase matcher that matches any of its rule groups. + phrase_matcher = contact_center_insights_v1.PhraseMatcher() + phrase_matcher.display_name = "PHONE_SERVICE" + phrase_matcher.type_ = ( + contact_center_insights_v1.PhraseMatcher.PhraseMatcherType.ANY_OF + ) + phrase_matcher.active = True + + # Construct a rule group to match the word "PHONE" or "CELLPHONE", ignoring case sensitivity. + rule_group = contact_center_insights_v1.PhraseMatchRuleGroup() + rule_group.type_ = ( + contact_center_insights_v1.PhraseMatchRuleGroup.PhraseMatchRuleGroupType.ANY_OF + ) + + for word in ["PHONE", "CELLPHONE"]: + rule = contact_center_insights_v1.PhraseMatchRule() + rule.query = word + rule.config.exact_match_config = contact_center_insights_v1.ExactMatchConfig() + rule_group.phrase_match_rules.append(rule) + phrase_matcher.phrase_match_rule_groups.append(rule_group) + + # Call the Insights client to create a phrase matcher. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + phrase_matcher = insights_client.create_phrase_matcher( + parent=parent, phrase_matcher=phrase_matcher + ) + + print(f"Created {phrase_matcher.name}") + return phrase_matcher + + +# [END contactcenterinsights_create_phrase_matcher_any_of] diff --git a/contact-center-insights/snippets/enable_pubsub_notifications.py b/contact-center-insights/snippets/enable_pubsub_notifications.py new file mode 100644 index 000000000000..c36d562d4e9f --- /dev/null +++ b/contact-center-insights/snippets/enable_pubsub_notifications.py @@ -0,0 +1,60 @@ +# 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. +# +# [START contactcenterinsights_enable_pubsub_notifications] +from google.api_core import protobuf_helpers +from google.cloud import contact_center_insights_v1 + + +def enable_pubsub_notifications( + project_id: str, topic_create_conversation: str, topic_create_analysis: str +) -> None: + """Enables Cloud Pub/Sub notifications for specified events. + + Args: + project_id: + The project identifier. For example, 'my-project'. + topic_create_conversation: + The Cloud Pub/Sub topic to notify of conversation creation events. + Format is 'projects/{project_id}/topics/{topic_id}'. + For example, 'projects/my-project/topics/my-topic'. + topic_create_analysis: + The Cloud Pub/Sub topic to notify of analysis creation events. + Format is 'projects/{project_id}/topics/{topic_id}'. + For example, 'projects/my-project/topics/my-topic'. + + Returns: + None. + """ + # Construct a settings resource. + settings = contact_center_insights_v1.Settings() + settings.name = ( + contact_center_insights_v1.ContactCenterInsightsClient.settings_path( + project_id, "us-central1" + ) + ) + settings.pubsub_notification_settings = { + "create-conversation": topic_create_conversation, + "create-analysis": topic_create_analysis, + } + + update_mask = protobuf_helpers.field_mask(None, type(settings).pb(settings)) + + # Call the Insights client to enable Pub/Sub notifications. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + insights_client.update_settings(settings=settings, update_mask=update_mask) + print("Enabled Pub/Sub notifications") + + +# [END contactcenterinsights_enable_pubsub_notifications] diff --git a/contact-center-insights/snippets/export_to_bigquery.py b/contact-center-insights/snippets/export_to_bigquery.py new file mode 100644 index 000000000000..48f8b2973938 --- /dev/null +++ b/contact-center-insights/snippets/export_to_bigquery.py @@ -0,0 +1,61 @@ +# 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. +# +# [START contactcenterinsights_export_to_bigquery] +from google.cloud import contact_center_insights_v1 + + +def export_to_bigquery( + project_id: str, + bigquery_project_id: str, + bigquery_dataset_id: str, + bigquery_table_id: str, +) -> None: + """Exports data to BigQuery. + + Args: + project_id: + The project identifier that owns the data source to be exported. + For example, 'my-project'. + bigquery_project_id: + The project identifier that owns the BigQuery sink to export data to. + For example, 'my-project'. + bigquery_dataset_id: + The BigQuery dataset identifier. For example, 'my-dataset'. + bigquery_table_id: + The BigQuery table identifier. For example, 'my-table'. + + Returns: + None. + """ + # Construct an export request. + request = contact_center_insights_v1.ExportInsightsDataRequest() + request.parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + request.big_query_destination.project_id = bigquery_project_id + request.big_query_destination.dataset = bigquery_dataset_id + request.big_query_destination.table = bigquery_table_id + request.filter = 'agent_id="007"' + + # Call the Insights client to export data to BigQuery. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + export_operation = insights_client.export_insights_data(request=request) + export_operation.result(timeout=600000) + print("Exported data to BigQuery") + + +# [END contactcenterinsights_export_to_bigquery] diff --git a/contact-center-insights/snippets/get_operation.py b/contact-center-insights/snippets/get_operation.py new file mode 100644 index 000000000000..f8bd03a91c6c --- /dev/null +++ b/contact-center-insights/snippets/get_operation.py @@ -0,0 +1,47 @@ +# 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. +# +# Get a long-running operation. +# [START contactcenterinsights_get_operation] +from google.cloud import contact_center_insights_v1 +from google.longrunning import operations_pb2 + + +def get_operation(operation_name: str) -> operations_pb2.Operation: + """Gets an operation. + + Args: + operation_name: + The operation name. + Format is 'projects/{project_id}/locations/{location_id}/operations/{operation_id}'. + For example, 'projects/my-project/locations/us-central1/operations/123456789'. + + Returns: + An operation. + """ + # Construct an Insights client that will authenticate via Application Default Credentials. + # See authentication details at https://cloud.google.com/docs/authentication/production. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + + # Call the Insights client to get the operation. + operation = insights_client.transport.operations_client.get_operation( + operation_name + ) + if operation.done: + print("Operation is done") + else: + print("Operation is in progress") + + +# [END contactcenterinsights_get_operation] diff --git a/contact-center-insights/snippets/noxfile_config.py b/contact-center-insights/snippets/noxfile_config.py new file mode 100644 index 000000000000..de104dbc64d3 --- /dev/null +++ b/contact-center-insights/snippets/noxfile_config.py @@ -0,0 +1,292 @@ +# Copyright 2019 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 print_function + +import glob +import os +from pathlib import Path +import sys +from typing import Callable, Dict, Optional + +import nox + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" + +# Copy `noxfile_config.py` to your directory and modify it instead. + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + "ignored_versions": [], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "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': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append(".") + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars() -> Dict[str, str]: + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG["gcloud_project_env"] + # This should error out if not set. + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG["envs"]) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to test samples. +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + +# +# Style Checks +# + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session: nox.sessions.Session) -> None: + if not TEST_CONFIG["enforce_type_hints"]: + session.install("flake8") + else: + session.install("flake8", "flake8-annotations") + + args = FLAKE8_COMMON_ARGS + [ + ".", + ] + session.run("flake8", *args) + + +# +# Black +# + + +@nox.session +def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + session.run("black", *python_files) + + +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests( + session: nox.sessions.Session, post_install: Callable = None +) -> None: + # check for presence of tests + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) + + if len(test_list) == 0: + print("No tests found, skipping directory.") + return + + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") + """Runs py.test for a particular project.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("requirements-test.txt"): + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session: nox.sessions.Session) -> None: + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) + + +# +# Readmegen +# + + +def _get_repo_root() -> Optional[str]: + """Returns the root folder of the project.""" + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + # .git is not available in repos cloned via Cloud Build + # setup.py is always in the library's root, so use that instead + # https://github.com/googleapis/synthtool/issues/792 + if Path(p / "setup.py").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session: nox.sessions.Session, path: str) -> None: + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/contact-center-insights/snippets/requirements-test.txt b/contact-center-insights/snippets/requirements-test.txt new file mode 100644 index 000000000000..e3d9b4d517e3 --- /dev/null +++ b/contact-center-insights/snippets/requirements-test.txt @@ -0,0 +1,3 @@ +google-auth==2.16.0 +google-cloud-pubsub==2.13.12 +pytest==7.2.1 diff --git a/contact-center-insights/snippets/requirements.txt b/contact-center-insights/snippets/requirements.txt new file mode 100644 index 000000000000..c1672ab994cc --- /dev/null +++ b/contact-center-insights/snippets/requirements.txt @@ -0,0 +1,3 @@ +google-api-core==2.11.0 +google-cloud-bigquery==3.4.1 +google-cloud-contact-center-insights==1.6.0 diff --git a/contact-center-insights/snippets/set_project_ttl.py b/contact-center-insights/snippets/set_project_ttl.py new file mode 100644 index 000000000000..a56476a6ef29 --- /dev/null +++ b/contact-center-insights/snippets/set_project_ttl.py @@ -0,0 +1,65 @@ +# 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. +# +# Set a project-level TTL for all incoming conversations. +# [START contactcenterinsights_set_project_ttl] +from google.api_core import protobuf_helpers +from google.cloud import contact_center_insights_v1 +from google.protobuf import duration_pb2 + + +def set_project_ttl(project_id: str) -> None: + """Sets a project-level TTL for all incoming conversations. + + Args: + project_id: + The project identifier. For example, 'my-project'. + + Returns: + None. + """ + # Construct a settings resource. + settings = contact_center_insights_v1.Settings() + settings.name = ( + contact_center_insights_v1.ContactCenterInsightsClient.settings_path( + project_id, "us-central1" + ) + ) + + conversation_ttl = duration_pb2.Duration() + conversation_ttl.seconds = 86400 + settings.conversation_ttl = conversation_ttl + + # Construct an update mask to only update the fields that are set on the settings resource. + update_mask = protobuf_helpers.field_mask(None, type(settings).pb(settings)) + + # Construct an Insights client that will authenticate via Application Default Credentials. + # See authentication details at https://cloud.google.com/docs/authentication/production. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + + # Call the Insights client to set a project-level TTL. + insights_client.update_settings(settings=settings, update_mask=update_mask) + + # Call the Insights client to get the project-level TTL to confirm that it was set. + new_conversation_ttl = insights_client.get_settings( + name=settings.name + ).conversation_ttl + print( + "Set TTL for all incoming conversations to {} day".format( + new_conversation_ttl.days + ) + ) + + +# [END contactcenterinsights_set_project_ttl] diff --git a/contact-center-insights/snippets/test_create_analysis.py b/contact-center-insights/snippets/test_create_analysis.py new file mode 100644 index 000000000000..0d660123dd2c --- /dev/null +++ b/contact-center-insights/snippets/test_create_analysis.py @@ -0,0 +1,68 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import create_analysis + +TRANSCRIPT_URI = "gs://cloud-samples-data/ccai/chat_sample.json" +AUDIO_URI = "gs://cloud-samples-data/ccai/voice_6912.txt" + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def conversation_resource(project_id): + # Create a conversation. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + conversation = contact_center_insights_v1.Conversation() + conversation.data_source.gcs_source.transcript_uri = TRANSCRIPT_URI + conversation.data_source.gcs_source.audio_uri = AUDIO_URI + conversation.medium = contact_center_insights_v1.Conversation.Medium.CHAT + + conversation = insights_client.create_conversation( + parent=parent, conversation=conversation + ) + yield conversation + + # Delete the conversation. + delete_request = contact_center_insights_v1.DeleteConversationRequest() + delete_request.name = conversation.name + delete_request.force = True + insights_client.delete_conversation(request=delete_request) + + +@pytest.fixture +def analysis_resource(conversation_resource): + conversation_name = conversation_resource.name + yield create_analysis.create_analysis(conversation_name) + + +def test_create_analysis(capsys, analysis_resource): + analysis = analysis_resource + out, err = capsys.readouterr() + assert "Created {}".format(analysis.name) in out diff --git a/contact-center-insights/snippets/test_create_conversation.py b/contact-center-insights/snippets/test_create_conversation.py new file mode 100644 index 000000000000..a3ca4c2c51b4 --- /dev/null +++ b/contact-center-insights/snippets/test_create_conversation.py @@ -0,0 +1,42 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import create_conversation + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def conversation_resource(project_id): + # Create a conversation + conversation = create_conversation.create_conversation(project_id) + yield conversation + + # Delete the conversation. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + insights_client.delete_conversation(name=conversation.name) + + +def test_create_conversation(capsys, conversation_resource): + conversation = conversation_resource + out, err = capsys.readouterr() + assert "Created {}".format(conversation.name) in out diff --git a/contact-center-insights/snippets/test_create_conversation_with_ttl.py b/contact-center-insights/snippets/test_create_conversation_with_ttl.py new file mode 100644 index 000000000000..53ea32135728 --- /dev/null +++ b/contact-center-insights/snippets/test_create_conversation_with_ttl.py @@ -0,0 +1,42 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import create_conversation_with_ttl + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def conversation_resource(project_id): + # Create a conversation + conversation = create_conversation_with_ttl.create_conversation_with_ttl(project_id) + yield conversation + + # Delete the conversation. + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + insights_client.delete_conversation(name=conversation.name) + + +def test_create_conversation_with_ttl(capsys, conversation_resource): + conversation = conversation_resource + out, err = capsys.readouterr() + assert "Created {}".format(conversation.name) in out diff --git a/contact-center-insights/snippets/test_create_issue_model.py b/contact-center-insights/snippets/test_create_issue_model.py new file mode 100644 index 000000000000..2b5f128d635e --- /dev/null +++ b/contact-center-insights/snippets/test_create_issue_model.py @@ -0,0 +1,70 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import create_issue_model + +MIN_CONVERSATION_COUNT = 10000 + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def insights_client(): + return contact_center_insights_v1.ContactCenterInsightsClient() + + +@pytest.fixture +def count_conversations(project_id, insights_client): + # Check if the project has the minimum number of conversations required to create an issue model. + # See https://cloud.google.com/contact-center/insights/docs/topic-model. + list_request = contact_center_insights_v1.ListConversationsRequest() + list_request.page_size = 1000 + list_request.parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + conversations = insights_client.list_conversations(request=list_request) + conversation_count = len(list(conversations)) + + yield conversation_count + + +@pytest.fixture +def issue_model_resource(project_id, insights_client, count_conversations): + conversation_count = count_conversations + if conversation_count >= MIN_CONVERSATION_COUNT: + # Create an issue model. + issue_model = create_issue_model.create_issue_model(project_id) + yield issue_model + + # Delete the issue model. + insights_client.delete_issue_model(name=issue_model.name) + else: + yield None + + +def test_create_issue_model(capsys, issue_model_resource): + issue_model = issue_model_resource + if issue_model: + out, err = capsys.readouterr() + assert "Created {}".format(issue_model.name) in out diff --git a/contact-center-insights/snippets/test_create_phrase_matcher_all_of.py b/contact-center-insights/snippets/test_create_phrase_matcher_all_of.py new file mode 100644 index 000000000000..6c9b217e67a1 --- /dev/null +++ b/contact-center-insights/snippets/test_create_phrase_matcher_all_of.py @@ -0,0 +1,48 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import create_phrase_matcher_all_of + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def insights_client(): + return contact_center_insights_v1.ContactCenterInsightsClient() + + +@pytest.fixture +def phrase_matcher_all_of(project_id, insights_client): + # Create a phrase matcher. + phrase_matcher = create_phrase_matcher_all_of.create_phrase_matcher_all_of( + project_id + ) + yield phrase_matcher + + # Delete the phrase matcher. + insights_client.delete_phrase_matcher(name=phrase_matcher.name) + + +def test_create_phrase_matcher_all_of(capsys, phrase_matcher_all_of): + phrase_matcher = phrase_matcher_all_of + out, err = capsys.readouterr() + assert f"Created {phrase_matcher.name}" in out diff --git a/contact-center-insights/snippets/test_create_phrase_matcher_any_of.py b/contact-center-insights/snippets/test_create_phrase_matcher_any_of.py new file mode 100644 index 000000000000..62efcccfd7d4 --- /dev/null +++ b/contact-center-insights/snippets/test_create_phrase_matcher_any_of.py @@ -0,0 +1,48 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import create_phrase_matcher_any_of + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def insights_client(): + return contact_center_insights_v1.ContactCenterInsightsClient() + + +@pytest.fixture +def phrase_matcher_any_of(project_id, insights_client): + # Create a phrase matcher. + phrase_matcher = create_phrase_matcher_any_of.create_phrase_matcher_any_of( + project_id + ) + yield phrase_matcher + + # Delete the phrase matcher. + insights_client.delete_phrase_matcher(name=phrase_matcher.name) + + +def test_create_phrase_matcher_any_of(capsys, phrase_matcher_any_of): + phrase_matcher = phrase_matcher_any_of + out, err = capsys.readouterr() + assert f"Created {phrase_matcher.name}" in out diff --git a/contact-center-insights/snippets/test_enable_pubsub_notifications.py b/contact-center-insights/snippets/test_enable_pubsub_notifications.py new file mode 100644 index 000000000000..d3ae6959dbe6 --- /dev/null +++ b/contact-center-insights/snippets/test_enable_pubsub_notifications.py @@ -0,0 +1,80 @@ +# 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. +# +import uuid + +import google.auth +from google.cloud import contact_center_insights_v1, pubsub_v1 +from google.protobuf import field_mask_pb2 +import pytest + +import enable_pubsub_notifications + +UUID = uuid.uuid4().hex[:8] +CONVERSATION_TOPIC_ID = "create-conversation-" + UUID +ANALYSIS_TOPIC_ID = "create-analysis-" + UUID + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def pubsub_topics(project_id): + # Create Pub/Sub topics. + pubsub_client = pubsub_v1.PublisherClient() + conversation_topic_path = pubsub_client.topic_path( + project_id, CONVERSATION_TOPIC_ID + ) + conversation_topic = pubsub_client.create_topic( + request={"name": conversation_topic_path} + ) + analysis_topic_path = pubsub_client.topic_path(project_id, ANALYSIS_TOPIC_ID) + analysis_topic = pubsub_client.create_topic(request={"name": analysis_topic_path}) + yield conversation_topic.name, analysis_topic.name + + # Delete Pub/Sub topics. + pubsub_client.delete_topic(request={"topic": conversation_topic.name}) + pubsub_client.delete_topic(request={"topic": analysis_topic.name}) + + +@pytest.fixture +def disable_pubsub_notifications(project_id): + yield + settings = contact_center_insights_v1.Settings() + settings.name = ( + contact_center_insights_v1.ContactCenterInsightsClient.settings_path( + project_id, "us-central1" + ) + ) + settings.pubsub_notification_settings = {} + update_mask = field_mask_pb2.FieldMask() + update_mask.paths.append("pubsub_notification_settings") + + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + insights_client.update_settings(settings=settings, update_mask=update_mask) + + +def test_enable_pubsub_notifications( + capsys, project_id, pubsub_topics, disable_pubsub_notifications +): + conversation_topic, analysis_topic = pubsub_topics + + enable_pubsub_notifications.enable_pubsub_notifications( + project_id, conversation_topic, analysis_topic + ) + out, err = capsys.readouterr() + assert "Enabled Pub/Sub notifications" in out diff --git a/contact-center-insights/snippets/test_export_to_bigquery.py b/contact-center-insights/snippets/test_export_to_bigquery.py new file mode 100644 index 000000000000..c9ada15601ed --- /dev/null +++ b/contact-center-insights/snippets/test_export_to_bigquery.py @@ -0,0 +1,63 @@ +# 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. +# +import uuid + +import google.auth +from google.cloud import bigquery +import pytest + +import export_to_bigquery + +GCLOUD_TESTS_PREFIX = "python_samples_tests" + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def unique_id(): + uuid_hex = uuid.uuid4().hex[:8] + return f"{GCLOUD_TESTS_PREFIX}_{uuid_hex}" + + +@pytest.fixture +def bigquery_resources(project_id, unique_id): + # Create a BigQuery dataset. + bigquery_client = bigquery.Client() + dataset_id = unique_id + table_id = unique_id + + dataset = bigquery.Dataset(f"{project_id}.{dataset_id}") + dataset.location = "US" + bigquery_client.create_dataset(dataset, timeout=30) + + # Create a BigQuery table under the created dataset. + table = bigquery.Table(f"{project_id}.{dataset_id}.{table_id}") + bigquery_client.create_table(table) + + yield dataset_id, table_id + + # Delete the BigQuery dataset and table. + bigquery_client.delete_dataset(dataset_id, delete_contents=True) + + +def test_export_data_to_bigquery(capsys, project_id, bigquery_resources): + dataset_id, table_id = bigquery_resources + export_to_bigquery.export_to_bigquery(project_id, project_id, dataset_id, table_id) + out, err = capsys.readouterr() + assert "Exported data to BigQuery" in out diff --git a/contact-center-insights/snippets/test_get_operation.py b/contact-center-insights/snippets/test_get_operation.py new file mode 100644 index 000000000000..087d6fa0ea2b --- /dev/null +++ b/contact-center-insights/snippets/test_get_operation.py @@ -0,0 +1,80 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +import pytest + +import get_operation + +TRANSCRIPT_URI = "gs://cloud-samples-data/ccai/chat_sample.json" +AUDIO_URI = "gs://cloud-samples-data/ccai/voice_6912.txt" + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def insights_client(): + return contact_center_insights_v1.ContactCenterInsightsClient() + + +@pytest.fixture +def conversation_resource(project_id, insights_client): + # Create a conversation. + parent = ( + contact_center_insights_v1.ContactCenterInsightsClient.common_location_path( + project_id, "us-central1" + ) + ) + + conversation = contact_center_insights_v1.Conversation() + conversation.data_source.gcs_source.transcript_uri = TRANSCRIPT_URI + conversation.data_source.gcs_source.audio_uri = AUDIO_URI + conversation.medium = contact_center_insights_v1.Conversation.Medium.CHAT + + conversation = insights_client.create_conversation( + parent=parent, conversation=conversation + ) + yield conversation + + # Delete the conversation. + delete_request = contact_center_insights_v1.DeleteConversationRequest() + delete_request.name = conversation.name + delete_request.force = True + insights_client.delete_conversation(request=delete_request) + + +@pytest.fixture +def analysis_operation(conversation_resource, insights_client): + # Create an analysis. + conversation_name = conversation_resource.name + analysis = contact_center_insights_v1.Analysis() + analysis_operation = insights_client.create_analysis( + parent=conversation_name, analysis=analysis + ) + + # Wait until the analysis operation is done and return the operation. + analysis_operation.result(timeout=600) + yield analysis_operation + + +def test_get_operation(capsys, analysis_operation): + operation_name = analysis_operation.operation.name + get_operation.get_operation(operation_name) + out, err = capsys.readouterr() + assert "Operation is done" in out diff --git a/contact-center-insights/snippets/test_set_project_ttl.py b/contact-center-insights/snippets/test_set_project_ttl.py new file mode 100644 index 000000000000..6ddc3a024725 --- /dev/null +++ b/contact-center-insights/snippets/test_set_project_ttl.py @@ -0,0 +1,49 @@ +# 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. +# +import google.auth +from google.cloud import contact_center_insights_v1 +from google.protobuf import field_mask_pb2 +import pytest + +import set_project_ttl + + +@pytest.fixture +def project_id(): + _, project_id = google.auth.default() + return project_id + + +@pytest.fixture +def clear_project_ttl(project_id): + yield + settings = contact_center_insights_v1.Settings() + settings.name = ( + contact_center_insights_v1.ContactCenterInsightsClient.settings_path( + project_id, "us-central1" + ) + ) + settings.conversation_ttl = None + update_mask = field_mask_pb2.FieldMask() + update_mask.paths.append("conversation_ttl") + + insights_client = contact_center_insights_v1.ContactCenterInsightsClient() + insights_client.update_settings(settings=settings, update_mask=update_mask) + + +def test_set_project_ttl(capsys, project_id, clear_project_ttl): + set_project_ttl.set_project_ttl(project_id) + out, err = capsys.readouterr() + assert "Set TTL for all incoming conversations to 1 day" in out