Files
ai_studio/Sources/Library.swift
T
Mark Gregory 2238df4631 Build AI Studio for macOS
Add branded startup, Ollama and MLX inference, persistent chat and document retrieval, confirmed MCP tools, and reproducible build and test scripts.
2026-11-16 13:14:00 +00:00

102 lines
4.2 KiB
Swift

import Foundation
import PDFKit
import NaturalLanguage
struct LibraryDocument: Identifiable, Equatable {
let id: UUID
let title: String
}
struct DocumentExcerpt: Equatable {
let title: String
let text: String
}
enum LibraryImport {
static func chunks(at url: URL) throws -> [String] {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
let bytes = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
guard bytes <= 20_000_000 else { throw StudioError("Choose a file smaller than 20 MB.") }
let text: String
switch url.pathExtension.lowercased() {
case "pdf":
guard let document = PDFDocument(url: url), !document.isLocked,
document.pageCount <= 500 else {
throw StudioError("Choose an unlocked PDF with up to 500 pages.")
}
text = document.string ?? ""
case "txt", "md", "markdown", "csv":
text = try String(contentsOf: url, encoding: .utf8)
default:
throw StudioError("Import a PDF, UTF-8 text, Markdown or CSV file.")
}
return try chunks(text)
}
static func chunks(_ text: String) throws -> [String] {
let words = text.split(whereSeparator: \.isWhitespace)
guard !words.isEmpty else { throw StudioError("The document contains no extractable text.") }
guard words.count <= 100_000 else { throw StudioError("Choose a document with up to 100,000 words.") }
var excerpts: [String] = []
var start = 0
while start < words.count {
let end = min(start + 180, words.count)
excerpts.append(words[start..<end].map { String($0.prefix(200)) }.joined(separator: " "))
if end == words.count { break }
start += 150
}
return excerpts
}
static func matchQuery(_ text: String) -> String {
let ignored: Set<String> = ["what", "where", "when", "which", "with", "from", "this", "that", "about", "please"]
let words = text.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init)
return Set(words.filter { $0.count >= 3 && !ignored.contains($0) }.prefix(16))
.sorted().map { #""\#($0)""# }.joined(separator: " OR ")
}
}
struct DocumentVector {
let language: String
let values: [Float]
var encoded: String { values.withUnsafeBytes { Data($0).base64EncodedString() } }
func similarity(to encoded: String) -> Float? {
guard let bytes = Data(base64Encoded: encoded),
bytes.count == values.count * MemoryLayout<Float>.stride else { return nil }
return bytes.withUnsafeBytes { raw in
var score: Float = 0
for (index, value) in values.enumerated() {
let other = raw.loadUnaligned(fromByteOffset: index * MemoryLayout<Float>.stride, as: Float.self)
score += value * other
}
return score.isFinite ? score : nil
}
}
static func forChunks(_ chunks: [String]) -> [Self?] {
guard let first = chunks.first,
let language = NLLanguageRecognizer.dominantLanguage(for: first),
let model = NLEmbedding.sentenceEmbedding(for: language) else {
return Array(repeating: nil, count: chunks.count)
}
return chunks.map { vector(for: $0, language: language, model: model) }
}
static func forPrompt(_ text: String) -> Self? {
guard let language = NLLanguageRecognizer.dominantLanguage(for: text),
let model = NLEmbedding.sentenceEmbedding(for: language) else { return nil }
return vector(for: text, language: language, model: model)
}
private static func vector(for text: String, language: NLLanguage, model: NLEmbedding) -> Self? {
guard let values = model.vector(for: String(text.prefix(1200))) else { return nil }
let magnitude = sqrt(values.reduce(0) { $0 + $1 * $1 })
guard magnitude.isFinite, magnitude > 0 else { return nil }
return Self(language: "\(language.rawValue):\(model.revision)", values: values.map { Float($0 / magnitude) })
}
}