Skip to content

Commit 6c3db43

Browse files
authored
automl: add natural language sentiment analysis ga samples [(#2677)](GoogleCloudPlatform/python-docs-samples#2677)
* automl: add natural language sentiment analysis ga samples * Add links to documentation * Update tests to use centralized project * Fix environment variable, make translate test less flaky
1 parent e529d69 commit 6c3db43

25 files changed

+296
-21
lines changed

samples/snippets/delete_model_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import delete_model
1818

19-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
19+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
2020

2121

2222
def test_delete_model(capsys):

samples/snippets/deploy_model_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
import deploy_model
2020

21-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
21+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
2222
MODEL_ID = "TRL0000000000000000000"
2323

2424

samples/snippets/get_model_evaluation_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919

2020
import get_model_evaluation
2121

22-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
23-
MODEL_ID = "TEN1499896588007374848"
22+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
23+
MODEL_ID = os.environ["ENTITY_EXTRACTION_MODEL_ID"]
2424

2525

2626
@pytest.fixture(scope="function")

samples/snippets/get_model_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616

1717
import get_model
1818

19-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
20-
MODEL_ID = "TEN1499896588007374848"
19+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
20+
MODEL_ID = os.environ["ENTITY_EXTRACTION_MODEL_ID"]
2121

2222

2323
def test_get_model(capsys):
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
def create_dataset(project_id, display_name):
17+
"""Create a dataset."""
18+
# [START automl_language_sentiment_analysis_create_dataset]
19+
from google.cloud import automl
20+
21+
# TODO(developer): Uncomment and set the following variables
22+
# project_id = "YOUR_PROJECT_ID"
23+
# display_name = "YOUR_DATASET_NAME"
24+
25+
client = automl.AutoMlClient()
26+
27+
# A resource that represents Google Cloud Platform location.
28+
project_location = client.location_path(project_id, "us-central1")
29+
30+
# Each dataset requires a sentiment score with a defined sentiment_max
31+
# value, for more information on TextSentimentDatasetMetadata, see:
32+
# https://cloud.google.com/natural-language/automl/docs/prepare#sentiment-analysis
33+
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsentimentdatasetmetadata
34+
metadata = automl.types.TextSentimentDatasetMetadata(
35+
sentiment_max=4
36+
) # Possible max sentiment score: 1-10
37+
38+
dataset = automl.types.Dataset(
39+
display_name=display_name, text_sentiment_dataset_metadata=metadata
40+
)
41+
42+
# Create a dataset with the dataset metadata in the region.
43+
response = client.create_dataset(project_location, dataset)
44+
45+
created_dataset = response.result()
46+
47+
# Display the dataset information
48+
print("Dataset name: {}".format(created_dataset.name))
49+
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))
50+
# [END automl_language_sentiment_analysis_create_dataset]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import datetime
16+
import os
17+
18+
from google.cloud import automl
19+
20+
import language_sentiment_analysis_create_dataset
21+
22+
23+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
24+
25+
26+
def test_sentiment_analysis_create_dataset(capsys):
27+
dataset_name = "test_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
28+
language_sentiment_analysis_create_dataset.create_dataset(
29+
PROJECT_ID, dataset_name
30+
)
31+
out, _ = capsys.readouterr()
32+
assert "Dataset id: " in out
33+
34+
# Delete the created dataset
35+
dataset_id = out.splitlines()[1].split()[2]
36+
client = automl.AutoMlClient()
37+
dataset_full_id = client.dataset_path(
38+
PROJECT_ID, "us-central1", dataset_id
39+
)
40+
response = client.delete_dataset(dataset_full_id)
41+
response.result()
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
def create_model(project_id, dataset_id, display_name):
17+
"""Create a model."""
18+
# [START automl_language_sentiment_analysis_create_model]
19+
from google.cloud import automl
20+
21+
# TODO(developer): Uncomment and set the following variables
22+
# project_id = "YOUR_PROJECT_ID"
23+
# dataset_id = "YOUR_DATASET_ID"
24+
# display_name = "YOUR_MODEL_NAME"
25+
26+
client = automl.AutoMlClient()
27+
28+
# A resource that represents Google Cloud Platform location.
29+
project_location = client.location_path(project_id, "us-central1")
30+
# Leave model unset to use the default base model provided by Google
31+
metadata = automl.types.TextSentimentModelMetadata()
32+
model = automl.types.Model(
33+
display_name=display_name,
34+
dataset_id=dataset_id,
35+
text_sentiment_model_metadata=metadata,
36+
)
37+
38+
# Create a model with the model metadata in the region.
39+
response = client.create_model(project_location, model)
40+
41+
print("Training operation name: {}".format(response.operation.name))
42+
print("Training started...")
43+
# [END automl_language_sentiment_analysis_create_model]
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
17+
from google.cloud import automl
18+
import pytest
19+
20+
import language_sentiment_analysis_create_model
21+
22+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
23+
DATASET_ID = os.environ["SENTIMENT_ANALYSIS_DATASET_ID"]
24+
25+
26+
@pytest.mark.slow
27+
def test_sentiment_analysis_create_model(capsys):
28+
language_sentiment_analysis_create_model.create_model(
29+
PROJECT_ID, DATASET_ID, "object_test_create_model"
30+
)
31+
out, _ = capsys.readouterr()
32+
assert "Training started" in out
33+
34+
# Cancel the operation
35+
operation_id = out.split("Training operation name: ")[1].split("\n")[0]
36+
client = automl.AutoMlClient()
37+
client.transport._operations_client.cancel_operation(operation_id)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
def predict(project_id, model_id, content):
17+
"""Predict."""
18+
# [START automl_language_sentiment_analysis_predict]
19+
from google.cloud import automl
20+
21+
# TODO(developer): Uncomment and set the following variables
22+
# project_id = "YOUR_PROJECT_ID"
23+
# model_id = "YOUR_MODEL_ID"
24+
# content = "text to predict"
25+
26+
prediction_client = automl.PredictionServiceClient()
27+
28+
# Get the full path of the model.
29+
model_full_id = prediction_client.model_path(
30+
project_id, "us-central1", model_id
31+
)
32+
33+
# Supported mime_types: 'text/plain', 'text/html'
34+
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsnippet
35+
text_snippet = automl.types.TextSnippet(
36+
content=content, mime_type="text/plain"
37+
)
38+
payload = automl.types.ExamplePayload(text_snippet=text_snippet)
39+
40+
response = prediction_client.predict(model_full_id, payload)
41+
42+
for annotation_payload in response.payload:
43+
print(
44+
"Predicted class name: {}".format(annotation_payload.display_name)
45+
)
46+
print(
47+
"Predicted sentiment score: {}".format(
48+
annotation_payload.text_sentiment.sentiment
49+
)
50+
)
51+
# [END automl_language_sentiment_analysis_predict]
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
17+
from google.cloud import automl
18+
import pytest
19+
20+
import language_sentiment_analysis_predict
21+
22+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
23+
MODEL_ID = os.environ["SENTIMENT_ANALYSIS_MODEL_ID"]
24+
25+
26+
@pytest.fixture(scope="function")
27+
def verify_model_state():
28+
client = automl.AutoMlClient()
29+
model_full_id = client.model_path(PROJECT_ID, "us-central1", MODEL_ID)
30+
31+
model = client.get_model(model_full_id)
32+
if model.deployment_state == automl.enums.Model.DeploymentState.UNDEPLOYED:
33+
# Deploy model if it is not deployed
34+
response = client.deploy_model(model_full_id)
35+
response.result()
36+
37+
38+
def test_predict(capsys, verify_model_state):
39+
verify_model_state
40+
text = "Hopefully this Claritin kicks in soon"
41+
language_sentiment_analysis_predict.predict(PROJECT_ID, MODEL_ID, text)
42+
out, _ = capsys.readouterr()
43+
assert "Predicted sentiment score: " in out

samples/snippets/list_model_evaluations_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
import list_model_evaluations
1818

1919

20-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
21-
MODEL_ID = "TEN1499896588007374848"
20+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
21+
MODEL_ID = os.environ["ENTITY_EXTRACTION_MODEL_ID"]
2222

2323

2424
def test_list_get_eval_model(capsys):

samples/snippets/list_models_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import list_models
1818

19-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
19+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
2020

2121

2222
def test_list_get_eval_model(capsys):

samples/snippets/translate_create_dataset.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ def create_dataset(project_id, display_name):
2626

2727
# A resource that represents Google Cloud Platform location.
2828
project_location = client.location_path(project_id, "us-central1")
29+
# For a list of supported languages, see:
30+
# https://cloud.google.com/translate/automl/docs/languages
2931
dataset_metadata = automl.types.TranslationDatasetMetadata(
3032
source_language_code="en", target_language_code="ja"
3133
)

samples/snippets/translate_create_dataset_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import translate_create_dataset
2121

2222

23-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
23+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
2424

2525

2626
def test_translate_create_dataset(capsys):

samples/snippets/translate_create_model_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818

1919
import translate_create_model
2020

21-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
22-
DATASET_ID = "TRL3876092572857648864"
21+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
22+
DATASET_ID = os.environ["TRANSLATION_DATASET_ID"]
2323

2424

2525
def test_translate_create_model(capsys):

samples/snippets/translate_predict_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919

2020
import translate_predict
2121

22-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
23-
MODEL_ID = "TRL3128559826197068699"
22+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
23+
MODEL_ID = os.environ["TRANSLATION_MODEL_ID"]
2424

2525

2626
@pytest.fixture(scope="function")

samples/snippets/undeploy_model_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
import undeploy_model
2020

21-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
21+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
2222
MODEL_ID = "TRL0000000000000000000"
2323

2424

samples/snippets/vision_classification_create_dataset.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def create_dataset(project_id, display_name):
3030
# Types:
3131
# MultiLabel: Multiple labels are allowed for one example.
3232
# MultiClass: At most one label is allowed per example.
33+
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#classificationtype
3334
metadata = automl.types.ImageClassificationDatasetMetadata(
3435
classification_type=automl.enums.ClassificationType.MULTILABEL
3536
)

samples/snippets/vision_classification_create_dataset_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import vision_classification_create_dataset
2222

2323

24-
PROJECT_ID = os.environ["GCLOUD_PROJECT"]
24+
PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
2525

2626

2727
@pytest.mark.slow

0 commit comments

Comments
 (0)