類別 SpeechClient (2.15.0)

SpeechClient(*, credentials: typing.Optional[google.auth.credentials.Credentials] = None, transport: typing.Optional[typing.Union[str, google.cloud.speech_v1p1beta1.services.speech.transports.base.SpeechTransport]] = None, client_options: typing.Optional[typing.Union[google.api_core.client_options.ClientOptions, dict]] = None, client_info: google.api_core.gapic_v1.client_info.ClientInfo = <google.api_core.gapic_v1.client_info.ClientInfo object>)

執行 Google Cloud Speech API 的服務。

屬性

transport

傳回用戶端例項使用的傳輸方式。

退貨
類型說明
SpeechTransport用戶端執行個體使用的傳輸方式。

方法

SpeechClient

SpeechClient(*, credentials: typing.Optional[google.auth.credentials.Credentials] = None, transport: typing.Optional[typing.Union[str, google.cloud.speech_v1p1beta1.services.speech.transports.base.SpeechTransport]] = None, client_options: typing.Optional[typing.Union[google.api_core.client_options.ClientOptions, dict]] = None, client_info: google.api_core.gapic_v1.client_info.ClientInfo = <google.api_core.gapic_v1.client_info.ClientInfo object>)

例項化語音用戶端。

參數
名稱說明
credentials Optional[google.auth.credentials.Credentials]

要附加至要求的授權憑證。這些憑證會向服務識別應用程式;如未指定任何憑證,用戶端會嘗試從環境中確認憑證。

transport Union[str, SpeechTransport]

要使用的傳輸方式。如果設為 None,系統會自動選擇傳輸方式。

client_options Optional[Union[google.api_core.client_options.ClientOptions, dict]]

為客戶提供自訂選項。如果提供 transport 執行個體,這項設定就不會生效。(1) api_endpoint 屬性可用於覆寫用戶端提供的預設端點。您也可以使用 GOOGLE_API_USE_MTLS_ENDPOINT 環境變數覆寫端點:「always」(一律使用預設的 mTLS 端點)、「never」(一律使用預設的一般端點) 和「auto」(如果存在用戶端憑證,則自動切換至預設的 mTLS 端點,這是預設值)。不過,如果提供 api_endpoint 屬性,系統會優先採用該屬性。(2) 如果 GOOGLE_API_USE_CLIENT_CERTIFICATE 環境變數為「true」,則 client_cert_source 屬性可用於提供用戶端憑證,以進行相互 TLS 傳輸。如未提供,系統會使用預設的 SSL 用戶端憑證 (如有)。如果 GOOGLE_API_USE_CLIENT_CERTIFICATE 為「false」或未設定,系統就不會使用用戶端憑證。

client_info google.api_core.gapic_v1.client_info.ClientInfo

用於傳送使用者代理程式字串和 API 要求的用戶端資訊。如果為 None,系統會使用預設資訊。一般來說,只有在開發自己的用戶端程式庫時,才需要設定這項屬性。

例外狀況
類型說明
google.auth.exceptions.MutualTLSChannelError如果因任何原因無法建立相互 TLS 傳輸作業。

__exit__

__exit__(type, value, traceback)

釋出基礎傳輸的資源。

common_billing_account_path

common_billing_account_path(billing_account: str) -> str

傳回完整帳單帳戶字串。

common_folder_path

common_folder_path(folder: str) -> str

傳回完整資料夾字串。

common_location_path

common_location_path(project: str, location: str) -> str

傳回完整的地理位置字串。

common_organization_path

common_organization_path(organization: str) -> str

傳回完整的機構字串。

common_project_path

common_project_path(project: str) -> str

傳回完整的專案字串。

custom_class_path

custom_class_path(project: str, location: str, custom_class: str) -> str

傳回完全符合規定的 custom_class 字串。

from_service_account_file

from_service_account_file(filename: str, *args, **kwargs)

使用提供的憑證檔案建立這個用戶端的執行個體。

參數
名稱說明
filename str

服務帳戶私密金鑰 JSON 檔案的路徑。

退貨
類型說明
SpeechClient建構的用戶端。

from_service_account_info

from_service_account_info(info: dict, *args, **kwargs)

使用提供的憑證資訊建立這個用戶端的執行個體。

參數
名稱說明
info dict

服務帳戶私密金鑰資訊。

退貨
類型說明
SpeechClient建構的用戶端。

from_service_account_json

from_service_account_json(filename: str, *args, **kwargs)

使用提供的憑證檔案建立這個用戶端的執行個體。

參數
名稱說明
filename str

服務帳戶私密金鑰 JSON 檔案的路徑。

退貨
類型說明
SpeechClient建構的用戶端。

get_mtls_endpoint_and_cert_source

get_mtls_endpoint_and_cert_source(
    client_options: typing.Optional[
        google.api_core.client_options.ClientOptions
    ] = None,
)

傳回 mTLS 的 API 端點和用戶端憑證來源。

用戶端憑證來源的判斷順序如下: (1) 如果 GOOGLE_API_USE_CLIENT_CERTIFICATE 環境變數不是「true」,則用戶端憑證來源為 None。 (2) 如果提供 client_options.client_cert_source,則使用提供的來源;如果存在預設用戶端憑證來源,則使用預設來源;否則用戶端憑證來源為 None。

API 端點的決定順序如下: (1) 如果提供 client_options.api_endpoint,則使用提供的端點。 (2) 如果 GOOGLE_API_USE_CLIENT_CERTIFICATE 環境變數為「always」,請使用預設的 mTLS 端點;如果環境變數為「never」,請使用預設的 API 端點;否則,如果存在用戶端憑證來源,請使用預設的 mTLS 端點,否則請使用預設的 API 端點。

詳情請參閱 https://google.aip.dev/auth/4114

參數
名稱說明
client_options google.api_core.client_options.ClientOptions

為客戶提供自訂選項。這個方法只能使用 api_endpointclient_cert_source 屬性。

例外狀況
類型說明
google.auth.exceptions.MutualTLSChannelError如果發生任何錯誤。
退貨
類型說明
Tuple[str, Callable[[], Tuple[bytes, bytes]]]傳回要使用的 API 端點和用戶端憑證來源。

get_operation

get_operation(
    request: typing.Optional[
        google.longrunning.operations_pb2.GetOperationRequest
    ] = None,
    *,
    retry: typing.Union[
        google.api_core.retry.Retry, google.api_core.gapic_v1.method._MethodDefault
    ] = _MethodDefault._DEFAULT_VALUE,
    timeout: typing.Union[float, object] = _MethodDefault._DEFAULT_VALUE,
    metadata: typing.Sequence[typing.Tuple[str, str]] = ()
) -> google.longrunning.operations_pb2.Operation

取得長時間執行的作業的最新狀態。

參數
名稱說明
request .operations_pb2.GetOperationRequest

要求物件。GetOperation 方法的要求訊息。

retry google.api_core.retry.Retry

指定應重試的錯誤 (如有)。

timeout float

這項要求的逾時時間。

metadata Sequence[Tuple[str, str]]

應隨要求一併傳送的字串 (做為中繼資料)。

退貨
類型說明
.operations_pb2.OperationOperation 物件。

list_operations

list_operations(
    request: typing.Optional[
        google.longrunning.operations_pb2.ListOperationsRequest
    ] = None,
    *,
    retry: typing.Union[
        google.api_core.retry.Retry, google.api_core.gapic_v1.method._MethodDefault
    ] = _MethodDefault._DEFAULT_VALUE,
    timeout: typing.Union[float, object] = _MethodDefault._DEFAULT_VALUE,
    metadata: typing.Sequence[typing.Tuple[str, str]] = ()
) -> google.longrunning.operations_pb2.ListOperationsResponse

列出符合要求中指定篩選器的作業。

參數
名稱說明
request .operations_pb2.ListOperationsRequest

要求物件。ListOperations 方法的要求訊息。

retry google.api_core.retry.Retry

指定應重試的錯誤 (如有)。

timeout float

這項要求的逾時時間。

metadata Sequence[Tuple[str, str]]

應隨要求一併傳送的字串 (做為中繼資料)。

退貨
類型說明
.operations_pb2.ListOperationsResponseListOperations 方法的回應訊息。

long_running_recognize

long_running_recognize(
    request: typing.Optional[
        typing.Union[
            google.cloud.speech_v1p1beta1.types.cloud_speech.LongRunningRecognizeRequest, dict
        ]
    ] = None,
    *,
    config: typing.Optional[
        google.cloud.speech_v1p1beta1.types.cloud_speech.RecognitionConfig
    ] = None,
    audio: typing.Optional[
        google.cloud.speech_v1p1beta1.types.cloud_speech.RecognitionAudio
    ] = None,
    retry: typing.Union[
        google.api_core.retry.Retry, google.api_core.gapic_v1.method._MethodDefault
    ] = _MethodDefault._DEFAULT_VALUE,
    timeout: typing.Union[float, object] = _MethodDefault._DEFAULT_VALUE,
    metadata: typing.Sequence[typing.Tuple[str, str]] = ()
) -> google.api_core.operation.Operation

執行非同步語音辨識:透過 google.longrunning.Operations 介面接收結果。傳回 Operation.error 或包含 LongRunningRecognizeResponse 訊息的 Operation.response。如要進一步瞭解非同步語音辨識,請參閱<https://cloud.google.com/speech-to-text/docs/async-recognize>

# 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 speech_v1p1beta1

def sample_long_running_recognize():
    # Create a client
    client = speech_v1p1beta1.SpeechClient()

    # Initialize request argument(s)
    config = speech_v1p1beta1.RecognitionConfig()
    config.language_code = "language_code_value"

    audio = speech_v1p1beta1.RecognitionAudio()
    audio.content = b'content_blob'

    request = speech_v1p1beta1.LongRunningRecognizeRequest(
        config=config,
        audio=audio,
    )

    # Make the request
    operation = client.long_running_recognize(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)
參數
名稱說明
request Union[google.cloud.speech_v1p1beta1.types.LongRunningRecognizeRequest, dict]

要求物件。用戶端為 LongRunningRecognize 方法傳送的頂層訊息。

config google.cloud.speech_v1p1beta1.types.RecognitionConfig

這是必要旗標,提供資訊給辨識器,指定如何處理要求。這對應於 request 例項的 config 欄位;如果提供 request,則不應設定此欄位。

audio google.cloud.speech_v1p1beta1.types.RecognitionAudio

這是必要旗標,待辨識的音訊資料。這對應於 request 例項的 audio 欄位;如果提供 request,則不應設定此欄位。

retry google.api_core.retry.Retry

指定應重試的錯誤 (如有)。

timeout float

這項要求的逾時時間。

metadata Sequence[Tuple[str, str]]

應隨要求一併傳送的字串 (做為中繼資料)。

退貨
類型說明
google.api_core.operation.Operation代表長時間執行的作業的物件。這項作業的結果類型為 LongRunningRecognizeResponse。LongRunningRecognize 方法傳回給用戶端的唯一訊息。其中包含零或多個連續的 SpeechRecognitionResult 訊息,做為結果。這項資訊會包含在 google::longrunning::Operations 服務的 GetOperation 呼叫所傳回的 Operation 的 result.response 欄位中。

parse_common_billing_account_path

parse_common_billing_account_path(path: str) -> typing.Dict[str, str]

將 billing_account 路徑剖析為元件區隔。

parse_common_folder_path

parse_common_folder_path(path: str) -> typing.Dict[str, str]

將資料夾路徑剖析為元件區段。

parse_common_location_path

parse_common_location_path(path: str) -> typing.Dict[str, str]

將位置路徑剖析為元件區段。

parse_common_organization_path

parse_common_organization_path(path: str) -> typing.Dict[str, str]

將機構路徑剖析為元件區隔。

parse_common_project_path

parse_common_project_path(path: str) -> typing.Dict[str, str]

將專案路徑剖析為元件區隔。

parse_custom_class_path

parse_custom_class_path(path: str) -> typing.Dict[str, str]

將 custom_class 路徑剖析為元件區隔。

parse_phrase_set_path

parse_phrase_set_path(path: str) -> typing.Dict[str, str]

將 phrase_set 路徑剖析為元件區隔。

phrase_set_path

phrase_set_path(project: str, location: str, phrase_set: str) -> str

傳回完整片語集字串。

recognize

recognize(
    request: typing.Optional[
        typing.Union[google.cloud.speech_v1p1beta1.types.cloud_speech.RecognizeRequest, dict]
    ] = None,
    *,
    config: typing.Optional[
        google.cloud.speech_v1p1beta1.types.cloud_speech.RecognitionConfig
    ] = None,
    audio: typing.Optional[
        google.cloud.speech_v1p1beta1.types.cloud_speech.RecognitionAudio
    ] = None,
    retry: typing.Union[
        google.api_core.retry.Retry, google.api_core.gapic_v1.method._MethodDefault
    ] = _MethodDefault._DEFAULT_VALUE,
    timeout: typing.Union[float, object] = _MethodDefault._DEFAULT_VALUE,
    metadata: typing.Sequence[typing.Tuple[str, str]] = ()
) -> google.cloud.speech_v1p1beta1.types.cloud_speech.RecognizeResponse

執行同步語音辨識:在所有音訊傳送及處理完畢後接收結果。

# 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 speech_v1p1beta1

def sample_recognize():
    # Create a client
    client = speech_v1p1beta1.SpeechClient()

    # Initialize request argument(s)
    config = speech_v1p1beta1.RecognitionConfig()
    config.language_code = "language_code_value"

    audio = speech_v1p1beta1.RecognitionAudio()
    audio.content = b'content_blob'

    request = speech_v1p1beta1.RecognizeRequest(
        config=config,
        audio=audio,
    )

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

    # Handle the response
    print(response)
參數
名稱說明
request Union[google.cloud.speech_v1p1beta1.types.RecognizeRequest, dict]

要求物件。用戶端為 Recognize 方法傳送的頂層訊息。

config google.cloud.speech_v1p1beta1.types.RecognitionConfig

這是必要旗標,提供資訊給辨識器,指定如何處理要求。這對應於 request 例項的 config 欄位;如果提供 request,則不應設定此欄位。

audio google.cloud.speech_v1p1beta1.types.RecognitionAudio

這是必要旗標,待辨識的音訊資料。這對應於 request 例項的 audio 欄位;如果提供 request,則不應設定此欄位。

retry google.api_core.retry.Retry

指定應重試的錯誤 (如有)。

timeout float

這項要求的逾時時間。

metadata Sequence[Tuple[str, str]]

應隨要求一併傳送的字串 (做為中繼資料)。

退貨
類型說明
google.cloud.speech_v1p1beta1.types.RecognizeResponse這是 Recognize 方法傳回給用戶端的唯一訊息。其中包含零或多個連續的 SpeechRecognitionResult 訊息。

streaming_recognize

streaming_recognize(
    requests: typing.Optional[
        typing.Iterator[
            google.cloud.speech_v1p1beta1.types.cloud_speech.StreamingRecognizeRequest
        ]
    ] = None,
    *,
    retry: typing.Union[
        google.api_core.retry.Retry, google.api_core.gapic_v1.method._MethodDefault
    ] = _MethodDefault._DEFAULT_VALUE,
    timeout: typing.Union[float, object] = _MethodDefault._DEFAULT_VALUE,
    metadata: typing.Sequence[typing.Tuple[str, str]] = ()
) -> typing.Iterable[
    google.cloud.speech_v1p1beta1.types.cloud_speech.StreamingRecognizeResponse
]

執行雙向串流語音辨識:在傳送音訊時接收結果。這個方法只能透過 gRPC API (而非 REST) 使用。

# 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 speech_v1p1beta1

def sample_streaming_recognize():
    # Create a client
    client = speech_v1p1beta1.SpeechClient()

    # Initialize request argument(s)
    streaming_config = speech_v1p1beta1.StreamingRecognitionConfig()
    streaming_config.config.language_code = "language_code_value"

    request = speech_v1p1beta1.StreamingRecognizeRequest(
        streaming_config=streaming_config,
    )

    # This method expects an iterator which contains
    # 'speech_v1p1beta1.StreamingRecognizeRequest' objects
    # Here we create a generator that yields a single `request` for
    # demonstrative purposes.
    requests = [request]

    def request_generator():
        for request in requests:
            yield request

    # Make the request
    stream = client.streaming_recognize(requests=request_generator())

    # Handle the response
    for response in stream:
        print(response)
參數
名稱說明
requests Iterator[google.cloud.speech_v1p1beta1.types.StreamingRecognizeRequest]

要求物件迭代器。用戶端為 StreamingRecognize 方法傳送的頂層訊息。系統傳送多封 StreamingRecognizeRequest 訊息。第一個訊息必須包含 streaming_config 訊息,且不得包含 audio_content。所有後續訊息都必須包含 audio_content,且不得包含 streaming_config 訊息。

retry google.api_core.retry.Retry

指定應重試的錯誤 (如有)。

timeout float

這項要求的逾時時間。

metadata Sequence[Tuple[str, str]]

應隨要求一併傳送的字串 (做為中繼資料)。

退貨
類型說明
Iterable[google.cloud.speech_v1p1beta1.types.StreamingRecognizeResponse]StreamingRecognize 只會將 StreamingRecognizeResponse 訊息傳回給用戶端。系統會將一系列零或多個 StreamingRecognizeResponse 訊息串流回用戶端。如果沒有可辨識的音訊,且 single_utterance 設為 false,系統就不會將任何訊息串流回用戶端。以下是在處理音訊時可能傳回的一系列 StreamingRecognizeResponses 範例:1. results { alternatives { transcript: "tube" } stability: 0.01 } 2. results { alternatives { transcript: "to be a" } stability: 0.01 } 3. results { alternatives { transcript: "to be" } stability: 0.9 } results { alternatives { transcript: " or not to be" } stability: 0.01 } 4. results { alternatives { transcript: "to be or not to be" confidence: 0.92 } alternatives { transcript: "to bee or not to bee" } is_final: true } 5. results { alternatives { transcript: " that's" } stability: 0.01 } 6. results { alternatives { transcript: " that is" } stability: 0.9 } results { alternatives { transcript: " the question" } stability: 0.01 } 7. results { alternatives { transcript: " that is the question" confidence: 0.98 } alternatives { transcript: " that was the question" } is_final: true } 注意事項:- 上述回應中只有 #4 和 #7 包含最終結果,這些結果會以 is_final: true 表示。將這些內容串連在一起,即可產生完整轉錄稿:「to be or not to be that is the question」(生存還是毀滅,這是個問題)。- 其他檔案則包含中期結果。#3 和 #6 包含兩個暫時性 \results:第一部分穩定性高,不太可能變更;第二部分穩定性低,很可能變更。UI 設計師可能會選擇只顯示高穩定性結果。- 上方顯示的特定穩定性和信賴度值僅供說明。實際值可能會有差異。- 在每個回應中,只會設定其中一個欄位:錯誤、speech_event_type 或一或多個 (重複) 結果。