Implement storage architecture from ai_blueprint.md

Primary sync: replace PersistenceActor JSON file with SwiftData + CloudKit
- Add SavedCardModel (@Model class) and PersistenceController (ModelContainer
  with .automatic CloudKit, fallback to local). BackgroundPersistenceActor
  (@ModelActor) handles all DB I/O off the main thread.
- One-time migration imports user_collection.json into SwiftData and renames
  the original file to prevent re-import.
- Inject modelContainer into SwiftUI environment in IYmtgApp.

Image storage: Documents/UserContent/ subfolder (blueprint requirement)
- ImageManager.dir now targets iCloud Documents/UserContent/ (or local equiv).
- migrateImagesToUserContent() moves existing JPGs to the new subfolder on
  first launch; called during the SwiftData migration.

Firebase: demoted to optional manual backup (metadata only, no images)
- Remove all automatic CloudEngine.save/delete/batchUpdatePrices calls from
  CollectionViewModel mutations.
- Add backupAllToFirebase() for user-triggered metadata sync.
- Add isFirebaseBackupEnabled to AppConfig (default false).
- Add Cloud Backup section in Library settings with iCloud vs Firebase
  explanation and "Backup Metadata to Firebase Now" button.

Also: full modular refactor (Data/, Features/, Services/ directories) and
README updated with CloudKit setup steps and revised release checklist.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-05 12:13:17 -05:00
parent b993ef4020
commit 24dcb44af4
38 changed files with 2786 additions and 2105 deletions

View File

@@ -0,0 +1,50 @@
import Vision
import CoreML
import UIKit
struct DamageObservation: Identifiable, Sendable {
let id = UUID()
let type: String
let rect: CGRect
let confidence: Float
}
// MARK: - CONDITION ENGINE
class ConditionEngine {
enum Severity: Int { case minor = 1; case critical = 10 }
static var model: VNCoreMLModel? = {
guard AppConfig.enableConditionGrading else { return nil }
return ModelManager.shared.getModel(name: "IYmtgConditionClassifier")
}()
static func getSeverity(for type: String) -> Severity {
return (type == "Inking" || type == "Rips" || type == "WaterDamage") ? .critical : .minor
}
static func detectDamage(image: CGImage, orientation: CGImagePropertyOrientation = .up) -> [DamageObservation] {
guard let model = model else { return [] }
let request = VNCoreMLRequest(model: model)
request.imageCropAndScaleOption = .scaleFill
let handler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
do {
try handler.perform([request])
guard let results = request.results as? [VNRecognizedObjectObservation] else { return [] }
return results.filter { $0.confidence > 0.7 }.map { obs in
DamageObservation(type: obs.labels.first?.identifier ?? "Unknown", rect: obs.boundingBox, confidence: obs.confidence)
}
} catch { return [] }
}
static func overallGrade(damages: [DamageObservation]) -> String {
if model == nil && damages.isEmpty { return "Ungraded" }
var score = 0
for d in damages {
if getSeverity(for: d.type) == .critical { return "Damaged" }
score += 1
}
if score == 0 { return "Near Mint (NM)" }
if score <= 2 { return "Excellent (EX)" }
return "Played (PL)"
}
}

View File

@@ -0,0 +1,48 @@
import Vision
import CoreML
import CoreGraphics
// MARK: - FOIL ENGINE
actor FoilEngine {
private var frameCounter = 0
private var lowConfidenceStreak = 0
static var model: VNCoreMLModel? = {
guard AppConfig.enableFoilDetection else { return nil }
return ModelManager.shared.getModel(name: "IYmtgFoilClassifier")
}()
private lazy var request: VNCoreMLRequest? = {
guard let model = FoilEngine.model else { return nil }
let req = VNCoreMLRequest(model: model)
req.imageCropAndScaleOption = .scaleFill
return req
}()
func addFrame(_ image: CGImage, orientation: CGImagePropertyOrientation = .up) -> String? {
frameCounter += 1
// SAFETY: Prevent integer overflow in long-running sessions
if frameCounter > 1000 { frameCounter = 0 }
if frameCounter % 5 != 0 { return nil }
guard let request = self.request else { return AppConfig.Defaults.defaultFoil }
let handler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
do {
try handler.perform([request])
guard let results = request.results as? [VNClassificationObservation], let top = results.first else { return AppConfig.Defaults.defaultFoil }
if top.confidence > 0.85 {
lowConfidenceStreak = 0
return top.identifier
} else {
lowConfidenceStreak += 1
if lowConfidenceStreak >= 3 {
return AppConfig.Defaults.defaultFoil
} else {
return nil
}
}
} catch { return AppConfig.Defaults.defaultFoil }
}
}

View File

@@ -0,0 +1,75 @@
import CoreML
import Vision
import FirebaseStorage
struct SharedEngineResources {
static let context = CIContext()
}
// MARK: - MODEL MANAGER (OTA Updates)
class ModelManager {
static let shared = ModelManager()
private let defaults = UserDefaults.standard
func getModel(name: String) -> VNCoreMLModel? {
// 1. Check Documents (Downloaded Update)
if let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let modelURL = docDir.appendingPathComponent("models/\(name).mlmodelc")
if FileManager.default.fileExists(atPath: modelURL.path),
let model = try? MLModel(contentsOf: modelURL),
let vnModel = try? VNCoreMLModel(for: model) {
return vnModel
}
}
// 2. Check Bundle (Built-in Fallback)
if let bundleURL = Bundle.main.url(forResource: name, withExtension: "mlmodelc"),
let model = try? MLModel(contentsOf: bundleURL),
let vnModel = try? VNCoreMLModel(for: model) {
return vnModel
}
return nil
}
func checkForUpdates() {
guard FirebaseApp.app() != nil else { return }
let models = ["IYmtgFoilClassifier", "IYmtgConditionClassifier", "IYmtgStampClassifier", "IYmtgSetClassifier"]
for name in models {
let ref = Storage.storage().reference().child("models/\(name).mlmodel")
ref.getMetadata { meta, error in
guard let meta = meta, let remoteDate = meta.updated else { return }
let localDate = self.defaults.object(forKey: "ModelDate_\(name)") as? Date ?? Date.distantPast
if remoteDate > localDate {
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(name).mlmodel")
ref.write(toFile: tempURL) { url, error in
guard let url = url else { return }
DispatchQueue.global(qos: .utility).async {
do {
let compiledURL = try MLModel.compileModel(at: url)
let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("models")
try FileManager.default.createDirectory(at: docDir, withIntermediateDirectories: true)
let destURL = docDir.appendingPathComponent("\(name).mlmodelc")
let tempDestURL = docDir.appendingPathComponent("temp_\(name).mlmodelc")
try? FileManager.default.removeItem(at: tempDestURL)
try FileManager.default.copyItem(at: compiledURL, to: tempDestURL)
if FileManager.default.fileExists(atPath: destURL.path) {
_ = try FileManager.default.replaceItem(at: destURL, withItemAt: tempDestURL, backupItemName: nil, options: [])
} else {
try FileManager.default.moveItem(at: tempDestURL, to: destURL)
}
self.defaults.set(remoteDate, forKey: "ModelDate_\(name)")
print("✅ OTA Model Updated: \(name)")
} catch {
print("❌ Model Update Failed for \(name): \(error)")
}
}
}
}
}
}
}
}

View File

@@ -0,0 +1,29 @@
import Vision
import CoreML
import CoreGraphics
// MARK: - SET SYMBOL ENGINE
class SetSymbolEngine {
static var model: VNCoreMLModel? = {
guard AppConfig.enableSetSymbolDetection else { return nil }
return ModelManager.shared.getModel(name: "IYmtgSetClassifier")
}()
static func recognizeSet(image: CGImage, orientation: CGImagePropertyOrientation = .up) -> String? {
guard let model = model else { return nil }
let request = VNCoreMLRequest(model: model)
request.imageCropAndScaleOption = .scaleFill
// FIX: Use regionOfInterest (Normalized 0..1, Bottom-Left origin)
// Target: x=0.85 (Right), y=0.36 (Mid-Lower), w=0.12, h=0.09
request.regionOfInterest = CGRect(x: 0.85, y: 0.36, width: 0.12, height: 0.09)
let handler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
do {
try handler.perform([request])
guard let results = request.results as? [VNClassificationObservation], let top = results.first else { return nil }
return top.confidence > 0.6 ? top.identifier : nil
} catch { return nil }
}
}