SPB Git

Repository Public

main.swift 16.2 KB 283 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Drive9// File             : infra/textkit/main.swift10// Module           : infra11// Repository       : https://git.spboucher.ai/sp-drive12// Project Website  : https://drive.spboucher.ai13// Created          : 2026-11-1914// Last Modified    : 2026-11-1915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// spd-textkit — local text extraction, OCR, perceptual hashing and sentence embeddings for SP Drive.89//90// Compiled on the node by scripts/textkit-build.sh (Command Line Tools are enough) and only ever started by the worker91// inside the sandbox-exec profile of services/api/src/tools.ts: no network, no access to the home directory, one92// decrypted input file in a private work directory. Nothing here talks to a server; Apple's on-device frameworks only.93//94//   spd-textkit probe95//   spd-textkit extract <input> <output.json> [--max-pages N] [--ocr on|off] [--ocr-max-pages N] [--max-chars N] [--langs fr-FR,en-US]96//   spd-textkit dhash <image> [--max-pixels N]97//   spd-textkit embed <input.json> <output.json> [--model sentence|contextual]98import AppKit99import CoreGraphics100import Foundation101import ImageIO102import NaturalLanguage103import PDFKit104import Vision105106setvbuf(stdout, nil, _IONBF, 0)107func fail(_ message: String, code: Int32 = 1) -> Never { FileHandle.standardError.write((message + "\n").data(using: .utf8)!); exit(code) }108func writeJSON(_ object: Any, to path: String) {109  guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else { fail("cannot encode the result") }110  do { try data.write(to: URL(fileURLWithPath: path), options: .atomic) } catch { fail("cannot write \(path): \(error.localizedDescription)") }111}112func option(_ name: String, _ args: [String]) -> String? { if let i = args.firstIndex(of: "--\(name)"), i + 1 < args.count { return args[i + 1] }; return nil }113114// --- OCR -----------------------------------------------------------------------------------------------------115func recognise(_ image: CGImage, langs: [String]) -> String {116  let request = VNRecognizeTextRequest()117  request.recognitionLevel = .accurate118  request.usesLanguageCorrection = true119  request.recognitionLanguages = langs120  let handler = VNImageRequestHandler(cgImage: image, options: [:])121  do { try handler.perform([request]) } catch { FileHandle.standardError.write("ocr: \(error.localizedDescription)\n".data(using: .utf8)!); return "" }122  let lines = (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }123  return lines.joined(separator: "\n")124}125/** Largest picture (in pixels) that is ever decoded; set by --max-pixels. A tiny file can declare a gigapixel image. */126var maxPixels = 120_000_000127func loadImage(_ path: String, maxPixel: Int) -> CGImage? {128  guard let src = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil) else { return nil }129  // the declared size is read from the header, before any pixel is decoded130  guard let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any],131        let w = (props[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue, let h = (props[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue, w > 0, h > 0 else { return nil }132  if w > 100_000 || h > 100_000 || w * h > maxPixels { fail("image too large to decode (\(w) x \(h) pixels)", code: 4) }133  let opts: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxPixel]134  guard let img = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) else { return nil }135  return flatten(img)136}137/** Transparent pixels become white (a PNG of black text on a clear background would otherwise read as a black page). */138func flatten(_ img: CGImage) -> CGImage {139  switch img.alphaInfo { case .none, .noneSkipFirst, .noneSkipLast: return img; default: break }140  guard let ctx = CGContext(data: nil, width: img.width, height: img.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return img }141  let r = CGRect(x: 0, y: 0, width: img.width, height: img.height)142  ctx.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1)); ctx.fill(r); ctx.draw(img, in: r)143  return ctx.makeImage() ?? img144}145/** A PDF page as a bitmap, about 200 dpi, bounded so a poster-sized page cannot exhaust memory. */146func render(_ page: PDFPage) -> CGImage? {147  let box = page.bounds(for: .mediaBox)148  guard box.width > 1, box.height > 1 else { return nil }149  let scale = min(200.0 / 72.0, 3400.0 / max(box.width, box.height))150  let w = Int(box.width * scale), h = Int(box.height * scale)151  guard w > 0, h > 0, let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }152  ctx.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1)); ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))153  ctx.scaleBy(x: scale, y: scale)154  ctx.translateBy(x: -box.origin.x, y: -box.origin.y)155  page.draw(with: .mediaBox, to: ctx)156  return ctx.makeImage()157}158159// --- extract -------------------------------------------------------------------------------------------------160func extract(_ args: [String]) {161  guard args.count >= 2 else { fail("usage: extract <input> <output.json>", code: 2) }162  let input = args[0], output = args[1]163  let maxPages = Int(option("max-pages", args) ?? "") ?? 500164  let ocr = (option("ocr", args) ?? "on") == "on"165  let ocrMaxPages = Int(option("ocr-max-pages", args) ?? "") ?? 60166  let maxChars = Int(option("max-chars", args) ?? "") ?? 2_000_000167  let langs = (option("langs", args) ?? "fr-FR,en-US").split(separator: ",").map(String.init)168  var pages: [[String: Any]] = []169  var total = 0, ocrPages = 0, textPages = 0, truncated = false, pageCount = 0170  let ext = (input as NSString).pathExtension.lowercased()171  if ext == "pdf" {172    guard let doc = PDFDocument(url: URL(fileURLWithPath: input)) else { fail("unreadable PDF", code: 3) }173    if doc.isLocked { writeJSON(["kind": "pdf", "locked": true, "pageCount": doc.pageCount, "pages": [], "ocrPages": 0, "textPages": 0, "truncated": false], to: output); return }174    pageCount = doc.pageCount175    for i in 0..<min(pageCount, maxPages) {176      if total >= maxChars { truncated = true; break }177      autoreleasepool {178        guard let page = doc.page(at: i) else { return }179        var text = (page.string ?? "").trimmingCharacters(in: .whitespacesAndNewlines)180        var viaOcr = false181        // a page with (almost) no text layer is a scan: read it with Vision182        if text.count < 16 && ocr && ocrPages < ocrMaxPages, let img = render(page) {183          let seen = recognise(img, langs: langs).trimmingCharacters(in: .whitespacesAndNewlines)184          if seen.count > text.count { text = seen; viaOcr = true }185          ocrPages += 1186        }187        if text.isEmpty { return }188        if total + text.count > maxChars { text = String(text.prefix(maxChars - total)); truncated = true }189        total += text.count190        if viaOcr { } else { textPages += 1 }191        pages.append(["page": i + 1, "text": text, "ocr": viaOcr])192      }193    }194    if pageCount > maxPages { truncated = true }195    let ocrUsed = pages.contains { ($0["ocr"] as? Bool) == true }196    writeJSON(["kind": "pdf", "locked": false, "pageCount": pageCount, "pages": pages, "ocrPages": ocrPages, "textPages": textPages, "truncated": truncated,197               "source": ocrUsed ? (textPages > 0 ? "pdf-text+ocr" : "ocr") : "pdf-text"], to: output)198    return199  }200  // an image: OCR is the only source of text201  guard ocr else { writeJSON(["kind": "image", "pageCount": 1, "pages": [], "ocrPages": 0, "textPages": 0, "truncated": false, "source": "ocr"], to: output); return }202  guard let img = loadImage(input, maxPixel: 4096) else { fail("unreadable image", code: 3) }203  var text = recognise(img, langs: langs).trimmingCharacters(in: .whitespacesAndNewlines)204  if text.count > maxChars { text = String(text.prefix(maxChars)); truncated = true }205  if !text.isEmpty { pages.append(["page": 1, "text": text, "ocr": true]) }206  writeJSON(["kind": "image", "pageCount": 1, "pages": pages, "ocrPages": 1, "textPages": 0, "truncated": truncated, "source": "ocr"], to: output)207}208209// --- dhash: 64-bit difference hash (9×8 greyscale, each bit = "left pixel brighter than its right neighbour") -----210func dhash(_ args: [String]) {211  guard let path = args.first, let img = loadImage(path, maxPixel: 512) else { fail("unreadable image", code: 3) }212  let w = 9, h = 8213  var px = [UInt8](repeating: 0, count: w * h)214  guard let ctx = CGContext(data: &px, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { fail("no bitmap context") }215  ctx.interpolationQuality = .high216  ctx.draw(img, in: CGRect(x: 0, y: 0, width: w, height: h))217  var bits: UInt64 = 0218  for y in 0..<h { for x in 0..<(w - 1) { bits = (bits << 1) | (px[y * w + x] > px[y * w + x + 1] ? 1 : 0) } }219  print(String(format: "%016llx", bits))220}221222// --- embeddings ----------------------------------------------------------------------------------------------223func language(of text: String) -> NLLanguage {224  let r = NLLanguageRecognizer(); r.languageConstraints = [.french, .english]; r.processString(String(text.prefix(2000)))225  return r.dominantLanguage ?? .french226}227func normalise(_ v: [Double]) -> [Double] { let n = (v.reduce(0) { $0 + $1 * $1 }).squareRoot(); return n > 0 ? v.map { $0 / n } : v }228var sentenceModels: [NLLanguage: NLEmbedding] = [:]229func sentenceModel(_ l: NLLanguage) -> NLEmbedding? { if let m = sentenceModels[l] { return m }; let m = NLEmbedding.sentenceEmbedding(for: l); if let m { sentenceModels[l] = m }; return m }230var contextual: NLContextualEmbedding?231func contextualModel() -> NLContextualEmbedding? {232  if let c = contextual { return c }233  guard let m = NLContextualEmbedding(language: .french) ?? NLContextualEmbedding(script: .latin) else { return nil }234  guard m.hasAvailableAssets else { return nil }235  do { try m.load() } catch { return nil }236  contextual = m; return m237}238func contextualVector(_ text: String, lang: NLLanguage) -> [Double]? {239  guard let m = contextualModel(), let r = try? m.embeddingResult(for: text, language: lang) else { return nil }240  var sum = [Double](repeating: 0, count: m.dimension), n = 0241  r.enumerateTokenVectors(in: text.startIndex..<text.endIndex) { v, _ in for i in 0..<min(v.count, sum.count) { sum[i] += v[i] }; n += 1; return true }242  return n > 0 ? normalise(sum.map { $0 / Double(n) }) : nil243}244func embed(_ args: [String]) {245  guard args.count >= 2, let data = FileManager.default.contents(atPath: args[0]), let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let texts = obj["texts"] as? [[String: Any]] else { fail("usage: embed <input.json> <output.json>", code: 2) }246  let model = option("model", args) ?? "sentence"247  var rows: [String] = [], dim = 0248  for t in texts {249    let text = String((t["text"] as? String ?? "").prefix(4000))250    let lang = (t["lang"] as? String).flatMap { $0 == "en" ? NLLanguage.english : $0 == "fr" ? NLLanguage.french : nil } ?? language(of: text)251    let code = lang == .english ? "en" : "fr"252    var vector: [Double]?253    if model == "contextual" { vector = contextualVector(text, lang: lang) }254    else if let m = sentenceModel(lang), let v = m.vector(for: text) { vector = normalise(v) }255    if let v = vector { dim = v.count; rows.append("{\"lang\":\"\(code)\",\"vector\":[" + v.map { String(format: "%.5f", $0) }.joined(separator: ",") + "]}") }256    else { rows.append("{\"lang\":\"\(code)\",\"vector\":null}") }257  }258  // written by hand: JSONSerialization prints a Double with seventeen digits, five are plenty for a cosine259  let json = "{\"model\":\"\(model == "contextual" ? "contextual" : "sentence")\",\"dim\":\(dim),\"vectors\":[" + rows.joined(separator: ",") + "]}"260  do { try json.data(using: .utf8)!.write(to: URL(fileURLWithPath: args[1]), options: .atomic) } catch { fail("cannot write \(args[1])") }261}262263func probe() {264  var info: [String: Any] = ["ok": true, "vision": true, "pdfkit": true]265  info["ocrLanguages"] = (try? VNRecognizeTextRequest().supportedRecognitionLanguages()) ?? []266  info["sentence"] = ["fr": NLEmbedding.sentenceEmbedding(for: .french)?.dimension ?? 0, "en": NLEmbedding.sentenceEmbedding(for: .english)?.dimension ?? 0]267  if let c = NLContextualEmbedding(language: .french) ?? NLContextualEmbedding(script: .latin) {268    info["contextual"] = ["identifier": c.modelIdentifier, "dimension": c.dimension, "assets": c.hasAvailableAssets]269  } else { info["contextual"] = NSNull() }270  let data = try! JSONSerialization.data(withJSONObject: info, options: [.sortedKeys])271  print(String(data: data, encoding: .utf8)!)272}273274let argv = Array(CommandLine.arguments.dropFirst())275if let m = option("max-pixels", argv), let n = Int(m), n > 0 { maxPixels = n }276switch argv.first {277case "probe": probe()278case "extract": extract(Array(argv.dropFirst()))279case "dhash": dhash(Array(argv.dropFirst()))280case "embed": embed(Array(argv.dropFirst()))281default: fail("usage: spd-textkit probe | extract | dhash | embed", code: 2)282}283
Files main
Menu

Theme