Use the Python SDK to create, list, query, update, and delete custom vocabularies for speech recognition.
ImportantAlibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions. The new dedicated domains deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
- China (Beijing): from
dashscope.aliyuncs.comto{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore: from
dashscope-intl.aliyuncs.comto{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
Replace {WorkspaceId} with your actual Workspace ID. The existing domains remain fully functional.
User guide: Improve recognition accuracy.
ImportantCustom vocabulary is supported only in the primary workspace. Sub-workspaces don't support it.
Endpoint
The SDK connects to the China (Beijing) endpoint by default. To use a different region, specify the region parameter when constructing dashscope.Client (for example, ap-southeast-1 for the Singapore region).
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Replace {WorkspaceId} with your actual Workspace ID.
China (Beijing)
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Replace {WorkspaceId} with your actual workspace ID.
To switch to the Singapore region:
import os
import dashscope
# Specify the region when constructing the Client
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
Note:
- API keys differ across regions. Use the API key that matches your region.
- The region setting is specific to the
dashscope.Clientinstance and only affects API calls made through that client.
client.audio.vocabularies
Resource: the client.audio.vocabularies resource of a dashscope.Client instance
Description: Creates, lists, queries, updates, and deletes custom vocabularies.
Constructor
import os
import dashscope
client = dashscope.Client(
api_key=os.getenv('DASHSCOPE_API_KEY'),
workspace='{WorkspaceId}',
region='ap-southeast-1',
)
If api_key is not passed, the SDK automatically reads the value of the DASHSCOPE_API_KEY environment variable.
create() - Create a custom vocabulary
Method signature:
def create(
self,
*,
target_model: str,
prefix: str,
vocabulary: List[dict]) -> Vocabulary
Parameters:
Parameter | Type | Required | Description |
|---|---|---|---|
target_model | str | Yes | The speech recognition model that uses this vocabulary. This value must match the model you specify when calling the speech recognition API. |
prefix | str | Yes | A custom prefix for the vocabulary. Only lowercase letters and digits are allowed, with a maximum length of 10 characters. |
vocabulary | List[dict] | Yes | A list of hotwords. Each entry is a dict with fields text, weight, and lang. For more information, see Hotword dictionary structure. |
Return value:
Type | Description |
|---|---|
Vocabulary | The vocabulary object. Use the |
list() - List custom vocabularies
Maps to the HTTP API action: list_vocabulary.
Method signature:
def list(
self,
*,
prefix: str = None,
page_index: int = 0,
page_size: int = 10) -> VocabularyList
Parameters:
Parameter | Type | Required | Description |
|---|---|---|---|
prefix | str | No | The custom prefix of the vocabulary. When specified, only vocabularies with this prefix are returned. |
page_index | int | No | The page number, starting from 0. Default value: 0. |
page_size | int | No | The number of entries per page. Default value: 10. |
Return value:
Type | Description |
|---|---|
VocabularyList | A paginated vocabulary list object. The |
Fields returned by list():
Field | Type | Description |
|---|---|---|
vocabulary_id | str | The vocabulary ID. |
gmt_create | str | The creation time. |
gmt_modified | str | The last modification time. |
status | str | The status:
|
get() - Query a custom vocabulary
Maps to query_vocabulary() in the 1.x SDK.
Method signature:
def get(
self,
vocabulary_id: str) -> Vocabulary
Parameters:
Parameter | Type | Required | Description |
|---|---|---|---|
vocabulary_id | str | Yes | The ID of the custom vocabulary to query. |
Return value:
Type | Description |
|---|---|
Vocabulary | A vocabulary details object containing vocabulary, target_model, gmt_create, gmt_modified, and status. |
Fields returned by get():
Field | Type | Description |
|---|---|---|
vocabulary | List[dict] | The hotword list content. |
target_model | str | The speech recognition model that uses this vocabulary. This value must match the model you specify when calling the speech recognition API. |
gmt_create | str | The creation time. |
gmt_modified | str | The last modification time. |
status | str | The status:
|
update() - Update a custom vocabulary
Method signature:
def update(
self,
vocabulary_id: str,
*,
vocabulary: List[dict]) -> JobStatus
Parameters:
Parameter | Type | Required | Description |
|---|---|---|---|
vocabulary_id | str | Yes | The ID of the vocabulary to update. |
vocabulary | List[dict] | Yes | The new vocabulary. This completely replaces the existing entries. |
Return value: A JobStatus object, whose status field indicates the operation status.
delete() - Delete a custom vocabulary
Method signature:
def delete(
self,
vocabulary_id: str) -> JobStatus
Parameters:
Parameter | Type | Required | Description |
|---|---|---|---|
vocabulary_id | str | Yes | The ID of the vocabulary to delete. |
Return value: A JobStatus object, whose status field indicates the operation status.
Hotword dictionary structure
Fields in each vocabulary dict:
Field | Type | Required | Description |
|---|---|---|---|
text | str | Yes | The vocabulary entry text. The text language must be supported by the selected model. Supported languages vary by model. Use actual words rather than arbitrary character combinations to improve recognition accuracy. Maximum length: 15 characters for text that includes non-ASCII characters, or 7 space-separated words for ASCII-only text. |
weight | int | Yes | The vocabulary entry weight. Recommended value: 4. Valid values: 1 to 5. If recognition accuracy doesn't improve, increase the weight. An excessively high weight may reduce the recognition accuracy of other words. |
lang | str | No | The language code of the audio to be recognized. When set, the system improves recognition of vocabulary entries in the specified language. If you can't determine the language in advance, leave this parameter unset. The model detects the language automatically. Valid values (vary by model):
|
Sample code
All examples read the API key from an environment variable.
Create a custom vocabulary
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace='{WorkspaceId}',
region='ap-southeast-1',
)
prefix = 'testpfx'
target_model = "fun-asr"
my_vocabulary = [
{"text": "Seediq Bale", "weight": 4}
]
# Create the vocabulary
vocabulary = client.audio.vocabularies.create(
prefix=prefix,
target_model=target_model,
vocabulary=my_vocabulary)
print(f"Vocabulary ID: {vocabulary.vocabulary_id}")
List custom vocabularies
import json
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace='{WorkspaceId}',
region='ap-southeast-1',
)
result = client.audio.vocabularies.list()
print(f"Vocabularies: {json.dumps(result.vocabularies)}")
Query a custom vocabulary
import json
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace='{WorkspaceId}',
region='ap-southeast-1',
)
# Replace with the actual vocabulary ID when querying
vocabulary = client.audio.vocabularies.get("vocab-testpfx-xxx")
print(f"Vocabulary: {json.dumps(vocabulary.vocabulary, ensure_ascii=False)}")
Update a custom vocabulary
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace='{WorkspaceId}',
region='ap-southeast-1',
)
my_vocabulary = [
{"text": "Seediq Bale", "weight": 4, "lang": "en"}
]
# Replace with the actual vocabulary ID
result = client.audio.vocabularies.update("vocab-testpfx-xxx", vocabulary=my_vocabulary)
print(f"Update status: {result.status}")
Delete a custom vocabulary
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace='{WorkspaceId}',
region='ap-southeast-1',
)
# Replace with the actual vocabulary table ID
result = client.audio.vocabularies.delete("vocab-testpfx-xxxx")
print(f"Deletion status: {result.status}")