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:
@@ -548,6 +548,10 @@ routes are public and are gated only by the share token.
|
|||||||
| GET | `/api/events/:id/tether/file?name=` | owner | Stream one waiting frame to the editor |
|
| GET | `/api/events/:id/tether/file?name=` | owner | Stream one waiting frame to the editor |
|
||||||
| DELETE | `/api/events/:id/tether/file?name=` | owner | Remove a frame after it imported |
|
| DELETE | `/api/events/:id/tether/file?name=` | owner | Remove a frame after it imported |
|
||||||
| PUT | `/api/presets` | session | Replace the stored preset library |
|
| PUT | `/api/presets` | session | Replace the stored preset library |
|
||||||
|
| GET | `/api/lens-profiles` | session | Team-measured lens calibrations, shared by every member |
|
||||||
|
| POST | `/api/lens-profiles` | session | Add a calibration; coefficient ranges and sample shapes are validated |
|
||||||
|
| PUT | `/api/lens-profiles/:id` | author or admin | Replace a calibration |
|
||||||
|
| DELETE | `/api/lens-profiles/:id` | author or admin | Remove a calibration |
|
||||||
| PUT | `/api/events/:id` | owner | Upsert an event record |
|
| PUT | `/api/events/:id` | owner | Upsert an event record |
|
||||||
| DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) |
|
| DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) |
|
||||||
| PUT | `/api/photos/:id` | owner | Upsert a photo record; accepts a data-URL thumbnail, which is written to `thumbs/` |
|
| PUT | `/api/photos/:id` | owner | Upsert a photo record; accepts a data-URL thumbnail, which is written to `thumbs/` |
|
||||||
@@ -923,6 +927,10 @@ pins the output against maps captured from the previous implementation.
|
|||||||
Luminary adds no profiles of its own.
|
Luminary adds no profiles of its own.
|
||||||
- **Engine** — `src/lib/lensDb.ts` (loading, matching, camera lookup) and
|
- **Engine** — `src/lib/lensDb.ts` (loading, matching, camera lookup) and
|
||||||
`src/lib/lensEngine.ts` (maps, auto-scale), both MIT like the rest of the app code.
|
`src/lib/lensEngine.ts` (maps, auto-scale), both MIT like the rest of the app code.
|
||||||
|
- **Team calibrations** — lenses the database lacks can be measured in-house and added
|
||||||
|
from the Optics panel (“Team calibrations”). They are stored in the server's SQLite
|
||||||
|
database (`lens_profiles`), searched next to the bundled profiles with the same sample
|
||||||
|
layout, and are Luminary's own data rather than Lensfun content.
|
||||||
- **Bundled files** — `public/lens-db/NOTICE.md` records the attribution and the pin;
|
- **Bundled files** — `public/lens-db/NOTICE.md` records the attribution and the pin;
|
||||||
`public/lens-db/profiles.json` carries the same provenance in its `source` field.
|
`public/lens-db/profiles.json` carries the same provenance in its `source` field.
|
||||||
|
|
||||||
@@ -930,7 +938,8 @@ See [Third-party attribution and licences](#third-party-attribution-and-licences
|
|||||||
redistributing the app or its container image.
|
redistributing the app or its container image.
|
||||||
|
|
||||||
Profiles load lazily the first time the Optics panel needs one, so a library that never
|
Profiles load lazily the first time the Optics panel needs one, so a library that never
|
||||||
uses lens correction does not download the ~5 MB database. A profile is built for the
|
uses lens correction does not download the ~1.8 MB database. Team calibrations are a
|
||||||
|
small extra request and are ignored when offline or signed out. A profile is built for the
|
||||||
photo's current focal length and aperture; it is not interpolated between zoom
|
photo's current focal length and aperture; it is not interpolated between zoom
|
||||||
positions. Camera-lens defaults require both a normalised camera and lens name to match.
|
positions. Camera-lens defaults require both a normalised camera and lens name to match.
|
||||||
|
|
||||||
|
|||||||
@@ -204,6 +204,25 @@ db.exec(`
|
|||||||
prune_notified_at INTEGER,
|
prune_notified_at INTEGER,
|
||||||
last_quota_email_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. */
|
/* Databases created before account disabling existed get the column in place. */
|
||||||
@@ -544,6 +563,28 @@ const q = {
|
|||||||
kvSet: db.prepare(
|
kvSet: db.prepare(
|
||||||
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
'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) {
|
function parse(json) {
|
||||||
@@ -1113,3 +1154,52 @@ export const kv = {
|
|||||||
},
|
},
|
||||||
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
|
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,
|
getPhoto,
|
||||||
invites,
|
invites,
|
||||||
kv,
|
kv,
|
||||||
|
lensProfiles,
|
||||||
listEvents,
|
listEvents,
|
||||||
listPhotos,
|
listPhotos,
|
||||||
livePhotoBytes,
|
livePhotoBytes,
|
||||||
@@ -89,6 +90,7 @@ import {
|
|||||||
} from './bridge.mjs';
|
} from './bridge.mjs';
|
||||||
import { cameraThumb16, jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
|
import { cameraThumb16, jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
|
||||||
import { createZip } from './zip.mjs';
|
import { createZip } from './zip.mjs';
|
||||||
|
import { parseCalibration } from './lensCalibration.mjs';
|
||||||
import {
|
import {
|
||||||
cancelPrune,
|
cancelPrune,
|
||||||
quotaState,
|
quotaState,
|
||||||
@@ -1858,6 +1860,68 @@ route('PUT', '/api/presets', async ({ req, res }) => {
|
|||||||
json(res, 200, { ok: true });
|
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
|
* 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.
|
* 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -46,6 +46,8 @@ import {
|
|||||||
} from '../lib/lensDefaults';
|
} from '../lib/lensDefaults';
|
||||||
import type { LensProfile } from '../types';
|
import type { LensProfile } from '../types';
|
||||||
import LensDefaultsModal from './LensDefaultsModal';
|
import LensDefaultsModal from './LensDefaultsModal';
|
||||||
|
import LensCalibrationModal from './LensCalibrationModal';
|
||||||
|
import { TEAM_PREFIX } from '../lib/lensProfiles';
|
||||||
import Slider from './Slider';
|
import Slider from './Slider';
|
||||||
|
|
||||||
export function Panel({
|
export function Panel({
|
||||||
@@ -1874,6 +1876,7 @@ export function OpticsPanel({
|
|||||||
const [available, setAvailable] = useState<number | null>(null);
|
const [available, setAvailable] = useState<number | null>(null);
|
||||||
const [defaultProfile, setDefaultProfile] = useState<CameraLensDefault | null>(null);
|
const [defaultProfile, setDefaultProfile] = useState<CameraLensDefault | null>(null);
|
||||||
const [defaultsOpen, setDefaultsOpen] = useState(false);
|
const [defaultsOpen, setDefaultsOpen] = useState(false);
|
||||||
|
const [calibrationOpen, setCalibrationOpen] = useState(false);
|
||||||
const patch = (next: Partial<Edits['geometry']>, label: string) =>
|
const patch = (next: Partial<Edits['geometry']>, label: string) =>
|
||||||
set({ geometry: { ...geometry, ...next } }, label);
|
set({ geometry: { ...geometry, ...next } }, label);
|
||||||
|
|
||||||
@@ -2054,7 +2057,7 @@ export function OpticsPanel({
|
|||||||
>
|
>
|
||||||
<span>{result.model}</span>
|
<span>{result.model}</span>
|
||||||
<span className="muted small">
|
<span className="muted small">
|
||||||
{result.maker} · {result.crop}×
|
{result.maker} · {result.crop}×{result.team ? ' · Team' : ''}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
@@ -2082,6 +2085,9 @@ export function OpticsPanel({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="lens-default-manage">
|
<div className="lens-default-manage">
|
||||||
|
<button className="btn ghost tiny" onClick={() => setCalibrationOpen(true)}>
|
||||||
|
Team calibrations
|
||||||
|
</button>
|
||||||
<button className="btn ghost tiny" onClick={() => setDefaultsOpen(true)}>
|
<button className="btn ghost tiny" onClick={() => setDefaultsOpen(true)}>
|
||||||
Manage saved defaults
|
Manage saved defaults
|
||||||
</button>
|
</button>
|
||||||
@@ -2174,6 +2180,22 @@ export function OpticsPanel({
|
|||||||
onChanged={refreshDefault}
|
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
@@ -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;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
res = await fetch(path, { credentials: 'same-origin', ...init });
|
res = await fetch(path, { credentials: 'same-origin', ...init });
|
||||||
|
|||||||
+150
-4
@@ -1,6 +1,14 @@
|
|||||||
import { beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
import { availableFor, findCamera, findLensForMeta, searchLens, type LensDatabase } from './lensDb';
|
import {
|
||||||
|
availableFor,
|
||||||
|
findCamera,
|
||||||
|
findLensForMeta,
|
||||||
|
getLensEntry,
|
||||||
|
searchLens,
|
||||||
|
type LensDatabase,
|
||||||
|
} from './lensDb';
|
||||||
import { fixtureLenses } from './lensEngine.fixture';
|
import { fixtureLenses } from './lensEngine.fixture';
|
||||||
|
import { invalidateTeamProfiles, type TeamLensProfile } from './lensProfiles';
|
||||||
import type { LensProfile } from '../types';
|
import type { LensProfile } from '../types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,10 +19,11 @@ import type { LensProfile } from '../types';
|
|||||||
const database: LensDatabase = {
|
const database: LensDatabase = {
|
||||||
source: { project: 'lensfun', commit: 'test', licence: 'CC BY-SA 3.0', note: '' },
|
source: { project: 'lensfun', commit: 'test', licence: 'CC BY-SA 3.0', note: '' },
|
||||||
models: { distortion: ['poly3', 'poly5', 'ptlens', 'linear', 'acm'], tca: ['poly3', 'linear', 'acm'] },
|
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: [
|
cameras: [
|
||||||
{ maker: 'Nikon Corporation', model: 'Nikon D700', mount: 'Nikon F AF', crop: 1 },
|
{ 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 R5', mount: 'Canon EF', crop: 1 },
|
||||||
|
{ maker: 'Canon', model: 'Canon EOS 60D', mount: 'Canon EF-S', crop: 1.62 },
|
||||||
],
|
],
|
||||||
lenses: [
|
lenses: [
|
||||||
...fixtureLenses,
|
...fixtureLenses,
|
||||||
@@ -31,11 +40,75 @@ const database: LensDatabase = {
|
|||||||
t: [],
|
t: [],
|
||||||
v: [],
|
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(() => {
|
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', () => {
|
describe('lens search', () => {
|
||||||
@@ -58,6 +131,28 @@ describe('lens search', () => {
|
|||||||
expect(match?.maker).toBe('Tamron');
|
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 () => {
|
it('returns nothing for a name that is not in the database', async () => {
|
||||||
expect(await searchLens('zzzz nonexistent lens')).toEqual([]);
|
expect(await searchLens('zzzz nonexistent lens')).toEqual([]);
|
||||||
expect(await searchLens('')).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', () => {
|
describe('availability', () => {
|
||||||
it('reports which corrections a profile supports', async () => {
|
it('reports which corrections a profile supports', async () => {
|
||||||
const [tamron] = fixtureLenses;
|
const [tamron] = fixtureLenses;
|
||||||
|
|||||||
+53
-8
@@ -1,3 +1,4 @@
|
|||||||
|
import { TEAM_PREFIX, loadTeamProfiles, teamProfileToEntry } from './lensProfiles';
|
||||||
import type { LensProfile, PhotoMeta } from '../types';
|
import type { LensProfile, PhotoMeta } from '../types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -35,6 +36,8 @@ export interface LensEntry {
|
|||||||
d: DistortionSample[];
|
d: DistortionSample[];
|
||||||
t: TcaSample[];
|
t: TcaSample[];
|
||||||
v: VignettingSample[];
|
v: VignettingSample[];
|
||||||
|
/** Set for a calibration the team stored on the server, not the bundle. */
|
||||||
|
team?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CameraEntry {
|
export interface CameraEntry {
|
||||||
@@ -68,6 +71,8 @@ export interface LensSearchResult {
|
|||||||
score: number;
|
score: number;
|
||||||
/** Bit mask of the corrections the calibration supports. */
|
/** Bit mask of the corrections the calibration supports. */
|
||||||
available: number;
|
available: number;
|
||||||
|
/** True when the profile came from the team's own calibrations. */
|
||||||
|
team?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FLAG_TCA = 1;
|
export const FLAG_TCA = 1;
|
||||||
@@ -76,6 +81,19 @@ export const FLAG_DISTORTION = 8;
|
|||||||
|
|
||||||
let databasePromise: Promise<LensDatabase> | null = null;
|
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> {
|
export function loadLensDatabase(): Promise<LensDatabase> {
|
||||||
if (!databasePromise) {
|
if (!databasePromise) {
|
||||||
databasePromise = fetch('/lens-db/profiles.json')
|
databasePromise = fetch('/lens-db/profiles.json')
|
||||||
@@ -108,6 +126,7 @@ export function toResult(entry: LensEntry, score = 0): LensSearchResult {
|
|||||||
crop: entry.crop,
|
crop: entry.crop,
|
||||||
score,
|
score,
|
||||||
available: availableFlags(entry),
|
available: availableFlags(entry),
|
||||||
|
team: entry.team,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,7 +176,18 @@ function queryVariants(query: string): string[] {
|
|||||||
const raw = query.trim();
|
const raw = query.trim();
|
||||||
if (raw.length < 2) return [];
|
if (raw.length < 2) return [];
|
||||||
const compact = raw.replace(/(\d)\s*mm\b/gi, '$1mm').replace(/\s+/g, ' ');
|
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 */
|
/* ------------------------------------------------------------------- queries */
|
||||||
@@ -171,17 +201,26 @@ export async function searchLens(
|
|||||||
const db = await loadLensDatabase();
|
const db = await loadLensDatabase();
|
||||||
const camera = await findCamera(meta?.camera);
|
const camera = await findCamera(meta?.camera);
|
||||||
const mount = camera?.mount ?? '';
|
const mount = camera?.mount ?? '';
|
||||||
const scored: { entry: LensEntry; score: number }[] = [];
|
const scored: { entry: LensEntry; score: number; rank: number }[] = [];
|
||||||
for (const entry of db.lenses) {
|
for (const entry of [...db.lenses, ...(await loadTeamEntries())]) {
|
||||||
const score = scoreEntry(entry, variants);
|
const score = scoreEntry(entry, variants);
|
||||||
if (score < 0.5) continue;
|
if (score < 0.5) continue;
|
||||||
// A mount the camera actually uses is a tie-break, never a filter: a
|
// 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
|
// profile that is in the database but filed under another mount must still
|
||||||
// be findable.
|
// be findable. A crop Canon body lists Canon EF-S, so EF glass (and the
|
||||||
const fits = mount && entry.mounts.includes(mount) ? 0.3 : 0;
|
// third-party lenses filed under it) only gets the family bonus.
|
||||||
scored.push({ entry, score: score + fits });
|
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)));
|
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> {
|
): Promise<LensSearchResult | null> {
|
||||||
if (!meta.lens) return null;
|
if (!meta.lens) return null;
|
||||||
const results = await searchLens(meta.lens, meta);
|
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>();
|
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> {
|
export async function getLensEntry(profile: LensProfile): Promise<LensEntry | null> {
|
||||||
const db = await loadLensDatabase();
|
const db = await loadLensDatabase();
|
||||||
if (profile.id) {
|
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);
|
const byId = db.lenses.find((entry) => entry.id === profile.id);
|
||||||
if (byId) return byId;
|
if (byId) return byId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -4844,6 +4844,7 @@ figcaption {
|
|||||||
.lens-default-manage {
|
.lens-default-manage {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
|
gap: 4px;
|
||||||
margin-top: 4px;
|
margin-top: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4851,6 +4852,71 @@ figcaption {
|
|||||||
width: min(640px, 100%);
|
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 {
|
.settings-kicker {
|
||||||
display: block;
|
display: block;
|
||||||
margin-bottom: 3px;
|
margin-bottom: 3px;
|
||||||
|
|||||||
Reference in New Issue
Block a user