Referência da API de palavras-chave personalizadas
Referência do SDK Java para hotwords personalizadas
Use o SDK Java para criar, 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 usa o endpoint da região China (Pequim). Para mudar para outra região, modifique Constants.baseHttpApiUrl antes da inicialização.
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, defina Constants.baseHttpApiUrl antes da inicialização:
Copy
import com.alibaba.dashscope.utils.Constants;// Set this at the beginning of your codeConstants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
Observação:
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 à API DashScope.
createVocabulary() - Criar um vocabulário personalizado
Assinatura do método:
Copy
public Vocabulary createVocabulary(String targetModel,String prefix,JsonArray vocabulary) throws NoApiKeyException, InputRequiredException
Parâmetros:
Parâmetro
Tipo
Obrigatório
Descrição
targetModel
String
Sim
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
String
Sim
Prefixo personalizado para o vocabulário. São permitidos apenas letras minúsculas e dígitos, com comprimento máximo de 10 caracteres.
vocabulary
JsonArray
Sim
Lista de hotwords. Cada JsonObject contém campos como text, weight e lang.
queryVocabulary() - Consultar um vocabulário personalizado
Assinatura do método:
Copy
public Vocabulary queryVocabulary(String vocabularyId) throws NoApiKeyException, InputRequiredException
Parâmetros:
Parâmetro
Tipo
Obrigatório
Descrição
vocabularyId
String
Sim
ID do vocabulário personalizado a ser consultado.
Valor de retorno:
Tipo
Descrição
Vocabulary
Objeto Vocabulary contendo as entradas de hotwords e metadados.
Campos retornados por queryVocabulary():
Campo
Tipo
Descrição
vocabulary
JsonArray
Conteúdo do vocabulário personalizado.
targetModel
String
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 ter suporte no modelo selecionado. Os idiomas suportados variam conforme o modelo.
Use palavras reais em vez de combinações arbitrárias de caracteres para melhorar a precisão do reconhecimento.
Comprimento máximo: 15 caracteres para texto com caracteres não ASCII ou 7 palavras separadas por espaços para texto 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
String
Não
Código do idioma do áudio a ser reconhecido. Quando definido, o sistema aprimora o reconhecimento das entradas de vocabulário no idioma especificado. Se não for possível determinar o idioma antecipadamente, deixe este parâmetro indefinido. O modelo detecta o idioma automaticamente.
import com.alibaba.dashscope.audio.asr.vocabulary.Vocabulary;import com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService;import com.alibaba.dashscope.exception.InputRequiredException;import com.alibaba.dashscope.exception.NoApiKeyException;import com.alibaba.dashscope.utils.Constants;import com.google.gson.JsonArray;import com.google.gson.JsonObject;import java.util.ArrayList;import java.util.List;public class Main { // The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key // If you have not configured an environment variable, replace the following line with your Model Studio API key: public static String apiKey = "sk-xxx" public static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void main(String[] args) throws NoApiKeyException, InputRequiredException { // The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region. Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; String targetModel = "fun-asr"; JsonArray vocabularyJson = new JsonArray(); List<Hotword> wordList = new ArrayList<>(); wordList.add(new Hotword("Wu yi gong", 4)); wordList.add(new Hotword("A Family in Queli", 4)); for (Hotword word : wordList) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("text", word.text); jsonObject.addProperty("weight", word.weight); vocabularyJson.add(jsonObject); } VocabularyService service = new VocabularyService(apiKey); Vocabulary vocabulary = service.createVocabulary(targetModel, "testpfx", vocabularyJson); System.out.println("Custom vocabulary ID: " + vocabulary.getVocabularyId()); }}class Hotword { String text; int weight; public Hotword(String text, int weight) { this.text = text; this.weight = weight; }}
import com.alibaba.dashscope.audio.asr.vocabulary.Vocabulary;import com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService;import com.alibaba.dashscope.exception.InputRequiredException;import com.alibaba.dashscope.exception.NoApiKeyException;import com.alibaba.dashscope.utils.Constants;import com.google.gson.Gson;import com.google.gson.GsonBuilder;public class Main { // The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key // If you have not configured an environment variable, replace the following line with your Model Studio API key: public static String apiKey = "sk-xxx" public static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void main(String[] args) throws NoApiKeyException, InputRequiredException { // The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region. Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; VocabularyService service = new VocabularyService(apiKey); Vocabulary[] vocabularies = service.listVocabulary("testpfx"); Gson gson = new GsonBuilder() .setPrettyPrinting() .create(); System.out.println("Custom vocabularies: " + gson.toJson(vocabularies)); }}
import com.alibaba.dashscope.audio.asr.vocabulary.Vocabulary;import com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService;import com.alibaba.dashscope.exception.InputRequiredException;import com.alibaba.dashscope.exception.NoApiKeyException;import com.alibaba.dashscope.utils.Constants;import com.google.gson.Gson;import com.google.gson.GsonBuilder;public class Main { // The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key // If you have not configured an environment variable, replace the following line with your Model Studio API key: public static String apiKey = "sk-xxx" public static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void main(String[] args) throws NoApiKeyException, InputRequiredException { // The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region. Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; VocabularyService service = new VocabularyService(apiKey); // Replace with the actual custom vocabulary ID when querying Vocabulary vocabulary = service.queryVocabulary("vocab-testpfx-xxxx"); Gson gson = new GsonBuilder() .setPrettyPrinting() .create(); System.out.println("Custom vocabulary: " + gson.toJson(vocabulary.getData())); }}
import com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService;import com.alibaba.dashscope.exception.InputRequiredException;import com.alibaba.dashscope.exception.NoApiKeyException;import com.alibaba.dashscope.utils.Constants;import com.google.gson.JsonArray;import com.google.gson.JsonObject;import java.util.ArrayList;import java.util.List;public class Main { // The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key // If you have not configured an environment variable, replace the following line with your Model Studio API key: public static String apiKey = "sk-xxx" public static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void main(String[] args) throws NoApiKeyException, InputRequiredException { // The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region. Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; JsonArray vocabularyJson = new JsonArray(); List<Hotword> wordList = new ArrayList<>(); wordList.add(new Hotword("Wu yi gong", 4, "en")); wordList.add(new Hotword("A Family in Queli", 4, "en")); for (Hotword word : wordList) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("text", word.text); jsonObject.addProperty("weight", word.weight); jsonObject.addProperty("lang", word.lang); vocabularyJson.add(jsonObject); } VocabularyService service = new VocabularyService(apiKey); // Replace with the actual custom vocabulary ID service.updateVocabulary("vocab-testpfx-xxx", vocabularyJson); }}class Hotword { String text; int weight; String lang; public Hotword(String text, int weight, String lang) { this.text = text; this.weight = weight; this.lang = lang; }}
import com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService;import com.alibaba.dashscope.exception.InputRequiredException;import com.alibaba.dashscope.exception.NoApiKeyException;import com.alibaba.dashscope.utils.Constants;public class Main { // 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: public static String apiKey = "sk-xxx" public static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void main(String[] args) throws NoApiKeyException, InputRequiredException { // The following configuration is for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region. Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; VocabularyService service = new VocabularyService(apiKey); // Replace with the actual vocabulary ID when deleting service.deleteVocabulary("vocab-testpfx-xxxx"); }}