open-standards/aac/aac-rs/tools/symbols/ocr_vision.swift
2026-10-13 22:26:53 -04:00

33 lines
1.4 KiB
Swift

// Drawn-text reader for build_nc.py: Apple Vision's text recognition
// (accurate level) in the sets' languages and their neighbours. Built by
// build_nc.py with swiftc into its cache; macOS only.
//
// ocr <image>... one JSON line per image:
// {"path": ..., "texts": [{"text": ..., "conf": ...}]}
import Foundation
import Vision
import AppKit
let langs = ["es-ES", "nl-NL", "en-US", "fr-FR", "de-DE", "ca-ES", "pt-BR", "it-IT"]
for path in CommandLine.arguments.dropFirst() {
var out: [[String: Any]] = []
if let img = NSImage(contentsOfFile: path),
let cg = img.cgImage(forProposedRect: nil, context: nil, hints: nil) {
let req = VNRecognizeTextRequest()
req.recognitionLevel = .accurate
req.usesLanguageCorrection = false
req.recognitionLanguages = langs
req.minimumTextHeight = 0.02
let handler = VNImageRequestHandler(cgImage: cg, options: [:])
do { try handler.perform([req]) } catch { FileHandle.standardError.write("\(path): \(error)\n".data(using: .utf8)!) }
for obs in req.results ?? [] {
if let top = obs.topCandidates(1).first {
out.append(["text": top.string, "conf": top.confidence])
}
}
}
let line: [String: Any] = ["path": path, "texts": out]
if let data = try? JSONSerialization.data(withJSONObject: line), let s = String(data: data, encoding: .utf8) {
print(s)
}
}