SPB Git

Repository Public

ModelDetailView.swift 8.2 KB 156 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Models/ModelDetailView.swift3// Description: One Hugging Face repository: live metadata, downloadable candidates with size, memory estimate and this device's verdict, and the model card.4import SwiftUI5import LocalChatCore6import LocalChatModelHub78struct ModelDetailView: View {9    @Environment(AppModel.self) private var app10    @Environment(\.dismiss) private var dismiss11    let repoID: String12    let showDownloads: () -> Void13    @State private var repo: HubModel?14    @State private var candidates: [ModelCandidate] = []15    @State private var readme: String?16    @State private var error: String?17    @State private var loading = true18    @State private var showAll = false19    @State private var actionError: String?2021    var body: some View {22        VStack(spacing: 0) {23            HStack(alignment: .top) {24                VStack(alignment: .leading, spacing: 3) {25                    Text(repo?.name ?? repoID.split(separator: "/").last.map(String.init) ?? repoID).font(DS.F.title).foregroundStyle(DS.C.text).lineLimit(2)26                    Text(repo?.organization ?? repoID).font(DS.F.caption).foregroundStyle(DS.C.muted)27                }28                Spacer()29                if let url = repo?.webURL ?? URL(string: "https://huggingface.co/\(repoID)") {30                    Link(destination: url) { Image(systemName: "safari").frame(width: 28, height: 28) }.foregroundStyle(DS.C.text2).accessibilityLabel("Open on Hugging Face")31                }32                IconButton("xmark", label: "Close") { dismiss() }.keyboardShortcut(.cancelAction)33            }34            .padding(DS.S.lg)35            Rectangle().fill(DS.C.border).frame(height: 1)36            ScrollView {37                VStack(alignment: .leading, spacing: DS.S.md) {38                    if loading { HStack { Spacer(); ThinkingDots(); Spacer() }.padding(.vertical, DS.S.xxl) }39                    if let error {40                        InlineNotice(.error, error)41                        Button("Try again") { Task { await load() } }.buttonStyle(.lcSecondaryCompact)42                    }43                    if let repo { summary(repo); files(repo); card }44                }45                .padding(DS.S.lg)46            }47        }48        .screenBackground()49        .frame(minWidth: 340, idealWidth: 720, minHeight: 420, idealHeight: 720)50        .task { await load() }51    }5253    private func load() async {54        loading = true; error = nil55        do {56            let fetched = try await app.hub.model(repoID)57            repo = fetched58            candidates = app.hubResolver.candidates(for: fetched)59            loading = false60            readme = try? await app.hub.readme(repoID)61        } catch { self.error = hubErrorText(error); loading = false }62    }6364    @ViewBuilder private func summary(_ repo: HubModel) -> some View {65        ScrollView(.horizontal, showsIndicators: false) {66            HStack(spacing: 6) {67                if let d = repo.downloads { Pill("\(ModelFacts.compact(d)) downloads", symbol: "arrow.down.circle") }68                if let l = repo.likes { Pill("\(ModelFacts.compact(l)) likes", symbol: "heart") }69                if let u = ModelFacts.relative(repo.lastModified) { Pill("updated \(u)", symbol: "clock") }70                if let lic = repo.license { Pill(lic, symbol: "doc.text") }71                if let t = repo.modelType { Pill(t, symbol: "cube") }72                if let p = repo.pipelineTag { Pill(p) }73                if let c = repo.commit { Pill(String(c.prefix(7)), symbol: "number") }74            }75        }76        if repo.isGated {77            InlineNotice(.warning, app.hasHubToken78                         ? "This repository is gated. Downloads work only if your Hugging Face account accepted its license."79                         : "This repository is gated: accept its license on huggingface.co, then add a token (key button in Discover).")80        }81        if let base = repo.baseModel { Text("Base model: \(base)").font(DS.F.caption).foregroundStyle(DS.C.text2) }82    }8384    @ViewBuilder private func files(_ repo: HubModel) -> some View {85        SectionHeader("Downloads", subtitle: "Verdicts are estimates for this \(app.device.platform == .mac ? "Mac" : "device") (\(ByteFormat.memory(app.device.usableModelMemoryBytes)) usable by a model).", symbol: "arrow.down.circle")86        if candidates.isEmpty && !loading {87            InlineNotice(.info, "This repository has no file Local Chat can run (it needs MLX weights or a .gguf file).")88        }89        if let actionError { InlineNotice(.error, actionError) }90        let shown = showAll ? candidates : Array(candidates.prefix(8))91        ForEach(shown) { candidate in CandidateRow(candidate: candidate, showDownloads: showDownloads, onError: { actionError = $0 }) }92        if candidates.count > shown.count { Button("Show all \(candidates.count) files") { withAnimation(DS.M.smooth) { showAll = true } }.buttonStyle(.lcSecondaryCompact) }93    }9495    @ViewBuilder private var card: some View {96        if let readme, !readme.isEmpty {97            SectionHeader("Model card", subtitle: "Excerpt from the repository README.", symbol: "doc.richtext")98            MarkdownView(text: Self.excerpt(readme)).card()99        }100    }101102    /// Strips the YAML front matter and keeps the beginning of the card.103    static func excerpt(_ raw: String) -> String {104        var text = raw105        if text.hasPrefix("---"), let end = text.range(of: "\n---", range: text.index(text.startIndex, offsetBy: 3)..<text.endIndex) {106            text = String(text[end.upperBound...])107        }108        text = text.trimmingCharacters(in: .whitespacesAndNewlines)109        return text.count > 3500 ? String(text.prefix(3500)) + "\n\n…" : text110    }111}112113private struct CandidateRow: View {114    @Environment(AppModel.self) private var app115    let candidate: ModelCandidate; let showDownloads: () -> Void; let onError: (String?) -> Void116    var body: some View {117        let d = candidate.descriptor118        let verdict = app.compatibility(d)119        VStack(alignment: .leading, spacing: 8) {120            HStack(alignment: .top) {121                VStack(alignment: .leading, spacing: 3) {122                    Text(d.fileName ?? d.name).font(DS.F.mono(12.5, weight: .medium)).foregroundStyle(DS.C.text).lineLimit(2).truncationMode(.middle)123                    FactsLine(facts: facts(d))124                }125                Spacer(minLength: 8)126                CandidateAction(candidate: candidate, verdict: verdict, showDownloads: showDownloads, onError: onError)127            }128            ScrollView(.horizontal, showsIndicators: false) {129                HStack(spacing: 5) {130                    BackendBadge(d.backend); FitBadge(verdict)131                    if candidate.isGated { Pill("Gated", symbol: "lock.fill", tone: .warn) }132                    if candidate.projector != nil { Pill("+ vision projector", symbol: "eye") }133                    CapabilityChips(capabilities: d.capabilities)134                }135            }136            if let reason = candidate.unsupportedReason { Text(reason).font(DS.F.caption).foregroundStyle(DS.C.danger).fixedSize(horizontal: false, vertical: true) }137            ForEach(verdict.reasons, id: \.self) { r in138                Text(r).font(DS.F.caption).foregroundStyle(verdict.fit == .comfortable ? DS.C.muted : verdict.fit == .tight ? DS.C.warn : DS.C.danger).fixedSize(horizontal: false, vertical: true)139            }140            ForEach(candidate.notes, id: \.self) { n in Text(n).font(DS.F.caption).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true) }141        }142        .card(padding: DS.S.md)143    }144145    private func facts(_ d: ModelDescriptor) -> [String] {146        var out: [String] = []147        if let q = d.quantization { out.append(q) }148        if let p = ModelFacts.parameters(d) { out.append(p) }149        if let c = d.contextLength { out.append("\(ModelFacts.compact(c)) ctx") }150        out.append(candidate.downloadBytes > 0 ? "\(ByteFormat.string(candidate.downloadBytes)) download" : "size unknown")151        if let m = d.estimatedMemoryBytes() { out.append("≈\(ByteFormat.memory(m)) memory (estimate)") }152        if let l = d.license { out.append(l) }153        return out154    }155}156
Files main
Menu

Theme