Match EXIF lens names by brand and share team calibrations

EXIF folds the brand into the focal range ("EF75-300mm"), so split letters
from digits before scoring, keep the score a pure name score that a caller can
trust, and rank a same-mount-family lens higher without filtering. Auto-match
now declines below 0.75 rather than applying the best of a bad list.

Lenses the bundled database lacks can be measured in-house: /api/lens-profiles
stores calibrations in SQLite, the Optics panel edits them and marks them
"Team", and search treats them as ordinary entries.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-28 05:49:47 +00:00
parent 16456c3c69
commit 749047ae9e
13 changed files with 1363 additions and 15 deletions
+510
View File
@@ -0,0 +1,510 @@
import { useEffect, useState } from 'react';
import {
deleteTeamProfile,
loadTeamProfiles,
saveTeamProfile,
type TeamLensDraft,
type TeamLensProfile,
} from '../lib/lensProfiles';
import type { LensProfile, PhotoRecord } from '../types';
/**
* Calibrations the team measured for lenses the bundled database lacks. The
* numbers are stored on the server next to the bundled data, so everyone's
* editor and exports pick them up.
*/
interface Props {
photo: PhotoRecord;
/** Profile currently applied, used to prefill the form. */
profile?: LensProfile;
onClose: () => void;
/** Apply a saved calibration to the photo on screen. */
onUse: (profile: TeamLensProfile) => void;
}
const DISTORTION_MODEL_ID = { poly3: 0, poly5: 1, ptlens: 2 } as const;
const DISTORTION_MODEL_NAME = { 0: 'poly3', 1: 'poly5', 2: 'ptlens' } as const;
const TCA_MODEL_ID = { poly3: 0, linear: 1 } as const;
const TCA_MODEL_NAME = { 0: 'poly3', 1: 'linear' } as const;
type DistortionModel = keyof typeof DISTORTION_MODEL_ID;
type TcaModel = keyof typeof TCA_MODEL_ID;
interface DistortionRow {
focal: string;
model: DistortionModel;
a: string;
b: string;
c: string;
}
interface TcaRow {
focal: string;
model: TcaModel;
br: string;
cr: string;
vr: string;
bb: string;
cb: string;
vb: string;
}
interface VignettingRow {
focal: string;
aperture: string;
distance: string;
k1: string;
k2: string;
k3: string;
}
interface Draft {
id?: string;
maker: string;
model: string;
mount: string;
crop: string;
notes: string;
d: DistortionRow[];
t: TcaRow[];
v: VignettingRow[];
}
const num = (value: string) => (value.trim() === '' ? 0 : Number(value));
const text = (value: number) => (Number.isFinite(value) && value !== 0 ? String(value) : '');
function toDraft(profile: TeamLensProfile): Draft {
return {
id: profile.id,
maker: profile.maker,
model: profile.model,
mount: profile.mount,
crop: String(profile.crop),
notes: profile.notes,
d: profile.d.map(([focal, model, a, b, c]) => ({
focal: String(focal),
model: DISTORTION_MODEL_NAME[model as 0 | 1 | 2] ?? 'poly3',
a: text(a),
b: text(b),
c: text(c),
})),
t: profile.t.map(([focal, model, br, cr, vr, bb, cb, vb]) => ({
focal: String(focal),
model: TCA_MODEL_NAME[model as 0 | 1] ?? 'poly3',
br: text(br),
cr: text(cr),
vr: text(vr),
bb: text(bb),
cb: text(cb),
vb: text(vb),
})),
v: profile.v.map(([focal, aperture, distance, k1, k2, k3]) => ({
focal: String(focal),
aperture: String(aperture),
distance: text(distance),
k1: text(k1),
k2: text(k2),
k3: text(k3),
})),
};
}
function toPayload(draft: Draft): TeamLensDraft {
const focal = draft.d.find((row) => row.focal.trim())?.focal;
return {
id: draft.id,
maker: draft.maker.trim(),
model: draft.model.trim(),
mount: draft.mount.trim(),
crop: num(draft.crop) || 1,
aspect: 0,
centerX: 0,
centerY: 0,
notes: draft.notes.trim(),
d: draft.d
.filter((row) => row.focal.trim())
.map((row) => [
num(row.focal),
DISTORTION_MODEL_ID[row.model],
num(row.a),
num(row.b),
num(row.c),
0,
]),
t: draft.t
.filter((row) => row.focal.trim())
.map((row) => [
num(row.focal),
TCA_MODEL_ID[row.model],
num(row.br),
num(row.cr),
num(row.vr),
num(row.bb),
num(row.cb),
num(row.vb),
]),
v: draft.v
.filter((row) => row.focal.trim())
.map((row) => [
num(row.focal),
num(row.aperture),
num(row.distance) || 1000,
num(row.k1),
num(row.k2),
num(row.k3),
]),
};
}
const sampleCounts = (profile: TeamLensProfile) =>
[
profile.d.length ? `${profile.d.length} distortion` : '',
profile.t.length ? `${profile.t.length} CA` : '',
profile.v.length ? `${profile.v.length} vignetting` : '',
]
.filter(Boolean)
.join(' · ') || 'no samples';
export default function LensCalibrationModal({ photo, profile, onClose, onUse }: Props) {
const [profiles, setProfiles] = useState<TeamLensProfile[] | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const blank = (): Draft => ({
maker: profile?.maker ?? '',
model: profile?.model ?? photo.meta?.lens ?? '',
mount: '',
crop: String(profile?.crop ?? 1),
notes: '',
d: [
{
focal: photo.meta?.focal ? String(photo.meta.focal) : '',
model: 'ptlens',
a: '',
b: '',
c: '',
},
],
t: [],
v: [],
});
useEffect(() => {
let alive = true;
loadTeamProfiles(true)
.then((saved) => alive && setProfiles(saved))
.catch((err) => {
if (!alive) return;
setProfiles([]);
setError(err instanceof Error ? err.message : 'Could not load the team calibrations');
});
return () => {
alive = false;
};
}, []);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const patch = (next: Partial<Draft>) => setDraft((current) => (current ? { ...current, ...next } : current));
const patchRow = <K extends 'd' | 't' | 'v'>(
key: K,
index: number,
patchValue: Partial<Draft[K][number]>,
) =>
setDraft((current) => {
if (!current) return current;
const rows = current[key].map((row, i) => (i === index ? { ...row, ...patchValue } : row));
return { ...current, [key]: rows } as Draft;
});
const addRow = (key: 'd' | 't' | 'v') =>
setDraft((current) => {
if (!current) return current;
const focal = photo.meta?.focal ? String(photo.meta.focal) : '';
const aperture = photo.meta?.aperture ? String(photo.meta.aperture) : '';
if (key === 'd') return { ...current, d: [...current.d, { focal, model: 'ptlens', a: '', b: '', c: '' }] };
if (key === 't') {
return {
...current,
t: [...current.t, { focal, model: 'poly3', br: '', cr: '', vr: '', bb: '', cb: '', vb: '' }],
};
}
return { ...current, v: [...current.v, { focal, aperture, distance: '1000', k1: '', k2: '', k3: '' }] };
});
const removeRow = (key: 'd' | 't' | 'v', index: number) =>
setDraft((current) => {
if (!current) return current;
return { ...current, [key]: current[key].filter((_, i) => i !== index) } as Draft;
});
const save = async () => {
if (!draft || busy) return;
setBusy(true);
setError(null);
try {
const saved = await saveTeamProfile(toPayload(draft));
setProfiles((current) =>
current
? [saved, ...current.filter((entry) => entry.id !== saved.id)]
: [saved],
);
setDraft(null);
onUse(saved);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not save the calibration');
} finally {
setBusy(false);
}
};
const remove = async (entry: TeamLensProfile) => {
if (busy) return;
if (!window.confirm(`Delete the team calibration for ${entry.maker} ${entry.model}?`)) return;
setBusy(true);
setError(null);
try {
await deleteTeamProfile(entry.id);
setProfiles((current) => current?.filter((saved) => saved.id !== entry.id) ?? []);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not delete the calibration');
} finally {
setBusy(false);
}
};
const field = (label: string, value: string, onChange: (value: string) => void, type = 'text') => (
<label className="lens-calib-field">
<span className="muted small">{label}</span>
<input
className="text-input"
type={type}
step="any"
value={value}
onChange={(event) => onChange(event.target.value)}
/>
</label>
);
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal lens-calib-modal">
<header className="modal-head">
<div>
<span className="settings-kicker">Team</span>
<h2>Lens calibrations</h2>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
✕
</button>
</header>
<div className="modal-body">
{draft ? (
<>
<p className="muted small lens-defaults-lead">
Enter the measurements from your calibration tool. Coefficients are used as measured:
distortion is a·r³ + b·r² + c·r + 1 for PanoTools, 1 + a·r² + b·r⁴ for poly5 and
1 + k₁·r² for poly3. Add a row per focal length you measured.
</p>
<div className="lens-calib-grid">
{field('Maker', draft.maker, (value) => patch({ maker: value }))}
{field('Model', draft.model, (value) => patch({ model: value }))}
{field('Mount', draft.mount, (value) => patch({ mount: value }))}
{field('Crop factor', draft.crop, (value) => patch({ crop: value }), 'number')}
</div>
{field('Notes', draft.notes, (value) => patch({ notes: value }))}
<section className="lens-calib-section">
<header>
<strong>Distortion</strong>
<button className="btn ghost tiny" onClick={() => addRow('d')}>
+ Sample
</button>
</header>
{draft.d.length === 0 && <p className="muted small">No distortion measured.</p>}
{draft.d.map((row, index) => (
<div className="lens-calib-row cols-distortion" key={index}>
{field('Focal mm', row.focal, (value) => patchRow('d', index, { focal: value }), 'number')}
<label className="lens-calib-field">
<span className="muted small">Model</span>
<select
className="text-input"
value={row.model}
onChange={(event) =>
patchRow('d', index, { model: event.target.value as DistortionModel })
}
>
<option value="ptlens">PanoTools</option>
<option value="poly3">poly3</option>
<option value="poly5">poly5</option>
</select>
</label>
{field('a', row.a, (value) => patchRow('d', index, { a: value }), 'number')}
{field('b', row.b, (value) => patchRow('d', index, { b: value }), 'number')}
{field('c', row.c, (value) => patchRow('d', index, { c: value }), 'number')}
<button
className="icon-btn"
title="Remove sample"
onClick={() => removeRow('d', index)}
>
✕
</button>
</div>
))}
</section>
<section className="lens-calib-section">
<header>
<strong>Chromatic aberration</strong>
<button className="btn ghost tiny" onClick={() => addRow('t')}>
+ Sample
</button>
</header>
{draft.t.length === 0 && <p className="muted small">No lateral CA measured.</p>}
{draft.t.map((row, index) => (
<div className="lens-calib-row cols-tca" key={index}>
{field('Focal mm', row.focal, (value) => patchRow('t', index, { focal: value }), 'number')}
<label className="lens-calib-field">
<span className="muted small">Model</span>
<select
className="text-input"
value={row.model}
onChange={(event) => patchRow('t', index, { model: event.target.value as TcaModel })}
>
<option value="poly3">poly3</option>
<option value="linear">linear</option>
</select>
</label>
{field('red b', row.br, (value) => patchRow('t', index, { br: value }), 'number')}
{field('red c', row.cr, (value) => patchRow('t', index, { cr: value }), 'number')}
{field('red v', row.vr, (value) => patchRow('t', index, { vr: value }), 'number')}
{field('blue b', row.bb, (value) => patchRow('t', index, { bb: value }), 'number')}
{field('blue c', row.cb, (value) => patchRow('t', index, { cb: value }), 'number')}
{field('blue v', row.vb, (value) => patchRow('t', index, { vb: value }), 'number')}
<button
className="icon-btn"
title="Remove sample"
onClick={() => removeRow('t', index)}
>
✕
</button>
</div>
))}
</section>
<section className="lens-calib-section">
<header>
<strong>Vignetting</strong>
<button className="btn ghost tiny" onClick={() => addRow('v')}>
+ Sample
</button>
</header>
{draft.v.length === 0 && <p className="muted small">No vignetting measured.</p>}
{draft.v.map((row, index) => (
<div className="lens-calib-row cols-vignetting" key={index}>
{field('Focal mm', row.focal, (value) => patchRow('v', index, { focal: value }), 'number')}
{field('Aperture', row.aperture, (value) => patchRow('v', index, { aperture: value }), 'number')}
{field('Distance', row.distance, (value) => patchRow('v', index, { distance: value }), 'number')}
{field('k₁', row.k1, (value) => patchRow('v', index, { k1: value }), 'number')}
{field('k₂', row.k2, (value) => patchRow('v', index, { k2: value }), 'number')}
{field('k₃', row.k3, (value) => patchRow('v', index, { k3: value }), 'number')}
<button
className="icon-btn"
title="Remove sample"
onClick={() => removeRow('v', index)}
>
✕
</button>
</div>
))}
</section>
</>
) : profiles === null ? (
<p className="muted small">Loading the team calibrations…</p>
) : (
<>
<p className="muted small lens-defaults-lead">
These are shared with everyone signed in to this library. The Optics panel finds them
by maker or model, next to the bundled profiles.
</p>
<div className="lens-defaults-list">
{profiles.length === 0 && (
<p className="muted small">No team calibrations yet — add the first one.</p>
)}
{profiles.map((entry) => (
<article className="lens-default-item" key={entry.id}>
<div className="lens-default-main">
<div className="lens-default-title">
<strong>
{entry.maker} {entry.model}
</strong>
<span className="muted small">crop {entry.crop}×</span>
</div>
<p className="lens-default-match">
{entry.mount || 'any mount'} <span className="muted small">· {sampleCounts(entry)}</span>
</p>
{entry.notes && <p className="muted small lens-default-meta">{entry.notes}</p>}
</div>
<div className="lens-default-actions">
<button className="btn ghost small" onClick={() => onUse(entry)}>
Use
</button>
<button className="btn ghost tiny" onClick={() => setDraft(toDraft(entry))}>
Edit
</button>
<button
className="btn ghost tiny"
disabled={busy}
onClick={() => void remove(entry)}
>
Delete
</button>
</div>
</article>
))}
</div>
</>
)}
{error && <p className="small lens-error">{error}</p>}
</div>
<footer className="modal-foot">
{draft ? (
<>
<button className="btn ghost" onClick={() => setDraft(null)} disabled={busy}>
Cancel
</button>
<button className="btn primary" onClick={() => void save()} disabled={busy}>
{busy ? 'Saving…' : draft.id ? 'Save calibration' : 'Add calibration'}
</button>
</>
) : (
<>
<button className="btn ghost" onClick={onClose}>
Done
</button>
<button className="btn primary" onClick={() => setDraft(blank())} disabled={busy}>
New calibration
</button>
</>
)}
</footer>
</div>
</div>
);
}
+23 -1
View File
@@ -46,6 +46,8 @@ import {
} from '../lib/lensDefaults';
import type { LensProfile } from '../types';
import LensDefaultsModal from './LensDefaultsModal';
import LensCalibrationModal from './LensCalibrationModal';
import { TEAM_PREFIX } from '../lib/lensProfiles';
import Slider from './Slider';
export function Panel({
@@ -1874,6 +1876,7 @@ export function OpticsPanel({
const [available, setAvailable] = useState<number | null>(null);
const [defaultProfile, setDefaultProfile] = useState<CameraLensDefault | null>(null);
const [defaultsOpen, setDefaultsOpen] = useState(false);
const [calibrationOpen, setCalibrationOpen] = useState(false);
const patch = (next: Partial<Edits['geometry']>, label: string) =>
set({ geometry: { ...geometry, ...next } }, label);
@@ -2054,7 +2057,7 @@ export function OpticsPanel({
>
<span>{result.model}</span>
<span className="muted small">
{result.maker} · {result.crop}×
{result.maker} · {result.crop}×{result.team ? ' · Team' : ''}
</span>
</button>
))}
@@ -2082,6 +2085,9 @@ export function OpticsPanel({
</div>
)}
<div className="lens-default-manage">
<button className="btn ghost tiny" onClick={() => setCalibrationOpen(true)}>
Team calibrations
</button>
<button className="btn ghost tiny" onClick={() => setDefaultsOpen(true)}>
Manage saved defaults
</button>
@@ -2174,6 +2180,22 @@ export function OpticsPanel({
onChanged={refreshDefault}
/>
)}
{calibrationOpen && (
<LensCalibrationModal
photo={photo}
profile={profile}
onClose={() => setCalibrationOpen(false)}
onUse={(saved) => {
applyProfile({
id: `${TEAM_PREFIX}${saved.id}`,
maker: saved.maker,
model: saved.model,
crop: saved.crop,
});
setCalibrationOpen(false);
}}
/>
)}
</>
);
}
+1 -1
View File
@@ -39,7 +39,7 @@ export class ApiError extends Error {
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(path, { credentials: 'same-origin', ...init });
+150 -4
View File
@@ -1,6 +1,14 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { availableFor, findCamera, findLensForMeta, searchLens, type LensDatabase } from './lensDb';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import {
availableFor,
findCamera,
findLensForMeta,
getLensEntry,
searchLens,
type LensDatabase,
} from './lensDb';
import { fixtureLenses } from './lensEngine.fixture';
import { invalidateTeamProfiles, type TeamLensProfile } from './lensProfiles';
import type { LensProfile } from '../types';
/**
@@ -11,10 +19,11 @@ import type { LensProfile } from '../types';
const database: LensDatabase = {
source: { project: 'lensfun', commit: 'test', licence: 'CC BY-SA 3.0', note: '' },
models: { distortion: ['poly3', 'poly5', 'ptlens', 'linear', 'acm'], tca: ['poly3', 'linear', 'acm'] },
mounts: ['Nikon F AF', 'Canon EF', 'Canon EF-M'],
mounts: ['Nikon F AF', 'Canon EF', 'Canon EF-M', 'Canon EF-S', 'Sony E'],
cameras: [
{ maker: 'Nikon Corporation', model: 'Nikon D700', mount: 'Nikon F AF', crop: 1 },
{ maker: 'Canon', model: 'Canon EOS R5', mount: 'Canon EF', crop: 1 },
{ maker: 'Canon', model: 'Canon EOS 60D', mount: 'Canon EF-S', crop: 1.62 },
],
lenses: [
...fixtureLenses,
@@ -31,11 +40,75 @@ const database: LensDatabase = {
t: [],
v: [],
},
{
id: 'canon-ef-75-300',
maker: 'Canon',
model: 'Canon EF 75-300mm f/4-5.6 III USM',
crop: 1,
mounts: ['Canon EF'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[75, 2, 0.01, -0.02, 0.03, 0]],
t: [[75, 0, 0.001, 0, 0, 0.001, 0, 0]],
v: [],
},
{
id: 'canon-ef-s-17-85',
maker: 'Canon',
model: 'Canon EF-S 17-85mm f/4-5.6 IS USM',
crop: 1.6,
mounts: ['Canon EF-S'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[17, 0, 0, -0.03, 0, 0]],
t: [],
v: [],
},
{
id: 'tamron-11-20-sony',
maker: 'Tamron',
model: 'Tamron E 11-20mm F2.8',
crop: 1,
mounts: ['Sony E'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[11, 0, 0, -0.02, 0, 0]],
t: [],
v: [],
},
{
id: 'tamron-11-20-canon',
maker: 'Tamron',
model: 'Tamron 11-20mm F2.8 Di III-A',
crop: 1,
mounts: ['Canon EF'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[11, 0, 0, -0.02, 0, 0]],
t: [],
v: [],
},
],
};
/** Calibrations the team stored on the server; filled by the merge test. */
const teamProfiles: TeamLensProfile[] = [];
beforeAll(() => {
vi.stubGlobal('fetch', async () => new Response(JSON.stringify(database), { status: 200 }));
vi.stubGlobal('fetch', async (input: RequestInfo | URL) => {
const url = String(input);
const body = url.includes('/api/lens-profiles') ? { profiles: teamProfiles } : database;
return new Response(JSON.stringify(body), { status: 200 });
});
});
afterEach(() => {
teamProfiles.length = 0;
invalidateTeamProfiles();
});
describe('lens search', () => {
@@ -58,6 +131,28 @@ describe('lens search', () => {
expect(match?.maker).toBe('Tamron');
});
it('matches EXIF names that fold the brand into the focal range', async () => {
const match = await findLensForMeta({
camera: 'Canon Canon EOS 60D',
lens: 'EF75-300mm f/4-5.6 USM',
});
expect(match?.model).toContain('75-300');
expect(match?.model).not.toContain('17-85');
});
it('does not guess a profile from a weak name match', async () => {
// Nothing in the fixture shares the focal range or the brand, so despite
// overlapping aperture tokens the auto-match must decline.
const meta = { camera: 'Canon Canon EOS 60D', lens: 'Sigma 18-35mm f/1.8 DC HSM' };
expect(await findLensForMeta(meta)).toBeNull();
expect((await searchLens(meta.lens, meta)).length).toBe(0);
});
it('ranks a lens from the same mount family first', async () => {
const results = await searchLens('tamron 11-20', { camera: 'Canon Canon EOS 60D' });
expect(results[0]?.model).toBe('Tamron 11-20mm F2.8 Di III-A');
});
it('returns nothing for a name that is not in the database', async () => {
expect(await searchLens('zzzz nonexistent lens')).toEqual([]);
expect(await searchLens('')).toEqual([]);
@@ -77,6 +172,57 @@ describe('camera lookup', () => {
});
});
describe('team calibrations', () => {
const measured: TeamLensProfile = {
id: 'team-1',
maker: 'Sigma',
model: 'Sigma 24-70mm f/2.8 DG DN Art',
mount: 'Canon EF',
crop: 1,
aspect: 0,
centerX: 0,
centerY: 0,
notes: 'measured on a 5D',
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
t: [],
v: [],
createdBy: 'user-1',
createdAt: 1,
updatedAt: 1,
};
it('is found by a search and marked as the team\u2019s own', async () => {
teamProfiles.push(measured);
invalidateTeamProfiles();
const results = await searchLens('sigma 24-70');
const match = results.find((result) => result.team);
expect(match).toMatchObject({ id: 'team:team-1', maker: 'Sigma' });
});
it('resolves a stored profile by its team id', async () => {
teamProfiles.push(measured);
invalidateTeamProfiles();
const entry = await getLensEntry({
id: 'team:team-1',
maker: 'Sigma',
model: 'Sigma 24-70mm f/2.8 DG DN Art',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
});
expect(entry?.id).toBe('team:team-1');
// Only distortion was measured, so the panel must offer only that.
expect(
await availableFor({
id: 'team:team-1',
maker: 'Sigma',
model: 'Sigma 24-70mm f/2.8 DG DN Art',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
}),
).toBe(8);
});
});
describe('availability', () => {
it('reports which corrections a profile supports', async () => {
const [tamron] = fixtureLenses;
+53 -8
View File
@@ -1,3 +1,4 @@
import { TEAM_PREFIX, loadTeamProfiles, teamProfileToEntry } from './lensProfiles';
import type { LensProfile, PhotoMeta } from '../types';
/**
@@ -35,6 +36,8 @@ export interface LensEntry {
d: DistortionSample[];
t: TcaSample[];
v: VignettingSample[];
/** Set for a calibration the team stored on the server, not the bundle. */
team?: boolean;
}
export interface CameraEntry {
@@ -68,6 +71,8 @@ export interface LensSearchResult {
score: number;
/** Bit mask of the corrections the calibration supports. */
available: number;
/** True when the profile came from the team's own calibrations. */
team?: boolean;
}
export const FLAG_TCA = 1;
@@ -76,6 +81,19 @@ export const FLAG_DISTORTION = 8;
let databasePromise: Promise<LensDatabase> | null = null;
/**
* Team calibrations are additive and optional: a signed-out or offline browser
* still gets the bundled database, so a failed request is not an error.
*/
async function loadTeamEntries(): Promise<LensEntry[]> {
try {
const profiles = await loadTeamProfiles();
return profiles.map(teamProfileToEntry);
} catch {
return [];
}
}
export function loadLensDatabase(): Promise<LensDatabase> {
if (!databasePromise) {
databasePromise = fetch('/lens-db/profiles.json')
@@ -108,6 +126,7 @@ export function toResult(entry: LensEntry, score = 0): LensSearchResult {
crop: entry.crop,
score,
available: availableFlags(entry),
team: entry.team,
};
}
@@ -157,7 +176,18 @@ function queryVariants(query: string): string[] {
const raw = query.trim();
if (raw.length < 2) return [];
const compact = raw.replace(/(\d)\s*mm\b/gi, '$1mm').replace(/\s+/g, ' ');
return [...new Set([raw, compact, compact.replace(/\s+/g, '')])].filter((text) => text.length >= 2);
// EXIF folds the brand into the focal range ("EF75-300mm", "SEL2870", "RF24-105mm");
// splitting letters from digits lets "ef 75" meet "EF 75-300mm".
const split = compact.replace(/([a-z])(\d)/gi, '$1 $2');
return [...new Set([raw, compact, compact.replace(/\s+/g, ''), split])].filter(
(text) => text.length >= 2,
);
}
/** "Canon EF" and "Canon EF-S" are one family when ranking fits. */
function sameMountFamily(a: string, b: string) {
const family = (mount: string) => mount.trim().split(/\s+/)[0] ?? '';
return family(a) !== '' && family(a) === family(b);
}
/* ------------------------------------------------------------------- queries */
@@ -171,17 +201,26 @@ export async function searchLens(
const db = await loadLensDatabase();
const camera = await findCamera(meta?.camera);
const mount = camera?.mount ?? '';
const scored: { entry: LensEntry; score: number }[] = [];
for (const entry of db.lenses) {
const scored: { entry: LensEntry; score: number; rank: number }[] = [];
for (const entry of [...db.lenses, ...(await loadTeamEntries())]) {
const score = scoreEntry(entry, variants);
if (score < 0.5) continue;
// A mount the camera actually uses is a tie-break, never a filter: a
// profile that is in the database but filed under another mount must still
// be findable.
const fits = mount && entry.mounts.includes(mount) ? 0.3 : 0;
scored.push({ entry, score: score + fits });
// be findable. A crop Canon body lists Canon EF-S, so EF glass (and the
// third-party lenses filed under it) only gets the family bonus.
const fits = !mount
? 0
: entry.mounts.includes(mount)
? 0.3
: entry.mounts.some((other) => sameMountFamily(other, mount))
? 0.1
: 0;
// `score` stays a pure name score so callers can trust a threshold;
// `rank` is what orders the list.
scored.push({ entry, score, rank: score + fits });
}
scored.sort((a, b) => b.score - a.score || a.entry.model.length - b.entry.model.length);
scored.sort((a, b) => b.rank - a.rank || a.entry.model.length - b.entry.model.length);
return scored.slice(0, 20).map(({ entry, score }) => toResult(entry, Math.min(3, score)));
}
@@ -190,7 +229,9 @@ export async function findLensForMeta(
): Promise<LensSearchResult | null> {
if (!meta.lens) return null;
const results = await searchLens(meta.lens, meta);
return results.find((result) => result.score >= 0.75) ?? results[0] ?? null;
// Applying the wrong profile is worse than applying none: the closest match
// must share most of the EXIF name, not merely outrank the alternatives.
return results.find((result) => result.score >= 0.75) ?? null;
}
const cameraCache = new Map<string, CameraMatch | null>();
@@ -228,6 +269,10 @@ export async function findCamera(camera?: string): Promise<CameraMatch | null> {
export async function getLensEntry(profile: LensProfile): Promise<LensEntry | null> {
const db = await loadLensDatabase();
if (profile.id) {
if (profile.id.startsWith(TEAM_PREFIX)) {
const team = (await loadTeamEntries()).find((entry) => entry.id === profile.id);
if (team) return team;
}
const byId = db.lenses.find((entry) => entry.id === profile.id);
if (byId) return byId;
}
+98
View File
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
TEAM_PREFIX,
deleteTeamProfile,
invalidateTeamProfiles,
loadTeamProfiles,
saveTeamProfile,
teamProfileToEntry,
type TeamLensProfile,
} from './lensProfiles';
const profile: TeamLensProfile = {
id: 'abc-123',
maker: 'Tamron',
model: 'SP 24-70mm f/2.8 Di VC USD',
mount: 'Canon EF',
crop: 1,
aspect: 0,
centerX: 0,
centerY: 0,
notes: '',
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
t: [],
v: [],
createdBy: 'user-1',
createdAt: 1,
updatedAt: 1,
};
let calls: { url: string; method: string }[] = [];
function stubFetch(handler: (url: string, init?: RequestInit) => unknown) {
vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
calls.push({ url, method: init?.method ?? 'GET' });
return new Response(JSON.stringify(handler(url, init)), { status: 200 });
});
}
beforeEach(() => {
calls = [];
invalidateTeamProfiles();
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('team lens profiles', () => {
it('loads the list once and caches it', async () => {
stubFetch(() => ({ profiles: [profile] }));
const first = await loadTeamProfiles();
const second = await loadTeamProfiles();
expect(first).toHaveLength(1);
expect(second).toBe(first);
expect(calls.filter((call) => call.url === '/api/lens-profiles')).toHaveLength(1);
});
it('turns a saved profile into an entry the engine can use', () => {
const entry = teamProfileToEntry(profile);
expect(entry).toMatchObject({
id: `${TEAM_PREFIX}abc-123`,
maker: 'Tamron',
mounts: ['Canon EF'],
crop: 1,
team: true,
});
expect(entry.d).toHaveLength(1);
});
it('posts a new profile and drops the cached list', async () => {
stubFetch((url, init) => {
if (url === '/api/lens-profiles' && init?.method === 'POST') return { profile };
return { profiles: [profile] };
});
await loadTeamProfiles();
const { id: _id, createdBy: _by, createdAt: _at, updatedAt: _up, ...draft } = profile;
const saved = await saveTeamProfile(draft);
expect(saved.id).toBe('abc-123');
const post = calls.find((call) => call.method === 'POST');
expect(post?.url).toBe('/api/lens-profiles');
// The next read must go back to the server rather than the pre-save cache.
await loadTeamProfiles();
expect(calls.filter((call) => call.method === 'GET').length).toBe(2);
});
it('updates an existing profile with PUT to its id', async () => {
stubFetch(() => ({ profile }));
await saveTeamProfile({ ...profile, notes: 're-measured' });
expect(calls[0]).toEqual({ url: '/api/lens-profiles/abc-123', method: 'PUT' });
});
it('deletes by id', async () => {
stubFetch(() => ({ ok: true }));
await deleteTeamProfile('abc-123');
expect(calls[0]).toEqual({ url: '/api/lens-profiles/abc-123', method: 'DELETE' });
});
});
+90
View File
@@ -0,0 +1,90 @@
import { request } from './api';
import type { DistortionSample, LensEntry, TcaSample, VignettingSample } from './lensDb';
/**
* Lens calibrations measured by the team and stored on the server, so a lens
* the bundled database lacks can still be corrected for everyone. The rows use
* the same layout as the bundled profiles, which keeps one engine for both.
*/
/** Profile ids from this table carry this prefix so lookups know where to go. */
export const TEAM_PREFIX = 'team:';
export interface TeamLensProfile {
id: string;
maker: string;
model: string;
/** Mount the calibration was measured on; empty when the lens fits many. */
mount: string;
crop: number;
/** Calibration sensor aspect ratio, 0 when not recorded. */
aspect: number;
centerX: number;
centerY: number;
notes: string;
d: DistortionSample[];
t: TcaSample[];
v: VignettingSample[];
createdBy: string;
createdAt: number;
updatedAt: number;
}
export type TeamLensDraft = Pick<
TeamLensProfile,
'maker' | 'model' | 'mount' | 'crop' | 'aspect' | 'centerX' | 'centerY' | 'notes' | 'd' | 't' | 'v'
> & { id?: string };
let cache: Promise<TeamLensProfile[]> | null = null;
/** The team's calibrations, fetched once per session unless forced. */
export function loadTeamProfiles(force = false): Promise<TeamLensProfile[]> {
if (!cache || force) {
cache = request<{ profiles: TeamLensProfile[] }>('/api/lens-profiles')
.then((body) => (Array.isArray(body.profiles) ? body.profiles : []))
.catch((err) => {
cache = null;
throw err;
});
}
return cache;
}
/** Drop the cached list after a save or delete. */
export function invalidateTeamProfiles(): void {
cache = null;
}
export function teamProfileToEntry(profile: TeamLensProfile): LensEntry {
return {
id: `${TEAM_PREFIX}${profile.id}`,
maker: profile.maker,
model: profile.model,
crop: profile.crop,
mounts: profile.mount ? [profile.mount] : [],
aspect: profile.aspect,
centerX: profile.centerX,
centerY: profile.centerY,
d: profile.d,
t: profile.t,
v: profile.v,
team: true,
};
}
export async function saveTeamProfile(draft: TeamLensDraft): Promise<TeamLensProfile> {
const init: RequestInit = {
method: draft.id ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(draft),
};
const path = draft.id ? `/api/lens-profiles/${encodeURIComponent(draft.id)}` : '/api/lens-profiles';
const saved = await request<{ profile: TeamLensProfile }>(path, init);
invalidateTeamProfiles();
return saved.profile;
}
export async function deleteTeamProfile(id: string): Promise<void> {
await request(`/api/lens-profiles/${encodeURIComponent(id)}`, { method: 'DELETE' });
invalidateTeamProfiles();
}
+66
View File
@@ -4844,6 +4844,7 @@ figcaption {
.lens-default-manage {
display: flex;
justify-content: flex-end;
gap: 4px;
margin-top: 4px;
}
@@ -4851,6 +4852,71 @@ figcaption {
width: min(640px, 100%);
}
/* Team-calibrated lens profiles */
.lens-calib-modal {
width: min(880px, 100%);
}
.lens-calib-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 8px;
margin-bottom: 8px;
}
.lens-calib-field {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
}
.lens-calib-field .text-input {
width: 100%;
}
.lens-calib-section {
margin-top: 14px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel-2);
}
.lens-calib-section > header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.lens-calib-row {
display: grid;
gap: 6px;
align-items: end;
margin-top: 6px;
}
.lens-calib-row.cols-distortion {
grid-template-columns: 90px 130px repeat(3, minmax(0, 1fr)) 28px;
}
.lens-calib-row.cols-tca {
grid-template-columns: 90px 110px repeat(6, minmax(0, 1fr)) 28px;
}
.lens-calib-row.cols-vignetting {
grid-template-columns: 90px 90px 100px repeat(3, minmax(0, 1fr)) 28px;
}
.lens-default-actions {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.settings-kicker {
display: block;
margin-bottom: 3px;