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:
@@ -204,6 +204,25 @@ db.exec(`
|
||||
prune_notified_at INTEGER,
|
||||
last_quota_email_at INTEGER
|
||||
);
|
||||
|
||||
/* Lens calibrations measured by the team, alongside the bundled database. */
|
||||
CREATE TABLE IF NOT EXISTS lens_profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
maker TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
mount TEXT NOT NULL DEFAULT '',
|
||||
crop REAL NOT NULL DEFAULT 1,
|
||||
aspect REAL NOT NULL DEFAULT 0,
|
||||
center_x REAL NOT NULL DEFAULT 0,
|
||||
center_y REAL NOT NULL DEFAULT 0,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
data TEXT NOT NULL,
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS lens_profiles_updated ON lens_profiles(updated_at);
|
||||
`);
|
||||
|
||||
/* Databases created before account disabling existed get the column in place. */
|
||||
@@ -544,6 +563,28 @@ const q = {
|
||||
kvSet: db.prepare(
|
||||
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
||||
),
|
||||
|
||||
allLensProfiles: db.prepare(
|
||||
'SELECT * FROM lens_profiles ORDER BY maker COLLATE NOCASE ASC, model COLLATE NOCASE ASC',
|
||||
),
|
||||
lensProfile: db.prepare('SELECT * FROM lens_profiles WHERE id = ?'),
|
||||
upsertLensProfile: db.prepare(`
|
||||
INSERT INTO lens_profiles
|
||||
(id, maker, model, mount, crop, aspect, center_x, center_y, notes, data, created_by, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
maker = excluded.maker,
|
||||
model = excluded.model,
|
||||
mount = excluded.mount,
|
||||
crop = excluded.crop,
|
||||
aspect = excluded.aspect,
|
||||
center_x = excluded.center_x,
|
||||
center_y = excluded.center_y,
|
||||
notes = excluded.notes,
|
||||
data = excluded.data,
|
||||
updated_at = excluded.updated_at
|
||||
`),
|
||||
deleteLensProfile: db.prepare('DELETE FROM lens_profiles WHERE id = ?'),
|
||||
};
|
||||
|
||||
function parse(json) {
|
||||
@@ -1113,3 +1154,52 @@ export const kv = {
|
||||
},
|
||||
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
|
||||
};
|
||||
|
||||
function lensProfileFromRow(row) {
|
||||
const data = parse(row.data) ?? {};
|
||||
return {
|
||||
id: row.id,
|
||||
maker: row.maker,
|
||||
model: row.model,
|
||||
mount: row.mount,
|
||||
crop: Number(row.crop),
|
||||
aspect: Number(row.aspect),
|
||||
centerX: Number(row.center_x),
|
||||
centerY: Number(row.center_y),
|
||||
notes: row.notes,
|
||||
d: Array.isArray(data.d) ? data.d : [],
|
||||
t: Array.isArray(data.t) ? data.t : [],
|
||||
v: Array.isArray(data.v) ? data.v : [],
|
||||
createdBy: row.created_by,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** Team-measured calibrations, shared by every signed-in member. */
|
||||
export const lensProfiles = {
|
||||
list: () => q.allLensProfiles.all().map(lensProfileFromRow),
|
||||
get: (id) => {
|
||||
const row = q.lensProfile.get(String(id));
|
||||
return row ? lensProfileFromRow(row) : null;
|
||||
},
|
||||
save: (record) => {
|
||||
q.upsertLensProfile.run(
|
||||
record.id,
|
||||
record.maker,
|
||||
record.model,
|
||||
record.mount ?? '',
|
||||
Number(record.crop ?? 1),
|
||||
Number(record.aspect ?? 0),
|
||||
Number(record.centerX ?? 0),
|
||||
Number(record.centerY ?? 0),
|
||||
record.notes ?? '',
|
||||
JSON.stringify({ d: record.d ?? [], t: record.t ?? [], v: record.v ?? [] }),
|
||||
record.createdBy ?? '',
|
||||
record.createdAt ?? Date.now(),
|
||||
record.updatedAt ?? Date.now(),
|
||||
);
|
||||
return lensProfiles.get(record.id);
|
||||
},
|
||||
remove: (id) => q.deleteLensProfile.run(String(id)).changes > 0,
|
||||
};
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
getPhoto,
|
||||
invites,
|
||||
kv,
|
||||
lensProfiles,
|
||||
listEvents,
|
||||
listPhotos,
|
||||
livePhotoBytes,
|
||||
@@ -89,6 +90,7 @@ import {
|
||||
} from './bridge.mjs';
|
||||
import { cameraThumb16, jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
|
||||
import { createZip } from './zip.mjs';
|
||||
import { parseCalibration } from './lensCalibration.mjs';
|
||||
import {
|
||||
cancelPrune,
|
||||
quotaState,
|
||||
@@ -1858,6 +1860,68 @@ route('PUT', '/api/presets', async ({ req, res }) => {
|
||||
json(res, 200, { ok: true });
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------- team lens calibrations */
|
||||
|
||||
route('GET', '/api/lens-profiles', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
json(res, 200, { profiles: lensProfiles.list() });
|
||||
});
|
||||
|
||||
route('POST', '/api/lens-profiles', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
const body = await readJson(req, 256 * 1024);
|
||||
const parsed = parseCalibration(body);
|
||||
if (parsed.error) return error(res, 400, parsed.error);
|
||||
const now = Date.now();
|
||||
const profile = lensProfiles.save({
|
||||
...parsed.value,
|
||||
id: crypto.randomUUID(),
|
||||
createdBy: user.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
json(res, 201, { profile });
|
||||
});
|
||||
|
||||
/** Any member can read the team's calibrations; the author or an admin edits them. */
|
||||
function editableProfile(id, user) {
|
||||
const profile = lensProfiles.get(id);
|
||||
if (!profile) return { status: 404, message: 'No such lens profile' };
|
||||
if (profile.createdBy !== user.id && user.role !== 'admin') {
|
||||
return { status: 403, message: 'Only the member who added this profile or an admin can change it' };
|
||||
}
|
||||
return { profile };
|
||||
}
|
||||
|
||||
route('PUT', '/api/lens-profiles/:id', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
const found = editableProfile(params.id, user);
|
||||
if (found.status) return error(res, found.status, found.message);
|
||||
const body = await readJson(req, 256 * 1024);
|
||||
const parsed = parseCalibration(body);
|
||||
if (parsed.error) return error(res, 400, parsed.error);
|
||||
const profile = lensProfiles.save({
|
||||
...parsed.value,
|
||||
id: found.profile.id,
|
||||
createdBy: found.profile.createdBy,
|
||||
createdAt: found.profile.createdAt,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
json(res, 200, { profile });
|
||||
});
|
||||
|
||||
route('DELETE', '/api/lens-profiles/:id', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
const found = editableProfile(params.id, user);
|
||||
if (found.status) return error(res, found.status, found.message);
|
||||
lensProfiles.remove(found.profile.id);
|
||||
json(res, 200, { ok: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Store the original file. Raw files are demosaiced here so every browser can
|
||||
* edit them; ordinary images are kept byte-for-byte and previewed client-side.
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Validation for team-measured lens calibrations.
|
||||
*
|
||||
* A profile carries the same sample rows the bundled Lensfun database uses, so
|
||||
* the correction engine can read both without a second code path:
|
||||
*
|
||||
* d: [focal, model, a, b, c, realFocal] distortion
|
||||
* t: [focal, model, br, cr, vr, bb, cb, vb] lateral chromatic aberration
|
||||
* v: [focal, aperture, distance, k1, k2, k3] vignetting
|
||||
*
|
||||
* Coefficients are entered as measured: the engine rescales them by focal and
|
||||
* sensor size exactly as it does for the bundled data.
|
||||
*/
|
||||
|
||||
const MAX_DISTORTION = 60;
|
||||
const MAX_TCA = 60;
|
||||
const MAX_VIGNETTING = 120;
|
||||
const MAX_COEFFICIENT = 100;
|
||||
|
||||
const DISTORTION_MODELS = [0, 1, 2]; // poly3, poly5, ptlens
|
||||
const TCA_MODELS = [0, 1]; // poly3, linear
|
||||
|
||||
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||
const clampText = (value, max) =>
|
||||
typeof value === 'string' ? value.trim().replace(/\s+/g, ' ').slice(0, max) : '';
|
||||
|
||||
function row(values, count) {
|
||||
if (!Array.isArray(values) || values.length !== count) return null;
|
||||
const numbers = values.map((value) => (typeof value === 'number' ? value : Number(value)));
|
||||
return numbers.every(finite) ? numbers : null;
|
||||
}
|
||||
|
||||
function distortionRows(input) {
|
||||
if (input === undefined) return { rows: [] };
|
||||
if (!Array.isArray(input)) return { error: 'Distortion samples must be a list' };
|
||||
if (input.length > MAX_DISTORTION) return { error: `At most ${MAX_DISTORTION} distortion samples` };
|
||||
const rows = [];
|
||||
for (const entry of input) {
|
||||
const values = row(entry, 6);
|
||||
if (!values) return { error: 'Each distortion sample needs 6 numbers' };
|
||||
const [focal, model, a, b, c, realFocal] = values;
|
||||
if (!(focal > 0)) return { error: 'Distortion samples need a focal length above zero' };
|
||||
if (!DISTORTION_MODELS.includes(model)) return { error: 'Unknown distortion model' };
|
||||
if ([a, b, c].some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
|
||||
return { error: 'Distortion coefficients look out of range' };
|
||||
}
|
||||
if (realFocal < 0 || realFocal > 2000) return { error: 'Real focal length looks out of range' };
|
||||
rows.push([focal, model, a, b, c, realFocal]);
|
||||
}
|
||||
return { rows };
|
||||
}
|
||||
|
||||
function tcaRows(input) {
|
||||
if (input === undefined) return { rows: [] };
|
||||
if (!Array.isArray(input)) return { error: 'Chromatic aberration samples must be a list' };
|
||||
if (input.length > MAX_TCA) return { error: `At most ${MAX_TCA} chromatic aberration samples` };
|
||||
const rows = [];
|
||||
for (const entry of input) {
|
||||
const values = row(entry, 8);
|
||||
if (!values) return { error: 'Each chromatic aberration sample needs 8 numbers' };
|
||||
const [focal, model] = values;
|
||||
if (!(focal > 0)) return { error: 'Chromatic aberration samples need a focal length above zero' };
|
||||
if (!TCA_MODELS.includes(model)) return { error: 'Unknown chromatic aberration model' };
|
||||
if (values.some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
|
||||
return { error: 'Chromatic aberration coefficients look out of range' };
|
||||
}
|
||||
rows.push(values);
|
||||
}
|
||||
return { rows };
|
||||
}
|
||||
|
||||
function vignettingRows(input) {
|
||||
if (input === undefined) return { rows: [] };
|
||||
if (!Array.isArray(input)) return { error: 'Vignetting samples must be a list' };
|
||||
if (input.length > MAX_VIGNETTING) return { error: `At most ${MAX_VIGNETTING} vignetting samples` };
|
||||
const rows = [];
|
||||
for (const entry of input) {
|
||||
const values = row(entry, 6);
|
||||
if (!values) return { error: 'Each vignetting sample needs 6 numbers' };
|
||||
const [focal, aperture, distance, k1, k2, k3] = values;
|
||||
if (!(focal > 0)) return { error: 'Vignetting samples need a focal length above zero' };
|
||||
if (!(aperture > 0)) return { error: 'Vignetting samples need an aperture above zero' };
|
||||
if (!(distance > 0)) return { error: 'Vignetting samples need a focus distance above zero' };
|
||||
if ([k1, k2, k3].some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
|
||||
return { error: 'Vignetting coefficients look out of range' };
|
||||
}
|
||||
rows.push(values);
|
||||
}
|
||||
return { rows };
|
||||
}
|
||||
|
||||
/** Returns `{ value }` for a valid body, or `{ error }` describing the first problem. */
|
||||
export function parseCalibration(body) {
|
||||
if (!body || typeof body !== 'object') return { error: 'Expected a lens profile' };
|
||||
const maker = clampText(body.maker, 80);
|
||||
const model = clampText(body.model, 120);
|
||||
if (!maker) return { error: 'Lens maker is required' };
|
||||
if (!model) return { error: 'Lens model is required' };
|
||||
|
||||
const crop = Number(body.crop);
|
||||
if (!(crop >= 0.5 && crop <= 3)) return { error: 'Crop factor must be between 0.5 and 3' };
|
||||
|
||||
const aspect = body.aspect === undefined || body.aspect === '' ? 0 : Number(body.aspect);
|
||||
if (!(aspect >= 0 && aspect <= 4)) return { error: 'Aspect ratio must be between 0 and 4' };
|
||||
|
||||
const centerX = body.centerX === undefined || body.centerX === '' ? 0 : Number(body.centerX);
|
||||
const centerY = body.centerY === undefined || body.centerY === '' ? 0 : Number(body.centerY);
|
||||
if (Math.abs(centerX) > 0.5 || Math.abs(centerY) > 0.5) {
|
||||
return { error: 'Lens centre offset must be between -0.5 and 0.5' };
|
||||
}
|
||||
|
||||
const distortion = distortionRows(body.d);
|
||||
if (distortion.error) return { error: distortion.error };
|
||||
const tca = tcaRows(body.t);
|
||||
if (tca.error) return { error: tca.error };
|
||||
const vignetting = vignettingRows(body.v);
|
||||
if (vignetting.error) return { error: vignetting.error };
|
||||
|
||||
if (!distortion.rows.length && !tca.rows.length && !vignetting.rows.length) {
|
||||
return { error: 'Add at least one distortion, chromatic aberration or vignetting sample' };
|
||||
}
|
||||
|
||||
return {
|
||||
value: {
|
||||
maker,
|
||||
model,
|
||||
mount: clampText(body.mount, 40),
|
||||
crop,
|
||||
aspect,
|
||||
centerX,
|
||||
centerY,
|
||||
notes: clampText(body.notes, 500),
|
||||
d: distortion.rows,
|
||||
t: tca.rows,
|
||||
v: vignetting.rows,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseCalibration } from './lensCalibration.mjs';
|
||||
|
||||
const base = {
|
||||
maker: 'Tamron',
|
||||
model: 'SP 24-70mm f/2.8 Di VC USD',
|
||||
mount: 'Canon EF',
|
||||
crop: 1,
|
||||
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
|
||||
};
|
||||
|
||||
describe('team lens calibration validation', () => {
|
||||
it('accepts a measured profile and normalises its text', () => {
|
||||
const result = parseCalibration({ ...base, maker: ' Tamron ', notes: ' shot on a 5D ' });
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.value).toMatchObject({
|
||||
maker: 'Tamron',
|
||||
model: 'SP 24-70mm f/2.8 Di VC USD',
|
||||
mount: 'Canon EF',
|
||||
crop: 1,
|
||||
notes: 'shot on a 5D',
|
||||
aspect: 0,
|
||||
centerX: 0,
|
||||
centerY: 0,
|
||||
});
|
||||
expect(result.value.d).toEqual([[24, 2, 0.01, -0.02, 0.03, 0]]);
|
||||
});
|
||||
|
||||
it('requires a maker and a model', () => {
|
||||
expect(parseCalibration({ ...base, maker: ' ' }).error).toMatch(/maker/i);
|
||||
expect(parseCalibration({ ...base, model: '' }).error).toMatch(/model/i);
|
||||
});
|
||||
|
||||
it('rejects unknown models and impossible focals', () => {
|
||||
expect(parseCalibration({ ...base, d: [[24, 7, 0.01, 0, 0, 0]] }).error).toMatch(/model/i);
|
||||
expect(parseCalibration({ ...base, d: [[0, 2, 0.01, 0, 0, 0]] }).error).toMatch(/focal/i);
|
||||
});
|
||||
|
||||
it('rejects a row with the wrong number of values', () => {
|
||||
expect(parseCalibration({ ...base, d: [[24, 2, 0.01]] }).error).toMatch(/6 numbers/);
|
||||
expect(parseCalibration({ ...base, t: [[24, 0, 0, 0]] }).error).toMatch(/8 numbers/);
|
||||
});
|
||||
|
||||
it('rejects a crop factor no lens has', () => {
|
||||
expect(parseCalibration({ ...base, crop: 0 }).error).toMatch(/crop/i);
|
||||
expect(parseCalibration({ ...base, crop: 9 }).error).toMatch(/crop/i);
|
||||
});
|
||||
|
||||
it('needs at least one sample of any kind', () => {
|
||||
expect(parseCalibration({ ...base, d: [] }).error).toMatch(/at least one/i);
|
||||
});
|
||||
|
||||
it('keeps vignetting samples that a measurement pass produced', () => {
|
||||
const result = parseCalibration({
|
||||
...base,
|
||||
d: [],
|
||||
v: [
|
||||
[24, 2.8, 1000, 0.31, -0.12, 0.02],
|
||||
[70, 2.8, 1000, 0.42, -0.2, 0.05],
|
||||
],
|
||||
});
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.value.v).toHaveLength(2);
|
||||
expect(result.value.d).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects vignetting without an aperture', () => {
|
||||
expect(parseCalibration({ ...base, d: [], v: [[24, 0, 1000, 0.3, 0, 0]] }).error).toMatch(/aperture/i);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user