Referência da API de palavras-chave personalizadas
Referência do SDK Python para palavras-chave personalizadas
Use o SDK Python para criar, listar, consultar, atualizar e excluir vocabulários personalizados de reconhecimento de fala.
O Alibaba Cloud Model Studio lançou domínios específicos por workspace para as regiões China (Pequim) e Singapura. Os novos domínios dedicados oferecem desempenho superior e maior estabilidade nas solicitações de inferência. Recomendamos migrar para os novos domínios:
China (Pequim): de dashscope.aliyuncs.com para {WorkspaceId}.cn-beijing.maas.aliyuncs.com
Singapura: de dashscope-intl.aliyuncs.com para {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
Substitua {WorkspaceId} pelo seu ID do Workspace real. Os domínios existentes permanecem totalmente funcionais.
Por padrão, o SDK conecta-se ao endpoint da China (Pequim). Para usar outra região, defina dashscope.base_http_api_url antes de fazer qualquer chamada de API.
China (Pequim)
Singapura
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1Substitua {WorkspaceId} pelo seu ID do workspace real.
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1Substitua {WorkspaceId} pelo seu ID do Workspace real.
Singapura
China (Pequim)
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1Substitua {WorkspaceId} pelo seu ID do Workspace real.
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1Substitua {WorkspaceId} pelo seu ID do workspace real.
Para usar a região de Singapura, configure dashscope.base_http_api_url antes de fazer chamadas:
Copy
import dashscope# Set this at the beginning of your codedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
Nota:
As chaves de API variam conforme a região. Use a chave correspondente à sua região.
A configuração de região é global e afeta todas as chamadas da API DashScope.
Modelo de reconhecimento de fala que usa este vocabulário. Este valor deve corresponder exatamente ao modelo especificado na chamada da API de reconhecimento de fala.
prefix
str
Sim
Prefixo personalizado para o vocabulário. Aceita apenas letras minúsculas e dígitos, com limite de 10 caracteres.
vocabulary
List[dict]
Sim
Lista de palavras-chave. Cada entrada é um dicionário com os campos text, weight e lang.
Corresponde à ação da API HTTP action: list_vocabulary (a API HTTP usa o singular, enquanto o método Python list_vocabularies usa o plural).Assinatura do método:
Copy
def list_vocabularies( self, prefix: str = None, page_index: int = 0, page_size: int = 10) -> List[dict]
Parâmetros:
Parâmetro
Tipo
Obrigatório
Descrição
prefix
str
Não
Prefixo personalizado do vocabulário. Se especificado, a resposta incluirá apenas vocabulários com este prefixo.
page_index
int
Não
Número da página, começando em 0.
Valor padrão: 0.
page_size
int
Não
Quantidade de itens por página.
Valor padrão: 10.
Valor de retorno:
Tipo
Descrição
List[dict]
Lista de objetos de vocabulário contendo vocabulary_id, gmt_create, gmt_modified e status.
Objeto de vocabulário contendo vocabulary, target_model, gmt_create, gmt_modified e status.
Campos retornados por query_vocabulary():
Campo
Tipo
Descrição
vocabulary
List[dict]
Conteúdo da lista de palavras-chave.
target_model
str
Modelo de reconhecimento de fala que usa este vocabulário. Este valor deve corresponder exatamente ao modelo especificado na chamada da API de reconhecimento de fala.
O idioma do texto deve ser compatível com o modelo selecionado. Os idiomas suportados variam conforme o modelo.
Use palavras reais em vez de combinações arbitrárias de caracteres para aumentar a precisão do reconhecimento.
Limite máximo: 15 caracteres para textos com caracteres não ASCII ou 7 palavras separadas por espaços para textos exclusivamente ASCII.
weight
int
Sim
Peso da entrada do vocabulário. Valor recomendado: 4.
Valores válidos: 1 a 5.
Se a precisão do reconhecimento não melhorar, aumente o peso. Um peso excessivamente alto pode reduzir a precisão no reconhecimento de outras palavras.
lang
str
Não
Código do idioma do áudio a reconhecer. Quando definido, o sistema aprimora o reconhecimento das entradas do vocabulário no idioma especificado. Caso não seja possível determinar o idioma antecipadamente, deixe este parâmetro indefinido. O modelo detecta o idioma automaticamente.
import dashscopefrom dashscope.audio.asr import *import os# The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key# If no environment variable is configured, replace the following line with your Model Studio API key: dashscope.api_key = "sk-xxx"dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')# The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'prefix = 'testpfx'target_model = "fun-asr"my_vocabulary = [ {"text": "Seediq Bale", "weight": 4}]# Create a custom vocabularyservice = VocabularyService()vocabulary_id = service.create_vocabulary( prefix=prefix, target_model=target_model, vocabulary=my_vocabulary)print(f"Vocabulary ID: {vocabulary_id}")
import dashscopefrom dashscope.audio.asr import *import jsonimport os# The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key# If no environment variable is configured, replace the following line with your Model Studio API key: dashscope.api_key = "sk-xxx"dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')# The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'service = VocabularyService()vocabularies = service.list_vocabularies()print(f"Vocabularies: {json.dumps(vocabularies)}")
import dashscopefrom dashscope.audio.asr import *import jsonimport os# The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key# If no environment variable is configured, replace the following line with your Model Studio API key: dashscope.api_key = "sk-xxx"dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')# The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'service = VocabularyService()# Replace with the actual vocabulary ID when queryingvocabulary = service.query_vocabulary("vocab-testpfx-xxx")print(f"Vocabulary: {json.dumps(vocabulary, ensure_ascii=False)}")
import dashscopefrom dashscope.audio.asr import *import os# The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key# If no environment variable is configured, replace the following line with your Model Studio API key: dashscope.api_key = "sk-xxx"dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')# The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'service = VocabularyService()my_vocabulary = [ {"text": "Seediq Bale", "weight": 4, "lang": "en"}]# Replace with the actual vocabulary ID when updatingservice.update_vocabulary("vocab-testpfx-xxx", my_vocabulary)
import dashscopefrom dashscope.audio.asr import *import os# The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key# If no environment variable is configured, replace the following line with your Model Studio API key: dashscope.api_key = "sk-xxx"dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')# The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'service = VocabularyService()# Replace with the actual vocabulary ID when deletingservice.delete_vocabulary("vocab-testpfx-xxxx")