Files
ai_studio/Sources/ModelDownload.swift
T

587 lines
28 KiB
Swift

import Foundation
import SwiftUI
import UniformTypeIdentifiers
import AppKit
struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
let id: String
let title: String
let size: String
let repository: String
let revision: String
let files: [String]
var downloads: Int? = nil
var likes: Int? = nil
static let all: [Self] = [
.init(id: "smollm2-135m", title: "SmolLM2 135M Instruct", size: "270 MB",
repository: "HuggingFaceTB/SmolLM2-135M-Instruct",
revision: "12fd25f77366fa6b3b4b768ec3050bf629380bac",
files: ["config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json",
"generation_config.json", "special_tokens_map.json"]),
.init(id: "qwen3-0.6b-4bit", title: "Qwen3 0.6B 4-bit", size: "350 MB",
repository: "mlx-community/Qwen3-0.6B-4bit",
revision: "73e3e38d981303bc594367cd910ea6eb48349da8",
files: ["config.json", "model.safetensors", "model.safetensors.index.json", "tokenizer.json",
"tokenizer_config.json", "special_tokens_map.json", "added_tokens.json"])
]
static func search(_ query: String) async throws -> [Self] {
var url = URLComponents()
url.scheme = "https"
url.host = "huggingface.co"
url.path = "/api/models"
url.queryItems = [
.init(name: "author", value: "mlx-community"),
.init(name: "pipeline_tag", value: "text-generation"),
.init(name: "search", value: query),
.init(name: "limit", value: "25"),
.init(name: "sort", value: "downloads"),
.init(name: "direction", value: "-1"),
.init(name: "full", value: "true")
]
guard let endpoint = url.url else { throw StudioError("Could not prepare the model search.") }
let response = try await WebFetch.load(endpoint, types: ["application/json"])
return try decodeSearch(response.data)
}
static func decodeSearch(_ data: Data) throws -> [Self] {
struct Entry: Decodable {
struct File: Decodable { let rfilename: String }
let id: String
let sha: String?
let siblings: [File]?
let downloads: Int?
let likes: Int?
}
return try JSONDecoder().decode([Entry].self, from: data).compactMap { entry in
let prefix = "mlx-community/"
guard entry.id.hasPrefix(prefix), let revision = entry.sha, revision.count == 40,
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }) else { return nil }
let name = String(entry.id.dropFirst(prefix.count))
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
guard !name.isEmpty, name.unicodeScalars.allSatisfy(safe.contains) else { return nil }
let files = (entry.siblings ?? []).map(\.rfilename).filter { file in
!file.hasPrefix(".") && file.unicodeScalars.allSatisfy(safe.contains) &&
(file.hasSuffix(".safetensors") || file.hasSuffix(".json") || file.hasSuffix(".txt") ||
file.hasSuffix(".model") || file.hasSuffix(".jinja") || file.hasSuffix(".tiktoken"))
}
guard files.contains("config.json"), files.contains(where: { $0.hasSuffix(".safetensors") }),
!files.contains("adapter_config.json"), !files.contains("adapter_model.safetensors") else { return nil }
return Self(id: "hf-" + name, title: name, size: "", repository: entry.id, revision: revision,
files: Array(Set(files)).sorted(), downloads: entry.downloads, likes: entry.likes)
}
}
var source: URL { URL(string: "https://huggingface.co/" + repository)! }
var localFolder: URL {
URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory)
.appending(path: id, directoryHint: .isDirectory)
}
func installed(at folder: URL) -> Bool {
files.allSatisfy {
let file = folder.appending(path: $0)
return ((try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) > 0
}
}
func install(
to destination: URL,
progress: @Sendable (String, Double) async -> Void
) async throws {
if installed(at: destination) { return }
let manager = FileManager.default
if manager.fileExists(atPath: destination.path) {
throw StudioError("Remove the incomplete managed model before reinstalling.")
}
let staging = URL.temporaryDirectory.appending(path: "AIStudio-model-\(UUID())", directoryHint: .isDirectory)
try manager.createDirectory(at: staging, withIntermediateDirectories: false)
defer { try? manager.removeItem(at: staging) }
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 60
config.timeoutIntervalForResource = 3600
let session = URLSession(configuration: config)
defer { session.finishTasksAndInvalidate() }
for (offset, file) in files.enumerated() {
try Task.checkCancellation()
await progress("Downloading \(file) (\(offset + 1) of \(files.count))…", Double(offset) / Double(files.count))
let url = source.appending(path: "resolve/\(revision)/\(file)")
let (download, response) = try await session.download(from: url)
defer { try? manager.removeItem(at: download) }
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
http.url?.scheme == "https" else {
throw StudioError("Could not download \(file).")
}
try manager.moveItem(at: download, to: staging.appending(path: file))
}
try Task.checkCancellation()
guard installed(at: staging) else { throw StudioError("The download was incomplete.") }
try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
try manager.moveItem(at: staging, to: destination)
}
}
struct ModelCatalogView: View {
@ObservedObject var studio: StudioModel
@AppStorage("mlxPath") private var mlxPath = ""
@AppStorage("mlxOnly") private var mlxOnly = false
@State private var downloads: [String: Task<Void, Never>] = [:]
@State private var downloadStates: [String: DownloadState] = [:]
private struct DownloadState {
let message: String
let fraction: Double?
}
@AppStorage("mlxRegisteredPaths") private var registered = Data()
@State private var pickingLibrary = false
@State private var scanningLibrary = false
@State private var scanRequested = false
@State private var libraryStatus = ""
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
@State private var removing: CatalogModel?
@State private var status = ""
@AppStorage("managedMLXModels") private var managed = Data()
@State private var query = ""
@State private var matches: [CatalogModel] = []
@State private var searching = false
@State private var searchStatus = ""
@State private var loadingPath: String?
@AppStorage("favoriteModelKeys") private var favoriteData = Data()
@State private var backend = "MLX"
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
@AppStorage("ollamaModel") private var ollamaModel = ""
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
@State private var ollamaQuery = ""
@State private var ollamaCatalog: [String] = []
@State private var ollamaSearching = false
@State private var ollamaCatalogStatus = ""
private var installedModels: [CatalogModel] {
let saved = (try? JSONDecoder().decode([CatalogModel].self, from: managed)) ?? []
return saved + CatalogModel.all.filter { $0.installed(at: $0.localFolder) }
}
private var readyModels: [CatalogModel] {
installedModels.filter { $0.installed(at: $0.localFolder) }
}
private var favorites: Set<String> {
(try? JSONDecoder().decode(Set<String>.self, from: favoriteData)) ?? []
}
private func favoriteFirst<T>(_ rows: [T], key: (T) -> String) -> [T] {
let saved = favorites
return rows.filter { saved.contains(key($0)) } + rows.filter { !saved.contains(key($0)) }
}
private func favoriteButton(_ key: String) -> some View {
let saved = favorites.contains(key)
let label = saved ? "Remove from Favorites" : "Add to Favorites"
return Button(label, systemImage: saved ? "star.fill" : "star") {
var updated = favorites
if saved { updated.remove(key) } else { updated.insert(key) }
if let data = try? JSONEncoder().encode(updated) { favoriteData = data }
}
.labelStyle(.iconOnly)
.buttonStyle(.borderless)
.help(label)
}
var body: some View {
VStack(spacing: 0) {
Picker("Model runtime", selection: $backend) {
Text("MLX").tag("MLX")
Text("Ollama").tag("Ollama")
}
.pickerStyle(.segmented)
.frame(width: 260)
.padding()
if backend == "Ollama" {
ollamaLibrary
} else {
mlxLibrary
}
}
}
private var mlxLibrary: some View {
Form {
Section("Installed MLX Models") {
HStack {
Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true }
Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true }
if scanningLibrary { ProgressView().controlSize(.small) }
}
.disabled(studio.running || scanningLibrary)
if library.isEmpty && readyModels.isEmpty {
Text("Register an existing MLX folder, scan a model library, or download a catalog model below.")
.foregroundStyle(.secondary)
}
ForEach(favoriteFirst(readyModels) { "mlx:" + $0.id }) { model in modelRow(model) }
let paths = library.filter { path in !readyModels.contains { $0.localFolder.path == path } }
ForEach(favoriteFirst(paths) { "folder:" + $0 }, id: \.self) { path in
HStack {
Text(URL(fileURLWithPath: path).lastPathComponent).help(path)
favoriteButton("folder:" + path)
Spacer()
Button(mlxPath == path && mlxOnly ? "Active" : "Load Model") { load(path) }
.disabled(studio.running || loadingPath != nil || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)) ||
(mlxPath == path && mlxOnly))
Button("Reveal") {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
}
Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running)
}
}
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
Section("Hugging Face") {
HStack {
TextField("Search MLX models", text: $query, prompt: Text("e.g. Qwen, Gemma"))
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search)
Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching || hasMLXDownloads)
if searching { ProgressView().controlSize(.small) }
}
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
let available = matches.filter { model in !readyModels.contains { $0.id == model.id } }
ForEach(favoriteFirst(available) { "mlx:" + $0.id }) { model in
modelRow(model)
}
}
Section("Recommended Models") {
ForEach(favoriteFirst(CatalogModel.all.filter { !$0.installed(at: $0.localFolder) }) { "mlx:" + $0.id }) { model in modelRow(model) }
}
if !status.isEmpty && !hasMLXDownloads {
Section {
Text(status).textSelection(.enabled).foregroundStyle(.secondary)
if loadingPath != nil { ProgressView().controlSize(.small) }
}
}
}
.formStyle(.grouped)
.onAppear { if matches.isEmpty && searchStatus.isEmpty { search() } }
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
do {
let url = try result.get()
if scanRequested {
scanningLibrary = true
Task {
defer { scanningLibrary = false }
do {
let found = try await Task.detached { try MLXLibrary.discover(in: url) }.value
registered = try JSONEncoder().encode(Array(Set(library + found.map(\.path))).sorted())
libraryStatus = "Found \(found.count) compatible MLX model folder(s)."
} catch { libraryStatus = error.localizedDescription }
}
} else {
guard MLXLibrary.isModel(at: url) else {
throw StudioError("Choose an MLX folder with config.json and safetensors weights.")
}
registered = try JSONEncoder().encode(Array(Set(library + [url.resolvingSymlinksInPath().path])).sorted())
libraryStatus = "Registered \(url.lastPathComponent)."
}
} catch { libraryStatus = error.localizedDescription }
}
.confirmationDialog("Remove downloaded model?", isPresented: Binding(
get: { removing != nil }, set: { if !$0 { removing = nil } }
), titleVisibility: .visible, presenting: removing) { model in
Button("Remove Model", role: .destructive) { remove(model) }
} message: { model in Text(model.title) }
}
private var ollamaLibrary: some View {
Form {
Section("Installed on Ollama") {
LabeledContent("Server", value: ollamaEndpoint)
Button("Refresh Installed Models") { studio.refresh(endpoint: ollamaEndpoint) }
.disabled(studio.managing)
if studio.modelListEndpoint == ollamaEndpoint {
if studio.models.isEmpty { Text("No models installed on this server.").foregroundStyle(.secondary) }
ForEach(favoriteFirst(studio.models) { "ollama:" + $0.name }) { model in
HStack {
Label(model.name, systemImage: "cube")
favoriteButton("ollama:" + model.name)
Spacer()
if let size = model.size {
Text(ByteCountFormatter.string(fromByteCount: size, countStyle: .file))
.font(.caption).foregroundStyle(.secondary)
}
let active = ollamaModel == model.name && !mlxOnly && !compatibleEnabled
Button(active ? "Active" : "Use Model") {
studio.selectOllamaModel(model.name)
}
.disabled(active || studio.running)
}
}
}
if !studio.modelStatus.isEmpty { Text(studio.modelStatus).foregroundStyle(.secondary) }
if studio.managing {
ProgressView().controlSize(.small)
Button("Cancel") { studio.cancelManagement() }
}
}
Section("Ollama Catalog") {
HStack {
TextField("Search Ollama models", text: $ollamaQuery, prompt: Text("e.g. Qwen, Llama"))
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(searchOllama)
Button(ollamaQuery.isEmpty ? "Browse" : "Search", action: searchOllama).disabled(ollamaSearching || hasOllamaDownloads)
if ollamaSearching { ProgressView().controlSize(.small) }
}
if !ollamaCatalogStatus.isEmpty { Text(ollamaCatalogStatus).foregroundStyle(.secondary) }
ForEach(favoriteFirst(ollamaCatalog) { "ollama:" + $0 + ":latest" }, id: \.self) { name in
VStack(alignment: .leading, spacing: 6) {
HStack {
Text(name).font(.headline)
favoriteButton("ollama:" + name + ":latest")
Spacer()
if let card = URL(string: "https://ollama.com/library/" + name) {
Link("Tags", destination: card)
}
if studio.modelListEndpoint == ollamaEndpoint,
studio.models.contains(where: { $0.name == name || $0.name == name + ":latest" }) {
Text("Installed").foregroundStyle(.secondary)
} else if let task = downloads["ollama:" + name] {
Button("Cancel Download") { task.cancel() }
} else {
Button("Pull Latest") { pull(name) }
}
}
downloadProgress("ollama:" + name)
}
}
}
}
.formStyle(.grouped)
.onAppear {
studio.refresh(endpoint: ollamaEndpoint)
if ollamaCatalog.isEmpty && ollamaCatalogStatus.isEmpty { searchOllama() }
}
}
private var hasMLXDownloads: Bool { downloads.keys.contains { $0.hasPrefix("mlx:") } }
private var hasOllamaDownloads: Bool { downloads.keys.contains { $0.hasPrefix("ollama:") } }
@ViewBuilder private func downloadProgress(_ key: String) -> some View {
if let state = downloadStates[key] {
if downloads[key] != nil {
ProgressView(value: state.fraction).progressViewStyle(.linear)
.accessibilityLabel("Download progress")
}
Text(state.message).font(.caption).foregroundStyle(.secondary)
}
}
private func pull(_ name: String) {
let key = "ollama:" + name
guard downloads[key] == nil else { return }
let endpoint = ollamaEndpoint
downloadStates[key] = DownloadState(message: "Preparing download…", fraction: nil)
downloads[key] = Task {
defer {
downloads[key] = nil
if !hasOllamaDownloads && endpoint == ollamaEndpoint {
Task {
while studio.managing { try await Task.sleep(for: .milliseconds(100)) }
if endpoint == ollamaEndpoint { studio.refresh(endpoint: endpoint) }
}
}
}
do {
let client = try studio.ollamaClient(endpoint: endpoint)
for try await message in client.pull(name) {
let percent = message.hasSuffix("%") ? message.split(separator: " ").last.flatMap { Double($0.dropLast()) } : nil
downloadStates[key] = DownloadState(message: message, fraction: percent.map { $0 / 100 })
}
try Task.checkCancellation()
downloadStates[key] = DownloadState(message: "Downloaded.", fraction: nil)
} catch {
downloadStates[key] = DownloadState(message: Task.isCancelled ? "Download cancelled." : error.localizedDescription, fraction: nil)
}
}
}
private func searchOllama() {
guard !ollamaSearching, !hasOllamaDownloads else { return }
let term = ollamaQuery.trimmingCharacters(in: .whitespacesAndNewlines)
ollamaSearching = true
ollamaCatalogStatus = ""
Task {
defer { ollamaSearching = false }
do {
ollamaCatalog = try await OllamaCatalog.search(term)
if ollamaCatalog.isEmpty { ollamaCatalogStatus = "No models found." }
} catch { ollamaCatalogStatus = error.localizedDescription }
}
}
private func modelRow(_ model: CatalogModel) -> some View {
let saved = installedModels.first { $0.id == model.id } ?? model
let installed = saved.installed(at: saved.localFolder)
let isActive = mlxPath == saved.localFolder.path && mlxOnly
let diskBytes = installed ? try? MLXRuntimeLimits.weightBytes(in: saved.localFolder) : nil
return VStack(alignment: .leading, spacing: 6) {
HStack {
Text(model.title).font(.headline)
favoriteButton("mlx:" + model.id)
}
HStack {
if let diskBytes {
Text(ByteCountFormatter.string(fromByteCount: Int64(clamping: diskBytes), countStyle: .file) + " weights")
} else if !model.size.isEmpty {
Text(model.size)
}
if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") }
if let count = model.likes { Label(count.formatted(), systemImage: "heart") }
if isActive { Label("Active", systemImage: "checkmark.circle.fill") }
}.font(.caption).foregroundStyle(.secondary)
HStack {
Link("Model Card", destination: model.source)
Spacer()
if installed {
Button("Load Model") { load(saved.localFolder.path) }
.disabled(studio.running || loadingPath != nil)
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
} else {
if let task = downloads["mlx:" + model.id] {
Button("Cancel Download") { task.cancel() }
} else {
Button("Download") { download(model) }
}
}
if FileManager.default.fileExists(atPath: saved.localFolder.path) {
Button("Remove…", role: .destructive) { removing = saved }
.disabled(studio.running || downloads["mlx:" + model.id] != nil || loadingPath != nil)
}
}
downloadProgress("mlx:" + model.id)
}
.padding(.vertical, 4)
}
private func search() {
let term = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !searching, !hasMLXDownloads else { return }
searching = true
searchStatus = ""
Task {
defer { searching = false }
do {
matches = try await CatalogModel.search(term)
if matches.isEmpty { searchStatus = "No MLX checkpoints matched." }
} catch { searchStatus = error.localizedDescription }
}
}
private func load(_ path: String) {
guard loadingPath == nil, !studio.running else { return }
loadingPath = path
let name = URL(fileURLWithPath: path).lastPathComponent
status = "Loading \(name)…"
Task {
defer { loadingPath = nil }
do {
try await studio.loadMLX(path)
studio.selectMLXModel(path)
status = "Loaded \(name)."
} catch { status = error.localizedDescription }
}
}
private func download(_ model: CatalogModel) {
let key = "mlx:" + model.id
guard downloads[key] == nil else { return }
downloadStates[key] = DownloadState(message: "Preparing download…", fraction: 0)
downloads[key] = Task {
defer { downloads[key] = nil }
do {
try await model.install(to: model.localFolder) { message, fraction in
await MainActor.run { downloadStates[key] = DownloadState(message: message, fraction: fraction) }
}
if !CatalogModel.all.contains(where: { $0.id == model.id }) {
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) } + [model])
}
downloadStates[key] = DownloadState(message: "Downloaded.", fraction: nil)
} catch {
downloadStates[key] = DownloadState(message: Task.isCancelled ? "Download cancelled." : error.localizedDescription, fraction: nil)
}
}
}
private func remove(_ model: CatalogModel) {
guard !studio.running, downloads["mlx:" + model.id] == nil else { return }
do {
try FileManager.default.removeItem(at: model.localFolder)
if mlxPath == model.localFolder.path {
mlxPath = ""
studio.unloadMLX()
}
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) })
status = "Removed \(model.title)."
} catch { status = error.localizedDescription }
}
}
enum MLXLibrary {
static func discover(in root: URL) throws -> [URL] {
let scoped = root.startAccessingSecurityScopedResource()
defer { if scoped { root.stopAccessingSecurityScopedResource() } }
let manager = FileManager.default
var queue: [(URL, Int)] = [(root.resolvingSymlinksInPath(), 0)]
var found: [URL] = []
var offset = 0
while offset < queue.count && offset < 2000 && found.count < 100 {
try Task.checkCancellation()
let (folder, depth) = queue[offset]
offset += 1
if isModel(at: folder) { found.append(folder); continue }
guard depth < 4 else { continue }
let children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants])
for child in children where queue.count < 2000 {
if let values = try? child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
values.isDirectory == true, values.isSymbolicLink != true {
queue.append((child, depth + 1))
}
}
}
return found.sorted { $0.path < $1.path }
}
static func isModel(at url: URL) -> Bool {
FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) &&
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0
}
}
enum OllamaCatalog {
static func search(_ term: String) async throws -> [String] {
var parts = URLComponents()
parts.scheme = "https"
parts.host = "ollama.com"
parts.path = "/search"
parts.queryItems = [.init(name: "q", value: term)]
guard let url = parts.url else { throw StudioError("Could not prepare the Ollama catalog request.") }
let result = try await WebFetch.load(url, types: ["text/html"])
return modelNames(in: String(decoding: result.data, as: UTF8.self))
}
static func modelNames(in html: String) -> [String] {
let pattern = #"href\s*=\s*["']/library/([A-Za-z0-9._-]+)["']"#
guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] }
var seen = Set<String>()
return regex.matches(in: html, range: NSRange(html.startIndex..., in: html)).compactMap { match in
guard let range = Range(match.range(at: 1), in: html) else { return nil }
let name = String(html[range])
return name != "." && name != ".." && seen.insert(name).inserted ? name : nil
}
}
}