Skip to main content

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
});
category
ModelCategory
required
The model category to refresh
options
object
models
ModelMetaBase[]
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);
});
models
ModelMetaBase[]
Array of cached model metadata

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,
  }
);
category
ModelCategory
required
The model category
id
string
required
Model ID to download
options
object
result
DownloadResult

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');
}
path
string | null
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`);
models
ModelMetaBase[]
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
}
downloaded
boolean
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));
}
status
CacheStatus

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
ModelMetaBase | null
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:
1

Download checksum.txt

Fetches checksum.txt from GitHub Release and caches it in memory
2

Archive validation (tar.bz2)

Uses native libarchive hashing during extraction for efficient validation
3

Single-file validation (.onnx)

Uses local SHA-256 calculation after download
4

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

listDownloadedModelsWithMetadata

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);
category
ModelCategory
required
Model category to clean up
options
object
deletedIds
string[]
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

Build docs developers (and LLMs) love