Skip to content

Commit

Permalink
samples: create custom highlights (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
TrucHLe authored Sep 20, 2021
1 parent 61ad847 commit fbe592f
Show file tree
Hide file tree
Showing 7 changed files with 259 additions and 21 deletions.
74 changes: 74 additions & 0 deletions contact-center-insights/snippets/create_phrase_matcher_all_of.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# 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:
# 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]
58 changes: 58 additions & 0 deletions contact-center-insights/snippets/create_phrase_matcher_any_of.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# 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:
# 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]
44 changes: 25 additions & 19 deletions contact-center-insights/snippets/noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,31 +39,29 @@

TEST_CONFIG = {
# You can opt out from the test for specific Python versions.
'ignored_versions': [],

"ignored_versions": [],
# 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',
# 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': {},
"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))
Expand All @@ -78,12 +76,12 @@ def get_pytest_env_vars() -> Dict[str, str]:
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


Expand All @@ -92,11 +90,14 @@ def get_pytest_env_vars() -> Dict[str, str]:
ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"]

# 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])

INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true")
INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in (
"True",
"true",
)
#
# Style Checks
#
Expand Down Expand Up @@ -141,7 +142,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]:

@nox.session
def lint(session: nox.sessions.Session) -> None:
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")
Expand All @@ -150,9 +151,11 @@ def lint(session: nox.sessions.Session) -> None:
args = FLAKE8_COMMON_ARGS + [
"--application-import-names",
",".join(local_names),
"."
".",
]
session.run("flake8", *args)


#
# Black
#
Expand All @@ -165,6 +168,7 @@ def blacken(session: nox.sessions.Session) -> None:

session.run("black", *python_files)


#
# Sample Tests
#
Expand All @@ -173,7 +177,9 @@ def blacken(session: nox.sessions.Session) -> None:
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]


def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None:
def _session_tests(
session: nox.sessions.Session, post_install: Callable = None
) -> None:
if TEST_CONFIG["pip_version_override"]:
pip_version = TEST_CONFIG["pip_version_override"]
session.install(f"pip=={pip_version}")
Expand Down Expand Up @@ -203,7 +209,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None)
# 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()
env=get_pytest_env_vars(),
)


Expand All @@ -213,9 +219,9 @@ def py(session: nox.sessions.Session) -> None:
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)
)


#
Expand Down
2 changes: 1 addition & 1 deletion contact-center-insights/snippets/requirements-test.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
google-auth==2.0.2
google-cloud-pubsub==2.8.0
protobuf==3.17.3
pytest==6.2.5
pytest==6.2.5
2 changes: 1 addition & 1 deletion contact-center-insights/snippets/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
google-api-core==2.0.1
google-cloud-bigquery==2.26.0
google-cloud-contact-center-insights==0.2.0
google-cloud-contact-center-insights==0.2.0
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 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

0 comments on commit fbe592f

Please sign in to comment.