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
+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();
}