loadOrDownloadModel function

Future<LanguageIdentifier> loadOrDownloadModel(
  1. PretrainedModel model, {
  2. required String directory,
  3. void onProgress(
    1. DownloadProgress progress
    )?,
  4. ModelDownloader? downloader,
})

Loads model from directory, downloading it first if it is not there.

The one-liner most callers want: the weights are not shipped with the package, so the first run fetches them and every later run reads the file that is already on disk.

final identifier = await loadOrDownloadModel(
  PretrainedModel.compact,
  directory: 'models',
);

Pass downloader to control the mirror, the HttpClient or the retry policy; otherwise a default one is created and closed here.

Implementation

Future<LanguageIdentifier> loadOrDownloadModel(
  PretrainedModel model, {
  required String directory,
  void Function(DownloadProgress progress)? onProgress,
  ModelDownloader? downloader,
}) async {
  final client = downloader ?? ModelDownloader();
  try {
    final file = await client.download(
      model,
      directory: directory,
      onProgress: onProgress,
    );
    return .fromBytes(await file.readAsBytes());
  } finally {
    if (downloader == null) {
      await client.close();
    }
  }
}