// 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_HARNESSimportAccelerateimportCoreGraphicsimportFoundationimportVision/// What looking at one picture found (`AlbumsAnalysis`).structAlbumsLook: Sendable, Equatable {/// The long edge of the picture the phone gave, in pixels.var side: Intvar degraded: Bool/// Vision's feature print, and its revision (prints of different revisions never compare).var print: Data?var printRevision: Intvar 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: Floatvar 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: Floatvar 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}structAlbumsGreyPicture: Sendable, Equatable {let width: Intlet height: Intlet pixels: Datainit?(_ image: CGImage) {let w = image.width, h = image.heightguard w > 0, h > 0else { returnnil }var bytes = Data(count: w * h)let drawn: Bool = bytes.withUnsafeMutableBytes { buffer inguardlet context = CGContext(data: buffer.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { returnfalse } context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))returntrue }guard drawn else { returnnil } width = w height = h pixels = bytes }}structAlbumsFace: Sendable, Equatable {/// Normalised to the picture, origin top left.var x: Float, y: Float, w: Float, h: Floatvar 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: Floatvar 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?}enumAlbumsAnalysis {/// 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.staticlet side: CGFloat = 360/// A face must be at least this many pixels across in the picture its vector is made from, and this clear.staticlet faceMinimum: Float = 48staticlet qualityMinimum: Float = 0.3/// Looks at one picture. `faces`: whether faces are on (they are by default; one switch in You turns them off).staticfunc look(_ image: CGImage, degraded: Bool, asset: LibraryAsset, faces: Bool, model: AlbumsFaceModel?) async -> AlbumsLook {let started = ContinuousClock.nowlet handler = ImageRequestHandler(image)var print: FeaturePrintObservation?var aesthetics: ImageAestheticsScoresObservation?var document = falsevar text: Float = 0do {let (p, a, t, d) = tryawait 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.iflet d {let q = [d.topLeft, d.topRight, d.bottomRight, d.bottomLeft]var area = 0.0for i in0..<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 ? awaitSelf.faces(handler, image, asset: asset, model: model) : []let grey = Grey(image)let elapsed = started.duration(to: .now)returnAlbumsLook( 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.staticfunc faces(_ handler: ImageRequestHandler, _ image: CGImage, asset: LibraryAsset, model: AlbumsFaceModel?) async -> [AlbumsFace] {var found: [FaceObservation] = []do { found = tryawait handler.perform(Self.placed(DetectFaceRectanglesRequest())) } catch { Self.once("rectangles", error) }guard !found.isEmpty else { return [] }var marking = Self.placed(DetectFaceLandmarksRequest()) marking.inputFaceObservations = founddo { found = tryawait 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 = tryawait 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) * widthvar points: [Float] = []iflet 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)iflet 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.staticfunc closerSide(_ look: AlbumsLook, asset: LibraryAsset) -> CGFloat? {let wanting = look.faces.filter { $0.vector == nil && $0.pixels < faceMinimum && $0.originalPixels >= faceMinimum }guardlet smallest = wanting.map(\.pixels).min(), smallest > 0else { returnnil }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).staticfunc closer(_ image: CGImage, asset: LibraryAsset, model: AlbumsFaceModel?) async -> [AlbumsFace] {await faces(ImageRequestHandler(image), image, asset: asset, model: model) } nonisolated(unsafe) privatestaticvar said = Set<String>()privatestaticlet saying = NSLock()/// A request that failed, said once a run (with where it may run), not once a photo.staticfunc 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.staticfunc placed<R: VisionRequest>(_ request: R) -> R { #if targetEnvironment(simulator)var request = requestfor (stage, devices) in request.supportedComputeStageDevices {iflet cpu = devices.first(where: { ifcase .cpu = $0 { returntrue } else { returnfalse } }) { request.setComputeDevice(cpu, for: stage) } }return request #elsereturn request #endif }privatestaticfunc 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)returnInt(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.staticfunc 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 { returnnil }return (pts.map(\.0).reduce(0, +) / Float(pts.count), pts.map(\.1).reduce(0, +) / Float(pts.count)) }guardlet 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 >= 2else { 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)))guardlet 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 > 0else { return [] }return out }}/// The 64 px grey picture's numbers.structGrey {var sharpness: Float = 0var light: Float = 0var clipped: Float = 0var dhash: UInt64 = 0init(_ image: CGImage) {let side = 64guardlet pixels = Self.draw(image, width: side, height: side) else { return }let n = Float(side * side)var sum: Float = 0, dark = 0, bright = 0for v in pixels { sum += vif v < 4 { dark += 1 } elseif 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 in1..<(side - 1) {for x in1..<(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".iflet small = Self.draw(image, width: 9, height: 8) {var hash: UInt64 = 0for y in0..<8 {for x in0..<8where 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.staticfunc draw(_ image: CGImage, width: Int, height: Int) -> [Float]? {var bytes = [UInt8](repeating: 0, count: width * height)let drawn: Bool = bytes.withUnsafeMutableBytes { buffer inguardlet context = CGContext(data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { returnfalse } context.interpolationQuality = .medium context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))returntrue }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.enumAlbumsAlign {staticlet 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.staticfunc 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) / 112let 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 = 0for i in0..<5 {let sx = src[i].0 - ms.0, sy = src[i].1 - ms.1let 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 > 0else { returnnil }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 inguardlet context = CGContext(data: buffer.baseAddress, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { returnfalse } 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)))returntrue }guard ok else { returnnil }var rgb = [UInt8](repeating: 0, count: side * side * 3)for i in0..<(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 }privatestaticfunc mean(_ p: [(Float, Float)]) -> (Float, Float) { (p.map(\.0).reduce(0, +) / Float(p.count), p.map(\.1).reduce(0, +) / Float(p.count)) }}#endif