Skip to content

Commit

Permalink
feat: Migrate API to use python micro-generator (#41)
Browse files Browse the repository at this point in the history
* migrate API to use micro-generator

* migrate API to use micro-generator

* update

* doc changes

* add samples

* add samples

* add samples and readme

* Update README.md

* Update README.md

* Update UPGRADING.md file

* update synth.py

Co-authored-by: arithmetic1728 <liusijun1985@gmail.com>
  • Loading branch information
hkdevandla and arithmetic1728 committed Oct 16, 2020
1 parent 498813c commit 25c46dd
Show file tree
Hide file tree
Showing 23 changed files with 144 additions and 152 deletions.
4 changes: 4 additions & 0 deletions language/snippets/api/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ This directory contains samples for Google Cloud Natural Language API. The `Goog

.. _Google Cloud Natural Language API: https://cloud.google.com/natural-language/docs/





Setup
-------------------------------------------------------------------------------

Expand Down
3 changes: 1 addition & 2 deletions language/snippets/api/analyze_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ def test_analyze_sentiment(capsys):
assert sentiment["magnitude"] < 1

result = analyze.analyze_sentiment(
"cheerio, mate - I greatly admire the pallor of your visage, and your "
"angle of repose leaves little room for improvement."
"cheerio, mate - I greatly admire the pallor of your visage, and your angle of repose leaves little room for improvement."
)

sentiment = result["documentSentiment"]
Expand Down
26 changes: 14 additions & 12 deletions language/snippets/api/noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,24 @@

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

# An envvar key for determining the project id to use. Change it
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
# build specific Cloud project. You can also use your own string
# to use your own Cloud project.
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',

# A dictionary you want to inject into your test. Don't put any
# secrets here. These values will override predefined values.
"envs": {},
'envs': {},
}


try:
# Ensure we can import noxfile_config in the project's directory.
sys.path.append(".")
sys.path.append('.')
from noxfile_config import TEST_CONFIG_OVERRIDE
except ImportError as e:
print("No user noxfile_config found: detail: {}".format(e))
Expand All @@ -67,12 +69,12 @@ def get_pytest_env_vars():
ret = {}

# Override the GCLOUD_PROJECT and the alias.
env_key = TEST_CONFIG["gcloud_project_env"]
env_key = TEST_CONFIG['gcloud_project_env']
# This should error out if not set.
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]
ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key]

# Apply user supplied envs.
ret.update(TEST_CONFIG["envs"])
ret.update(TEST_CONFIG['envs'])
return ret


Expand All @@ -81,7 +83,7 @@ def get_pytest_env_vars():
ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"]

# Any default versions that should be ignored.
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
IGNORED_VERSIONS = TEST_CONFIG['ignored_versions']

TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])

Expand Down Expand Up @@ -136,7 +138,7 @@ def lint(session):
args = FLAKE8_COMMON_ARGS + [
"--application-import-names",
",".join(local_names),
".",
"."
]
session.run("flake8", *args)

Expand Down Expand Up @@ -180,9 +182,9 @@ def py(session):
if session.python in TESTED_VERSIONS:
_session_tests(session)
else:
session.skip(
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
)
session.skip("SKIPPED: {} tests are disabled for this sample.".format(
session.python
))


#
Expand Down
4 changes: 4 additions & 0 deletions language/snippets/classify_text/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ This tutorial demostrates how to use the `classify_text` method to classify cont

.. _Google Cloud Natural Language API: https://cloud.google.com/natural-language/docs/





Setup
-------------------------------------------------------------------------------

Expand Down
10 changes: 5 additions & 5 deletions language/snippets/classify_text/classify_text_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import json
import os

from google.cloud import language
from google.cloud import language_v1
import numpy
import six

Expand All @@ -37,12 +37,12 @@
def classify(text, verbose=True):
"""Classify the input text into categories. """

language_client = language.LanguageServiceClient()
language_client = language_v1.LanguageServiceClient()

document = language.types.Document(
content=text, type=language.enums.Document.Type.PLAIN_TEXT
document = language_v1.Document(
content=text, type_=language_v1.Document.Type.PLAIN_TEXT
)
response = language_client.classify_text(document)
response = language_client.classify_text(request={'document': document})
categories = response.categories

result = {}
Expand Down
26 changes: 14 additions & 12 deletions language/snippets/classify_text/noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,24 @@

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

# An envvar key for determining the project id to use. Change it
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
# build specific Cloud project. You can also use your own string
# to use your own Cloud project.
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',

# A dictionary you want to inject into your test. Don't put any
# secrets here. These values will override predefined values.
"envs": {},
'envs': {},
}


try:
# Ensure we can import noxfile_config in the project's directory.
sys.path.append(".")
sys.path.append('.')
from noxfile_config import TEST_CONFIG_OVERRIDE
except ImportError as e:
print("No user noxfile_config found: detail: {}".format(e))
Expand All @@ -67,12 +69,12 @@ def get_pytest_env_vars():
ret = {}

# Override the GCLOUD_PROJECT and the alias.
env_key = TEST_CONFIG["gcloud_project_env"]
env_key = TEST_CONFIG['gcloud_project_env']
# This should error out if not set.
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]
ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key]

# Apply user supplied envs.
ret.update(TEST_CONFIG["envs"])
ret.update(TEST_CONFIG['envs'])
return ret


Expand All @@ -81,7 +83,7 @@ def get_pytest_env_vars():
ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"]

# Any default versions that should be ignored.
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
IGNORED_VERSIONS = TEST_CONFIG['ignored_versions']

TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])

Expand Down Expand Up @@ -136,7 +138,7 @@ def lint(session):
args = FLAKE8_COMMON_ARGS + [
"--application-import-names",
",".join(local_names),
".",
"."
]
session.run("flake8", *args)

Expand Down Expand Up @@ -180,9 +182,9 @@ def py(session):
if session.python in TESTED_VERSIONS:
_session_tests(session)
else:
session.skip(
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
)
session.skip("SKIPPED: {} tests are disabled for this sample.".format(
session.python
))


#
Expand Down
26 changes: 14 additions & 12 deletions language/snippets/cloud-client/v1/noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,24 @@

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

# An envvar key for determining the project id to use. Change it
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
# build specific Cloud project. You can also use your own string
# to use your own Cloud project.
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',

# A dictionary you want to inject into your test. Don't put any
# secrets here. These values will override predefined values.
"envs": {},
'envs': {},
}


try:
# Ensure we can import noxfile_config in the project's directory.
sys.path.append(".")
sys.path.append('.')
from noxfile_config import TEST_CONFIG_OVERRIDE
except ImportError as e:
print("No user noxfile_config found: detail: {}".format(e))
Expand All @@ -67,12 +69,12 @@ def get_pytest_env_vars():
ret = {}

# Override the GCLOUD_PROJECT and the alias.
env_key = TEST_CONFIG["gcloud_project_env"]
env_key = TEST_CONFIG['gcloud_project_env']
# This should error out if not set.
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]
ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key]

# Apply user supplied envs.
ret.update(TEST_CONFIG["envs"])
ret.update(TEST_CONFIG['envs'])
return ret


Expand All @@ -81,7 +83,7 @@ def get_pytest_env_vars():
ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"]

# Any default versions that should be ignored.
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
IGNORED_VERSIONS = TEST_CONFIG['ignored_versions']

TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])

Expand Down Expand Up @@ -136,7 +138,7 @@ def lint(session):
args = FLAKE8_COMMON_ARGS + [
"--application-import-names",
",".join(local_names),
".",
"."
]
session.run("flake8", *args)

Expand Down Expand Up @@ -180,9 +182,9 @@ def py(session):
if session.python in TESTED_VERSIONS:
_session_tests(session)
else:
session.skip(
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
)
session.skip("SKIPPED: {} tests are disabled for this sample.".format(
session.python
))


#
Expand Down
10 changes: 4 additions & 6 deletions language/snippets/cloud-client/v1/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,21 @@ def run_quickstart():
# [START language_quickstart]
# Imports the Google Cloud client library
# [START language_python_migration_imports]
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
from google.cloud import language_v1

# [END language_python_migration_imports]

# Instantiates a client
# [START language_python_migration_client]
client = language.LanguageServiceClient()
client = language_v1.LanguageServiceClient()
# [END language_python_migration_client]

# The text to analyze
text = u"Hello, world!"
document = types.Document(content=text, type=enums.Document.Type.PLAIN_TEXT)
document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)

# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment

print("Text: {}".format(text))
print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude))
Expand Down
10 changes: 5 additions & 5 deletions language/snippets/cloud-client/v1/set_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@ def set_endpoint():
"""Change your endpoint"""
# [START language_set_endpoint]
# Imports the Google Cloud client library
from google.cloud import language
from google.cloud import language_v1

client_options = {"api_endpoint": "eu-language.googleapis.com:443"}

# Instantiates a client
client = language.LanguageServiceClient(client_options=client_options)
client = language_v1.LanguageServiceClient(client_options=client_options)
# [END language_set_endpoint]

# The text to analyze
document = language.types.Document(
content="Hello, world!", type=language.enums.Document.Type.PLAIN_TEXT
document = language_v1.Document(
content="Hello, world!", type_=language_v1.Document.Type.PLAIN_TEXT
)

# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment

print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
# [START language_sentiment_text]

from google.cloud import language_v1
from google.cloud.language_v1 import enums
import six


Expand All @@ -37,10 +36,10 @@ def sample_analyze_sentiment(content):
if isinstance(content, six.binary_type):
content = content.decode("utf-8")

type_ = enums.Document.Type.PLAIN_TEXT
document = {"type": type_, "content": content}
type_ = language_v1.Document.Type.PLAIN_TEXT
document = {"type_": type_, "content": content}

response = client.analyze_sentiment(document)
response = client.analyze_sentiment(request={'document': document})
sentiment = response.document_sentiment
print("Score: {}".format(sentiment.score))
print("Magnitude: {}".format(sentiment.magnitude))
Expand Down
Loading

0 comments on commit 25c46dd

Please sign in to comment.