Paraformer non-real-time speech recognition Python SDK
Use the Paraformer Python SDK to transcribe audio and video files with the DashScope API.
ImportantAlibaba Cloud Model Studio has released a workspace-specific domain for the China (Beijing) region. The new dedicated domain delivers superior performance and higher stability for inference requests. We recommend migrating from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com.
Replace {WorkspaceId} with your actual Workspace ID. The existing domain remains fully functional.
User guide:Non-real-time speech recognition
Prerequisites
You have activated the service and Obtain an API key. Please Configure API key as an environment variable instead of hardcoding it in your code to prevent security risks caused by code leakage.
NoteWhen you need to provide temporary access to third-party applications or users, or when you want to strictly control high-risk operations such as accessing or deleting sensitive data, we recommend using temporary authentication tokens.
Compared with long-term API Keys, temporary authentication tokens have a short validity period (60 seconds) and higher security, making them suitable for temporary call scenarios and effectively reducing the risk of API Key leakage.
Usage: In your code, replace the API Key originally used for authentication with the obtained temporary authentication token.
Getting started
The core resource (client.audio.asr) provides interfaces for asynchronous task submission, synchronous waiting for task completion, and asynchronous query of task execution results (the one-shot transcribe, or the step-by-step jobs.create + jobs.wait + jobs.fetch). Non-real-time speech recognition can be invoked in the following two ways:
- Async submission + synchronous wait for task completion: Submit a task, then block the current thread until the task completes and obtain the recognition result.
- Async submission + asynchronous query of task execution results: Submit a task, then call the task query interface to obtain the task execution result when needed.
Async submission + sync wait
-
Call the core resource (
client.audio.asr) (jobs.create/transcribe) and set the request parameters.Note
- The file transcription service processes tasks submitted through the API on a best-effort basis. After submission, a task enters the queued (
PENDING) state. The queue time depends on the queue length and file duration and cannot be precisely estimated, but typically completes within a few minutes. Once processing begins, speech recognition completes at several hundred times the real-time speed. - After each task completes, the recognition result and URL download link are valid for 24 hours. After expiration, you cannot query the task or download results through the previously provided URL.
- The file transcription service processes tasks submitted through the API on a best-effort basis. After submission, a task enters the queued (
-
Call the core resource (
client.audio.asr) (jobs.wait, or the one-shottranscribe) to wait synchronously for the task to complete.Task statuses include
PENDING,RUNNING,SUCCEEDED, andFAILED. When a task is in thePENDINGorRUNNINGstate, thewaitinterface blocks. When a task is in theSUCCEEDEDorFAILEDstate, thewaitinterface no longer blocks and returns the task execution result.jobs.waitreturns the final-stateJob(see Response parameters).
Click to view complete example
import os
import json
import dashscope
# If you have not set the API Key in an environment variable, replace the following line with your own API Key: api_key="sk-xxx"
# China (Beijing): Replace {WorkspaceId} with your actual workspace ID. The configuration varies by region.
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# Submit the file transcription task and wait synchronously until it completes
job = client.audio.asr.transcribe(
['{YOUR_AUDIO_URL}'],
model='paraformer-v2',
parameters={'language_hints': ['zh', 'en']} # The "language_hints" parameter only supports the paraformer-v2 model.
)
print(json.dumps(job.model_dump(), indent=4, ensure_ascii=False))
print('transcription done!')
dashscope CLI
# Submit a recorded file recognition task
export DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with your Workspace ID, and cn-beijing with the corresponding region (Singapore: ap-southeast-1, US East: us-east-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
dashscope transcription create -m paraformer-v2 --file-url "https://example.com/audio.mp3"
# Query the task list
dashscope transcription list
ImportantThe SDK Expert interactive assistant can accomplish the same development and troubleshooting in natural language. See
DashScope SDK Expert.For the complete region table, see Base URL overview.
Async submission + async polling
-
Call the core resource (
client.audio.asr) (jobs.create/transcribe) and set the request parameters.Note
- The file transcription service processes tasks submitted through the API on a best-effort basis. After submission, a task enters the queued (
PENDING) state. The queue time depends on the queue length and file duration and cannot be precisely estimated, but typically completes within a few minutes. Once processing begins, speech recognition completes at several hundred times the real-time speed. - After each task completes, the recognition result and URL download link are valid for 24 hours. After expiration, you cannot query the task or download results through the previously provided URL.
- The file transcription service processes tasks submitted through the API on a best-effort basis. After submission, a task enters the queued (
-
Repeatedly call the core resource (
client.audio.asr) (jobs.fetch) until the final task result is obtained.Stop polling and process the result when the task status is
SUCCEEDEDorFAILED.jobs.fetchreturns aJob(see Response parameters).
Click to view complete example
import os
import json
import dashscope
# China (Beijing): Replace {WorkspaceId} with your actual workspace ID. The configuration varies by region.
client = dashscope.Client(
# If you have not set the API Key in an environment variable, replace the following line with your own API Key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# Submit the file transcription task
job = client.audio.asr.jobs.create(
model='paraformer-v2',
file_urls=['{YOUR_AUDIO_URL}'],
parameters={'language_hints': ['zh', 'en']} # The "language_hints" parameter only supports the paraformer-v2 model.
)
# Poll the task until the final result is returned
while True:
if job.status == 'SUCCEEDED' or job.status == 'FAILED':
break
job = client.audio.asr.jobs.fetch(job.task_id)
print(json.dumps(job.model_dump(), indent=4, ensure_ascii=False))
print('transcription done!')
Request parameters
Request parameters are set through the jobs.create/transcribe methods of the core resource (client.audio.asr).
ImportantIf the speaker diarization results of multi-channel audio do not meet expectations, you can try converting the audio to mono and running recognition again. You can use ffmpeg for the conversion: ffmpeg -i input.wav -ac 1 output_mono.wav.
| Parameter | Type | Default | Required | Description |
|---|---|---|---|---|
model | str | Yes | The name of the Paraformer model used for audio and video file transcription. See Supported models. | |
file_urls | list[str] | Yes | A list of URLs for audio and video file transcription. The HTTP and HTTPS protocols are supported. A single request supports only 1 URL. If the recorded files are stored in Alibaba Cloud OSS, the SDK does not support temporary URLs prefixed with oss://. | |
vocabulary_id | str | No | The latest hot word ID. Supported by the latest v2 series models with language information configured. The hot words corresponding to this hot word ID take effect in this speech recognition. Disabled by default. For usage, see Custom hot words. | |
channel_id | list[int] | [0] | No | Specifies the audio track indexes to recognize in a multi-track audio file. Indexes start from 0. For example, [0] means recognizing the first track, and [0, 1] means recognizing both the first and second tracks simultaneously. If this parameter is omitted, only the first track is processed by default. ImportantEach specified track is billed independently. For example, requesting [0, 1] for a single file incurs two separate charges. |
disfluency_removal_enabled | bool | False | No | Filters filler words. Disabled by default. |
timestamp_alignment_enabled | bool | False | No | Whether to enable timestamp alignment. Disabled by default. |
special_word_filter | str | No | Specifies the sensitive words to be processed during speech recognition, and supports setting different processing methods for different sensitive words. If this parameter is not provided, the system uses the built-in sensitive word filtering logic, and words matching the Alibaba Cloud Model Studio sensitive word list in the recognition results will be replaced with If this parameter is provided, the following sensitive word processing strategies can be implemented:
The value of this parameter should be a JSON string with the following structure: JSON field descriptions:
| |
language_hints | list[str] | ["zh", "en"] | No | Specifies the language codes of the speech to be recognized. This parameter is only applicable to the paraformer-v2 model. Supported language codes:
|
diarization_enabled | bool | False | No | Automatic speaker diarization. Disabled by default. Only applicable to mono audio. Multi-channel audio does not support speaker diarization. When this feature is enabled, the recognition results will include a NoteIf speaker diarization is enabled, it is recommended that the audio duration does not exceed 2 hours, otherwise recognition may fail or time out. For an example of |
speaker_count | int | No | Reference speaker count. The value is an integer from 2 to 100 (inclusive). Takes effect after speaker diarization is enabled ( By default, the number of speakers is determined automatically. If this parameter is configured, it only guides the algorithm to output the specified count as closely as possible, without guaranteeing that this count will be output. |
Response
Job
Job encapsulates the basic task information (task_id and status) and the execution results (results, see Subtask recognition results, task_metrics, and usage). The Job returned by jobs.create after task submission contains only task_id and status; the Job returned by jobs.fetch and jobs.wait (as well as the one-shot transcribe) contains the task execution results.
Click to view Job structure example
The following is an example of the Job returned by the jobs.create method (the task is in the PENDING state after submission):
{
"request_id":"251aceab-a6aa-9fc4-b7f7-0cc6d3e2a9f3",
"task_id":"7d0a58a3-1dbe-4de9-8cff-5f48213128b0",
"status":"PENDING"
}
The following is an example of the Job returned by jobs.fetch and jobs.wait (as well as the one-shot transcribe):
{
"request_id":"251aceab-a6aa-9fc4-b7f7-0cc6d3e2a9f3",
"task_id":"7d0a58a3-1dbe-4de9-8cff-5f48213128b0",
"status":"PENDING",
"task_metrics":{
"TOTAL":1,
"SUCCEEDED":0,
"FAILED":0
}
}
{
"request_id":"d9d530f1-853c-9848-a5f1-f5de59086ff7",
"task_id":"6351feef-9694-45d2-9d32-63454f2ffb8d",
"status":"RUNNING",
"task_metrics":{
"TOTAL":1,
"SUCCEEDED":0,
"FAILED":0
}
}
{
"request_id":"16668704-6702-9e03-8ab7-a32a5d7bb095",
"task_id":"6351feef-9694-45d2-9d32-63454f2ffb8d",
"status":"SUCCEEDED",
"results":[
{
"file_url":"{YOUR_AUDIO_URL}",
"transcription_url":"https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/prod/paraformer-v2/20250213/17%3A31/20ee4e4f-0404-4806-b617-c7d4c62eed19-1.json?Expires=1739525481&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"subtask_status":"SUCCEEDED"
}
],
"task_metrics":{
"TOTAL":1,
"SUCCEEDED":1,
"FAILED":0
},
"usage":{
"duration":9
}
}
{
"request_id":"16668704-6702-9e03-8ab7-a32a5d7bb095",
"task_id":"7bac899c-06ec-4a79-8875-xxxxxxxxxxxx",
"status":"SUCCEEDED",
"results":[
{
"file_url":"{YOUR_AUDIO_URL}",
"code":"InvalidFile.DownloadFailed",
"message":"The audio file cannot be downloaded.",
"subtask_status":"FAILED"
}
],
"task_metrics":{
"TOTAL":1,
"SUCCEEDED":0,
"FAILED":1
},
"usage":{
"duration":9
}
}
Key parameters:
Parameter | Description |
|---|---|
request_id | The ID generated by the system to identify this call. |
task_id | The task ID. |
status | The task status. The four statuses are When a task contains multiple subtasks, if any subtask succeeds, the entire task status is marked as |
results | The subtask recognition results. Each item contains |
subtask_status | The subtask status. The four statuses are |
file_url | The URL of the audio to be recognized. |
transcription_url | The URL corresponding to the audio recognition result. The recognition result is saved as a JSON file. You can download the file from the link corresponding to |
usage | Metering information, including |
When a call fails, the Python SDK throws a DashScopeError exception. You can obtain the error code, HTTP status code, error message, and request ID through e.code/e.status_code/e.message/e.request_id. Subtask failures do not throw an exception; check subtask_status, code, and message in results.
results (subtask recognition results)
The results array corresponds to the subtask recognition results of each audio file in the Job. Each item contains file_url, transcription_url, and subtask_status; when a subtask fails, it also contains code and message.
Click to view results structure example
SUCCEEDED status
{
"file_url":"{YOUR_AUDIO_URL}",
"transcription_url":"https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/prod/paraformer-v2/20250213/17%3A59/70e737cc-bf8c-418b-b0c8-83fab192a0fa-1.json?Expires=1739527168&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"subtask_status":"SUCCEEDED"
}
FAILED status
code is the error code and message is the error message. These two fields appear only when a subtask fails. You can use these two fields together with the Error codes to troubleshoot issues.
{
"file_url": "{YOUR_AUDIO_URL}",
"code": "InvalidFile.DownloadFailed",
"message": "The audio file cannot be downloaded.",
"subtask_status": "FAILED"
}
Key parameters:
Parameter | Description |
|---|---|
code | The error code. Use it together with the |
message | The error message. Use it together with the |
subtask_status | The subtask status. The four statuses are |
file_url | The URL of the audio to be recognized. |
transcription_url | The URL corresponding to the audio recognition result. The recognition result is saved in JSON format in a JSON file. You can download the file from the link corresponding to |
Recognition result description
The recognition result is saved as a JSON file.
Click to view recognition result example
{
"file_url":"{YOUR_AUDIO_URL}",
"properties":{
"audio_format":"pcm_s16le",
"channels":[
0
],
"original_sampling_rate":16000,
"original_duration_in_milliseconds":3834
},
"transcripts":[
{
"channel_id":0,
"content_duration_in_milliseconds":3720,
"text":"Hello world, this is the Alibaba speech laboratory.",
"sentences":[
{
"begin_time":100,
"end_time":3820,
"text":"Hello world, this is the Alibaba speech laboratory.",
"sentence_id":1,
"speaker_id":0, //This field is only displayed when automatic speaker diarization is enabled
"words":[
{
"begin_time":100,
"end_time":596,
"text":"Hello ",
"punctuation":""
},
{
"begin_time":596,
"end_time":844,
"text":"world",
"punctuation":", "
}
// Other content omitted here
]
}
]
}
]
}
The key parameters are as follows:
Parameter | Type | Description |
|---|---|---|
audio_format | string | The audio format of the source file. |
channels | array[integer] | The audio track index information of the source file. Returns [0] for mono audio, [0, 1] for dual-track audio, and so on. |
original_sampling_rate | integer | The sampling rate (Hz) of the audio in the source file. |
original_duration | integer | The original audio duration (ms) of the source file. |
channel_id | integer | The audio track index of the transcription result, starting from 0. |
content_duration | integer | The duration (ms) of content identified as speech in the audio track. The Paraformer speech recognition model service only transcribes and meters content identified as speech in the audio track, and bills accordingly. Non-speech content is neither metered nor billed. Typically, the speech content duration is shorter than the original audio duration. Since the determination of whether speech content exists is made by an AI model, there may be some deviation from the actual situation. |
transcript | string | The paragraph-level speech transcription result. |
sentences | array | The sentence-level speech transcription result. |
words | array | The word-level speech transcription result. |
begin_time | integer | The start timestamp (ms). |
end_time | integer | The end timestamp (ms). |
text | string | The speech transcription result. |
speaker_id | integer | The index of the current speaker, starting from 0, used to distinguish different speakers. This field is only displayed in the recognition results when speaker diarization is enabled. |
punctuation | string | The predicted punctuation after the word (if any). |
Key interfaces
Core resource (client.audio.asr)
Non-real-time speech recognition is mounted on the client.audio.asr resource. You can use client.audio.asr.transcribe to submit and wait in one step, or use client.audio.asr.jobs for step-by-step control.
| Member method | Method signature | Description |
|---|---|---|
transcribe | | Submits a recorded file recognition task and blocks the current thread until the task completes (the task status is This method returns a |
jobs.create | | Asynchronously submits a speech recognition task. This method returns a |
jobs.wait | | Blocks the current thread until the asynchronous task completes (polling with exponential backoff, with a default total budget of 24 hours). This method returns the final-state |
jobs.fetch | | Asynchronously queries the current task execution result. This method returns a |
Other interfaces: Batch query task status / Cancel task
For details, see Manage asynchronous tasks: Supports batch querying of non-real-time speech recognition tasks submitted within the last 24 hours, and also supports canceling tasks in PENDING (queued) state.
Error codes
If you encounter errors, see Error codes for troubleshooting.
If the issue persists, join the developer community to report the issue and provide the Request ID for further investigation.
When a task contains multiple subtasks, if any subtask succeeds, the entire task status is marked as SUCCEEDED. Check the subtask_status field to determine the result of each subtask.
Error response example:
{
"request_id": "16668704-6702-9e03-8ab7-a32a5d7bb095",
"task_id": "7bac899c-06ec-4a79-8875-xxxxxxxxxxxx",
"status": "SUCCEEDED",
"results": [
{
"file_url": "{YOUR_AUDIO_URL}",
"code": "InvalidFile.DownloadFailed",
"message": "The audio file cannot be downloaded.",
"subtask_status": "FAILED"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 0,
"FAILED": 1
}
}
More examples
Explore more examples on GitHub.
FAQ
Features
Q: Does it support Base64-encoded audio?
No. Base64-encoded audio is not supported. Only audio accessible via publicly accessible URLs is supported. Binary streams and direct local file recognition are not supported.
Q: How to provide audio files as publicly accessible URLs?
Generally, follow these steps (this provides a general approach; specifics vary by storage product. We recommend uploading audio to Alibaba Cloud OSS):
1. Choose a storage and hosting method
For example:
-
Object Storage Service (recommended):
- Use a cloud provider's object storage service (such as Alibaba Cloud OSS) to upload audio files to a bucket and set them to public access.
- Advantages: High availability, CDN acceleration support, easy management.
-
Web server:
- Place audio files on a web server that supports HTTP/HTTPS access (such as Nginx or Apache).
- Advantages: Suitable for small projects or local testing.
-
Content Delivery Network (CDN):
- Host audio files on a CDN and access them through the CDN-provided URL.
- Advantages: Accelerated file delivery, suitable for high-concurrency scenarios.
2. Upload audio files
Upload audio files based on your chosen storage/hosting method, for example:
-
Object Storage Service:
- Log in to the cloud provider's console and create a bucket.
- Upload audio files and set file permissions to "public read" or generate temporary access links.
-
Web server:
- Place audio files in the server's designated directory (such as
/var/www/html/audio/). - Ensure files are accessible via HTTP/HTTPS.
- Place audio files in the server's designated directory (such as
3. Generate a publicly accessible URL
For example:
-
Object Storage Service:
- After uploading, the system automatically generates a public access URL (typically in the format
https://<bucket-name>.<region>.aliyuncs.com/<file-name>). - If you need a more user-friendly domain, you can bind a custom domain and enable HTTPS.
- After uploading, the system automatically generates a public access URL (typically in the format
-
Web server:
- The file access URL is typically the server address plus the file path (such as
https://your-domain.com/audio/file.mp3).
- The file access URL is typically the server address plus the file path (such as
-
CDN:
- After configuring CDN acceleration, use the CDN-provided URL (such as
https://cdn.your-domain.com/audio/file.mp3).
- After configuring CDN acceleration, use the CDN-provided URL (such as
4. Verify URL accessibility
In a public network environment, ensure the generated URL is accessible, for example:
- Open the URL in a browser and check whether the audio file can be played.
- Use tools (such as
curlor Postman) to verify whether the URL returns a correct HTTP response (status code 200).
When using the SDK, if the recorded files are stored in Alibaba Cloud OSS, temporary URLs with the oss:// prefix are not supported.
When using the RESTful API, if the recorded files are stored in Alibaba Cloud OSS, temporary URLs with the oss:// prefix are supported:
Important
- The temporary URL is valid for 48 hours and cannot be used after it expires. Do not use it in a production environment.
- The API for obtaining an upload credential is limited to 100 QPS and does not support scaling out. Do not use it in production environments, high-concurrency scenarios, or stress testing scenarios.
- For production environments, use a stable storage service such as Alibaba Cloud OSS to ensure long-term file availability and avoid rate limiting issues.
Q: How long does it take to get recognition results?
After submission, the task enters a queued (PENDING) state. The queue time depends on the queue length and file duration and cannot be precisely estimated, but typically completes within a few minutes. Please wait patiently. Longer audio files require more processing time.
Troubleshooting
For code errors, see Error codes.
Q: What should I do if the recognition results are out of sync with the audio playback?
Set the request parameter timestamp_alignment_enabled to true to enable timestamp calibration, which synchronizes the recognition results with the speech playback.
Q: Unable to get results after continuous polling?
This may be due to rate limiting. Please wait patiently. If you need capacity expansion, join the developer community to apply.
Q: Why is there no recognition result (unable to recognize speech)?
- Check whether the audio meets the requirements (format, sampling rate).
- If you are using the
paraformer-v2model, check whether thelanguage_hintssetting is correct. - If none of the above resolves the issue, you can customize hot words to improve the recognition of specific words.
Q: What should I do if all speaker diarization results are marked as the same Speaker?
Troubleshoot as follows:
- Check the number of audio channels. You can use ffprobe to check:
ffprobe -i input.wav -show_entries stream=channels -of default=noprint_wrappers=1. - If the audio is multi-channel, try converting it to mono and running recognition again:
ffmpeg -i input.wav -ac 1 output_mono.wav. - Confirm that
diarization_enabled=trueis set.speaker_countis optional; the number of speakers is determined automatically by default. If you need to set it, the value ranges from 2 to 100, but the number of speakers in the results is not guaranteed to match the configured value.
More questions
Visit the QA page on GitHub.