Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/SmartScan/SecurityCodeRedactor.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CoreGraphics42import Foundation4344/// Finds where a bank card's security code (CVV, CVC, CID) is printed, so it can45/// be blacked out before the photograph is stored. Rectangles are normalised to46/// the card image, origin top-left. Detection only proposes: the owner validates47/// the mask in the scanner.48enum SecurityCodeDetector {49 private static let labelWords: Set<String> = ["cvv", "cvv2", "cvc", "cvc2", "cid", "csc", "cvn", "cav", "cryptogramme"]5051 private static func isLabel(_ text: String) -> Bool {52 let words = CardTextParser.words(text)53 if words.contains(where: labelWords.contains) { return true }54 let joined = words.joined(separator: " ")55 return joined.contains("security code") || joined.contains("code de securite")56 }5758 private static func isCode(_ token: String) -> Bool {59 (3...4).contains(token.count) && token.allSatisfy(\.isNumber)60 }6162 /// Padding around a detected code, as a fraction of its own size.63 static let padding: CGFloat = 0.456465 private static func padded(_ box: CGRect) -> CGRect {66 box.insetBy(dx: -box.width * padding, dy: -box.height * padding).intersection(CGRect(x: 0, y: 0, width: 1, height: 1))67 }6869 /// - Parameter lines: every recognised line, whatever its confidence — for70 /// masking, a doubtful reading still counts.71 static func candidates(in lines: [RecognizedLine]) -> [CGRect] {72 let labels = lines.filter { isLabel($0.text) }73 var rects: [CGRect] = []74 for line in lines {75 let codes = line.tokens.filter { isCode($0.text) }76 guard !codes.isEmpty else { continue }77 let digitCount = line.text.filter(\.isNumber).count78 let hasLabel = isLabel(line.text)79 // The whole line is just the code ("737").80 let isolated = line.tokens.count == 1 && codes.count == 181 // A long digit sequence is a card or telephone number, not a code.82 let partOfLongNumber = digitCount >= 783 let nearLabel = labels.contains { label in84 label != line && abs(label.box.midY - line.box.midY) < 0.2 && label.box.minX < line.box.maxX + 0.25 && label.box.maxX > line.box.minX - 0.2585 }86 if hasLabel {87 rects.append(contentsOf: codes.map { padded($0.box) })88 } else if isolated || (nearLabel && !partOfLongNumber && codes.count == 1) {89 rects.append(padded(codes[0].box))90 }91 }92 return merged(rects)93 }9495 /// Four-digit code printed alone on the front of an American Express card.96 static func frontCandidates(in lines: [RecognizedLine]) -> [CGRect] {97 merged(lines.filter { $0.tokens.count == 1 && $0.text.count == 4 && $0.text.allSatisfy(\.isNumber) && !(1900...2100).contains(Int($0.text) ?? 0) }98 .map { padded($0.box) })99 }100101 private static func merged(_ rects: [CGRect]) -> [CGRect] {102 var out: [CGRect] = []103 for rect in rects where !rect.isEmpty {104 if let index = out.firstIndex(where: { $0.intersects(rect) }) { out[index] = out[index].union(rect) } else { out.append(rect) }105 }106 return out107 }108}109110/// Burns opaque black rectangles into a photograph. The result is a new bitmap:111/// inside the rectangles no original pixel survives, so the masked code cannot112/// be recovered from the stored image.113enum Redactor {114 static func redact(_ image: CGImage, rects: [CGRect]) -> CGImage {115 guard !rects.isEmpty else { return image }116 let w = image.width, h = image.height117 guard let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: ImagePipeline.sRGB,118 bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return image }119 context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))120 context.setFillColor(CGColor(red: 0, green: 0, blue: 0, alpha: 1))121 context.setBlendMode(.copy)122 context.setShouldAntialias(false)123 for rect in rects {124 // Normalised top-left → bitmap coordinates (origin bottom-left), grown to whole pixels.125 let pixel = CGRect(x: rect.minX * CGFloat(w), y: (1 - rect.maxY) * CGFloat(h), width: rect.width * CGFloat(w), height: rect.height * CGFloat(h))126 context.fill(pixel.insetBy(dx: -1, dy: -1).integral)127 }128 return context.makeImage() ?? image129 }130}131