An iOS app that finds duplicate photos and videos, picks the best copy of each, and deletes the rest. Everything runs on the device — no server, no network, no bundled model weights. It works in aeroplane mode.
- Platform: iOS 26+, iPhone and iPad
- Language: Swift 6 (strict concurrency), SwiftUI
- Bundle id:
com.rahil.OneShot
Nothing to fetch and nothing to generate: everything the app uses ships with iOS. Clone, open, run.
cd iOS
open OneShot.xcodeproj| Requirement | Notes |
|---|---|
| Xcode 26 or later | iOS 26 deployment target, Swift 6 strict concurrency. |
| An iOS 26 simulator or device | iPhone or iPad. |
Press ⌘R. On first launch, allow full photo library access — limited access cannot work, because a duplicate is a relationship between two photos and the app has to be able to see both. To scan without granting the library at all, choose Scan a folder instead and pick any folder from Files, including a USB drive or SD card plugged into the device.
Running on your own iPhone also needs your signing team selected, and the certificate trusted on the phone the first time — see DEPLOY.md.
The app finds duplicates that are already on the device, so an empty library or one whose photos live only in iCloud will correctly report that it found nothing. To try it, duplicate a few photos in Photos first (long-press a photo → Duplicate).
Five phases, in Engine/DuplicateScanner.swift.
PhotoLibraryService.fetchRecords flattens the library into AssetRecord values.
PHAsset is a non-Sendable PhotoKit class, so it is never carried across a
concurrency boundary — the scanner reads it once and re-fetches by identifier only
where PhotoKit is genuinely required (loading pixels, deleting).
File sizes here are estimates from pixel dimensions. Reading the true size means
loading PHAssetResource for every asset, which costs seconds on a large library.
enrich(_:) replaces them with real values later, for the few assets that actually
land in a group.
Each asset is decoded once, to a 128×128 square, and four signals come out of that one buffer:
| Signal | What it is | What it survives |
|---|---|---|
| dHash | 64-bit difference hash of luminance on a 9×8 grid | rescaling, recompression, exposure shifts |
| Chromaticity histogram | 8×8 bins over r/(r+g+b), g/(r+g+b) | brightness and exposure changes |
| Sharpness | variance of the Laplacian | — (used for ranking, not matching) |
| Exposure | clipping + tonal range | — (used for ranking, not matching) |
The histogram bins chromaticity, not RGB. That is not incidental: measured
against a brightened copy of the same photo, an RGB histogram scored 0.50 — well
below any usable threshold — while chromaticity scores ~0.99, because scaling all
three channels together cancels out of the ratio. The cost is that luminance is
discarded, so a black frame and a white frame both land in the achromatic centre;
meanLuma is compared separately to keep them apart.
Video takes the same path, with AVAssetImageGenerator sampling five keyframes at
fixed fractions of the duration, so a re-exported or trimmed copy still lines up
frame-for-frame.
Fingerprints are cached in SQLite keyed by asset id and validated against the modification date, so only new or edited assets are re-analysed on later scans.
This is exhaustive, and that is a deliberate reversal.
It was originally banded locality-sensitive hashing: split each 64-bit hash into eight 8-bit bands, only compare assets colliding in a band. Measuring it against a library with known duplicates showed why that was wrong. Real duplicates land at Hamming distances of 8 to 16, and at those distances banding surfaces only 57–70% of pairs. A five-member group survived because its ten pairs gave it ten chances to collide; a plain two-photo duplicate had exactly one chance and was silently missed.
So every pair is compared. 30,000 photos is 450 million pairs, but each is an XOR, a popcount and a compare over flat cache-resident arrays, parallelised across cores — about a second, against a decode phase measured in minutes. Complete recall is worth far more than that second. The 64-bin histogram is only touched for pairs that survive the hash test.
Rejections run cheapest-first: mean luminance, then aspect ratio, then hash, then histogram.
A pair is accepted by either of two routes:
- Structure-led — hash within
hashAcceptand histogram abovehistogramAccept. - Colour-led — histogram at or above
strongHistogram(near-perfect) and hash withincolourLedHashLimit.
The colour-led route exists because heavy JPEG recompression pushes a copy of the same photo to Hamming 16 while its colour distribution holds at 0.97+, whereas unrelated photographs sat at 0.40–0.52. Colour proved the more decisive signal, so it gets a route of its own rather than only ever acting as a veto.
It carries its own tight hash bound. Without one, Similar scenes merged five
unrelated photographs into a single group of eleven — its wide hashReject of 30 let
anything with a similar palette through on colour alone.
Pairs in the grey zone between the two routes escalate to
VNGenerateImageFeaturePrintRequest — Apple's on-device image embedding, which
ships inside iOS and runs on the Neural Engine. That is the "pre-existing model": no
download, no weights in the bundle, no network. It is roughly a thousand times more
expensive than a popcount, which is why it decides only the pairs the cheap signals
could not.
Blank frames get a special guard: an all-black photo has an all-zero hash and matches every other blank frame. Without it, thirty accidental lens-cap shots become one enormous bogus group.
Screenshots are a special case. Two screenshots of the same app share their status bar, navigation chrome and palette, so the colour histogram describes the app rather than the content — unrelated screens routinely score above 0.98. Screenshot-to- screenshot pairs therefore skip the colour-led route entirely and must agree structurally (hash ≤ 6).
The three sensitivities were originally just three sets of visual thresholds, with
.similar being the loosest. That does not work, and it is worth being precise about
why: a Hamming distance of 18 out of 64 plus a chromaticity match of 0.78 describes
an enormous share of ordinary photographs. A 64-bit luminance-gradient hash keys on
gross composition, so any "bright sky above, darker ground below" photo resembles
any other. Loosening thresholds library-wide grouped forty unrelated pictures.
The Vision escalation made it worse rather than better. Feature prints measure semantic similarity — two different photographs of two different beaches score close together, which is a true statement and completely the wrong question. At an acceptance distance of 0.85 it was confirming pairs that were merely the same kind of subject.
What the mode is actually for — burst frames, and re-taking a shot of the same
subject — has a property the thresholds were ignoring: it happens within seconds or
minutes. So .similar is now .strict plus a temporal route:
| Route | Thresholds | When |
|---|---|---|
| Anytime | .strict values |
any two photos, whenever taken |
| Same moment | relaxed values | captured within 3 minutes of each other |
| Model | feature print ≤ 0.60 | only for pairs one of the above already bracketed |
.similar therefore remains a strict superset of .strict — it can only ever find
more — while its extra reach is confined to frames that plausibly belong to one
moment. Assets with no capture date count as not the same moment, since without a
timestamp there is no evidence for the temporal route.
Gating escalation on the same test also stops .similar firing thousands of Vision
requests at pairs it was never going to accept, which makes it faster as well.
Union-find merges pairs into connected components, which is not quite the question being asked. It answers "is there a path of similarity between these two photos". If A resembles B, B resembles C and C resembles D, all four land in one group — even when A and D have nothing in common. On a real library those chains run for hundreds of photos and the first group swallows most of the library. A 19-image test corpus has chains too short to reveal this; a 40-frame morph sequence collapses into a single 35-member blob.
So each component is refined by star clustering: repeatedly take the best-connected photo still unassigned, and form a group from it and the photos that matched it directly. Every member of the resulting group is a confirmed match against the same anchor, so nothing arrives by transitive association and the group means what the user thinks it means — "these are all copies of this one". Groups are capped at 60 members; beyond that the least similar are left for the next anchor rather than piled onto one unreviewable card.
Each group member is then scored. Every measured dimension is normalised within that group: absolute sharpness is meaningless across scenes, but "sharpest of these four near-identical frames" is exactly the question. User intent (favourited, edited) is a flat bonus large enough to override the measurements — a starred photo should never lose to a marginally sharper copy.
| Weight | Dimension |
|---|---|
| 3.0 | Sharpness |
| 2.5 | Resolution (log scale) |
| 2.0 | Faces — count and eyes-open |
| 1.2 | Exposure |
| 0.8 | File size |
| +5.0 | Favourited |
| +1.2 | Your edit |
| +0.8 | Live Photo / HDR |
| −1.5 | A screenshot in a group that also has real photos |
Face detection is the most expensive per-asset operation in the app — a decode plus a Vision request per photo — so it is gated three ways:
- Only groups whose members differ meaningfully in sharpness (the burst case, where "who blinked" decides it). Exact copies have identical faces, so analysing them changes nothing.
- Only the top three contenders in a group, not every member. Photos already behind on sharpness and resolution cannot be rescued by an eye-open bonus, so analysing them is wasted work. Members that were not analysed receive a neutral half-share of the face weight rather than zero, so they are not punished for work that was deliberately skipped.
- A hard ceiling of 400 analyses per scan.
Reading true file sizes (PHAssetResource) is a per-asset hit on the Photos database
and is chunked across cores for the same reason.
Engine/ is deliberately free of UIKit and PhotoKit dependencies below
PhotoLibraryService, so the detection pipeline can be compiled and exercised
standalone on synthetic images with known relationships. That harness is what caught
every bug listed below.
Measured against a seeded library of 19 images with known ground truth — one photo saved five ways, a three-frame burst, a resized pair, six unrelated photographs, two identical black frames and a white frame:
Result: 4 groups, 8 duplicates — an exact match to ground truth, with no false positives. The six unrelated photographs and the lone white frame were correctly left ungrouped.
Representative distances from that run:
| Pair | Hamming | Histogram |
|---|---|---|
| original ↔ resized 50% | 13 | 0.999 |
| original ↔ resized 25% | 13 | 0.999 |
| original ↔ JPEG q25 | 11 | 0.987 |
| original ↔ brightened | 10 | 0.980 |
| valley original ↔ copy | 8 | 0.990 |
| unrelated photographs | 21–29 | 0.40–0.52 |
A 40-frame sequence morphing from one scene to an unrelated one: each frame is near-identical to its neighbour, the endpoints have nothing in common. This is the shape of a real photo library, and the shape a small test corpus cannot produce.
| Result | |
|---|---|
| Union-find components | 35, 5 |
| After star clustering | 12, 6, 5, 5, 3, 3, 2, 2 |
| First and last frame grouped together | no |
| Members not directly matched to their anchor | 0 |
The 35-member blob is the reported failure reproduced in miniature. Refinement breaks it into reviewable groups while the seeded library still resolves to exactly its 4 correct groups.
A corpus built to be hostile in the way a real library is: 43 photographs that all share the same gross composition, so the hash has every chance to confuse them. 6 burst frames 2 s apart, 2 reshoots of one subject 55 s apart, 25 unrelated photos one per day, and 10 unrelated photos only 30 s apart — the last group being the hard case, since closeness in time must not by itself imply duplication.
| Confirmed | Groups | Mixed groups | |
|---|---|---|---|
| Control (previous thresholds, no temporal gate) | 18 | 6, 3, 2 | 2 |
| Exact | 10 | 6, 2 | 0 |
| Near-identical | 16 | 6, 2 | 0 |
| Similar scenes | 16 | 6, 2 | 0 |
The control establishes that this corpus reproduces the reported failure. All three current modes find exactly the burst and the reshoot and nothing else; the 35 unrelated photographs are correctly left alone, including the ten taken half a minute apart.
Re-run in the app against the seeded library — where every asset shares an import
timestamp, so the temporal gate is wide open, the worst case for this design —
.similar returns the same 4 groups and 8 duplicates as .strict, with no
contamination.
- RGB histogram broke on exposure changes — a brightened copy scored 0.50 and was rejected before it was even a candidate. Fixed by binning chromaticity.
- LSH banding silently missed two-photo duplicates — 57–70% recall in the range where real duplicates live. Replaced with an exhaustive scan.
.aspectFillwas centre-cropping every thumbnail. Requesting a square target size with.aspectFillmakes PhotoKit return a centre crop, discarding the left and right quarters of every 4:3 frame — so the hash described only the middle of the picture, and none of the calibration applied to what the app actually did. Fixed by requesting.aspectFitand squashing to square inrasterize. This was the bug that hid the resized pair.- Confidence read as "Possible" for certain duplicates — the hash term was too harsh and averaging across a group's pairs dragged large groups down.
- Every group was labelled "Burst" — timestamps alone are not enough, since an imported batch shares one import time. Now requires identical pixel dimensions and three or more members.
- No way to rescan from the results screen without quitting the app.
- Cache size under-reported — counted only the main SQLite file, ignoring the WAL that held most of the data.
- Transitive chaining produced enormous groups — reported from real-device use:
a library of ~1000 photos returned ~900 of them as a single "duplicate" group.
Union-find's connected components chain through intermediate photos. Fixed with
star clustering, plus a tightened
colourLedHashLimit(18 → 14 at.strict, too close to the 21–29 band where unrelated photographs sit) and a structure-only rule for screenshot pairs. - The scoring phase was slow — face detection ran on every member of every group, and true file sizes were read serially. Now three contenders per group and chunked across cores.
Similar scenesgrouped forty unrelated photos — reported from real-device use, after the chaining fix had already landed. Loosening visual thresholds library-wide cannot express "the same moment", and the Vision escalation at 0.85 was confirming pairs that were merely the same kind of subject. Redesigned as.strictplus a time-gated route.- The group screen went stale after deleting from it.
removeDeletedrebuilds everyDuplicateGroup, but the detail screen holds the value it was pushed with, so it kept showing photos that no longer existed and offered to delete them a second time. It now closes itself on a successful delete. - An empty badge capsule floated on every ordinary photo —
AssetBadgesdrew its background unconditionally, even with nothing to put in it.
A tick means the photo is going; unticked means it stays. Duplicates arrive ticked and the suggested keeper arrives unticked, so the default is one tap away from being correct and the whole screen reduces to one idea.
Viewing and marking are separate gestures. Tapping a photo only ever shows it; tapping its checkbox marks it. An earlier version made a second tap on the focused photo toggle it, which meant browsing and deleting were the same gesture.
The recommendation is advice, not a lock — the starred photo can be ticked like any other. If every copy in a group ends up ticked the screen says so plainly rather than preventing it.
The synthetic corpus does not test crops or rotations, which dHash is inherently weak against — a meaningfully cropped copy will not match, by design.
The Vision escalation is never exercised offline, because the harness has no
Vision framework available to it. Its acceptance thresholds are reasoned from the
distance scale rather than measured, and they remain the least-validated numbers in
Tuning.
Tuning.sameSceneWindow is set to 3 minutes on judgement, not measurement. If
.similar still misses burst sequences it should go up; if it over-groups it should
come down. It is the first dial to reach for.
- No network code anywhere in the app.
isNetworkAccessAllowedis hard-codedfalseon every PhotoKit request, including the ones that load images for display. - Assets whose full-resolution pixels live only in iCloud are counted and reported in the UI, never silently skipped.
- Deletion goes through
PHAssetChangeRequest.deleteAssets, so items land in Recently Deleted and stay recoverable for 30 days. There are two confirmations: the app's own sheet, then iOS's ("Allow OneShot to delete N photos?"). Verified in the simulator — the system sheet appears there too. - Deleting from a folder goes through
FileManager.trashItem, so those files land in the volume's trash and can be put back too. Where a volume has no trash — some external drives — the move fails and the user is told, rather than the file being unlinked quietly behind the promise above. - A folder is read with no photo library permission at all. The gate in front of the library is not a gate in front of the app.
OneShot/
├── Models/ Value types: AssetRecord, Fingerprint, DuplicateGroup, ScanSource, Tuning
├── Engine/ Detection pipeline (no SwiftUI)
│ ├── AssetLoader routes each id to the photo library or a folder
│ ├── PhotoLibraryService PhotoKit: fetch, decode, delete
│ ├── FolderLibraryService the same for a picked folder: list, decode, trash
│ ├── Fingerprinter dHash, histogram, sharpness, exposure
│ ├── VideoFingerprinter keyframe sampling
│ ├── CandidateIndex exhaustive pair generation
│ ├── ClusterRefiner star clustering
│ ├── FeaturePrintService Vision escalation
│ ├── FaceAnalyzer face count, eyes-open estimate
│ ├── QualityScorer keeper selection
│ ├── FingerprintStore SQLite cache
│ └── DuplicateScanner orchestration
└── Views/ SwiftUI, with LibraryModel as the single source of truth
Design/ App icon source artwork, and PrepIcon.swift which crops it to AppIcon1024.png
Every threshold lives in Tuning in Models/ScanSettings.swift. The user-facing
control is the three-level Sensitivity enum — raw Hamming distances would be
meaningless to a user, so they never see one.