import Foundation import SwiftUI import CryptoKit struct HubGGUFAsset: Identifiable, Equatable, Sendable { let repository: String let revision: String let filename: String let bytes: Int64? let sha256: String? var id: String { repository + "@" + revision + "/" + filename } var url: URL { URL(string: "https://huggingface.co")! .appending(path: repository).appending(path: "resolve/\(revision)/\(filename)") } var destination: URL { URL.applicationSupportDirectory .appending(path: "AIStudio/Models/GGUF/\(repository)/\(revision)/\(filename)") } struct RepositoryResult: Decodable, Identifiable { let id: String let downloads: Int? let likes: Int? let gated: CatalogModel.HubGating? let isPrivate: Bool? enum CodingKeys: String, CodingKey { case id, downloads, likes, gated case isPrivate = "private" } } static func search(_ query: String, format: String = "gguf") async throws -> [RepositoryResult] { var parts = URLComponents() parts.scheme = "https" parts.host = "huggingface.co" parts.path = "/api/models" parts.queryItems = [ .init(name: "filter", value: format), .init(name: "pipeline_tag", value: "text-generation"), .init(name: "sort", value: "downloads"), .init(name: "direction", value: "-1"), .init(name: "limit", value: "25"), .init(name: "search", value: query), .init(name: "expand", value: "downloads"), .init(name: "expand", value: "gated"), .init(name: "expand", value: "private"), .init(name: "expand", value: "likes") ] guard let url = parts.url else { throw StudioError("Invalid Hugging Face search.") } let response = try await WebFetch.load(url, types: ["application/json"]) return try decodeSearch(response.data) } static func decodeSearch(_ data: Data) throws -> [RepositoryResult] { var seen = Set() return try JSONDecoder().decode([RepositoryResult].self, from: data).filter { CatalogModel.repositoryParts($0.id) != nil && $0.gated != .restricted && $0.isPrivate != true && seen.insert($0.id.lowercased()).inserted } } static func resolve(_ repository: String) async throws -> [Self] { guard CatalogModel.repositoryParts(repository) != nil else { throw StudioError("Enter a Hugging Face model ID in owner/model format.") } var parts = URLComponents() parts.scheme = "https" parts.host = "huggingface.co" parts.path = "/api/models/" + repository parts.queryItems = [.init(name: "blobs", value: "true")] guard let url = parts.url else { throw StudioError("Invalid Hugging Face model ID.") } let response = try await WebFetch.load(url, types: ["application/json"]) return try decodeRepository(response.data, requested: repository) } static func decodeRepository(_ data: Data, requested: String) throws -> [Self] { struct Repository: Decodable { enum CodingKeys: String, CodingKey { case id, sha, gated, siblings case isPrivate = "private" } let id: String let sha: String let isPrivate: Bool? let gated: CatalogModel.HubGating? let siblings: [HubModelMetadata.File] } let info = try JSONDecoder().decode(Repository.self, from: data) guard info.id.caseInsensitiveCompare(requested) == .orderedSame, CatalogModel.repositoryParts(info.id) != nil, isHex(info.sha, count: 40), info.isPrivate != true, info.gated != .restricted else { throw StudioError("Select a public Hugging Face GGUF repository.") } var seen = Set() let models: [Self] = info.siblings.compactMap { file in let name = file.rfilename let lowercase = name.lowercased() guard CatalogModel.safeComponent(name), lowercase.hasSuffix(".gguf"), !lowercase.hasPrefix("mmproj"), !lowercase.contains("adapter"), lowercase.range(of: #"-[0-9]{5}-of-[0-9]{5}\.gguf$"#, options: .regularExpression) == nil, seen.insert(name).inserted else { return nil } let bytes = file.lfs?.size ?? file.size let sha = file.lfs?.sha256.flatMap { isHex($0, count: 64) ? $0.lowercased() : nil } return Self(repository: info.id, revision: info.sha, filename: name, bytes: bytes.flatMap { $0 > 0 ? $0 : nil }, sha256: sha) } guard !models.isEmpty else { throw StudioError("This repository has no standalone GGUF model files.") } return models.sorted { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending } } private static func isHex(_ text: String, count: Int) -> Bool { text.count == count && text.allSatisfy { $0.isASCII && $0.isHexDigit } } typealias ProgressUpdate = @Sendable (Int64, Int64?) -> Void typealias Transfer = @Sendable (URL, URL, @escaping ProgressUpdate) async throws -> Void func install(to destination: URL, progress: @escaping ProgressUpdate, transfer: Transfer = HubGGUFTransfer.download) async throws -> GGUFModelMetadata { let manager = FileManager.default let parent = destination.deletingLastPathComponent() try manager.createDirectory(at: parent, withIntermediateDirectories: true) if manager.fileExists(atPath: destination.path) { return try validatedModel(at: destination) } let staging = parent.appending(path: ".download-\(UUID())") defer { try? manager.removeItem(at: staging) } try await transfer(url, staging, { written, expected in progress(written, self.bytes ?? expected) }) try Task.checkCancellation() let model = try validatedModel(at: staging) try Task.checkCancellation() try manager.moveItem(at: staging, to: destination) return GGUFModelMetadata(path: destination.resolvingSymlinksInPath().path, version: model.version, tensorFormat: model.tensorFormat, architecture: model.architecture, hasThinkingTemplate: model.hasThinkingTemplate) } private func validatedModel(at file: URL) throws -> GGUFModelMetadata { let fileSize = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) if let bytes, fileSize != bytes { throw StudioError("The downloaded file size does not match the repository metadata.") } if let sha256 { let handle = try FileHandle(forReadingFrom: file) defer { try? handle.close() } var digest = SHA256() while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty { try Task.checkCancellation() digest.update(data: chunk) } let actual = digest.finalize().map { String(format: "%02x", $0) }.joined() guard actual == sha256 else { throw StudioError("The download checksum does not match Hugging Face.") } } return try GGUFModelMetadata.read(file) } } enum HubGGUFTransfer { static let download: HubGGUFAsset.Transfer = { source, destination, progress in let config = URLSessionConfiguration.ephemeral config.timeoutIntervalForRequest = 60 config.timeoutIntervalForResource = 3600 let result = AsyncThrowingStream.makeStream() let observer = Observer(destination: destination, progress: progress, result: result.continuation) let session = URLSession(configuration: config, delegate: observer, delegateQueue: nil) defer { session.finishTasksAndInvalidate() } let task = session.downloadTask(with: source) // Wait for the delegate to release the temporary file even if the caller cancels. let completion = Task.detached { for try await _ in result.stream {} } try await withTaskCancellationHandler { task.resume() try await completion.value } onCancel: { task.cancel() } try Task.checkCancellation() } private final class Observer: NSObject, URLSessionDownloadDelegate { let destination: URL let progress: HubGGUFAsset.ProgressUpdate let result: AsyncThrowingStream.Continuation init(destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate, result: AsyncThrowingStream.Continuation) { self.destination = destination self.progress = progress self.result = result } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let http = downloadTask.response as? HTTPURLResponse, http.statusCode == 200, http.url?.scheme == "https" else { let status = (downloadTask.response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? "" result.finish(throwing: StudioError("Could not download the model file\(status).")) return } do { try FileManager.default.moveItem(at: location, to: destination) } catch { result.finish(throwing: error) } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { result.finish(throwing: error) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { progress(totalBytesWritten, totalBytesExpectedToWrite > 0 ? totalBytesExpectedToWrite : nil) } func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(request.url?.scheme == "https" ? request : nil) } } } struct HubCatalogRow: View { @ViewBuilder let heading: () -> Heading @ViewBuilder let metadata: () -> Metadata @ViewBuilder let actions: () -> Actions @ViewBuilder let footer: () -> Footer var body: some View { VStack(alignment: .leading, spacing: 6) { HStack(content: heading) .font(.headline) .lineLimit(2) .fixedSize(horizontal: false, vertical: true) ViewThatFits(in: .horizontal) { HStack(content: metadata).fixedSize(horizontal: true, vertical: false) VStack(alignment: .leading, spacing: 4, content: metadata) } .font(.caption) .foregroundStyle(.secondary) ViewThatFits(in: .horizontal) { HStack(content: actions).fixedSize(horizontal: true, vertical: false) VStack(alignment: .leading, spacing: 8, content: actions) .fixedSize(horizontal: false, vertical: true) } .buttonStyle(.bordered) footer() } .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 4) } } struct HubCatalogFavorite: View { let key: String @AppStorage("favoriteModelKeys") private var data = Data() var body: some View { let keys = (try? JSONDecoder().decode(Set.self, from: data)) ?? [] let saved = keys.contains(key) let label = saved ? "Remove from Favorites" : "Add to Favorites" Button(label, systemImage: saved ? "star.fill" : "star") { var updated = keys if saved { updated.remove(key) } else { updated.insert(key) } if let encoded = try? JSONEncoder().encode(updated) { data = encoded } } .labelStyle(.iconOnly) .buttonStyle(.borderless) .help(label) } } struct HubRepositoryRow: View { let result: HubGGUFAsset.RepositoryResult let format: String @ViewBuilder let action: () -> Action @State private var preview: ModelPreview? @State private var sizes: CatalogVariantSizes? @State private var sizeError = false var body: some View { let source = URL(string: "https://huggingface.co")!.appending(path: result.id) HubCatalogRow { Text(result.id).lineLimit(1).help(result.id) HubCatalogFavorite(key: format + ":" + result.id) } metadata: { Text(format) Text(sizes?.label ?? (sizeError ? "Size unavailable" : "Loading size…")) if let sizes { let budget = format == "Core ML" ? ModelMemoryBudget.system : ModelMemoryBudget.gpu if sizes.someExceed(budget: budget) { Label(sizes.allExceed(budget: budget) ? "Exceeds memory budget" : "Some variants exceed memory budget", systemImage: "exclamationmark.triangle.fill") .foregroundStyle(.red) } } if let count = result.downloads { Label(count.formatted(), systemImage: "arrow.down") } if let count = result.likes { Label(count.formatted(), systemImage: "heart") } } actions: { Button("Preview") { preview = ModelPreview(title: result.id, fields: [("Format", format), ("Size", sizes?.label), ("Downloads", result.downloads?.formatted()), ("Likes", result.likes?.formatted())], source: source) } Link("Model Card", destination: source) Spacer() action() } footer: {} .sheet(item: $preview) { ModelPreviewSheet(preview: $0) } .task(id: result.id + format) { do { let metadata = try await HubModelMetadata.load(repository: result.id) guard !Task.isCancelled else { return } sizes = metadata.variantSizes(format: format == "Core ML" ? .coreML : .gguf) sizeError = false } catch { if !Task.isCancelled { sizeError = true } } } } } struct HubGGUFDownloads: View { @AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data() @State private var repository = "" @State private var preview: ModelPreview? @State private var repositories: [HubGGUFAsset.RepositoryResult] = [] @State private var assets: [HubGGUFAsset] = [] @State private var lookupInProgress = false @State private var download: Task? @State private var downloadingID: String? @State private var written: Int64 = 0 @State private var expected: Int64? @State private var notice: String? @State private var failure: String? var body: some View { ModelLibrarySection("Hugging Face · GGUF", key: "catalogGGUFExpanded") { HStack { TextField("Search Hugging Face", text: $repository, prompt: Text("Model name or owner/model")) .textFieldStyle(.roundedBorder) .onSubmit(lookup) Button(repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "Browse" : "Search", action: lookup) .disabled(lookupInProgress || download != nil) if lookupInProgress { ProgressView().controlSize(.small) } } ForEach(repositories) { result in HubRepositoryRow(result: result, format: "GGUF") { Button("Choose Download…") { lookup(result.id) }.disabled(lookupInProgress || download != nil) } } ForEach(assets) { asset in let source = URL(string: "https://huggingface.co")!.appending(path: asset.repository) HubCatalogRow { Text(asset.filename).lineLimit(1).help(asset.filename) HubCatalogFavorite(key: "GGUF:" + asset.repository) } metadata: { Text("GGUF") Text(ModelLibrarySize.label(asset.bytes)) ModelMemoryWarning(bytes: asset.bytes) } actions: { Button("Preview") { preview = ModelPreview(title: asset.filename, fields: [("Format", "GGUF"), ("Size", ModelLibrarySize.label(asset.bytes)), ("Revision", asset.revision)], source: source) } Link("Model Card", destination: source) Spacer() if downloadingID == asset.id { Button("Cancel") { download?.cancel() } } else if isRegistered(asset) { Label("Installed", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary) } else { Button("Download") { start(asset) }.disabled(download != nil) } } footer: { if downloadingID == asset.id { let label = ByteCountFormatter.string(fromByteCount: written, countStyle: .file) if let expected, expected > 0 { ProgressView(label, value: Double(min(written, expected)), total: Double(expected)) .accessibilityLabel("Downloading " + asset.filename) } else { ProgressView("Downloading · " + label) } } } } if let notice { Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary) } if let failure { Label(failure, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) } } .sheet(item: $preview) { ModelPreviewSheet(preview: $0) } } private func isRegistered(_ asset: HubGGUFAsset) -> Bool { let path = asset.destination.resolvingSymlinksInPath().path return GGUFModelMetadata.library(in: stored).contains { $0.path == path } && FileManager.default.fileExists(atPath: path) } private func lookup() { lookup(repository) } private func lookup(_ term: String) { let query = term.trimmingCharacters(in: .whitespacesAndNewlines) guard !lookupInProgress, download == nil else { return } lookupInProgress = true failure = nil notice = nil assets = [] repositories = [] Task { defer { lookupInProgress = false } do { if query.contains("/") { repository = query assets = try await HubGGUFAsset.resolve(query) } else { repositories = try await HubGGUFAsset.search(query) if repositories.isEmpty { notice = "No public GGUF repositories found." } } } catch { failure = error.localizedDescription } } } private func start(_ asset: HubGGUFAsset) { guard download == nil else { return } downloadingID = asset.id written = 0 expected = asset.bytes notice = nil failure = nil download = Task { defer { download = nil downloadingID = nil } do { let model = try await asset.install(to: asset.destination, progress: { bytes, expectedBytes in Task { @MainActor in guard downloadingID == asset.id, bytes >= written else { return } written = bytes expected = expectedBytes } }) stored = try GGUFModelMetadata.register([model], in: stored) notice = "Installed \(asset.filename)" } catch { if Task.isCancelled { notice = "Download cancelled" } else { failure = error.localizedDescription } } } } }