Google Cloud Natural Language API client library providing sentiment analysis, entity recognition, text classification, and content moderation capabilities
—
Core client classes for interacting with the Google Cloud Natural Language API. The library provides both synchronous and asynchronous clients with configurable transport layers, authentication options, and error handling.
The primary client class for making synchronous API calls to Google Cloud Natural Language service.
class LanguageServiceClient:
def __init__(
self,
*,
credentials: ga_credentials.Credentials = None,
transport: Union[str, LanguageServiceTransport] = None,
client_options: Union[client_options_lib.ClientOptions, dict] = None,
client_info: gapic_v1.client_info.ClientInfo = None,
):
"""
Instantiates the language service client.
Args:
credentials: The credentials to use for authentication
transport: Transport to use for communication ('grpc', 'rest', or transport instance)
client_options: Custom options for the client
client_info: Client information for user agent
"""from google.cloud import language
from google.oauth2 import service_account
# Initialize with default credentials
client = language.LanguageServiceClient()
# Initialize with service account credentials
credentials = service_account.Credentials.from_service_account_file(
"path/to/service-account-key.json"
)
client = language.LanguageServiceClient(credentials=credentials)
# Initialize with custom transport
client = language.LanguageServiceClient(transport='rest')Asynchronous client for non-blocking API calls using async/await patterns.
class LanguageServiceAsyncClient:
def __init__(
self,
*,
credentials: ga_credentials.Credentials = None,
transport: Union[str, LanguageServiceAsyncTransport] = None,
client_options: Union[client_options_lib.ClientOptions, dict] = None,
client_info: gapic_v1.client_info.ClientInfo = None,
):
"""
Instantiates the asynchronous language service client.
Args:
credentials: The credentials to use for authentication
transport: Transport to use for communication ('grpc_asyncio' or transport instance)
client_options: Custom options for the client
client_info: Client information for user agent
"""All client methods are available in async versions:
async def analyze_sentiment(
self,
request: Optional[Union[AnalyzeSentimentRequest, dict]] = None,
*,
document: Optional[Document] = None,
encoding_type: Optional[EncodingType] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> AnalyzeSentimentResponse: ...
async def analyze_entities(
self,
request: Optional[Union[AnalyzeEntitiesRequest, dict]] = None,
*,
document: Optional[Document] = None,
encoding_type: Optional[EncodingType] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> AnalyzeEntitiesResponse: ...
async def classify_text(
self,
request: Optional[Union[ClassifyTextRequest, dict]] = None,
*,
document: Optional[Document] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> ClassifyTextResponse: ...
async def moderate_text(
self,
request: Optional[Union[ModerateTextRequest, dict]] = None,
*,
document: Optional[Document] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> ModerateTextResponse: ...
async def annotate_text(
self,
request: Optional[Union[AnnotateTextRequest, dict]] = None,
*,
document: Optional[Document] = None,
features: Optional[AnnotateTextRequest.Features] = None,
encoding_type: Optional[EncodingType] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> AnnotateTextResponse: ...async def analyze_entity_sentiment(
self,
request: Optional[Union[AnalyzeEntitySentimentRequest, dict]] = None,
*,
document: Optional[Document] = None,
encoding_type: Optional[EncodingType] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> AnalyzeEntitySentimentResponse: ...
async def analyze_syntax(
self,
request: Optional[Union[AnalyzeSyntaxRequest, dict]] = None,
*,
document: Optional[Document] = None,
encoding_type: Optional[EncodingType] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> AnalyzeSyntaxResponse: ...import asyncio
from google.cloud import language
async def main():
# Initialize async client
client = language.LanguageServiceAsyncClient()
# Create document
document = language.Document(
content="This is a great product!",
type_=language.Document.Type.PLAIN_TEXT
)
# Perform async analysis
response = await client.analyze_sentiment(
request={"document": document}
)
print(f"Sentiment: {response.document_sentiment.score}")
# Run async function
asyncio.run(main())The library supports multiple transport mechanisms for communicating with the API.
class LanguageServiceGrpcTransport:
def __init__(
self,
*,
host: str = "language.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = None,
always_use_jwt_access: Optional[bool] = False,
api_audience: Optional[str] = None,
): ...class LanguageServiceGrpcAsyncIOTransport:
def __init__(
self,
*,
host: str = "language.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = None,
always_use_jwt_access: Optional[bool] = False,
api_audience: Optional[str] = None,
): ...class LanguageServiceRestTransport:
def __init__(
self,
*,
host: str = "language.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = None,
always_use_jwt_access: Optional[bool] = False,
url_scheme: str = "https",
interceptor: Optional[LanguageServiceRestInterceptor] = None,
api_audience: Optional[str] = None,
): ...Common configuration options for customizing client behavior.
from google.api_core import client_options
# Configure API endpoint
options = client_options.ClientOptions(
api_endpoint="custom-language-endpoint.googleapis.com"
)
client = language.LanguageServiceClient(client_options=options)from google.api_core import retry
# Custom retry configuration
custom_retry = retry.Retry(
predicate=retry.if_exception_type(
core_exceptions.ServiceUnavailable,
core_exceptions.DeadlineExceeded,
),
deadline=60.0,
)
# Use with API calls
response = client.analyze_sentiment(
request={"document": document},
retry=custom_retry
)# Set timeout for API calls
response = client.analyze_sentiment(
request={"document": document},
timeout=30.0 # 30 seconds
)Required OAuth2 scopes for accessing the Cloud Natural Language API.
AUTH_SCOPES = (
"https://www.googleapis.com/auth/cloud-language",
"https://www.googleapis.com/auth/cloud-platform",
)DEFAULT_HOST = "language.googleapis.com"
DEFAULT_MTLS_HOST = "language.mtls.googleapis.com"Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-language