Integrate Hugging Face model library and separate web actions

This commit is contained in:
Mark Gregory
2026-11-17 09:12:51 +00:00
parent dd06e337fc
commit 92f4e58272
8 changed files with 361 additions and 125 deletions
+158 -42
View File
@@ -3,13 +3,15 @@ import SwiftUI
import UniformTypeIdentifiers
import AppKit
struct CatalogModel: Identifiable, Hashable, Sendable {
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",
@@ -24,6 +26,50 @@ struct CatalogModel: Identifiable, Hashable, Sendable {
"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: "search", value: query),
.init(name: "limit", value: "25"),
.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)
@@ -39,7 +85,7 @@ struct CatalogModel: Identifiable, Hashable, Sendable {
func install(
to destination: URL,
progress: @Sendable (String) async -> Void
progress: @Sendable (String, Double) async -> Void
) async throws {
if installed(at: destination) { return }
let manager = FileManager.default
@@ -57,7 +103,7 @@ struct CatalogModel: Identifiable, Hashable, Sendable {
defer { session.finishTasksAndInvalidate() }
for (offset, file) in files.enumerated() {
try Task.checkCancellation()
await progress("Downloading \(file) (\(offset + 1) of \(files.count))…")
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) }
@@ -89,6 +135,18 @@ struct ModelCatalogView: View {
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 progress: Double?
@State private var loadingPath: String?
private var installedModels: [CatalogModel] {
(try? JSONDecoder().decode([CatalogModel].self, from: managed)) ?? []
}
var body: some View {
Form {
@@ -107,12 +165,8 @@ struct ModelCatalogView: View {
HStack {
Text(URL(fileURLWithPath: path).lastPathComponent).help(path)
Spacer()
Button(mlxPath == path && mlxOnly ? "Selected" : "Use Model") {
mlxPath = path
mlxOnly = true
studio.unloadMLX()
}
.disabled(studio.running || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)) ||
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)])
@@ -124,41 +178,31 @@ struct ModelCatalogView: View {
}
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
Section("Download for on-device inference") {
ForEach(CatalogModel.all) { model in
let installed = model.installed(at: model.localFolder)
VStack(alignment: .leading, spacing: 6) {
HStack {
Text(model.title).font(.headline)
Spacer()
Text(model.size).font(.caption).foregroundStyle(.secondary)
}
HStack {
Link("Model Card", destination: model.source)
Spacer()
if installed {
Button(mlxPath == model.localFolder.path && mlxOnly ? "Selected" : "Use Model") {
mlxPath = model.localFolder.path
mlxOnly = true
studio.unloadMLX()
}
.disabled(studio.running || (mlxPath == model.localFolder.path && mlxOnly))
} else {
Button("Download") { download(model) }.disabled(active != nil)
}
if FileManager.default.fileExists(atPath: model.localFolder.path) {
Button("Remove…", role: .destructive) { removing = model }
.disabled(studio.running || active != nil)
}
}
}
.padding(.vertical, 4)
if !installedModels.isEmpty {
Section("Downloaded Models") {
ForEach(installedModels) { model in modelRow(model) }
}
}
Section("Hugging Face") {
HStack {
TextField("Search MLX models", text: $query).onSubmit(search)
Button("Search", action: search).disabled(searching || query.trimmingCharacters(in: .whitespaces).isEmpty)
if searching { ProgressView().controlSize(.small) }
}
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
ForEach(matches) { model in modelRow(model) }
}
Section("Recommended Models") {
ForEach(CatalogModel.all) { model in modelRow(model) }
}
if !status.isEmpty {
Section {
Text(status).textSelection(.enabled).foregroundStyle(.secondary)
if active != nil { Button("Cancel Download") { operation?.cancel() } }
if let progress, active != nil {
ProgressView(value: progress) { Text("Files downloaded") }
Button("Cancel Download") { operation?.cancel() }
}
if loadingPath != nil { ProgressView().controlSize(.small) }
}
}
}
@@ -192,14 +236,85 @@ struct ModelCatalogView: View {
} message: { model in Text(model.title) }
}
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) {
Text(model.title).font(.headline)
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 {
Button("Download") { download(model) }.disabled(active != nil)
}
if FileManager.default.fileExists(atPath: saved.localFolder.path) {
Button("Remove…", role: .destructive) { removing = saved }
.disabled(studio.running || active != nil || loadingPath != nil)
}
}
}
.padding(.vertical, 4)
}
private func search() {
let term = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !term.isEmpty, !searching 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)
mlxPath = path
mlxOnly = true
status = "Loaded \(name)."
} catch { status = error.localizedDescription }
}
}
private func download(_ model: CatalogModel) {
guard active == nil else { return }
active = model
progress = 0
status = "Preparing download…"
operation = Task {
defer { active = nil; operation = nil }
defer { active = nil; operation = nil; progress = nil }
do {
try await model.install(to: model.localFolder) { message in
await MainActor.run { status = message }
try await model.install(to: model.localFolder) { message, fraction in
await MainActor.run { status = message; progress = fraction }
}
if !CatalogModel.all.contains(where: { $0.id == model.id }) {
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id } + [model])
}
status = "Downloaded \(model.title)."
} catch {
@@ -216,6 +331,7 @@ struct ModelCatalogView: View {
mlxPath = ""
studio.unloadMLX()
}
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id })
status = "Removed \(model.title)."
} catch { status = error.localizedDescription }
}