Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) AI models store: pinned model + ONNX Runtime downloads, installed into the data folder

Egor Khindikaynen1dd35c757fc3
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.cs
index 5b6b6a22..eb426b6a 100644
--- a/src/managed/Nota.App/App.axaml.cs
+++ b/src/managed/Nota.App/App.axaml.cs
@@ -39,6 +39,7 @@ public partial class App : Avalonia.Application
services.AddSingleton<IPluginCatalog, PluginCatalog>();
services.AddSingleton<IPluginStore, PluginStore>();
services.AddSingleton<ISampleStore, SampleStore>();
+ services.AddSingleton<IModelStore>(_ => new ModelStore());
services.AddSingleton<IPresetLibrary, PresetLibrary>();
services.AddSingleton<IProjectStore, ProjectStore>();
services.AddSingleton<IProjectHistory>(_ => new ProjectHistory(AppInfo.Version));
diff --git a/src/managed/Nota.Application/Ports/IModelStore.cs b/src/managed/Nota.Application/Ports/IModelStore.cs
new file mode 100644
index 00000000..308fda36
--- /dev/null
+++ b/src/managed/Nota.Application/Ports/IModelStore.cs
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+
+namespace Nota.Application;
+
+/// <summary>Ids of the AI models Nota can download.</summary>
+public static class AiModels
+{
+ /// <summary>htdemucs: splits audio into drums, bass, other and vocals (Separate Stems).</summary>
+ public const string Stems = "htdemucs";
+ /// <summary>basic-pitch: polyphonic audio → notes (Convert Melody / Harmony).</summary>
+ public const string Transcription = "basic-pitch";
+ /// <summary>ONNX Runtime, the library every model runs on; installed with the first one.</summary>
+ public const string Runtime = "onnxruntime";
+}
+
+/// <summary>A downloadable AI model (or the runtime they share).</summary>
+public sealed record StoreModel(
+ string Id,
+ string Name,
+ string Feature, // what it does in Nota, e.g. "Separate Stems"
+ string Description,
+ string Author,
+ string License, // SPDX id
+ string Source, // where the model comes from
+ long Size, // download bytes
+ long UnpackedSize); // bytes on disk once installed
+
+/// <summary>Installs the AI models behind Separate Stems and Convert to MIDI, with the ONNX
+/// Runtime library they run on. Every download is pinned to a size + sha256; nothing is
+/// executed. Models live in Nota's data folder, not the Samples folder.</summary>
+public interface IModelStore
+{
+ /// <summary>The models the user can install (the runtime isn't listed).</summary>
+ IReadOnlyList<StoreModel> Models { get; }
+
+ /// <summary>The runtime for this computer, or null when there is no build for it.</summary>
+ StoreModel? Runtime { get; }
+
+ bool IsInstalled(string id);
+
+ /// <summary>Bytes installing <paramref name="id"/> downloads now: the model, plus the
+ /// runtime when it isn't installed yet.</summary>
+ long DownloadSize(string id);
+
+ /// <summary>Downloads, verifies and installs the model, and the runtime first if needed.
+ /// Throws <see cref="StoreException"/> with a user-facing message.</summary>
+ Task InstallAsync(string id, IProgress<StoreProgress>? progress = null, CancellationToken ct = default);
+
+ /// <summary>Removes the model; removing the last one also removes the runtime.</summary>
+ void Uninstall(string id);
+
+ /// <summary>The installed runtime's library file, or null.</summary>
+ string? RuntimePath { get; }
+
+ /// <summary>The installed model's file, or null.</summary>
+ string? ModelPath(string id);
+
+ /// <summary>Raised (on any thread) after an install or uninstall.</summary>
+ event Action? Changed;
+}
diff --git a/src/managed/Nota.Infrastructure/ModelStore/ModelCatalog.cs b/src/managed/Nota.Infrastructure/ModelStore/ModelCatalog.cs
new file mode 100644
index 00000000..3d9893ed
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/ModelStore/ModelCatalog.cs
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The AI models Nota can download, pinned in code: there are only a few, and each goes with
+// the C# that runs it (StemSeparator, PitchTranscriber), so a new model ships with a new Nota
+// rather than through a registry index. Every asset is fixed to a URL, size and sha256.
+// ONNX Runtime 1.23.2 — microsoft/onnxruntime's own release archives. 1.23 is the last
+// release with builds for all six targets (Intel Macs included); only the library and its
+// license files are kept out of each archive.
+// htdemucs — Demucs v4 (Meta, MIT) exported to ONNX without its STFT by
+// nota-daw/nota-models/scripts/export_htdemucs.py, published on that repo's releases.
+// basic-pitch — nmp.onnx straight from spotify/basic-pitch at the v0.4.0 tag.
+
+using System.Runtime.InteropServices;
+
+namespace Nota.Infrastructure;
+
+/// <summary>Where a model's bytes come from and what of them is installed.</summary>
+/// <param name="Archive">"file" (the download is the model), "tar" or "zip".</param>
+/// <param name="Keep">For archives: the paths inside it to install (flat, by file name).</param>
+/// <param name="Entry">The installed file Nota loads (model or runtime library).</param>
+public sealed record ModelAsset(string Url, string Sha256, long Size, string Archive, IReadOnlyList<string> Keep, string Entry);
+
+public sealed record CatalogModel(StoreModel Info, ModelAsset Asset);
+
+public static class ModelCatalog
+{
+ private const string OrtVersion = "1.23.2";
+ private const string OrtRelease = "https://github.com/microsoft/onnxruntime/releases/download/v" + OrtVersion + "/";
+
+ /// <summary>The models and this computer's runtime (null when ONNX Runtime has no build for it).</summary>
+ public static (IReadOnlyList<CatalogModel> Models, CatalogModel? Runtime) ForThisPlatform()
+ => (Models, RuntimeFor(Rid()));
+
+ public static readonly IReadOnlyList<CatalogModel> Models =
+ [
+ new(new StoreModel(AiModels.Stems, "htdemucs", "Separate Stems",
+ "Splits a mix into drums, bass, vocals and everything else, each on its own track.",
+ "Meta AI (Demucs v4)", "MIT", "https://github.com/facebookresearch/demucs",
+ 174264717, 174264717),
+ new ModelAsset("https://github.com/nota-daw/nota-models/releases/download/htdemucs-v1/htdemucs.onnx",
+ "04c2b1a149788d048f710a6140446a72f7b4bab3171bc42189176a64ed609c78", 174264717, "file", [], "htdemucs.onnx")),
+ new(new StoreModel(AiModels.Transcription, "basic-pitch", "Convert to MIDI",
+ "Hears every note in a recording, chords included, for Convert Melody and Convert Harmony.",
+ "Spotify", "Apache-2.0", "https://github.com/spotify/basic-pitch",
+ 230444, 230444),
+ new ModelAsset("https://raw.githubusercontent.com/spotify/basic-pitch/v0.4.0/basic_pitch/saved_models/icassp_2022/nmp.onnx",
+ "2c3c1d144bfa61ad236e92e169c13535c880469a12a047d4e73451f2c059a0ec", 230444, "file", [], "nmp.onnx")),
+ ];
+
+ /// <summary>"osx-arm64", "win-x64", "linux-aarch64", … — ONNX Runtime's archive names.</summary>
+ public static string Rid()
+ {
+ string os = OperatingSystem.IsMacOS() ? "osx" : OperatingSystem.IsWindows() ? "win" : "linux";
+ string arch = RuntimeInformation.ProcessArchitecture switch
+ {
+ Architecture.Arm64 => os == "linux" ? "aarch64" : "arm64",
+ Architecture.X64 => os == "osx" ? "x86_64" : "x64",
+ var a => a.ToString().ToLowerInvariant(),
+ };
+ return $"{os}-{arch}";
+ }
+
+ public static CatalogModel? RuntimeFor(string rid)
+ {
+ (string Sha, long Size, string Lib, long LibSize)? a = rid switch
+ {
+ "osx-arm64" => ("b4d513ab2b26f088c66891dbbc1408166708773d7cc4163de7bdca0e9bbb7856", 9999931, "lib/libonnxruntime.1.23.2.dylib", 35138784),
+ "osx-x86_64" => ("d10359e16347b57d9959f7e80a225a5b4a66ed7d7e007274a15cae86836485a6", 11676322, "lib/libonnxruntime.1.23.2.dylib", 39742608),
+ "win-x64" => ("0b38df9af21834e41e73d602d90db5cb06dbd1ca618948b8f1d66d607ac9f3cd", 78127794, "lib/onnxruntime.dll", 14186016),
+ "win-arm64" => ("1cfe88b6435df3b5fb0e9f6bd7d6f5df1e887b6174de7f6e2a47bab956f3f168", 78932411, "lib/onnxruntime.dll", 14868512),
+ "linux-x64" => ("1fa4dcaef22f6f7d5cd81b28c2800414350c10116f5fdd46a2160082551c5f9b", 8309231, "lib/libonnxruntime.so.1.23.2", 22326072),
+ "linux-aarch64" => ("7c63c73560ed76b1fac6cff8204ffe34fe180e70d6582b5332ec094810241e5c", 7254068, "lib/libonnxruntime.so.1.23.2", 18693384),
+ _ => null,
+ };
+ if (a is not { } r) return null;
+ bool win = rid.StartsWith("win", StringComparison.Ordinal);
+ string dir = $"onnxruntime-{rid}-{OrtVersion}/";
+ string file = $"onnxruntime-{rid}-{OrtVersion}" + (win ? ".zip" : ".tgz");
+ return new(new StoreModel(AiModels.Runtime, "ONNX Runtime", "AI runtime",
+ "The library Nota's AI models run on. Installed with the first model.",
+ "Microsoft", "MIT", "https://github.com/microsoft/onnxruntime",
+ r.Size, r.LibSize + 340_000),
+ new ModelAsset(OrtRelease + file, r.Sha, r.Size, win ? "zip" : "tar",
+ [dir + r.Lib, dir + "LICENSE", dir + "ThirdPartyNotices.txt"], Path.GetFileName(r.Lib)));
+ }
+}
diff --git a/src/managed/Nota.Infrastructure/ModelStore/ModelStore.cs b/src/managed/Nota.Infrastructure/ModelStore/ModelStore.cs
new file mode 100644
index 00000000..a4b7e9dd
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/ModelStore/ModelStore.cs
@@ -0,0 +1,197 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Downloads the AI models (ModelCatalog) and the ONNX Runtime library they run on. Like the
+// plugin and sample stores, a download must match its pinned size + sha256 before anything is
+// kept (RegistryClient.DownloadAsync), and only unpacks — nothing it fetches is executed.
+//
+// Layout (NOTA_MODELS_DIR relocates the root):
+// <data>/models/<id>/ the model file (or the runtime library + its license files)
+// .nota-model marker holding the asset's sha256: a folder is installed only if
+// its marker matches the catalog, so a new pinned version reads as
+// not installed and is fetched again
+// An install builds the folder as <root>/.staging-<id> and swaps it in, so a failed or
+// cancelled install never leaves a half-written model behind.
+
+namespace Nota.Infrastructure;
+
+public sealed class ModelStore : IModelStore
+{
+ public const string MarkerFile = ".nota-model";
+
+ private readonly string _root;
+ private readonly IReadOnlyList<CatalogModel> _models;
+ private readonly CatalogModel? _runtime;
+ private readonly RegistryClient _http;
+ private readonly SemaphoreSlim _installGate = new(1, 1);
+
+ public ModelStore() : this(DefaultRoot(), ModelCatalog.Models, ModelCatalog.ForThisPlatform().Runtime) { }
+
+ /// <param name="root">Where models are installed (tests pass a temp dir).</param>
+ public ModelStore(string root, IReadOnlyList<CatalogModel> models, CatalogModel? runtime, HttpMessageHandler? handler = null)
+ {
+ _root = root;
+ _models = models;
+ _runtime = runtime;
+ Directory.CreateDirectory(root);
+ // Only the downloader is used: models are pinned in code, there is no index to fetch.
+ _http = new RegistryClient("", "", "AI models", "Nota-ModelStore", handler);
+ }
+
+ private static string DefaultRoot()
+ => Environment.GetEnvironmentVariable("NOTA_MODELS_DIR") is { Length: > 0 } over ? over : NotaPaths.SubDir("models");
+
+ public event Action? Changed;
+
+ public IReadOnlyList<StoreModel> Models => _models.Select(m => m.Info).ToList();
+
+ public StoreModel? Runtime => _runtime?.Info;
+
+ public bool IsInstalled(string id) => Find(id) is { } m && Installed(m);
+
+ public long DownloadSize(string id)
+ {
+ var m = Find(id) ?? throw new StoreException($"Unknown AI model \"{id}\".");
+ long size = Installed(m) ? 0 : m.Asset.Size;
+ if (id != AiModels.Runtime && _runtime is not null && !Installed(_runtime)) size += _runtime.Asset.Size;
+ return size;
+ }
+
+ public string? RuntimePath => _runtime is not null && Installed(_runtime) ? EntryPath(_runtime) : null;
+
+ public string? ModelPath(string id) => Find(id) is { } m && Installed(m) ? EntryPath(m) : null;
+
+ public async Task InstallAsync(string id, IProgress<StoreProgress>? progress = null, CancellationToken ct = default)
+ {
+ var model = Find(id) ?? throw new StoreException($"Unknown AI model \"{id}\".");
+ if (id != AiModels.Runtime && _runtime is null)
+ throw new StoreException("AI models aren't available for this computer: ONNX Runtime has no build for it.");
+ await _installGate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ CheckFreeSpace(id);
+ if (id != AiModels.Runtime && !Installed(_runtime!)) await InstallOneAsync(_runtime!, progress, ct).ConfigureAwait(false);
+ if (!Installed(model)) await InstallOneAsync(model, progress, ct).ConfigureAwait(false);
+ }
+ finally
+ {
+ _installGate.Release();
+ }
+ Changed?.Invoke();
+ }
+
+ public void Uninstall(string id)
+ {
+ if (Find(id) is not { } m) return;
+ Delete(m);
+ // The runtime goes with the last model. On Windows a loaded DLL can't be deleted; it
+ // stays until the next uninstall then.
+ if (id != AiModels.Runtime && _runtime is not null && !_models.Any(Installed))
+ {
+ try { Delete(_runtime); } catch (StoreException) { }
+ }
+ Changed?.Invoke();
+ }
+
+ // ---- install ---------------------------------------------------------------------------
+
+ private async Task InstallOneAsync(CatalogModel m, IProgress<StoreProgress>? progress, CancellationToken ct)
+ {
+ if (!RegistryClient.IsValidId(m.Info.Id)) throw new StoreException($"Invalid model id \"{m.Info.Id}\".");
+ var work = Directory.CreateTempSubdirectory("nota-model-").FullName;
+ var staging = Path.Combine(_root, ".staging-" + m.Info.Id);
+ try
+ {
+ var a = m.Asset;
+ var file = Path.Combine(work, a.Archive == "file" ? a.Entry : "asset" + RegistryClient.ExtensionOf(a.Url, a.Archive));
+ await _http.DownloadAsync(a.Url, a.Size, a.Sha256, file, m.Info.Name, progress, ct).ConfigureAwait(false);
+
+ if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
+ Directory.CreateDirectory(staging);
+ if (a.Archive == "file")
+ {
+ File.Move(file, Path.Combine(staging, a.Entry));
+ }
+ else
+ {
+ progress?.Report(new StoreProgress(-1, $"Unpacking {m.Info.Name}…"));
+ var unpacked = Path.Combine(work, "x");
+ await Task.Run(() => ArchiveUnpacker.Unpack(file, a.Archive, unpacked, ct), ct).ConfigureAwait(false);
+ foreach (var keep in a.Keep)
+ {
+ var src = RegistryClient.Resolve(unpacked, keep);
+ if (!File.Exists(src)) throw new StoreException($"The download of {m.Info.Name} doesn't contain {keep}.");
+ File.Copy(src, Path.Combine(staging, Path.GetFileName(src)));
+ }
+ }
+ if (!File.Exists(Path.Combine(staging, a.Entry))) throw new StoreException($"The download of {m.Info.Name} doesn't contain {a.Entry}.");
+ File.WriteAllText(Path.Combine(staging, MarkerFile), a.Sha256);
+
+ var final = FolderOf(m);
+ if (Directory.Exists(final)) Directory.Delete(final, recursive: true);
+ Directory.Move(staging, final);
+ }
+ catch
+ {
+ try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } catch { /* best-effort */ }
+ throw;
+ }
+ finally
+ {
+ try { Directory.Delete(work, recursive: true); } catch { /* temp; best-effort */ }
+ }
+ }
+
+ // The download and the installed files both sit in temp / the models folder at once for a
+ // moment; checked up front for everything this install needs, with 5% headroom.
+ private void CheckFreeSpace(string id)
+ {
+ long need = 0;
+ foreach (var m in new[] { Find(id), id == AiModels.Runtime ? null : _runtime })
+ if (m is not null && !Installed(m)) need += m.Asset.Size + m.Info.UnpackedSize;
+ need += need / 20;
+ if (FreeBytes(_root) is { } free && free < need)
+ throw new StoreException($"Installing this model needs {Mb(need)} of free disk space, and there is {Mb(free)}.");
+ }
+
+ private static long? FreeBytes(string path)
+ {
+ try { return new DriveInfo(Path.GetPathRoot(Path.GetFullPath(path))!).AvailableFreeSpace; }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException) { return null; }
+ }
+
+ private static string Mb(long bytes) => bytes >= 1L << 30 ? $"{bytes / (double)(1L << 30):0.0} GB" : $"{bytes / (double)(1 << 20):0} MB";
+
+ // ---- state -----------------------------------------------------------------------------
+
+ private CatalogModel? Find(string id)
+ => id == AiModels.Runtime ? _runtime : _models.FirstOrDefault(m => m.Info.Id == id);
+
+ private string FolderOf(CatalogModel m) => Path.Combine(_root, m.Info.Id);
+
+ private string EntryPath(CatalogModel m) => Path.Combine(FolderOf(m), m.Asset.Entry);
+
+ private bool Installed(CatalogModel m)
+ {
+ try
+ {
+ var marker = Path.Combine(FolderOf(m), MarkerFile);
+ return File.Exists(marker) && File.ReadAllText(marker).Trim() == m.Asset.Sha256 && File.Exists(EntryPath(m));
+ }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ }
+
+ private void Delete(CatalogModel m)
+ {
+ var dir = FolderOf(m);
+ if (!File.Exists(Path.Combine(dir, MarkerFile))) return; // only ever a folder this store made
+ try { Directory.Delete(dir, recursive: true); }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException)
+ {
+ throw new StoreException($"Couldn't remove {m.Info.Name} — it may be in use. Restart Nota and try again.", e);
+ }
+ }
+}
diff --git a/tests/Nota.SmokeTest/ModelStoreTests.cs b/tests/Nota.SmokeTest/ModelStoreTests.cs
new file mode 100644
index 00000000..ff2958f8
--- /dev/null
+++ b/tests/Nota.SmokeTest/ModelStoreTests.cs
@@ -0,0 +1,160 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// AI models (IModelStore): install / uninstall end to end against local assets — a plain model
+// file and a runtime in a tar.gz, as ONNX Runtime ships — including the runtime coming with
+// the first model and going with the last, checksum and archive-content refusals, cancellation,
+// and a pinned version change. Also runnable alone: `--models`.
+
+using Nota.Application;
+using Nota.Infrastructure;
+using static Nota.SmokeTest.PluginStoreTests;
+
+namespace Nota.SmokeTest;
+
+internal static class ModelStoreTests
+{
+ public static IEnumerable<(bool Ok, string Label)> Run()
+ {
+ yield return (ModelCatalog.RuntimeFor("osx-arm64") is { Asset.Entry: "libonnxruntime.1.23.2.dylib" }
+ && ModelCatalog.RuntimeFor("win-x64") is { Asset.Archive: "zip", Asset.Entry: "onnxruntime.dll" }
+ && ModelCatalog.RuntimeFor("linux-aarch64") is { Asset.Entry: "libonnxruntime.so.1.23.2" }
+ && ModelCatalog.RuntimeFor("freebsd-x64") is null,
+ "every platform Nota ships on has a runtime; others have none");
+ yield return (ModelCatalog.RuntimeFor(ModelCatalog.Rid()) is not null, $"…including this one ({ModelCatalog.Rid()})");
+ yield return (ModelCatalog.Models.All(m => m.Asset.Sha256.Length == 64 && m.Asset.Size > 0 && m.Asset.Url.StartsWith("https://")),
+ "every model is pinned to an https URL, size and sha256");
+
+ var tmp = Directory.CreateTempSubdirectory("nota-models-test-").FullName;
+ try
+ {
+ foreach (var r in Flow(tmp)) yield return r;
+ }
+ finally
+ {
+ try { Directory.Delete(tmp, recursive: true); } catch { }
+ }
+ }
+
+ private static IEnumerable<(bool, string)> Flow(string tmp)
+ {
+ var src = Directory.CreateDirectory(Path.Combine(tmp, "src")).FullName;
+ var root = Path.Combine(tmp, "models");
+
+ var modelFile = Path.Combine(src, "m.onnx");
+ File.WriteAllText(modelFile, "model bytes");
+ var rtArchive = Path.Combine(src, "rt.tar.gz");
+ WriteTarGz(rtArchive, ("ort-1/lib/libort.so", "native"), ("ort-1/LICENSE", "MIT"), ("ort-1/include/ort.h", "header"));
+
+ CatalogModel Model(string id, string file, string? sha = null)
+ => new(new StoreModel(id, id, "Feature", "", "", "MIT", "", new FileInfo(file).Length, new FileInfo(file).Length),
+ new ModelAsset(file, sha ?? Sha(file), new FileInfo(file).Length, "file", [], "m.onnx"));
+ var runtime = new CatalogModel(new StoreModel(AiModels.Runtime, "Runtime", "", "", "", "MIT", "", new FileInfo(rtArchive).Length, 100),
+ new ModelAsset(rtArchive, Sha(rtArchive), new FileInfo(rtArchive).Length, "tar", ["ort-1/lib/libort.so", "ort-1/LICENSE"], "libort.so"));
+ var a = Model("model-a", modelFile);
+ var b = Model("model-b", modelFile);
+
+ var store = new ModelStore(root, [a, b], runtime);
+ int changed = 0;
+ store.Changed += () => changed++;
+ yield return (!store.IsInstalled("model-a") && store.RuntimePath is null && store.ModelPath("model-a") is null,
+ "nothing is installed at first");
+ yield return (store.DownloadSize("model-a") == a.Asset.Size + runtime.Asset.Size,
+ "the first model's download includes the runtime");
+
+ var stages = new List<string>();
+ store.InstallAsync("model-a", new SyncProgress(p => stages.Add(p.Message))).GetAwaiter().GetResult();
+ yield return (store.IsInstalled("model-a") && store.IsInstalled(AiModels.Runtime) && changed == 1,
+ "installing a model installs the runtime with it");
+ yield return (store.RuntimePath is { } rp && File.ReadAllText(rp) == "native"
+ && File.Exists(Path.Combine(root, AiModels.Runtime, "LICENSE"))
+ && !File.Exists(Path.Combine(root, AiModels.Runtime, "ort.h")),
+ "…keeping only the library and its license out of the archive");
+ yield return (store.ModelPath("model-a") is { } mp && File.ReadAllText(mp) == "model bytes",
+ "…and the model file where ModelPath says");
+ yield return (stages.Any(s => s.StartsWith("Downloading Runtime")) && stages.Any(s => s.StartsWith("Downloading model-a")),
+ "progress names each download");
+ yield return (store.DownloadSize("model-b") == b.Asset.Size, "the second model downloads only itself");
+ yield return (!Directory.EnumerateDirectories(root, ".staging-*").Any(), "no staging folder is left behind");
+
+ // A new pinned version of a model reads as not installed (and so is fetched again).
+ var a2 = Model("model-a", modelFile) with { Asset = a.Asset with { Sha256 = new string('0', 64) } };
+ var newer = new ModelStore(root, [a2, b], runtime);
+ yield return (!newer.IsInstalled("model-a") && newer.IsInstalled(AiModels.Runtime),
+ "a model whose pinned checksum changed is no longer installed");
+ yield return (Throws(() => newer.InstallAsync("model-a").GetAwaiter().GetResult()) && !newer.IsInstalled("model-a")
+ && store.IsInstalled("model-a"),
+ "…and a download that doesn't match the pin is refused, the old files untouched");
+
+ var badKeep = new CatalogModel(runtime.Info, runtime.Asset with { Keep = ["ort-1/lib/missing.so"], Entry = "missing.so" });
+ var fresh = new ModelStore(Path.Combine(tmp, "fresh"), [a], badKeep);
+ yield return (Throws(() => fresh.InstallAsync("model-a").GetAwaiter().GetResult()) && !fresh.IsInstalled(AiModels.Runtime) && !fresh.IsInstalled("model-a"),
+ "an archive missing the library installs nothing");
+
+ using (var cts = new CancellationTokenSource())
+ {
+ cts.Cancel();
+ var c = new ModelStore(Path.Combine(tmp, "cancel"), [a], runtime);
+ bool cancelled = false;
+ try { c.InstallAsync("model-a", null, cts.Token).GetAwaiter().GetResult(); }
+ catch (OperationCanceledException) { cancelled = true; }
+ yield return (cancelled && !c.IsInstalled("model-a") && !c.IsInstalled(AiModels.Runtime),
+ "a cancelled install leaves nothing");
+ }
+
+ yield return (Throws(() => new ModelStore(Path.Combine(tmp, "none"), [a], null).InstallAsync("model-a").GetAwaiter().GetResult()),
+ "without a runtime for this computer, models can't be installed");
+
+ // Uninstall: the runtime stays while a model needs it, and goes with the last one.
+ store.InstallAsync("model-b").GetAwaiter().GetResult();
+ store.Uninstall("model-a");
+ yield return (!store.IsInstalled("model-a") && store.IsInstalled("model-b") && store.IsInstalled(AiModels.Runtime),
+ "removing one model keeps the runtime for the other");
+ store.Uninstall("model-b");
+ yield return (!store.IsInstalled("model-b") && !store.IsInstalled(AiModels.Runtime) && !Directory.Exists(Path.Combine(root, AiModels.Runtime)),
+ "removing the last model removes the runtime too");
+
+ var stray = Directory.CreateDirectory(Path.Combine(root, "model-a")).FullName;
+ File.WriteAllText(Path.Combine(stray, "m.onnx"), "user file");
+ store.Uninstall("model-a");
+ yield return (File.Exists(Path.Combine(stray, "m.onnx")), "uninstall leaves a folder without the store's marker alone");
+ }
+
+ /// <summary>Live: installs the real runtime + basic-pitch from their pinned URLs into
+ /// <paramref name="root"/> and transcribes a tone (`--models-live <dir>`). htdemucs too when
+ /// <paramref name="withStems"/> — 174 MB.</summary>
+ public static IEnumerable<(bool Ok, string Label)> RunLive(string root, bool withStems)
+ {
+ var (models, rt) = ModelCatalog.ForThisPlatform();
+ var store = new ModelStore(root, models, rt);
+ foreach (var id in withStems ? new[] { AiModels.Transcription, AiModels.Stems } : [AiModels.Transcription])
+ {
+ string? err = null;
+ try { store.InstallAsync(id, new SyncProgress(_ => { })).GetAwaiter().GetResult(); }
+ catch (StoreException e) { err = e.Message; }
+ yield return (store.IsInstalled(id) && store.RuntimePath is not null, $"{id} and the runtime install from their pinned URLs{(err is null ? "" : $" ({err})")}");
+ }
+ if (store.RuntimePath is not { } runtime || store.ModelPath(AiModels.Transcription) is not { } model) yield break;
+
+ var tone = new float[PitchTranscriber.SampleRate * 2];
+ for (int i = 0; i < tone.Length; i++) tone[i] = 0.5f * (float)Math.Sin(2 * Math.PI * 440 * i / PitchTranscriber.SampleRate);
+ using var tr = new PitchTranscriber(runtime, model);
+ var notes = tr.Transcribe(tone);
+ yield return (notes.Count >= 1 && notes.All(n => n.Pitch == 69), $"the downloaded runtime + basic-pitch hear an A4 tone as A4 ({string.Join(", ", notes.Select(n => n.Pitch))})");
+
+ if (withStems && store.ModelPath(AiModels.Stems) is { } stems)
+ {
+ var l = new float[StemSeparator.SampleRate * 3];
+ for (int i = 0; i < l.Length; i++) l[i] = 0.3f * (float)Math.Sin(2 * Math.PI * 220 * i / StemSeparator.SampleRate);
+ using var sep = new StemSeparator(runtime, stems);
+ var o = sep.Separate(l, l);
+ yield return (o.Length == 4 && o[0][0].Length == l.Length, "the downloaded htdemucs separates");
+ }
+ }
+
+ // Progress<T> posts to the thread pool; tests want the reports in order, now.
+ private sealed class SyncProgress(Action<StoreProgress> report) : IProgress<StoreProgress>
+ {
+ public void Report(StoreProgress value) => report(value);
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 585ac452..b7e60f08 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -116,6 +116,22 @@ if (args.Length >= 1 && args[0] == "--samples")
Console.WriteLine(failures == 0 ? "SAMPLES PASSED" : $"SAMPLES FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// AI models store alone: `--models`.
+if (args.Length >= 1 && args[0] == "--models")
+{
+ Console.WriteLine("-- ai models: store --");
+ foreach (var (ok, label) in ModelStoreTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "MODELS PASSED" : $"MODELS FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+// Live installs of the real models: `--models-live <dir> [--stems]`.
+if (args.Length >= 2 && args[0] == "--models-live")
+{
+ Console.WriteLine("-- ai models: live installs --");
+ foreach (var (ok, label) in ModelStoreTests.RunLive(args[1], args.Contains("--stems"))) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "MODELS LIVE PASSED" : $"MODELS LIVE FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// AI models' DSP ports against the Python originals: `--ai-golden <libonnxruntime> <dir>`.
if (args.Length >= 3 && args[0] == "--ai-golden")
{
@@ -13634,5 +13650,9 @@ foreach (var (ok, label) in PluginStoreTests.Run()) Check(ok, label);
Console.WriteLine("-- get samples: sample registry store --");
foreach (var (ok, label) in SampleStoreTests.Run()) Check(ok, label);
+// --- ai models: model + runtime install/uninstall from local assets ---
+Console.WriteLine("-- ai models: store --");
+foreach (var (ok, label) in ModelStoreTests.Run()) Check(ok, label);
+
Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");
return failures == 0 ? 0 : 1;