|
| 1 | +import Collections |
| 2 | +import os |
| 3 | +import UIKit |
| 4 | +import Vision |
| 5 | + |
| 6 | +private let logger = Logger(subsystem: "AsyncImageKit", category: "SaliencyService") |
| 7 | + |
| 8 | +/// Detects the most salient (visually interesting) region in images using Vision framework. |
| 9 | +/// Results are cached by image URL. |
| 10 | +public actor SaliencyService { |
| 11 | + public nonisolated static let shared = SaliencyService() |
| 12 | + |
| 13 | + private nonisolated let cache = SaliencyCache() |
| 14 | + private var inflightTasks: [URL: Task<CGRect?, Never>] = [:] |
| 15 | + |
| 16 | + init() { |
| 17 | + Task.detached(priority: .utility) { [cache] in cache.loadFromDisk() } |
| 18 | + } |
| 19 | + |
| 20 | + /// Returns a cached rect synchronously without starting a task, or `nil` if not yet cached. |
| 21 | + public nonisolated func cachedSaliencyRect(for url: URL) -> CGRect? { |
| 22 | + cache.cachedRect(for: url) |
| 23 | + } |
| 24 | + |
| 25 | + /// Returns the bounding rect of the most salient region in UIKit normalized coordinates |
| 26 | + /// (origin top-left, values 0–1), or `nil` if detection fails or no salient objects are found. |
| 27 | + /// |
| 28 | + /// - warning: The underlying `Vision` framework works _only_ on the device. |
| 29 | + public func saliencyRect(for image: UIImage, url: URL) async -> CGRect? { |
| 30 | + if let cached = cache.cachedRect(for: url) { |
| 31 | + return cached |
| 32 | + } |
| 33 | + if let existing = inflightTasks[url] { |
| 34 | + return await existing.value |
| 35 | + } |
| 36 | + let task = Task<CGRect?, Never> { |
| 37 | + await SaliencyService.detect(in: image) |
| 38 | + } |
| 39 | + inflightTasks[url] = task |
| 40 | + let result = await task.value |
| 41 | + inflightTasks[url] = nil |
| 42 | + if let result { |
| 43 | + cache.store(result, for: url) |
| 44 | + } |
| 45 | + return result |
| 46 | + } |
| 47 | + |
| 48 | + /// Returns the frame for the image view within a container such that `saliencyRect` |
| 49 | + /// appears at `topInset` points from the top. Returns `nil` when no adjustment is needed |
| 50 | + /// (i.e. the image is not portrait relative to the container). |
| 51 | + public nonisolated func adjustedFrame( |
| 52 | + saliencyRect: CGRect, |
| 53 | + imageSize: CGSize, |
| 54 | + in containerSize: CGSize, |
| 55 | + topInset: CGFloat = 16 |
| 56 | + ) -> CGRect? { |
| 57 | + guard imageSize.width > 0, imageSize.height > 0, |
| 58 | + containerSize.width > 0, containerSize.height > 0 else { return nil } |
| 59 | + |
| 60 | + let imageAspect = imageSize.width / imageSize.height |
| 61 | + let containerAspect = containerSize.width / containerSize.height |
| 62 | + |
| 63 | + // Only adjust for portrait images shown in a wider container. |
| 64 | + guard imageAspect < containerAspect else { return nil } |
| 65 | + |
| 66 | + // Scale to fill container width; the scaled height will exceed container height. |
| 67 | + let scale = containerSize.width / imageSize.width |
| 68 | + let scaledHeight = imageSize.height * scale |
| 69 | + |
| 70 | + let salientTopInScaled = saliencyRect.origin.y * scaledHeight |
| 71 | + let desiredY = topInset - salientTopInScaled |
| 72 | + |
| 73 | + // Clamp so the image always covers the full container without empty gaps. |
| 74 | + let minY = containerSize.height - scaledHeight // negative |
| 75 | + let clampedY = min(0, max(minY, desiredY)) |
| 76 | + |
| 77 | + return CGRect(x: 0, y: clampedY, width: containerSize.width, height: scaledHeight) |
| 78 | + } |
| 79 | + |
| 80 | + private static func detect(in image: UIImage) async -> CGRect? { |
| 81 | + guard let cgImage = image.cgImage else { return nil } |
| 82 | + return await Task.detached(priority: .userInitiated) { |
| 83 | + let request = VNGenerateObjectnessBasedSaliencyImageRequest() |
| 84 | + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) |
| 85 | + do { |
| 86 | + try handler.perform([request]) |
| 87 | + } catch { |
| 88 | + return nil |
| 89 | + } |
| 90 | + guard let observation = request.results?.first, |
| 91 | + let salientObjects = observation.salientObjects, |
| 92 | + !salientObjects.isEmpty else { |
| 93 | + return nil |
| 94 | + } |
| 95 | + // Union all salient object bounding boxes. |
| 96 | + // Vision coordinates: origin at bottom-left, Y increases upward. |
| 97 | + let union = salientObjects.reduce(CGRect.null) { $0.union($1.boundingBox) } |
| 98 | + // Convert to UIKit coordinates (origin at top-left, Y increases downward). |
| 99 | + return CGRect( |
| 100 | + x: union.origin.x, |
| 101 | + y: 1.0 - union.origin.y - union.height, |
| 102 | + width: union.width, |
| 103 | + height: union.height |
| 104 | + ) |
| 105 | + }.value |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +private final class SaliencyCache: @unchecked Sendable { |
| 110 | + private var store: OrderedDictionary<String, CGRect> = [:] |
| 111 | + private let lock = NSLock() |
| 112 | + private var isDirty = false |
| 113 | + private var observer: AnyObject? |
| 114 | + |
| 115 | + private static let maxCount = 1000 |
| 116 | + private static let diskURL: URL = { |
| 117 | + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] |
| 118 | + return caches.appendingPathComponent("saliency_cache.json") |
| 119 | + }() |
| 120 | + |
| 121 | + init() { |
| 122 | + observer = NotificationCenter.default.addObserver( |
| 123 | + forName: UIApplication.didEnterBackgroundNotification, |
| 124 | + object: nil, |
| 125 | + queue: .main |
| 126 | + ) { [weak self] _ in |
| 127 | + guard let self else { return } |
| 128 | + Task.detached(priority: .utility) { self.saveToDisk() } |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + deinit { |
| 133 | + if let observer { NotificationCenter.default.removeObserver(observer) } |
| 134 | + } |
| 135 | + |
| 136 | + func cachedRect(for url: URL) -> CGRect? { |
| 137 | + lock.withLock { store[url.absoluteString] } |
| 138 | + } |
| 139 | + |
| 140 | + func store(_ rect: CGRect, for url: URL) { |
| 141 | + lock.withLock { |
| 142 | + let key = url.absoluteString |
| 143 | + store.updateValue(rect, forKey: key) |
| 144 | + if store.count > Self.maxCount, let oldest = store.keys.first { |
| 145 | + store.removeValue(forKey: oldest) |
| 146 | + } |
| 147 | + isDirty = true |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + func loadFromDisk() { |
| 152 | + guard let data = try? Data(contentsOf: Self.diskURL), |
| 153 | + let decoded = try? JSONDecoder().decode([String: CGRect].self, from: data) else { |
| 154 | + return |
| 155 | + } |
| 156 | + lock.withLock { |
| 157 | + store = OrderedDictionary(uniqueKeysWithValues: decoded.map { ($0.key, $0.value) }) |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + func saveToDisk() { |
| 162 | + let snapshot: OrderedDictionary<String, CGRect>? = lock.withLock { |
| 163 | + guard isDirty else { return nil } |
| 164 | + isDirty = false |
| 165 | + return store |
| 166 | + } |
| 167 | + guard let snapshot else { return } |
| 168 | + let dict = snapshot.reduce(into: [String: CGRect]()) { $0[$1.key] = $1.value } |
| 169 | + guard let data = try? JSONEncoder().encode(dict) else { return } |
| 170 | + try? data.write(to: Self.diskURL, options: .atomic) |
| 171 | + } |
| 172 | +} |
0 commit comments