📅  最后修改于: 2023-12-03 15:07:32.518000             🧑  作者: Mango
嘿谷歌是一种用于与Google Assistant进行语音交互的口令。当客户说出“嘿谷歌”时,Google Assistant会监听并进行相应的操作。程序员可以编写相应的代码来与Google Assistant进行交互,这样客户就可以通过语音指令使用他们的应用程序或服务。
与Google Assistant进行交互需要使用Google Assistant API。开发人员需要使用相应的凭据来访问API。使用API时,开发人员需要首先构建一个请求并将其发送到API端点。请求必须包含语音或文本指令,以便Assistant可以进行相应的操作。
以下是向Google Assistant API发送语音请求的代码示例:
import google.auth
from google.assistant.library import Assistant
from google.assistant.library.event import EventType
from google.assistant.library.file_helpers import (
existing_file,
read_project_id,
)
credentials, project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/assistant-sdk-prototype"])
device_model_id = read_project_id()
with Assistant(credentials, device_model_id) as assistant:
for event in assistant.start():
if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
print("Conversation started")
elif event.type == EventType.ON_CONVERSATION_TURN_FINISHED:
print("Conversation finished")
elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
print("You said:" + event.args["text"])
开发人员可以为他们的应用程序或服务定制自己的嘿谷歌口令。为此,他们可以使用Google Console创建自己的设备模型和口令短语,并将它们与Google Assistant API相关联。
以下是使用Google Console创建设备模型和口令短语的代码示例:
import google.auth
from google.assistant.api import device_model_pb2
from google.assistant.api import embedded_assistant_pb2
from google.assistant.api import embedded_assistant_pb2_grpc
from google.assistant.embedded.v1alpha2 import (
embedded_assistant_pb2 as embedded_assistant)
from google.assistant.embedded.v1alpha2 import embedded_assistant_pb2_grpc
from google.protobuf.json_format import MessageToJson
DEVICE_MODEL_ID = 'your_device_model_id'
DEVICE_INSTANCE_ID = 'your_device_instance_id'
credentials, _ = google.auth.default(scopes=['https://www.googleapis.com/auth/assistant-sdk-prototype'])
with open(FILENAME, 'rb') as file:
device_config = device_model_pb2.DeviceModel.Config()
device_config.ParseFromString(file.read())
device_model = device_model_pb2.DeviceModel(
device_model_id=DEVICE_MODEL_ID,
device_model_config=device_config
)
client = embedded_assistant_pb2_grpc.EmbeddedAssistantStub(
embedded_assistant_pb2_grpc.create_channel(
'embeddedassistant.googleapis.com',
credentials,
ssl_channel_credentials()
))
create_device_request = embedded_assistant_pb2.CreateDeviceInstanceRequest(
parent='projects/%s' % (project_id,),
device_model_id=DEVICE_MODEL_ID,
device_instance_id=DEVICE_INSTANCE_ID
)
create_device_response = client.CreateDeviceInstance(device_model)
phrases_request = embedded_assistant_pb2.CreateDevicePhrasesRequest(
parent=create_device_response.device_instance_id,
phrases_json=DeviceModelHelper.phrases_to_json(device_model.config.phrases)
)
client.CreateDevicePhrases(phrases_request)
嘿谷歌是一个强大的工具,可以让用户使用语音指令来控制他们的应用程序和服务。开发人员可以使用Google Assistant API与Google Assistant进行交互,并使用Google Console定制自己的设备模型和指令短语。这使得用户与应用程序和服务之间的互动更加自然和便捷。