Overview
The Model Download Manager provides a complete solution for downloading, caching, and managing Sherpa-ONNX model assets from official GitHub Releases. It handles archive models (.tar.bz2) and single-file models (.onnx), with built-in checksum validation, progress tracking, and disk space management.
Import from: react-native-sherpa-onnx/download
Key Features
Official model registry from GitHub Releases
Archive extraction with native libarchive (tar.bz2)
Checksum validation (SHA-256) for integrity verification
Download resume support for interrupted downloads
Progress events with speed and ETA calculation
Disk space checking before downloads
LRU cache cleanup for automatic model management
Retry logic with exponential backoff
Model Categories
The download manager organizes models by category:
import { ModelCategory } from 'react-native-sherpa-onnx/download' ;
enum ModelCategory {
Tts = 'tts' ,
Stt = 'stt' ,
Vad = 'vad' ,
Diarization = 'diarization' ,
Enhancement = 'enhancement' ,
Separation = 'separation' ,
}
Quick Start
Typical flow: refresh the model registry, download a model, then initialize STT/TTS with the local path.
import {
ModelCategory ,
refreshModelsByCategory ,
downloadModelByCategory ,
getLocalModelPathByCategory ,
} from 'react-native-sherpa-onnx/download' ;
import { createTTS } from 'react-native-sherpa-onnx/tts' ;
// 1. Refresh the TTS model registry
await refreshModelsByCategory ( ModelCategory . Tts , { forceRefresh: true });
// 2. Download a specific model
await downloadModelByCategory (
ModelCategory . Tts ,
'vits-piper-en_US-lessac-medium' ,
{
onProgress : ( progress ) => {
console . log ( ` ${ progress . percent . toFixed ( 1 ) } %` );
},
}
);
// 3. Get local path and initialize TTS
const localPath = await getLocalModelPathByCategory (
ModelCategory . Tts ,
'vits-piper-en_US-lessac-medium'
);
if ( localPath ) {
const tts = await createTTS ({
modelPath: { type: 'file' , path: localPath },
modelType: 'vits' ,
});
}
API Reference
refreshModelsByCategory
Fetch and cache the latest model list from GitHub Releases. Use this before showing the available models UI.
await refreshModelsByCategory ( ModelCategory . Stt , {
forceRefresh: true ,
cacheTtlMinutes: 1440 , // 24 hours
});
The model category to refresh
Bypass cache and fetch fresh data from GitHub
Cache time-to-live in minutes (default: 24 hours)
Maximum number of retry attempts on network failure
AbortSignal for cancellation support
Array of model metadata objects
listModelsByCategory
Return the cached model list. If no cache exists yet, returns an empty array.
const models = await listModelsByCategory ( ModelCategory . Stt );
models . forEach ( model => {
console . log ( model . id , model . displayName , model . bytes );
});
Array of cached model metadata Show ModelMetaBase properties
Human-readable model name
Archive file extension type
SHA-256 checksum for validation
downloadModelByCategory
Download a model by ID with support for progress callbacks, cancellation, and automatic retries.
await downloadModelByCategory (
ModelCategory . Stt ,
'sherpa-onnx-whisper-tiny' ,
{
onProgress : ( progress ) => {
console . log (
` ${ progress . percent . toFixed ( 1 ) } % - ` +
` ${ ( progress . speed ! / 1024 / 1024 ). toFixed ( 2 ) } MB/s - ` +
`ETA: ${ progress . eta ?. toFixed ( 0 ) } s`
);
},
maxRetries: 2 ,
}
);
onProgress
(progress: DownloadProgress) => void
Progress callback function type DownloadProgress = {
bytesDownloaded : number ;
totalBytes : number ;
percent : number ;
phase ?: 'downloading' | 'extracting' ;
speed ?: number ; // bytes per second
eta ?: number ; // estimated seconds remaining
};
Overwrite existing model files
AbortSignal for cancellation support
Maximum retry attempts on download failure
onChecksumIssue
(issue: ChecksumIssue) => Promise<boolean>
Custom handler for checksum validation issues. Return true to keep the file, false to delete and abort.
Show DownloadResult properties
Local filesystem path to the model directory
getLocalModelPathByCategory
Get the local path of a downloaded model for initialization. Updates the model’s lastUsed timestamp.
const localPath = await getLocalModelPathByCategory (
ModelCategory . Stt ,
'sherpa-onnx-whisper-tiny'
);
if ( localPath ) {
// Use the path to initialize STT/TTS
console . log ( 'Model path:' , localPath );
} else {
console . log ( 'Model not downloaded' );
}
Local path to the model directory, or null if not downloaded
listDownloadedModelsByCategory
Return only models that are fully downloaded on this device.
const downloaded = await listDownloadedModelsByCategory ( ModelCategory . Tts );
console . log ( ` ${ downloaded . length } models downloaded` );
Array of downloaded model metadata
isModelDownloadedByCategory
Check whether a specific model is downloaded and ready to use.
const isDownloaded = await isModelDownloadedByCategory (
ModelCategory . Stt ,
'sherpa-onnx-whisper-tiny'
);
if ( ! isDownloaded ) {
// Download the model
}
true if the model is downloaded and ready, false otherwise
getModelsCacheStatusByCategory
Return the last update timestamp for the cached model registry.
const status = await getModelsCacheStatusByCategory ( ModelCategory . Tts );
if ( status . lastUpdated ) {
console . log ( 'Cache last updated:' , new Date ( status . lastUpdated ));
}
Show CacheStatus properties
ISO timestamp of last cache update, or null if no cache
getModelByIdByCategory
Return metadata for a specific model ID from the cached registry.
const model = await getModelByIdByCategory (
ModelCategory . Tts ,
'vits-piper-en_US-lessac-medium'
);
if ( model ) {
console . log ( 'Model size:' , ( model . bytes / 1024 / 1024 ). toFixed ( 2 ), 'MB' );
}
Model metadata or null if not found
deleteModelByCategory
Remove a downloaded model and its cached files from disk.
await deleteModelByCategory (
ModelCategory . Tts ,
'vits-piper-en_US-lessac-medium'
);
console . log ( 'Model deleted' );
This permanently deletes all model files. Use with caution.
clearModelCacheByCategory
Clear the cached model registry for a category. Does not delete downloaded models.
await clearModelCacheByCategory ( ModelCategory . Stt );
Progress Events
subscribeDownloadProgress
Subscribe to global download progress updates for all models. Returns an unsubscribe function.
import { subscribeDownloadProgress } from 'react-native-sherpa-onnx/download' ;
const unsubscribe = subscribeDownloadProgress (( category , modelId , progress ) => {
console . log (
` ${ category } : ${ modelId } - ${ progress . percent . toFixed ( 1 ) } %` ,
progress . phase // 'downloading' | 'extracting'
);
if ( progress . speed ) {
console . log ( `Speed: ${ ( progress . speed / 1024 / 1024 ). toFixed ( 2 ) } MB/s` );
}
if ( progress . eta ) {
console . log ( `ETA: ${ progress . eta . toFixed ( 0 ) } seconds` );
}
});
// Call unsubscribe() when no longer needed
unsubscribe ();
listener
DownloadProgressListener
required
Callback function that receives progress updates type DownloadProgressListener = (
category : ModelCategory ,
modelId : string ,
progress : DownloadProgress
) => void ;
subscribeModelsListUpdated
Subscribe to model list refresh events. Returns an unsubscribe function.
import { subscribeModelsListUpdated } from 'react-native-sherpa-onnx/download' ;
const unsubscribe = subscribeModelsListUpdated (( category , models ) => {
console . log ( ` ${ category } list updated: ${ models . length } models` );
});
// Call unsubscribe() when no longer needed
unsubscribe ();
Checksum Validation
The download manager validates SHA-256 checksums when available to ensure file integrity:
Download checksum.txt
Fetches checksum.txt from GitHub Release and caches it in memory
Archive validation (tar.bz2)
Uses native libarchive hashing during extraction for efficient validation
Single-file validation (.onnx)
Uses local SHA-256 calculation after download
Fallback to GitHub digest
If checksum.txt doesn’t list a file, uses the GitHub asset digest if available
Checksum Issue Handling
By default, if checksum validation fails, the user is prompted with an alert dialog to either:
Delete and cancel : Remove the downloaded file and abort
Keep file : Continue with the potentially corrupted file
You can provide a custom handler:
await downloadModelByCategory ( ModelCategory . Stt , 'model-id' , {
onChecksumIssue : async ( issue ) => {
// Custom handling logic
console . error ( 'Checksum issue:' , issue . message );
return false ; // Delete file and abort
},
});
LRU Cache Management
Get all downloaded models with metadata including download time, last used time, and disk size.
import { listDownloadedModelsWithMetadata } from 'react-native-sherpa-onnx/download' ;
const modelsWithMetadata = await listDownloadedModelsWithMetadata (
ModelCategory . Tts
);
modelsWithMetadata . forEach ( item => {
console . log (
item . model . id ,
'Last used:' , item . lastUsed ,
'Size:' , ( item . sizeOnDisk || 0 ) / 1024 / 1024 , 'MB'
);
});
cleanupLeastRecentlyUsed
Automatically remove least recently used models to free disk space.
import { cleanupLeastRecentlyUsed } from 'react-native-sherpa-onnx/download' ;
// Free up at least 500 MB by removing old models
const deletedIds = await cleanupLeastRecentlyUsed ( ModelCategory . Stt , {
targetBytes: 500 * 1024 * 1024 ,
keepCount: 2 , // Always keep at least 2 models
maxModelsToDelete: 5 , // Delete max 5 models
});
console . log ( 'Deleted models:' , deletedIds );
Model category to clean up
Target amount of bytes to free. Cleanup stops once this is reached.
Minimum number of models to keep (won’t delete if count would go below this)
Maximum number of models to delete in one operation
Array of deleted model IDs
Download Resume
The download manager supports automatic resume for interrupted downloads:
Partial downloads are preserved when download is interrupted
Resume headers are sent on retry to continue from last byte
Non-resumable errors (404, 410) trigger full file deletion and restart
Extracted directories are cleaned up but archives are kept for resume
const controller = new AbortController ();
// Start download
const downloadPromise = downloadModelByCategory (
ModelCategory . Stt ,
'sherpa-onnx-whisper-tiny' ,
{ signal: controller . signal }
);
// Cancel after 5 seconds
setTimeout (() => controller . abort (), 5000 );
try {
await downloadPromise ;
} catch ( err ) {
console . log ( 'Download cancelled, will resume on next attempt' );
}
// Resume later - download continues from where it left off
await downloadModelByCategory ( ModelCategory . Stt , 'sherpa-onnx-whisper-tiny' );
Best Practices
Cache Before Download Always call refreshModelsByCategory before showing the model list UI to ensure users see the latest available models.
Progress Feedback Use onProgress callbacks to show download progress to users. Display phase, percentage, speed, and ETA.
Error Handling Handle download errors gracefully. Network failures will auto-retry with exponential backoff.
Disk Space Use cleanupLeastRecentlyUsed to automatically manage disk space when approaching limits.
Download Resume Leverage automatic resume support by preserving partial downloads on cancellation.
Checksum Validation Don’t skip checksum validation. It ensures model integrity and prevents corrupted files.
Storage Locations
Models are stored in platform-specific directories:
iOS : DocumentDirectoryPath/sherpa-onnx/models/{category}/
Android : DocumentDirectoryPath/sherpa-onnx/models/{category}/
Cache files are stored in:
DocumentDirectoryPath/sherpa-onnx/cache/
Each downloaded model has:
Model directory : {category}/{model-id}/
Ready marker : {category}/{model-id}/.ready
Manifest : {category}/{model-id}/manifest.json