The Download Manager provides a complete solution for downloading, validating, caching, and managing Sherpa-ONNX models from official GitHub releases. It supports automatic retries, checksum validation, progress tracking, and LRU cache management.
Core Functions
listModelsByCategory()
List available models for a category from local cache.
function listModelsByCategory<T extends ModelMetaBase>(
category: ModelCategory
): Promise<T[]>
Model category: ModelCategory.Tts, ModelCategory.Stt, ModelCategory.Vad, ModelCategory.Diarization, ModelCategory.Enhancement, or ModelCategory.Separation
Array of model metadata from cache (returns empty array if cache is empty)
Example:
import { listModelsByCategory, ModelCategory } from 'react-native-sherpa-onnx';
const ttsModels = await listModelsByCategory(ModelCategory.Tts);
console.log('Cached TTS models:', ttsModels);
refreshModelsByCategory()
Fetch the latest models from GitHub releases with caching and retry logic.
function refreshModelsByCategory<T extends ModelMetaBase>(
category: ModelCategory,
options?: {
forceRefresh?: boolean;
cacheTtlMinutes?: number;
maxRetries?: number;
signal?: AbortSignal;
}
): Promise<T[]>
Model category to refresh
Skip cache and force fetch from remote
Cache time-to-live in minutes (default: 24 hours)
Maximum number of retry attempts
Optional AbortSignal for cancellation
Array of model metadata with SHA256 checksums attached
Example:
import { refreshModelsByCategory, ModelCategory } from 'react-native-sherpa-onnx';
// Fetch latest TTS models
const models = await refreshModelsByCategory(ModelCategory.Tts);
console.log('Available models:', models);
// Force refresh, ignore cache
const freshModels = await refreshModelsByCategory(ModelCategory.Tts, {
forceRefresh: true,
});
// With cancellation support
const abortController = new AbortController();
try {
const models = await refreshModelsByCategory(ModelCategory.Tts, {
signal: abortController.signal,
});
} catch (error) {
if (error.name === 'AbortError') {
console.log('Refresh cancelled');
}
}
// Cancel the request
abortController.abort();
downloadModelByCategory()
Download and extract a model with progress tracking, checksum validation, and automatic retries.
function downloadModelByCategory<T extends ModelMetaBase>(
category: ModelCategory,
id: string,
options?: {
onProgress?: (progress: DownloadProgress) => void;
overwrite?: boolean;
signal?: AbortSignal;
maxRetries?: number;
onChecksumIssue?: (issue: ChecksumIssue) => Promise<boolean>;
}
): Promise<DownloadResult>
Model ID (e.g., "sherpa-onnx-vits-piper-en_US-amy-low")
Progress callback receiving DownloadProgress updates
Delete existing model before downloading
AbortSignal for cancellation support
Maximum download retry attempts
Custom checksum validation handler (returns true to keep file, false to delete)
Object with modelId and localPath of the downloaded model
Example:
import {
downloadModelByCategory,
ModelCategory,
type DownloadProgress
} from 'react-native-sherpa-onnx';
const modelId = 'sherpa-onnx-vits-piper-en_US-amy-low';
try {
const result = await downloadModelByCategory(
ModelCategory.Tts,
modelId,
{
onProgress: (progress: DownloadProgress) => {
console.log(
`${progress.phase}: ${progress.percent.toFixed(1)}% ` +
`(${(progress.bytesDownloaded / 1024 / 1024).toFixed(1)} MB / ` +
`${(progress.totalBytes / 1024 / 1024).toFixed(1)} MB)`
);
if (progress.eta) {
console.log(`ETA: ${Math.round(progress.eta)}s`);
}
},
}
);
console.log('Model downloaded to:', result.localPath);
} catch (error) {
console.error('Download failed:', error);
}
With cancellation:
const abortController = new AbortController();
const downloadPromise = downloadModelByCategory(
ModelCategory.Tts,
modelId,
{
signal: abortController.signal,
onProgress: (progress) => {
console.log(`Progress: ${progress.percent.toFixed(1)}%`);
},
}
);
// Cancel after 5 seconds
setTimeout(() => abortController.abort(), 5000);
try {
await downloadPromise;
} catch (error) {
if (error.name === 'AbortError') {
console.log('Download cancelled');
}
}
getLocalModelPathByCategory()
Get the local filesystem path of a downloaded model.
function getLocalModelPathByCategory(
category: ModelCategory,
id: string
): Promise<string | null>
Absolute path to model directory, or null if not downloaded
This function automatically updates the model’s lastUsed timestamp for LRU cache management.
Example:
import { getLocalModelPathByCategory, ModelCategory, createTTS } from 'react-native-sherpa-onnx';
const modelId = 'sherpa-onnx-vits-piper-en_US-amy-low';
const localPath = await getLocalModelPathByCategory(ModelCategory.Tts, modelId);
if (localPath) {
const tts = await createTTS({
modelPath: { type: 'file', path: localPath },
modelType: 'vits',
});
console.log('TTS initialized with downloaded model');
} else {
console.log('Model not downloaded');
}
isModelDownloadedByCategory()
Check if a model is fully downloaded and ready.
function isModelDownloadedByCategory(
category: ModelCategory,
id: string
): Promise<boolean>
true if model is fully downloaded and extracted, false otherwise
Example:
import { isModelDownloadedByCategory, ModelCategory } from 'react-native-sherpa-onnx';
const isDownloaded = await isModelDownloadedByCategory(
ModelCategory.Tts,
'sherpa-onnx-vits-piper-en_US-amy-low'
);
if (isDownloaded) {
console.log('Model is ready to use');
} else {
console.log('Model needs to be downloaded');
}
listDownloadedModelsByCategory()
List all downloaded models for a category.
function listDownloadedModelsByCategory<T extends ModelMetaBase>(
category: ModelCategory
): Promise<T[]>
Array of metadata for downloaded models
Example:
import { listDownloadedModelsByCategory, ModelCategory } from 'react-native-sherpa-onnx';
const downloadedTtsModels = await listDownloadedModelsByCategory(ModelCategory.Tts);
console.log('Downloaded TTS models:', downloadedTtsModels);
for (const model of downloadedTtsModels) {
console.log(`- ${model.displayName} (${(model.bytes / 1024 / 1024).toFixed(1)} MB)`);
}
deleteModelByCategory()
Delete a downloaded model and its archive.
function deleteModelByCategory(
category: ModelCategory,
id: string
): Promise<void>
Resolves when deletion is complete
Example:
import { deleteModelByCategory, ModelCategory } from 'react-native-sherpa-onnx';
try {
await deleteModelByCategory(ModelCategory.Tts, 'sherpa-onnx-vits-piper-en_US-amy-low');
console.log('Model deleted successfully');
} catch (error) {
console.error('Failed to delete model:', error);
}
Cache Management
List downloaded models with LRU cache metadata.
function listDownloadedModelsWithMetadata<T extends ModelMetaBase>(
category: ModelCategory
): Promise<ModelWithMetadata<T>[]>
models
Promise<ModelWithMetadata<T>[]>
Array of models with metadata:
model: Model metadata
downloadedAt: ISO timestamp of download
lastUsed: ISO timestamp of last access (or null)
sizeOnDisk: Size in bytes
Example:
import { listDownloadedModelsWithMetadata, ModelCategory } from 'react-native-sherpa-onnx';
const models = await listDownloadedModelsWithMetadata(ModelCategory.Tts);
for (const { model, downloadedAt, lastUsed, sizeOnDisk } of models) {
console.log(`${model.displayName}:`);
console.log(` Downloaded: ${new Date(downloadedAt).toLocaleDateString()}`);
console.log(` Last used: ${lastUsed ? new Date(lastUsed).toLocaleDateString() : 'Never'}`);
console.log(` Size: ${((sizeOnDisk ?? 0) / 1024 / 1024).toFixed(1)} MB`);
}
cleanupLeastRecentlyUsed()
Delete least recently used models to free disk space.
function cleanupLeastRecentlyUsed(
category: ModelCategory,
options?: {
targetBytes?: number;
maxModelsToDelete?: number;
keepCount?: number;
}
): Promise<string[]>
Target bytes to free (stops when reached)
options.maxModelsToDelete
Maximum number of models to delete
Minimum number of models to keep
Array of deleted model IDs
Example:
import { cleanupLeastRecentlyUsed, ModelCategory } from 'react-native-sherpa-onnx';
// Free at least 500 MB, keep at least 2 models
const deletedIds = await cleanupLeastRecentlyUsed(ModelCategory.Tts, {
targetBytes: 500 * 1024 * 1024,
keepCount: 2,
});
console.log('Deleted models:', deletedIds);
// Delete up to 3 oldest models
const deleted = await cleanupLeastRecentlyUsed(ModelCategory.Tts, {
maxModelsToDelete: 3,
keepCount: 1,
});
updateModelLastUsed()
Manually update a model’s last used timestamp.
function updateModelLastUsed(
category: ModelCategory,
id: string
): Promise<void>
Resolves when timestamp is updated
This is called automatically by getLocalModelPathByCategory(). Manual use is typically not needed.
clearModelCacheByCategory()
Clear the in-memory and on-disk cache for a category.
function clearModelCacheByCategory(
category: ModelCategory
): Promise<void>
Resolves when cache is cleared
Example:
import { clearModelCacheByCategory, ModelCategory } from 'react-native-sherpa-onnx';
// Clear TTS models cache (forces refresh on next call)
await clearModelCacheByCategory(ModelCategory.Tts);
Event Subscriptions
subscribeDownloadProgress()
Subscribe to download progress events for all models.
function subscribeDownloadProgress(
listener: DownloadProgressListener
): () => void
listener
DownloadProgressListener
required
Callback function: (category, modelId, progress) => void
Function to unsubscribe the listener
Example:
import { subscribeDownloadProgress, ModelCategory } from 'react-native-sherpa-onnx';
const unsubscribe = subscribeDownloadProgress((category, modelId, progress) => {
console.log(`[${category}] ${modelId}: ${progress.percent.toFixed(1)}% (${progress.phase})`);
});
// Later: unsubscribe
unsubscribe();
subscribeModelsListUpdated()
Subscribe to model list update events.
function subscribeModelsListUpdated(
listener: ModelsListUpdatedListener
): () => void
listener
ModelsListUpdatedListener
required
Callback function: (category, models) => void
Function to unsubscribe the listener
Example:
import { subscribeModelsListUpdated } from 'react-native-sherpa-onnx';
const unsubscribe = subscribeModelsListUpdated((category, models) => {
console.log(`[${category}] Model list updated: ${models.length} models`);
});
// Later: unsubscribe
unsubscribe();
Validation Functions
validateChecksum()
Validate a file’s SHA256 checksum.
function validateChecksum(
filePath: string,
expectedChecksum: string,
onProgress?: (bytesProcessed: number, totalBytes: number, percent: number) => void
): Promise<ValidationResult>
Expected SHA256 hash (hex string)
Optional progress callback
result
Promise<ValidationResult>
Validation result with success, error, and message properties
calculateFileChecksum()
Calculate SHA256 checksum of a file.
function calculateFileChecksum(
filePath: string,
onProgress?: (bytesProcessed: number, totalBytes: number, percent: number) => void
): Promise<string>
Optional progress callback
SHA256 hash as lowercase hex string
Type Definitions
ModelCategory
enum ModelCategory {
Tts = 'tts',
Stt = 'stt',
Vad = 'vad',
Diarization = 'diarization',
Enhancement = 'enhancement',
Separation = 'separation',
}
type TtsModelMeta = {
id: string; // Model ID (e.g., "sherpa-onnx-vits-piper-en_US-amy-low")
displayName: string; // Human-readable name
downloadUrl: string; // Download URL
archiveExt: 'tar.bz2' | 'onnx'; // Archive type
bytes: number; // Archive size in bytes
sha256?: string; // SHA256 checksum
category: ModelCategory.Tts;
type: TtsModelType; // Model type (vits, matcha, kokoro, etc.)
languages: string[]; // Supported language codes
quantization: Quantization; // Model quantization level
sizeTier: SizeTier; // Model size tier
};
DownloadProgress
type DownloadProgress = {
bytesDownloaded: number;
totalBytes: number;
percent: number; // 0-100
phase?: 'downloading' | 'extracting';
speed?: number; // Bytes per second
eta?: number; // Estimated seconds remaining
};
DownloadResult
type DownloadResult = {
modelId: string;
localPath: string; // Absolute path to model directory
};
type ModelWithMetadata<T extends ModelMetaBase = ModelMetaBase> = {
model: T;
downloadedAt: string; // ISO timestamp
lastUsed: string | null; // ISO timestamp or null
sizeOnDisk?: number; // Bytes
};
Best Practices
-
Always refresh before showing model list:
const models = await refreshModelsByCategory(ModelCategory.Tts);
-
Handle download errors gracefully:
try {
await downloadModelByCategory(ModelCategory.Tts, modelId, { onProgress });
} catch (error) {
if (error.name === 'AbortError') {
console.log('Download cancelled by user');
} else {
Alert.alert('Download Failed', error.message);
}
}
-
Implement LRU cleanup when disk space is low:
import { checkDiskSpace } from 'react-native-sherpa-onnx';
const diskSpace = await checkDiskSpace(modelBytes);
if (!diskSpace.success) {
await cleanupLeastRecentlyUsed(ModelCategory.Tts, {
targetBytes: modelBytes,
keepCount: 2,
});
}
-
Use subscriptions for global download tracking:
useEffect(() => {
const unsubscribe = subscribeDownloadProgress((category, modelId, progress) => {
setDownloadState({ category, modelId, progress });
});
return unsubscribe;
}, []);
-
Show download progress UI:
const [progress, setProgress] = useState<DownloadProgress | null>(null);
await downloadModelByCategory(ModelCategory.Tts, modelId, {
onProgress: setProgress,
});
// In your component:
{progress && (
<ProgressBar
progress={progress.percent / 100}
text={`${progress.phase}: ${progress.percent.toFixed(1)}%`}
/>
)}
- Model Paths - Path configuration for loaded models
- TTS API - Use downloaded models for text-to-speech
- STT API - Use downloaded models for speech recognition