SPB Git

Repository Public License

Duplicates.swift 6.1 KB 138 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Sources/ORIXImaging/Media/Duplicates.swift10// Description      : Duplicate detection for app-owned media: exact (SHA-256 of11//                    the file) and visual (64-bit difference hash).12// Module           : ORIXImaging13// Repository       : https://git.spboucher.ai/orix-camera14// Project Website  : https://www.orixlab.dev15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import CoreGraphics92import CryptoKit93import Foundation9495public enum DuplicateDetector {96    /// SHA-256 of the file contents, hex. Streams the file in 1 MB chunks.97    public static func contentHash(url: URL) -> String? {98        guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }99        defer { try? handle.close() }100        var hasher = SHA256()101        while let chunk = try? handle.read(upToCount: 1 << 20), !chunk.isEmpty { hasher.update(data: chunk) }102        return hasher.finalize().map { String(format: "%02x", $0) }.joined()103    }104105    /// Difference hash: 9×8 grey thumbnail, one bit per horizontal neighbour comparison.106    public static func differenceHash(_ image: CGImage) -> UInt64? {107        var pixels = [UInt8](repeating: 0, count: 72)108        let ok = pixels.withUnsafeMutableBytes { raw -> Bool in109            guard let context = CGContext(data: raw.baseAddress, width: 9, height: 8, bitsPerComponent: 8, bytesPerRow: 9,110                                          space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return false }111            context.interpolationQuality = .medium112            context.draw(image, in: CGRect(x: 0, y: 0, width: 9, height: 8))113            return true114        }115        guard ok else { return nil }116        var hash: UInt64 = 0117        for y in 0..<8 { for x in 0..<8 {118            hash <<= 1119            if pixels[y * 9 + x] > pixels[y * 9 + x + 1] { hash |= 1 }120        } }121        return hash122    }123124    public static func distance(_ a: UInt64, _ b: UInt64) -> Int { (a ^ b).nonzeroBitCount }125126    /// Groups ids whose hashes are within `threshold` bits of each other (single linkage). Groups of one are omitted.127    public static func groups<ID: Hashable>(_ hashes: [(id: ID, hash: UInt64)], threshold: Int = 4) -> [[ID]] {128        var parent = Array(hashes.indices)129        func find(_ i: Int) -> Int { var i = i; while parent[i] != i { parent[i] = parent[parent[i]]; i = parent[i] }; return i }130        for i in hashes.indices { for j in hashes.indices where j > i {131            if distance(hashes[i].hash, hashes[j].hash) <= threshold { parent[find(i)] = find(j) }132        } }133        var buckets: [Int: [ID]] = [:]134        for i in hashes.indices { buckets[find(i), default: []].append(hashes[i].id) }135        return buckets.values.filter { $0.count > 1 }136    }137}138
Files main
Menu

Theme