Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/ModelSelection/ModelQuery.swift4// Description: Pure search / filter / sort engine over the unified catalogue (model sheet and OpenRouter Explorer).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112enum ModelCapability: String, CaseIterable, Identifiable, Sendable {13 case vision, reasoning, tools, audioInput, imageGeneration, structuredOutput14 var id: String { rawValue }15 var symbol: String {16 switch self { case .vision: "eye"; case .reasoning: "brain"; case .tools: "wrench.and.screwdriver"; case .audioInput: "waveform"; case .imageGeneration: "photo"; case .structuredOutput: "curlybraces" }17 }18 var label: String {19 switch self {20 case .vision: String(localized: "Vision"); case .reasoning: String(localized: "Raisonnement"); case .tools: String(localized: "Outils")21 case .audioInput: String(localized: "Audio"); case .imageGeneration: String(localized: "Images"); case .structuredOutput: String(localized: "JSON structuré")22 }23 }24 func holds(for m: AIModel) -> Bool {25 switch self { case .vision: m.vision; case .reasoning: m.reasoning; case .tools: m.tools; case .audioInput: m.audioInput; case .imageGeneration: m.imageGeneration; case .structuredOutput: m.structuredOutput }26 }27}2829enum ModelSort: String, CaseIterable, Identifiable, Sendable {30 case recommended, name, priceAscending, priceDescending, context, newest, recentlyUsed31 var id: String { rawValue }32 var label: String {33 switch self {34 case .recommended: String(localized: "Recommandé"); case .name: String(localized: "Nom"); case .priceAscending: String(localized: "Prix croissant"); case .priceDescending: String(localized: "Prix décroissant")35 case .context: String(localized: "Contexte"); case .newest: String(localized: "Plus récents"); case .recentlyUsed: String(localized: "Utilisés récemment")36 }37 }38}3940struct ModelQuery: Equatable, Sendable {41 var text = ""42 /// Maker slugs (`creator`).43 var makers: Set<String> = []44 /// nil = every route.45 var route: String?46 var capabilities: Set<ModelCapability> = []47 var categories: Set<String> = []48 /// Upper bound on the input price, USD per million tokens.49 var maxInputPrice: Double?50 var minContext: Int?51 var freeOnly = false52 var openWeightOnly = false53 var favoritesOnly = false54 var verifiedOnly = false55 var sort: ModelSort = .recommended5657 var activeFilterCount: Int {58 makers.count + capabilities.count + categories.count + [route != nil, maxInputPrice != nil, minContext != nil, freeOnly, openWeightOnly, favoritesOnly, verifiedOnly].filter { $0 }.count59 }60 var hasFilters: Bool { activeFilterCount > 0 }61 mutating func clearFilters() { let t = text, s = sort; self = ModelQuery(); text = t; sort = s }6263 func matches(_ m: AIModel) -> Bool {64 if let route, m.route != route { return false }65 if !makers.isEmpty, !makers.contains(m.creator) { return false }66 if favoritesOnly, !m.favorite { return false }67 if verifiedOnly, !m.isVerified { return false }68 if freeOnly, !m.isFree { return false }69 if openWeightOnly, !m.isOpenWeight { return false }70 if let maxInputPrice { guard let p = m.priceInput, p <= maxInputPrice else { return false } }71 if let minContext { guard let c = m.contextWindow, c >= minContext else { return false } }72 for c in capabilities where !c.holds(for: m) { return false }73 for c in categories where !m.categories.contains(c) { return false }74 let tokens = text.lowercased().split(whereSeparator: { $0 == " " || $0 == "\n" })75 if !tokens.isEmpty {76 let hay = m.searchHaystack77 for t in tokens where !hay.contains(t) { return false }78 }79 return true80 }8182 func apply(to models: [AIModel]) -> [AIModel] { ModelQuery.sorted(models.filter(matches), by: sort, text: text) }8384 static func sorted(_ models: [AIModel], by sort: ModelSort, text: String = "") -> [AIModel] {85 func name(_ a: AIModel, _ b: AIModel) -> Bool { a.displayName.localizedStandardCompare(b.displayName) == .orderedAscending }86 switch sort {87 case .name: return models.sorted(by: name)88 case .priceAscending:89 // models without a published price go last, never first as if they were free90 return models.sorted { a, b in switch (a.priceInput, b.priceInput) { case (let x?, let y?): x != y ? x < y : name(a, b); case (nil, _?): false; case (_?, nil): true; default: name(a, b) } }91 case .priceDescending:92 return models.sorted { a, b in switch (a.priceInput, b.priceInput) { case (let x?, let y?): x != y ? x > y : name(a, b); case (nil, _?): false; case (_?, nil): true; default: name(a, b) } }93 case .context: return models.sorted { ($0.contextWindow ?? 0) != ($1.contextWindow ?? 0) ? ($0.contextWindow ?? 0) > ($1.contextWindow ?? 0) : name($0, $1) }94 case .newest: return models.sorted { ($0.catalog?.created ?? 0) != ($1.catalog?.created ?? 0) ? ($0.catalog?.created ?? 0) > ($1.catalog?.created ?? 0) : name($0, $1) }95 case .recentlyUsed:96 return models.sorted { a, b in switch (a.lastUsedAt, b.lastUsedAt) { case (let x?, let y?): x > y; case (nil, _?): false; case (_?, nil): true; default: name(a, b) } }97 case .recommended:98 let q = text.lowercased().trimmingCharacters(in: .whitespaces)99 func rank(_ m: AIModel) -> Int {100 var r = 0101 if m.favorite { r += 1000 }102 if m.isVerified { r += 400 + Int(m.qualityScore ?? 0) }103 if m.lastUsedAt != nil { r += 200 }104 if !q.isEmpty { let n = m.displayName.lowercased(); if n == q { r += 5000 } else if n.hasPrefix(q) { r += 2500 } }105 return r106 }107 return models.map { ($0, rank($0)) }.sorted { a, b in108 if a.1 != b.1 { return a.1 > b.1 }109 if (a.0.catalog?.created ?? 0) != (b.0.catalog?.created ?? 0) { return (a.0.catalog?.created ?? 0) > (b.0.catalog?.created ?? 0) }110 return name(a.0, b.0)111 }.map(\.0)112 }113 }114115 /// Makers present in a list, most models first — the maker filter chips.116 static func makers(in models: [AIModel]) -> [(slug: String, name: String, count: Int)] {117 var counts: [String: (String, Int)] = [:]118 for m in models { counts[m.creator, default: (m.creatorName, 0)].1 += 1 }119 return counts.map { ($0.key, $0.value.0, $0.value.1) }.sorted { $0.2 != $1.2 ? $0.2 > $1.2 : $0.1 < $1.1 }120 }121122 static let categoryOrder = ["local", "reasoning", "vision", "multimodal", "long-context", "tools", "coding", "research", "creative-writing", "fast", "image-generation", "open-weight", "free"]123 static func categoryLabel(_ c: String) -> String {124 switch c {125 case "reasoning": String(localized: "Raisonnement"); case "vision": String(localized: "Vision"); case "multimodal": String(localized: "Multimodal"); case "long-context": String(localized: "Long contexte")126 case "open-weight": String(localized: "Poids ouverts"); case "free": String(localized: "Gratuit"); case "image-generation": String(localized: "Génération d’images"); case "tools": String(localized: "Outils")127 case "local": String(localized: "Local"); case "coding": String(localized: "Code"); case "creative-writing": String(localized: "Écriture créative"); case "research": String(localized: "Recherche"); case "fast": String(localized: "Rapide")128 default: c129 }130 }131}132