Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

feat: Add support for ModerateText #433

Merged
merged 4 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions google/cloud/language/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
EncodingType,
Entity,
EntityMention,
ModerateTextRequest,
ModerateTextResponse,
PartOfSpeech,
Sentence,
Sentiment,
Expand Down Expand Up @@ -72,6 +74,8 @@
"Document",
"Entity",
"EntityMention",
"ModerateTextRequest",
"ModerateTextResponse",
"PartOfSpeech",
"Sentence",
"Sentiment",
Expand Down
4 changes: 4 additions & 0 deletions google/cloud/language_v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
EncodingType,
Entity,
EntityMention,
ModerateTextRequest,
ModerateTextResponse,
PartOfSpeech,
Sentence,
Sentiment,
Expand Down Expand Up @@ -68,6 +70,8 @@
"Entity",
"EntityMention",
"LanguageServiceClient",
"ModerateTextRequest",
"ModerateTextResponse",
"PartOfSpeech",
"Sentence",
"Sentiment",
Expand Down
15 changes: 15 additions & 0 deletions google/cloud/language_v1/gapic_metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@
"methods": [
"classify_text"
]
},
"ModerateText": {
"methods": [
"moderate_text"
]
}
}
},
Expand Down Expand Up @@ -74,6 +79,11 @@
"methods": [
"classify_text"
]
},
"ModerateText": {
"methods": [
"moderate_text"
]
}
}
},
Expand Down Expand Up @@ -109,6 +119,11 @@
"methods": [
"classify_text"
]
},
"ModerateText": {
"methods": [
"moderate_text"
]
}
}
}
Expand Down
98 changes: 98 additions & 0 deletions google/cloud/language_v1/services/language_service/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,104 @@ async def sample_classify_text():
# Done; return the response.
return response

async def moderate_text(
self,
request: Optional[Union[language_service.ModerateTextRequest, dict]] = None,
*,
document: Optional[language_service.Document] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = (),
) -> language_service.ModerateTextResponse:
r"""Moderates a document for harmful and sensitive
categories.

.. code-block:: python

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in:
# https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import language_v1

async def sample_moderate_text():
# Create a client
client = language_v1.LanguageServiceAsyncClient()

# Initialize request argument(s)
document = language_v1.Document()
document.content = "content_value"

request = language_v1.ModerateTextRequest(
document=document,
)

# Make the request
response = await client.moderate_text(request=request)

# Handle the response
print(response)

Args:
request (Optional[Union[google.cloud.language_v1.types.ModerateTextRequest, dict]]):
The request object. The document moderation request
message.
document (:class:`google.cloud.language_v1.types.Document`):
Required. Input document.
This corresponds to the ``document`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.

Returns:
google.cloud.language_v1.types.ModerateTextResponse:
The document moderation response
message.

"""
# Create or coerce a protobuf request object.
# Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([document])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)

request = language_service.ModerateTextRequest(request)

# If we have keyword arguments corresponding to fields on the
# request, apply these.
if document is not None:
request.document = document

# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.moderate_text,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)

# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)

# Done; return the response.
return response

async def annotate_text(
self,
request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None,
Expand Down
98 changes: 98 additions & 0 deletions google/cloud/language_v1/services/language_service/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,104 @@ def sample_classify_text():
# Done; return the response.
return response

def moderate_text(
self,
request: Optional[Union[language_service.ModerateTextRequest, dict]] = None,
*,
document: Optional[language_service.Document] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = (),
) -> language_service.ModerateTextResponse:
r"""Moderates a document for harmful and sensitive
categories.

.. code-block:: python

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in:
# https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import language_v1

def sample_moderate_text():
# Create a client
client = language_v1.LanguageServiceClient()

# Initialize request argument(s)
document = language_v1.Document()
document.content = "content_value"

request = language_v1.ModerateTextRequest(
document=document,
)

# Make the request
response = client.moderate_text(request=request)

# Handle the response
print(response)

Args:
request (Union[google.cloud.language_v1.types.ModerateTextRequest, dict]):
The request object. The document moderation request
message.
document (google.cloud.language_v1.types.Document):
Required. Input document.
This corresponds to the ``document`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.

Returns:
google.cloud.language_v1.types.ModerateTextResponse:
The document moderation response
message.

"""
# Create or coerce a protobuf request object.
# Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([document])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)

# Minor optimization to avoid making a copy if the user passes
# in a language_service.ModerateTextRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, language_service.ModerateTextRequest):
request = language_service.ModerateTextRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if document is not None:
request.document = document

# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.moderate_text]

# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)

# Done; return the response.
return response

def annotate_text(
self,
request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,11 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=600.0,
client_info=client_info,
),
self.moderate_text: gapic_v1.method.wrap_method(
self.moderate_text,
default_timeout=None,
client_info=client_info,
),
self.annotate_text: gapic_v1.method.wrap_method(
self.annotate_text,
default_retry=retries.Retry(
Expand Down Expand Up @@ -286,6 +291,18 @@ def classify_text(
]:
raise NotImplementedError()

@property
def moderate_text(
self,
) -> Callable[
[language_service.ModerateTextRequest],
Union[
language_service.ModerateTextResponse,
Awaitable[language_service.ModerateTextResponse],
],
]:
raise NotImplementedError()

@property
def annotate_text(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,35 @@ def classify_text(
)
return self._stubs["classify_text"]

@property
def moderate_text(
self,
) -> Callable[
[language_service.ModerateTextRequest], language_service.ModerateTextResponse
]:
r"""Return a callable for the moderate text method over gRPC.

Moderates a document for harmful and sensitive
categories.

Returns:
Callable[[~.ModerateTextRequest],
~.ModerateTextResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "moderate_text" not in self._stubs:
self._stubs["moderate_text"] = self.grpc_channel.unary_unary(
"/google.cloud.language.v1.LanguageService/ModerateText",
request_serializer=language_service.ModerateTextRequest.serialize,
response_deserializer=language_service.ModerateTextResponse.deserialize,
)
return self._stubs["moderate_text"]

@property
def annotate_text(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,36 @@ def classify_text(
)
return self._stubs["classify_text"]

@property
def moderate_text(
self,
) -> Callable[
[language_service.ModerateTextRequest],
Awaitable[language_service.ModerateTextResponse],
]:
r"""Return a callable for the moderate text method over gRPC.

Moderates a document for harmful and sensitive
categories.

Returns:
Callable[[~.ModerateTextRequest],
Awaitable[~.ModerateTextResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "moderate_text" not in self._stubs:
self._stubs["moderate_text"] = self.grpc_channel.unary_unary(
"/google.cloud.language.v1.LanguageService/ModerateText",
request_serializer=language_service.ModerateTextRequest.serialize,
response_deserializer=language_service.ModerateTextResponse.deserialize,
)
return self._stubs["moderate_text"]

@property
def annotate_text(
self,
Expand Down
Loading