Utilice el SDK de Java para crear, consultar, actualizar y eliminar vocabularios personalizados para el reconocimiento de voz.
ImportanteAlibaba Cloud Model Studio ha lanzado dominios específicos de espacio de trabajo para las regiones de China (Beijing) y Singapur. Los nuevos dominios dedicados ofrecen un rendimiento superior y una mayor estabilidad para las solicitudes de inferencia. Recomendamos migrar a los nuevos dominios:
- China (Pekín): de
dashscope.aliyuncs.coma{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapur: de
dashscope-intl.aliyuncs.coma{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Los dominios existentes permanecen totalmente funcionales.
Guía del usuario: Mejorar la precisión del reconocimiento.
ImportanteEl vocabulario personalizado solo es compatible con el espacio de trabajo principal. Los subespacios de trabajo no lo admiten.
Endpoint
El SDK utiliza el endpoint de China (Beijing) de forma predeterminada. Para cambiar a una región diferente, modifique Constants.baseHttpApiUrl antes de la inicialización.
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
China (Beijing)
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
Para usar la región Singapore, configure Constants.baseHttpApiUrl antes de la inicialización:
import com.alibaba.dashscope.utils.Constants;
// Set this at the beginning of your code
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
Nota:
- Las claves de API difieren entre regiones. Utilice la clave de API que coincida con su región.
- La configuración de región es global y afecta a todas las llamadas a la API de DashScope.
VocabularyService
Paquete: com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService
Descripción: Crea, consulta, actualiza y elimina vocabularios personalizados.
Constructor
public VocabularyService(String apiKey)
Parámetros:
Parámetro | Tipo | Descripción |
|---|---|---|
apiKey | String | Clave de API de DashScope |
createVocabulary() - Crear un vocabulario personalizado
Firma del método:
public Vocabulary createVocabulary(String targetModel,String prefix,JsonArray vocabulary) throws NoApiKeyException, InputRequiredException
Parámetros:
Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
targetModel | String | Sí | El modelo de reconocimiento de voz que utiliza este vocabulario. Este valor debe coincidir con el modelo que especifique al llamar a la API de reconocimiento de voz. |
prefix | String | Sí | Un prefijo personalizado para el vocabulario. Solo se permiten letras minúsculas y dígitos, con una longitud máxima de 10 caracteres. |
vocabulary | JsonArray | Sí | La lista de palabras clave. Cada JsonObject contiene campos como text, weight y lang. Para obtener más información, consulte Estructura del objeto de palabra clave. |
Valor de retorno:
Tipo | Descripción |
|---|---|
Vocabulary | Un objeto de vocabulario personalizado que contiene el ID del vocabulario y otros metadatos. |
Exceptions:
Exception | Descripción |
|---|---|
NoApiKeyException | La clave de API está vacía. |
InputRequiredException | Un parámetro obligatorio está vacío. |
listVocabulary() - Listar vocabularios personalizados
Firma del método:
public Vocabulary[] listVocabulary(String prefix) throws NoApiKeyException, InputRequiredException
public Vocabulary[] listVocabulary(String prefix, int pageIndex, int pageSize) throws NoApiKeyException, InputRequiredException
Parámetros:
Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
prefix | String | No | El prefijo personalizado del vocabulario. Cuando se especifica, solo se devuelven los vocabularios con este prefijo. |
pageIndex | int | No | El número de página, comenzando desde 0. Valor predeterminado: 0. |
pageSize | int | No | El número de entradas por página. Valor predeterminado: 10. |
Valor de retorno:
Tipo | Descripción |
|---|---|
Vocabulary[] | Una matriz de objetos de vocabulario personalizado. |
Campos devueltos por listVocabulary():
Campo | Tipo | Descripción |
|---|---|---|
vocabularyId | String | El ID del vocabulario. |
gmtCreate | String | La hora de creación. |
gmtModified | String | La hora de la última modificación. |
status | String | El estado:
|
Exceptions:
Exception | Descripción |
|---|---|
NoApiKeyException | La clave de API está vacía. |
InputRequiredException | Un parámetro obligatorio está vacío. |
queryVocabulary() - Consultar un vocabulario personalizado
Firma del método:
public Vocabulary queryVocabulary(String vocabularyId) throws NoApiKeyException, InputRequiredException
Parámetros:
Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
vocabularyId | String | Sí | El ID del vocabulario personalizado que se desea consultar. |
Valor de retorno:
Tipo | Descripción |
|---|---|
Vocabulary | Un objeto |
Campos devueltos por queryVocabulary():
Campo | Tipo | Descripción |
|---|---|---|
vocabulary | JsonArray | El contenido del vocabulario personalizado. |
targetModel | String | El modelo de reconocimiento de voz que utiliza este vocabulario. Este valor debe coincidir con el modelo que especifique al llamar a la API de reconocimiento de voz. |
gmtCreate | String | La hora de creación. |
gmtModified | String | La hora de la última modificación. |
status | String | El estado:
|
Exceptions:
Exception | Descripción |
|---|---|
NoApiKeyException | La clave de API está vacía. |
InputRequiredException | Un parámetro obligatorio está vacío. |
updateVocabulary() - Actualizar un vocabulario personalizado
Firma del método:
public void updateVocabulary(String vocabularyId,JsonArray vocabulary) throws NoApiKeyException, InputRequiredException
Parámetros:
Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
vocabularyId | String | Sí | El ID del vocabulario que se desea actualizar. |
vocabulary | JsonArray | Sí | El nuevo vocabulario. Esto reemplaza por completo las entradas existentes. |
Valor de retorno: None
Exceptions:
Exception | Descripción |
|---|---|
NoApiKeyException | La clave de API está vacía. |
InputRequiredException | Un parámetro obligatorio está vacío. |
deleteVocabulary() - Eliminar un vocabulario personalizado
Firma del método:
public void deleteVocabulary(String vocabularyId) throws NoApiKeyException, InputRequiredException
Parámetros:
Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
vocabularyId | String | Sí | El ID del vocabulario que se desea eliminar. |
Valor de retorno: None
Exceptions:
Exception | Descripción |
|---|---|
NoApiKeyException | La clave de API está vacía. |
InputRequiredException | Un parámetro obligatorio está vacío. |
Clase Vocabulary
Paquete: com.alibaba.dashscope.audio.asr.vocabulary.Vocabulary
Descripción: Almacena los metadatos y el contenido de un vocabulario personalizado.
Métodos
Método | Tipo de retorno | Descripción |
|---|---|---|
getVocabularyId() | String | Devuelve el ID del vocabulario. |
getTargetModel() | String | Devuelve el modelo objetivo. |
getVocabulary() | JsonArray | Devuelve el contenido del vocabulario personalizado. |
getStatus() | String | Devuelve el estado. |
getGmtCreate() | String | Devuelve la hora de creación. |
getGmtModified() | String | Devuelve la hora de la última modificación. |
getData() | JsonObject | Devuelve los datos completos en formato JSON. |
Estructura del objeto de palabra clave
Campos en cada JsonObject de palabra clave:
Campo | Tipo | Obligatorio | Descripción |
|---|---|---|---|
text | String | Sí | El texto de la entrada de vocabulario. El idioma del texto debe ser compatible con el modelo seleccionado. Los idiomas admitidos varían según el modelo. Utilice palabras reales en lugar de combinaciones arbitrarias de caracteres para mejorar la precisión del reconocimiento. Longitud máxima: 15 caracteres para texto que incluye caracteres no ASCII, o 7 palabras separadas por espacios para texto solo ASCII. |
weight | int | Sí | El peso de la entrada de vocabulario. Valor recomendado: 4. Valores válidos: de 1 a 5. Si la precisión del reconocimiento no mejora, aumente el peso. Un peso excesivamente alto puede reducir la precisión del reconocimiento de otras palabras. |
lang | String | No | El código de idioma del audio que se va a reconocer. Cuando se establece, el sistema mejora el reconocimiento de las entradas de vocabulario en el idioma especificado. Si no puede determinar el idioma de antemano, deje este parámetro sin configurar. El modelo detecta el idioma automáticamente. Valores válidos (varían según el modelo):
|
Código de ejemplo
Crear un vocabulario personalizado
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/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;
}
}
Listar vocabularios personalizados
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/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));
}
}
Consultar un vocabulario personalizado
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/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()));
}
}
Actualizar un vocabulario personalizado
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/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;
}
}
Eliminar un vocabulario personalizado
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/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");
}
}