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.. String { let ignored: Set = ["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.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.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 { try await page(from: address).text } static func page(from address: String) async throws -> WebPage { let types = ["text/html", "text/plain", "application/xhtml+xml"] let resource = try await WebFetch.load(try url(address), types: types) let data = resource.data let type = resource.type 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 WebPage(url: resource.url, text: String(content.prefix(12_000))) } static func plainText(_ html: String) -> String { html.replacingOccurrences(of: "(?is)<(script|style|head|noscript)\\b[^>]*>.*?", with: " ", options: .regularExpression) .replacingOccurrences(of: "(?s)", with: " ", options: .regularExpression) .replacingOccurrences(of: "(?i)|", with: "\n", options: .regularExpression) .replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression) .replacingOccurrences(of: " ", with: " ") .replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">") .replacingOccurrences(of: """, with: "\"") .replacingOccurrences(of: "&", with: "&") .components(separatedBy: .newlines) .map { $0.split(whereSeparator: \.isWhitespace).joined(separator: " ") } .filter { !$0.isEmpty }.joined(separator: "\n") } } struct WebPage { let url: URL let text: String var reference: String { "Source: \(url.absoluteString)\n\n\(text)" } } enum WebFetch { static func load(_ url: URL, types: [String]) async throws -> (url: URL, type: String, data: Data) { let config = URLSessionConfiguration.ephemeral config.httpShouldSetCookies = false config.timeoutIntervalForResource = 35 let session = URLSession(configuration: config) defer { session.invalidateAndCancel() } var request = URLRequest(url: url, timeoutInterval: 20) request.setValue(types.joined(separator: ", "), forHTTPHeaderField: "Accept") let (bytes, response) = try await session.bytes(for: request) guard let response = response as? HTTPURLResponse, let final = response.url else { throw StudioError("The server did not return an HTTP response.") } _ = try WebClipCapture.url(final.absoluteString) guard (200..<300).contains(response.statusCode) else { throw StudioError("The server returned HTTP \(response.statusCode).") } guard let type = response.mimeType, types.contains(type) else { throw StudioError("The server did not return the expected content type.") } var data = Data() for try await byte in bytes { try Task.checkCancellation() guard data.count < 1_048_576 else { throw StudioError("The response exceeds 1 MB.") } data.append(byte) } return (final, type, data) } } struct WebSearchResult: Identifiable, Equatable { let url: URL let title: String let snippet: String var id: URL { url } var reference: String { "\(title)\nSource: \(url.absoluteString)\n\(snippet)" } } enum WebSearch { static func requestURL(endpoint: String, query: String) throws -> URL { let query = query.trimmingCharacters(in: .whitespacesAndNewlines) guard !query.isEmpty, query.count <= 500 else { throw StudioError("Enter a search query of up to 500 characters.") } let base = try WebClipCapture.url(endpoint) guard var parts = URLComponents(url: base, resolvingAgainstBaseURL: false), parts.fragment == nil else { throw StudioError("Enter the SearXNG search URL without a fragment.") } var items = (parts.queryItems ?? []).filter { $0.name != "q" && $0.name != "format" } items += [.init(name: "q", value: query), .init(name: "format", value: "json")] parts.queryItems = items guard let url = parts.url else { throw StudioError("Could not prepare the search URL.") } return url } static func results(endpoint: String, query: String) async throws -> [WebSearchResult] { let resource = try await WebFetch.load(try requestURL(endpoint: endpoint, query: query), types: ["application/json"]) return try decode(resource.data) } static func decode(_ data: Data) throws -> [WebSearchResult] { struct Response: Decodable { struct Item: Decodable { let url: String? let title: String? let content: String? } let results: [Item] } let response = try JSONDecoder().decode(Response.self, from: data) var seen: Set = [] var output: [WebSearchResult] = [] for item in response.results { guard let address = item.url, let url = try? WebClipCapture.url(address), seen.insert(url).inserted else { continue } let title = WebClipCapture.plainText(item.title ?? "") let snippet = WebClipCapture.plainText(item.content ?? "") output.append(WebSearchResult(url: url, title: title.isEmpty ? (url.host ?? "Web result") : String(title.prefix(180)), snippet: String(snippet.prefix(500)))) if output.count == 10 { break } } return output } }