749047ae9e
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>
297 lines
10 KiB
TypeScript
297 lines
10 KiB
TypeScript
import { TEAM_PREFIX, loadTeamProfiles, teamProfileToEntry } from './lensProfiles';
|
|
import type { LensProfile, PhotoMeta } from '../types';
|
|
|
|
/**
|
|
* Lens profiles are built from the Lensfun project's calibration database
|
|
* (CC BY-SA 3.0, © Lensfun contributors) by `scripts/build-lens-db.mjs`. Only
|
|
* the measurements come from there; searching, matching and the correction
|
|
* maths are ours, so the editor ships no WebAssembly runtime and no database
|
|
* parser.
|
|
*
|
|
* The file is fetched the first time the Optics panel, a stored profile or a
|
|
* lens-corrected export needs it, and then kept in memory.
|
|
*/
|
|
|
|
/** [focal, model, a, b, c, realFocal] — a·r³ + b·r² + c·r + 1; 0 = nominal focal */
|
|
export type DistortionSample = [number, number, number, number, number, number];
|
|
/** [focal, model, br, cr, vr, bb, cb, vb] — r·(v + c·r + b·r²) per channel */
|
|
export type TcaSample = [number, number, number, number, number, number, number, number];
|
|
/** [focal, aperture, distance, k1, k2, k3] */
|
|
export type VignettingSample = [number, number, number, number, number, number];
|
|
|
|
export const DIST_MODEL = { poly3: 0, poly5: 1, ptlens: 2, linear: 3, acm: 4 } as const;
|
|
export const TCA_MODEL = { poly3: 0, linear: 1, acm: 2 } as const;
|
|
|
|
export interface LensEntry {
|
|
id: string;
|
|
maker: string;
|
|
model: string;
|
|
/** Crop factor the calibration was measured at. */
|
|
crop: number;
|
|
mounts: string[];
|
|
/** Calibration sensor aspect ratio, 0 when the database does not say. */
|
|
aspect: number;
|
|
centerX: number;
|
|
centerY: number;
|
|
d: DistortionSample[];
|
|
t: TcaSample[];
|
|
v: VignettingSample[];
|
|
/** Set for a calibration the team stored on the server, not the bundle. */
|
|
team?: boolean;
|
|
}
|
|
|
|
export interface CameraEntry {
|
|
maker: string;
|
|
model: string;
|
|
mount: string;
|
|
crop: number;
|
|
}
|
|
|
|
export interface LensDatabase {
|
|
source: { project: string; commit: string; licence: string; note: string };
|
|
models: { distortion: string[]; tca: string[] };
|
|
mounts: string[];
|
|
cameras: CameraEntry[];
|
|
lenses: LensEntry[];
|
|
}
|
|
|
|
export interface CameraMatch {
|
|
maker: string;
|
|
model: string;
|
|
mount: string;
|
|
cropFactor: number;
|
|
score: number;
|
|
}
|
|
|
|
export interface LensSearchResult {
|
|
id: string;
|
|
maker: string;
|
|
model: string;
|
|
crop: number;
|
|
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;
|
|
export const FLAG_VIGNETTING = 2;
|
|
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')
|
|
.then((response) => {
|
|
if (!response.ok) throw new Error(`The lens database could not be loaded (${response.status})`);
|
|
return response.json() as Promise<LensDatabase>;
|
|
})
|
|
.catch((err) => {
|
|
databasePromise = null;
|
|
throw err;
|
|
});
|
|
}
|
|
return databasePromise;
|
|
}
|
|
|
|
/** Available corrections for a profile, matching the flags the renderer uses. */
|
|
export function availableFlags(entry: LensEntry): number {
|
|
return (
|
|
(entry.d.length ? FLAG_DISTORTION : 0) |
|
|
(entry.t.length ? FLAG_TCA : 0) |
|
|
(entry.v.length ? FLAG_VIGNETTING : 0)
|
|
);
|
|
}
|
|
|
|
export function toResult(entry: LensEntry, score = 0): LensSearchResult {
|
|
return {
|
|
id: entry.id,
|
|
maker: entry.maker,
|
|
model: entry.model,
|
|
crop: entry.crop,
|
|
score,
|
|
available: availableFlags(entry),
|
|
team: entry.team,
|
|
};
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ matching */
|
|
|
|
/** Lowercase word tokens, with units folded so "28-75mm" meets "28-75". */
|
|
function tokens(value: string): string[] {
|
|
return value
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, ' ')
|
|
.trim()
|
|
.split(' ')
|
|
.filter(Boolean)
|
|
.map((token) => token.replace(/mm$/, '').replace(/^f(?=\d)/, ''));
|
|
}
|
|
|
|
function coverage(query: string[], target: Set<string>): number {
|
|
if (!query.length) return 0;
|
|
let hit = 0;
|
|
for (const token of query) if (target.has(token)) hit += 1;
|
|
return hit / query.length;
|
|
}
|
|
|
|
/**
|
|
* 3 for an exact model, otherwise the fraction of query words the entry covers,
|
|
* with a small bonus when every word matches. Both maker and model count, so
|
|
* "tamron" finds Tamron glass without needing the focal length.
|
|
*/
|
|
function scoreEntry(entry: LensEntry, variants: string[]): number {
|
|
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
|
|
const maker = tokens(entry.maker);
|
|
const model = tokens(entry.model);
|
|
let best = 0;
|
|
for (const variant of variants) {
|
|
const query = tokens(variant);
|
|
if (!query.length) continue;
|
|
const name = [...maker, ...model].join(' ');
|
|
if (query.join(' ') === name || query.join(' ') === model.join(' ')) return 3;
|
|
const hit = coverage(query, target);
|
|
best = Math.max(best, hit >= 1 ? 1.25 : hit);
|
|
}
|
|
return best;
|
|
}
|
|
|
|
/** Variants of the query worth matching: as typed, plus unit-normalised forms. */
|
|
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, ' ');
|
|
// 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 */
|
|
|
|
export async function searchLens(
|
|
query: string,
|
|
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
|
|
): Promise<LensSearchResult[]> {
|
|
const variants = queryVariants(query);
|
|
if (!variants.length) return [];
|
|
const db = await loadLensDatabase();
|
|
const camera = await findCamera(meta?.camera);
|
|
const mount = camera?.mount ?? '';
|
|
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. 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.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)));
|
|
}
|
|
|
|
export async function findLensForMeta(
|
|
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
|
): Promise<LensSearchResult | null> {
|
|
if (!meta.lens) return null;
|
|
const results = await searchLens(meta.lens, meta);
|
|
// 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>();
|
|
|
|
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
|
|
if (!camera) return null;
|
|
const cached = cameraCache.get(camera);
|
|
if (cached !== undefined) return cached;
|
|
const db = await loadLensDatabase();
|
|
const query = tokens(camera);
|
|
let best: CameraMatch | null = null;
|
|
let bestScore = 0;
|
|
for (const entry of db.cameras) {
|
|
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
|
|
// Ignore the maker prefix the EXIF repeats, e.g. "NIKON CORPORATION".
|
|
const model = tokens(entry.model);
|
|
const score = Math.max(coverage(query, target), coverage(model, target) * 0.9);
|
|
if (score > bestScore) {
|
|
bestScore = score;
|
|
best = {
|
|
maker: entry.maker,
|
|
model: entry.model,
|
|
mount: entry.mount,
|
|
cropFactor: entry.crop,
|
|
score,
|
|
};
|
|
}
|
|
}
|
|
const match = bestScore >= 0.6 ? best : null;
|
|
cameraCache.set(camera, match);
|
|
return match;
|
|
}
|
|
|
|
/** Exact entry for a stored profile, falling back to the closest name match. */
|
|
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;
|
|
}
|
|
const maker = profile.maker.trim().toLowerCase();
|
|
const model = profile.model.trim().toLowerCase();
|
|
const exact = db.lenses.find(
|
|
(entry) => entry.maker.toLowerCase() === maker && entry.model.toLowerCase() === model,
|
|
);
|
|
if (exact) return exact;
|
|
const sameModel = db.lenses.filter((entry) => entry.model.toLowerCase() === model);
|
|
if (sameModel.length === 1) return sameModel[0];
|
|
const scored = db.lenses
|
|
.map((entry) => ({ entry, score: scoreEntry(entry, [profile.model, `${profile.maker} ${profile.model}`]) }))
|
|
.sort((a, b) => b.score - a.score);
|
|
return scored[0] && scored[0].score >= 0.5 ? scored[0].entry : null;
|
|
}
|
|
|
|
export async function availableFor(profile: LensProfile): Promise<number> {
|
|
const entry = await getLensEntry(profile);
|
|
return entry ? availableFlags(entry) : 0;
|
|
}
|