Files
ai_studio/Sources/Library.swift
T

155 lines
7.1 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) })
}
}
enum WebClipCapture {
static func url(_ address: String) throws -> URL {
let input = address.trimmingCharacters(in: .whitespacesAndNewlines)
guard let parts = URLComponents(string: input), let scheme = parts.scheme?.lowercased(),
["http", "https"].contains(scheme), let host = parts.host, !host.isEmpty,
parts.user == nil, parts.password == nil, let url = parts.url else {
throw StudioError("Enter an HTTP or HTTPS page URL.")
}
return url
}
static func text(from address: String) async throws -> String {
let session = URLSession(configuration: .ephemeral)
defer { session.invalidateAndCancel() }
var request = URLRequest(url: try url(address), timeoutInterval: 20)
request.setValue("text/html, text/plain", forHTTPHeaderField: "Accept")
let (bytes, response) = try await session.bytes(for: request)
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
let type = response.mimeType, ["text/html", "text/plain", "application/xhtml+xml"].contains(type) else {
throw StudioError("The server did not return a supported text page.")
}
var data = Data()
for try await byte in bytes {
try Task.checkCancellation()
guard data.count < 1_048_576 else { throw StudioError("The page exceeds the 1 MB capture limit.") }
data.append(byte)
}
guard let raw = String(data: data, encoding: .utf8) else { throw StudioError("The page is not UTF-8.") }
let content = type == "text/plain" ? raw : plainText(raw)
guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw StudioError("The page contains no readable text.")
}
return String(content.prefix(12_000))
}
static func plainText(_ html: String) -> String {
html.replacingOccurrences(of: "(?is)<(script|style|head|noscript)\\b[^>]*>.*?</\\1\\s*>", with: " ",
options: .regularExpression)
.replacingOccurrences(of: "(?s)<!--.*?-->", with: " ", options: .regularExpression)
.replacingOccurrences(of: "(?i)</(?:p|div|li|section|article|h[1-6])\\s*>|<br\\s*/?>", with: "\n",
options: .regularExpression)
.replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression)
.replacingOccurrences(of: "&nbsp;", with: " ")
.replacingOccurrences(of: "&lt;", with: "<")
.replacingOccurrences(of: "&gt;", with: ">")
.replacingOccurrences(of: "&quot;", with: "\"")
.replacingOccurrences(of: "&amp;", with: "&")
.components(separatedBy: .newlines)
.map { $0.split(whereSeparator: \.isWhitespace).joined(separator: " ") }
.filter { !$0.isEmpty }.joined(separator: "\n")
}
}