仅通过项目密钥获取Google Speech-to-Text API有效位置的方法咨询
问题描述
我正在使用Google Speech-to-Text API开展项目,希望通过SpeechAdaption为选定词汇设置boost值。目前仅持有项目API密钥,没有project_id,但已能通过该密钥创建客户端。在使用适配客户端创建自定义类时,需要指定包含project_id和location的父资源路径(示例代码如下),想了解仅通过现有项目密钥如何获取对应项目的有效location,且无法按照文档要求创建新凭证,只能使用现有密钥。
# The parent resource where the custom class and phrase set will be created. parent = f"projects/{project_id}/locations/{location}" # Create the custom class resource adaptation_client.create_custom_class( { "parent": parent, "custom_class_id": custom_class_id, "custom_class": { "items": [ {"value": "barrows"} ] }, } )
解决方案
1. 先通过API密钥获取project_id
要获取location,首先得确定对应的project_id。可以调用Google Cloud Resource Manager API,用现有密钥请求项目列表:
import requests # 替换为你的现有API密钥 api_key = "YOUR_EXISTING_API_KEY" # 请求项目列表 response = requests.get(f"https://cloudresourcemanager.googleapis.com/v1/projects?key={api_key}") projects = response.json().get('projects', []) if projects: # 取第一个关联的项目ID(如果密钥绑定多个项目,按需选择) project_id = projects[0]['projectId'] print(f"获取到项目ID: {project_id}") else: print("该API密钥未关联任何项目,或没有权限访问项目列表")
2. 通过project_id获取有效location
拿到project_id后,调用Speech-to-Text API的locations列表接口,获取该项目支持的有效区域:
# 替换为上一步获取到的project_id project_id = "YOUR_PROJECT_ID" # 请求支持的区域列表 response = requests.get(f"https://speech.googleapis.com/v1/projects/{project_id}/locations?key={api_key}") locations = response.json().get('locations', []) if locations: # 取第一个有效区域(常用如us-central1、europe-west1等) valid_location = locations[0]['locationId'] print(f"获取到有效区域: {valid_location}") else: print("未找到该项目支持的Speech-to-Text区域")
3. 整合到现有代码中
将获取到的project_id和valid_location代入parent路径,即可正常创建自定义类:
parent = f"projects/{project_id}/locations/{valid_location}" adaptation_client.create_custom_class( { "parent": parent, "custom_class_id": custom_class_id, "custom_class": { "items": [ {"value": "barrows"} ] }, } )
注意事项
- 确保你的API密钥已被授予Cloud Resource Manager API的读取权限和Speech-to-Text API的权限,否则上述接口会返回权限错误。
- SpeechAdaption资源(自定义类、短语集)不支持
global区域,必须使用具体的区域ID(如us-central1)。
内容的提问来源于stack exchange,提问作者sai sandeep balbari
相关产品推荐
相关产品推荐

