// THE ANALYSIS LAYER (assets/design/albums/RESEARCH.md §2): what looking at one picture finds, all of it on this phone. // One Vision handler runs every request over the one small local picture (Apple: several requests through one // handler): the feature print (look-alike, for Sets), the aesthetics score and "utility" (best shot; receipts, // screenshots), faces with their landmarks and capture quality, a document's outline and how much text covers it. // Beside Vision, a 64 px grey picture gives sharpness (variance of the Laplacian), light and clipping, and the 9x8 // difference hash (the match key's picture part). Faces large and clear enough go to the identity model // (`AlbumsFaces`). // // THE CORE'S PART, NOT YET THE CORE'S: DECISIONS puts the grey picture's numbers, the difference hash and the face // crop and alignment in the Rust core, so his iPhone and Android agree. Until ALBUMS CORE 1 gives the methods, they are // computed here the way the core will (`proto/src/main.rs`'s hash, the ArcFace five-point template), and move there // unchanged in meaning. // ALBUMS_HARNESS: scripts/albums-vision-mac.sh builds this file on the Mac, to measure what Vision finds on real // hardware (a simulator's Vision answers its networks with garbage: constant prints, landmarks at 1e26). #if os(iOS) || ALBUMS_HARNESS import Accelerate import CoreGraphics import Foundation import Vision /// What looking at one picture found (`AlbumsAnalysis`). struct AlbumsLook: Sendable, Equatable { /// The long edge of the picture the phone gave, in pixels. var side: Int var degraded: Bool /// Vision's feature print, and its revision (prints of different revisions never compare). var print: Data? var printRevision: Int var printLength: Int /// Vision's aesthetics score −1…1, and whether it is a "utility" picture (a receipt, a screenshot, a document). var aesthetic: Float? var utility: Bool /// Variance of the Laplacian over the 64 px grey picture: low is blurred. var sharpness: Float /// Mean light 0…1 and the share of pixels at black or at white. var light: Float var clipped: Float /// The 9x8 difference hash of the 64 px grey picture (the portable match key's picture part). var dhash: UInt64 /// A document's outline was found. var document: Bool /// Text covers this much of the picture. var text: Float var faces: [AlbumsFace] /// Milliseconds the look took, the picture's fetch apart. var millis: Double /// The picture as 8-bit grey at the size it came, for the core (`albums.look.take`); never stored. var grey: AlbumsGreyPicture? = nil } struct AlbumsGreyPicture: Sendable, Equatable { let width: Int let height: Int let pixels: Data init?(_ image: CGImage) { let w = image.width, h = image.height guard w > 0, h > 0 else { return nil } var bytes = Data(count: w * h) let drawn: Bool = bytes.withUnsafeMutableBytes { buffer in guard let context = CGContext(data: buffer.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return false } context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h)) return true } guard drawn else { return nil } width = w height = h pixels = bytes } } struct AlbumsFace: Sendable, Equatable { /// Normalised to the picture, origin top left. var x: Float, y: Float, w: Float, h: Float var quality: Float? var yaw: Float, roll: Float, pitch: Float /// The five points the crop is aligned on (eyes, nose, mouth corners), normalised, origin top left. var points: [Float] /// Pixels across in the picture looked at, and across in the original. var pixels: Float var originalPixels: Float /// The identity vector, when the face was large and clear enough (`AlbumsFaces`), and the model that made it. var vector: [Float]? var model: String? } enum AlbumsAnalysis { /// The long edge asked of the phone for the first pass: what an Optimise Storage library still holds (RESEARCH.md /// §1, measured 342 px offline in one report), and enough for prints, scores and faces of 48 px in the original. static let side: CGFloat = 360 /// A face must be at least this many pixels across in the picture its vector is made from, and this clear. static let faceMinimum: Float = 48 static let qualityMinimum: Float = 0.3 /// Looks at one picture. `faces`: whether faces are on (they are by default; one switch in You turns them off). static func look(_ image: CGImage, degraded: Bool, asset: LibraryAsset, faces: Bool, model: AlbumsFaceModel?) async -> AlbumsLook { let started = ContinuousClock.now let handler = ImageRequestHandler(image) var print: FeaturePrintObservation? var aesthetics: ImageAestheticsScoresObservation? var document = false var text: Float = 0 do { let (p, a, t, d) = try await handler.perform( Self.placed(GenerateImageFeaturePrintRequest()), Self.placed(CalculateImageAestheticsScoresRequest()), Self.placed(DetectTextRectanglesRequest()), Self.placed(DetectDocumentSegmentationRequest()) ) print = p aesthetics = a text = t.reduce(Float(0)) { $0 + Float($1.boundingBox.width * $1.boundingBox.height) } // The request answers an outline for almost every picture: a document is a sure one covering a good part of it. if let d { let q = [d.topLeft, d.topRight, d.bottomRight, d.bottomLeft] var area = 0.0 for i in 0..<4 { area += Double(q[i].x * q[(i + 1) % 4].y - q[(i + 1) % 4].x * q[i].y) } document = d.confidence >= 0.9 && abs(area) / 2 >= 0.15 } } catch { Self.once("vision", error) } let outFaces = faces ? await Self.faces(handler, image, asset: asset, model: model) : [] let grey = Grey(image) let elapsed = started.duration(to: .now) return AlbumsLook( side: max(image.width, image.height), degraded: degraded, print: print?.data, printRevision: print?.originatingRequestDescriptor.map { Self.revision($0) } ?? 0, printLength: print?.elementCount ?? 0, aesthetic: aesthetics?.overallScore, utility: aesthetics?.isUtility ?? false, sharpness: grey.sharpness, light: grey.light, clipped: grey.clipped, dhash: grey.dhash, document: document, text: min(1, text), faces: outFaces, millis: Double(elapsed.components.seconds) * 1000 + Double(elapsed.components.attoseconds) / 1e15, grey: AlbumsGreyPicture(image)) } /// The faces in `image`: rectangles, then landmarks on them, then capture quality on them, each its own ask so /// one the phone cannot run leaves the others; a vector for each face large and clear enough. static func faces(_ handler: ImageRequestHandler, _ image: CGImage, asset: LibraryAsset, model: AlbumsFaceModel?) async -> [AlbumsFace] { var found: [FaceObservation] = [] do { found = try await handler.perform(Self.placed(DetectFaceRectanglesRequest())) } catch { Self.once("rectangles", error) } guard !found.isEmpty else { return [] } var marking = Self.placed(DetectFaceLandmarksRequest()) marking.inputFaceObservations = found do { found = try await handler.perform(marking) } catch { Self.once("landmarks", error) } var quality = Self.placed(DetectFaceCaptureQualityRequest()) quality.inputFaceObservations = found // Each face's quality is carried beside it, never written into the observation: the observation's // `captureQuality` setter exists only in iOS 27's Vision, and an iOS 26 phone would not launch (dyld). var qualities: [Float?] = found.map { $0.captureQuality?.score } do { let scored = try await handler.perform(quality) if scored.count == found.count { qualities = scored.map { $0.captureQuality?.score } } } catch { Self.once("quality", error) } let width = Float(image.width) let scaleToOriginal = Float(max(asset.width, asset.height)) / Float(max(image.width, image.height)) var out: [AlbumsFace] = [] for (face, score) in zip(found, qualities) { let box = face.boundingBox.verticallyFlipped() let pixels = Float(box.width) * width var points: [Float] = [] if let marks = face.landmarks { points = Self.fivePoints(marks, in: CGSize(width: image.width, height: image.height)) } var one = AlbumsFace( x: Float(box.origin.x), y: Float(box.origin.y), w: Float(box.width), h: Float(box.height), quality: score, yaw: Float(face.yaw.converted(to: .degrees).value), roll: Float(face.roll.converted(to: .degrees).value), pitch: Float(face.pitch.converted(to: .degrees).value), points: points, pixels: pixels, originalPixels: pixels * scaleToOriginal, vector: nil, model: nil) if let model, points.count == 10, pixels >= faceMinimum, (one.quality ?? 0) >= qualityMinimum, let crop = AlbumsAlign.crop(image, points: points, side: model.side) { one.vector = model.vector(crop) one.model = model.name } out.append(one) } return out } /// The long edge to ask for so the smallest face that would be `faceMinimum` across in the original reaches 64 px: /// nil when the small picture already gave every such face enough, or none would. static func closerSide(_ look: AlbumsLook, asset: LibraryAsset) -> CGFloat? { let wanting = look.faces.filter { $0.vector == nil && $0.pixels < faceMinimum && $0.originalPixels >= faceMinimum } guard let smallest = wanting.map(\.pixels).min(), smallest > 0 else { return nil } let side = CGFloat(look.side) * CGFloat(64 / smallest) return min(side, 2048, CGFloat(asset.longEdge)) } /// The faces again, from a larger picture the phone holds (network still off). static func closer(_ image: CGImage, asset: LibraryAsset, model: AlbumsFaceModel?) async -> [AlbumsFace] { await faces(ImageRequestHandler(image), image, asset: asset, model: model) } nonisolated(unsafe) private static var said = Set() private static let saying = NSLock() /// A request that failed, said once a run (with where it may run), not once a photo. static func once(_ what: String, _ error: Error) { saying.lock() defer { saying.unlock() } guard said.insert(what).inserted else { return } Log.write("albums: \(what) failed: \(error.localizedDescription) (\(error))") } /// On a simulator Vision's networks have no Neural Engine or GPU context ("Failed to create espresso context"): /// every stage on the CPU. On a phone the system chooses. static func placed(_ request: R) -> R { #if targetEnvironment(simulator) var request = request for (stage, devices) in request.supportedComputeStageDevices { if let cpu = devices.first(where: { if case .cpu = $0 { return true } else { return false } }) { request.setComputeDevice(cpu, for: stage) } } return request #else return request #endif } private static func revision(_ descriptor: RequestDescriptor) -> Int { // The descriptor names the request and its revision; the number is what prints are compared by. let said = String(describing: descriptor) return Int(said.split(whereSeparator: { !$0.isNumber }).last ?? "0") ?? 0 } /// Eyes (the one on the picture's left first), nose tip, mouth corners (left first): normalised to the picture, /// origin top left. static func fivePoints(_ marks: FaceObservation.Landmarks2D, in size: CGSize) -> [Float] { func points(_ region: FaceObservation.Landmarks2D.Region) -> [(Float, Float)] { region.pointsInImageCoordinates(size, origin: .upperLeft).map { (Float($0.x / size.width), Float($0.y / size.height)) } } func centre(_ pts: [(Float, Float)]) -> (Float, Float)? { guard !pts.isEmpty else { return nil } return (pts.map(\.0).reduce(0, +) / Float(pts.count), pts.map(\.1).reduce(0, +) / Float(pts.count)) } guard let a = centre(points(marks.leftPupil)) ?? centre(points(marks.leftEye)), let b = centre(points(marks.rightPupil)) ?? centre(points(marks.rightEye)) else { return [] } let nose = points(marks.nose) let lips = points(marks.outerLips) guard !nose.isEmpty, lips.count >= 2 else { return [] } // The nose tip: the lowest third of the nose outline, averaged. let low = Array(nose.sorted { $0.1 > $1.1 }.prefix(max(1, nose.count / 3))) guard let tip = centre(low) else { return [] } let left = lips.min { $0.0 < $1.0 }!, right = lips.max { $0.0 < $1.0 }! let (e1, e2) = a.0 <= b.0 ? (a, b) : (b, a) let out = [e1.0, e1.1, e2.0, e2.1, tip.0, tip.1, left.0, left.1, right.0, right.1] // Points off the picture are not a face's: no vector from them (a simulator's landmarks come back at 1e26). guard out.allSatisfy({ $0.isFinite && $0 > -0.25 && $0 < 1.25 }), e2.0 - e1.0 > 0 else { return [] } return out } } /// The 64 px grey picture's numbers. struct Grey { var sharpness: Float = 0 var light: Float = 0 var clipped: Float = 0 var dhash: UInt64 = 0 init(_ image: CGImage) { let side = 64 guard let pixels = Self.draw(image, width: side, height: side) else { return } let n = Float(side * side) var sum: Float = 0, dark = 0, bright = 0 for v in pixels { sum += v if v < 4 { dark += 1 } else if v > 251 { bright += 1 } } light = sum / n / 255 clipped = Float(dark + bright) / n // The Laplacian (4-neighbour) over the inside, then its variance. var lap: [Float] = [] lap.reserveCapacity((side - 2) * (side - 2)) for y in 1..<(side - 1) { for x in 1..<(side - 1) { let c = pixels[y * side + x] lap.append(pixels[(y - 1) * side + x] + pixels[(y + 1) * side + x] + pixels[y * side + x - 1] + pixels[y * side + x + 1] - 4 * c) } } var mean: Float = 0, deviation: Float = 0 vDSP_normalize(lap, 1, nil, 1, &mean, &deviation, vDSP_Length(lap.count)) sharpness = deviation * deviation // The difference hash: 9x8, each bit "brighter than the one to its right". if let small = Self.draw(image, width: 9, height: 8) { var hash: UInt64 = 0 for y in 0..<8 { for x in 0..<8 where small[y * 9 + x] > small[y * 9 + x + 1] { hash |= 1 << UInt64(y * 8 + x) } } dhash = hash } } /// The picture drawn grey at `width` by `height`, one byte a pixel, as floats. static func draw(_ image: CGImage, width: Int, height: Int) -> [Float]? { var bytes = [UInt8](repeating: 0, count: width * height) let drawn: Bool = bytes.withUnsafeMutableBytes { buffer in guard let context = CGContext(data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return false } context.interpolationQuality = .medium context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) return true } return drawn ? bytes.map(Float.init) : nil } } /// The face crop: a similarity transform taking the five points to ArcFace's 112 px template (the one SFace and the /// ArcFace family are trained on), drawn into `side` by `side` RGB. The core's own crop will replace this one. enum AlbumsAlign { static let template: [(Float, Float)] = [(38.2946, 51.6963), (73.5318, 51.5014), (56.0252, 71.7366), (41.5493, 92.3655), (70.7299, 92.2041)] /// RGB bytes, `side` square, row by row from the top. static func crop(_ image: CGImage, points: [Float], side: Int) -> [UInt8]? { let w = Float(image.width), h = Float(image.height) // The core's contract (assets/design/albums/align): pixel-index coordinates, centre of the top-left pixel at // (0, 0). Vision's points are continuous (centres at i + 0.5), so 0.5 comes off here. let src = (0..<5).map { (points[2 * $0] * w - 0.5, points[2 * $0 + 1] * h - 0.5) } let scale = Float(side) / 112 let dst = template.map { ($0.0 * scale, $0.1 * scale) } // Least squares similarity (Umeyama without reflection): dst ≈ s·R·src + t. let ms = mean(src), md = mean(dst) var a: Float = 0, b: Float = 0, norm: Float = 0 for i in 0..<5 { let sx = src[i].0 - ms.0, sy = src[i].1 - ms.1 let dx = dst[i].0 - md.0, dy = dst[i].1 - md.1 a += sx * dx + sy * dy b += sx * dy - sy * dx norm += sx * sx + sy * sy } guard norm > 0 else { return nil } let c = a / norm, s = b / norm // dst = [c -s; s c]·src + t, in pixel-index coordinates; CoreGraphics draws in continuous ones (centres at // i + 0.5 on both sides), so the translation takes M·(0.5, 0.5) off and 0.5 back on. let tx = md.0 - (c * ms.0 - s * ms.1) + 0.5 - (c * 0.5 - s * 0.5) let ty = md.1 - (s * ms.0 + c * ms.1) + 0.5 - (s * 0.5 + c * 0.5) var bytes = [UInt8](repeating: 0, count: side * side * 4) let ok: Bool = bytes.withUnsafeMutableBytes { buffer in guard let context = CGContext(data: buffer.baseAddress, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return false } context.interpolationQuality = .high // CoreGraphics' origin is at the bottom: flip to top-left pixel space on both sides of the transform. context.translateBy(x: 0, y: CGFloat(side)) context.scaleBy(x: 1, y: -1) context.concatenate(CGAffineTransform(a: CGFloat(c), b: CGFloat(s), c: CGFloat(-s), d: CGFloat(c), tx: CGFloat(tx), ty: CGFloat(ty))) context.translateBy(x: 0, y: CGFloat(h)) context.scaleBy(x: 1, y: -1) context.draw(image, in: CGRect(x: 0, y: 0, width: CGFloat(w), height: CGFloat(h))) return true } guard ok else { return nil } var rgb = [UInt8](repeating: 0, count: side * side * 3) for i in 0..<(side * side) { rgb[3 * i] = bytes[4 * i]; rgb[3 * i + 1] = bytes[4 * i + 1]; rgb[3 * i + 2] = bytes[4 * i + 2] } return rgb } private static func mean(_ p: [(Float, Float)]) -> (Float, Float) { (p.map(\.0).reduce(0, +) / Float(p.count), p.map(\.1).reduce(0, +) / Float(p.count)) } } #endif