CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-cloud-language

Google Cloud Natural Language API client library providing sentiment analysis, entity recognition, text classification, and content moderation capabilities

Pending
Overview
Eval results
Files

client-management.mddocs/

Client Management

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.

Capabilities

Synchronous Client

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
        """

Usage Example

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

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
        """

Async Methods

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: ...

Additional Async Methods (v1/v1beta2 only)

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: ...

Usage Example

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())

Transport Options

The library supports multiple transport mechanisms for communicating with the API.

gRPC Transport (Default)

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,
    ): ...

gRPC Async Transport

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,
    ): ...

REST Transport

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,
    ): ...

Client Configuration

Common configuration options for customizing client behavior.

Client Options

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)

Retry Configuration

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
)

Timeout Configuration

# Set timeout for API calls
response = client.analyze_sentiment(
    request={"document": document},
    timeout=30.0  # 30 seconds
)

Authentication Scopes

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",
)

Constants

DEFAULT_HOST = "language.googleapis.com"
DEFAULT_MTLS_HOST = "language.mtls.googleapis.com"

Install with Tessl CLI

npx tessl i tessl/pypi-google-cloud-language

docs

client-management.md

combined-analysis.md

content-moderation.md

entity-analysis.md

entity-sentiment-analysis.md

index.md

sentiment-analysis.md

syntax-analysis.md

text-classification.md

tile.json