Templates (IPTC pad, folders, file names, rename on arrival) take every variable of Photo Mechanic's list under its names and short names, in any case, with its modifiers (substrings, lc/UC/PC, tr:find/repl). IPTC variables are the photo's pad, as in Photo Mechanic. The pad gains every Photo Mechanic field with the same IIM/XMP tags, read back from incoming files. Camera details (exposure compensation, flash, metering, program, white balance, 35mm, lens range, firmware, owner, artist, GPS) are kept in photos.exif at ingest and read from the file at delivery for older photos. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
273 lines
15 KiB
TypeScript
273 lines
15 KiB
TypeScript
import { z } from "zod";
|
||
import { type CodeList, expandCodes } from "./codes.js";
|
||
import { lookup, render, type TemplateVars } from "./template.js";
|
||
|
||
/**
|
||
* The IPTC fields PhotoReport fills, in the order and grouping of the Photo Mechanic pad used today.
|
||
* `title` carries the names of the people in the photo (newsroom convention), filled from player
|
||
* identification and/or codes. Tag names are ExifTool's; each value is written to IIM and XMP so both
|
||
* old and new readers see it.
|
||
*/
|
||
export const IPTC_FIELDS = [
|
||
{ key: "title", label: "Title/Object Name", section: "newsroom", list: false, tags: ["IPTC:ObjectName", "XMP-dc:Title"] },
|
||
{ key: "caption", label: "Description/Caption", section: "newsroom", list: false, tags: ["IPTC:Caption-Abstract", "XMP-dc:Description"] },
|
||
{ key: "altText", label: "Alt Text", section: "newsroom", list: false, tags: ["XMP-iptcCore:AltTextAccessibility"] },
|
||
{ key: "extendedDescription", label: "Extended Description", section: "newsroom", list: false, tags: ["XMP-iptcCore:ExtDescrAccessibility"] },
|
||
{ key: "headline", label: "Headline", section: "newsroom", list: false, tags: ["IPTC:Headline", "XMP-photoshop:Headline"] },
|
||
{ key: "event", label: "Event", section: "generic", list: false, tags: ["XMP-iptcExt:Event"] },
|
||
{ key: "location", label: "Location", section: "generic", list: false, tags: ["IPTC:Sub-location", "XMP-iptcCore:Location"] },
|
||
{ key: "city", label: "City", section: "generic", list: false, tags: ["IPTC:City", "XMP-photoshop:City"] },
|
||
{ key: "copyright", label: "Copyright", section: "generic", list: false, tags: ["IPTC:CopyrightNotice", "XMP-dc:Rights"] },
|
||
{ key: "credit", label: "Credit", section: "generic", list: false, tags: ["IPTC:Credit", "XMP-photoshop:Credit"] },
|
||
{ key: "source", label: "Source", section: "generic", list: false, tags: ["IPTC:Source", "XMP-photoshop:Source"] },
|
||
{ key: "keywords", label: "Keywords", section: "generic", list: true, tags: ["IPTC:Keywords", "XMP-dc:Subject"] },
|
||
{ key: "supplementalCategories", label: "Supp Cat", section: "generic", list: true, tags: ["IPTC:SupplementalCategories", "XMP-photoshop:SupplementalCategories"] },
|
||
{ key: "creator", label: "Creator/Photographer", section: "generic", list: false, tags: ["IPTC:By-line", "XMP-dc:Creator"] },
|
||
// Photo Mechanic's "Creator's Identity": target tag to be confirmed against a file exported by Photo Mechanic.
|
||
{ key: "creatorIdentity", label: "Creator's Identity", section: "generic", list: false, tags: [] },
|
||
{ key: "personsShown", label: "Persons shown", section: "generic", list: true, tags: ["XMP-iptcExt:PersonInImage"] },
|
||
{ key: "licensors", label: "Licensors", section: "generic", list: true, tags: ["XMP-plus:LicensorName"] },
|
||
// The rest of Photo Mechanic's pad, with the tags it writes (IIM and XMP, as above).
|
||
{ key: "jobTitle", label: "Creator's Job Title", section: "contact", list: false, tags: ["IPTC:By-lineTitle", "XMP-photoshop:AuthorsPosition"] },
|
||
{ key: "creatorAddress", label: "Contact Address", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorAddress"] },
|
||
{ key: "creatorCity", label: "Contact City", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorCity"] },
|
||
{ key: "creatorRegion", label: "Contact State/Province", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorRegion"] },
|
||
{ key: "creatorPostalCode", label: "Contact Postal Code", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorPostalCode"] },
|
||
{ key: "creatorCountry", label: "Contact Country", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorCountry"] },
|
||
{ key: "creatorPhone", label: "Contact Phone", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorWorkTelephone"] },
|
||
{ key: "creatorEmail", label: "Contact Email", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorWorkEmail"] },
|
||
{ key: "creatorUrl", label: "Contact Web URL", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorWorkURL"] },
|
||
{ key: "captionWriter", label: "Caption Writer", section: "contact", list: false, tags: ["IPTC:Writer-Editor", "XMP-photoshop:CaptionWriter"] },
|
||
{ key: "state", label: "State/Province", section: "location", list: false, tags: ["IPTC:Province-State", "XMP-photoshop:State"] },
|
||
{ key: "country", label: "Country", section: "location", list: false, tags: ["IPTC:Country-PrimaryLocationName", "XMP-photoshop:Country"] },
|
||
{ key: "countryCode", label: "Country Code", section: "location", list: false, tags: ["IPTC:Country-PrimaryLocationCode", "XMP-iptcCore:CountryCode"] },
|
||
{ key: "locationTaken", label: "Location (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedSublocation"] },
|
||
{ key: "cityTaken", label: "City (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedCity"] },
|
||
{ key: "stateTaken", label: "State/Province (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedProvinceState"] },
|
||
{ key: "countryTaken", label: "Country (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedCountryName"] },
|
||
{ key: "countryCodeTaken", label: "Country Code (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedCountryCode"] },
|
||
{ key: "worldRegionTaken", label: "World Region (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedWorldRegion"] },
|
||
{ key: "transmissionReference", label: "Job ID/Transmission Reference", section: "status", list: false, tags: ["IPTC:OriginalTransmissionReference", "XMP-photoshop:TransmissionReference"] },
|
||
{ key: "instructions", label: "Instructions", section: "status", list: false, tags: ["IPTC:SpecialInstructions", "XMP-photoshop:Instructions"] },
|
||
{ key: "category", label: "Category", section: "status", list: false, tags: ["IPTC:Category", "XMP-photoshop:Category"] },
|
||
{ key: "urgency", label: "Urgency", section: "status", list: false, tags: ["IPTC:Urgency", "XMP-photoshop:Urgency"] },
|
||
{ key: "editStatus", label: "Edit Status", section: "status", list: false, tags: ["IPTC:EditStatus"] },
|
||
{ key: "genre", label: "Intellectual Genre", section: "status", list: false, tags: ["IPTC:ObjectAttributeReference", "XMP-iptcCore:IntellectualGenre"] },
|
||
{ key: "scene", label: "Scene", section: "status", list: false, tags: ["XMP-iptcCore:Scene"] },
|
||
{ key: "subjectCode", label: "Subject Code", section: "status", list: false, tags: ["IPTC:SubjectReference", "XMP-iptcCore:SubjectCode"] },
|
||
{ key: "usageTerms", label: "Rights Usage Terms", section: "status", list: false, tags: ["XMP-xmpRights:UsageTerms"] },
|
||
{ key: "copyrightUrl", label: "Copyright Info URL", section: "status", list: false, tags: ["XMP-xmpRights:WebStatement"] },
|
||
{ key: "digitalSourceType", label: "Digital Source Type", section: "status", list: false, tags: ["XMP-iptcExt:DigitalSourceType"] },
|
||
{ key: "imageSupplierName", label: "Image Supplier", section: "models", list: false, tags: ["XMP-plus:ImageSupplierName"] },
|
||
{ key: "imageSupplierId", label: "Image Supplier ID", section: "models", list: false, tags: ["XMP-plus:ImageSupplierID"] },
|
||
{ key: "imageSupplierImageId", label: "Image Supplier Image ID", section: "models", list: false, tags: ["XMP-plus:ImageSupplierImageID"] },
|
||
{ key: "modelReleaseId", label: "Model Release ID", section: "models", list: false, tags: ["XMP-plus:ModelReleaseID"] },
|
||
{ key: "modelAges", label: "Model Age", section: "models", list: false, tags: ["XMP-iptcExt:ModelAge"] },
|
||
{ key: "modelInfo", label: "Additional Model Info", section: "models", list: false, tags: ["XMP-iptcExt:AdditionalModelInformation"] },
|
||
] as const;
|
||
|
||
export type IptcFieldKey = (typeof IPTC_FIELDS)[number]["key"];
|
||
type ListKey = Extract<(typeof IPTC_FIELDS)[number], { list: true }>["key"];
|
||
type TextKey = Exclude<IptcFieldKey, ListKey>;
|
||
|
||
export type IptcValues = { [K in TextKey]?: string } & { [K in ListKey]?: string[] };
|
||
|
||
/**
|
||
* IIM has nominal length limits (Sub-location 32 bytes, for example), but Lightroom and Photo Mechanic write the
|
||
* full text and newsroom readers accept it; ours do the same (ExifTool `-m`), so a long venue is never cut.
|
||
*/
|
||
|
||
const text = z.string().max(4000);
|
||
const list = z.array(z.string().min(1).max(256)).max(100);
|
||
|
||
/** A template: the same shape as the values, each string may contain `{variables}` and `\codes\`. */
|
||
export const IptcTemplate = z.object({
|
||
title: text.optional(),
|
||
caption: text.optional(),
|
||
altText: text.optional(),
|
||
extendedDescription: text.optional(),
|
||
headline: text.optional(),
|
||
event: text.optional(),
|
||
location: text.optional(),
|
||
city: text.optional(),
|
||
copyright: text.optional(),
|
||
credit: text.optional(),
|
||
source: text.optional(),
|
||
keywords: list.optional(),
|
||
supplementalCategories: list.optional(),
|
||
creator: text.optional(),
|
||
creatorIdentity: text.optional(),
|
||
personsShown: list.optional(),
|
||
licensors: list.optional(),
|
||
jobTitle: text.optional(),
|
||
creatorAddress: text.optional(),
|
||
creatorCity: text.optional(),
|
||
creatorRegion: text.optional(),
|
||
creatorPostalCode: text.optional(),
|
||
creatorCountry: text.optional(),
|
||
creatorPhone: text.optional(),
|
||
creatorEmail: text.optional(),
|
||
creatorUrl: text.optional(),
|
||
captionWriter: text.optional(),
|
||
state: text.optional(),
|
||
country: text.optional(),
|
||
countryCode: text.optional(),
|
||
locationTaken: text.optional(),
|
||
cityTaken: text.optional(),
|
||
stateTaken: text.optional(),
|
||
countryTaken: text.optional(),
|
||
countryCodeTaken: text.optional(),
|
||
worldRegionTaken: text.optional(),
|
||
transmissionReference: text.optional(),
|
||
instructions: text.optional(),
|
||
category: text.optional(),
|
||
urgency: text.optional(),
|
||
editStatus: text.optional(),
|
||
genre: text.optional(),
|
||
scene: text.optional(),
|
||
subjectCode: text.optional(),
|
||
usageTerms: text.optional(),
|
||
copyrightUrl: text.optional(),
|
||
digitalSourceType: text.optional(),
|
||
imageSupplierName: text.optional(),
|
||
imageSupplierId: text.optional(),
|
||
imageSupplierImageId: text.optional(),
|
||
modelReleaseId: text.optional(),
|
||
modelAges: text.optional(),
|
||
modelInfo: text.optional(),
|
||
});
|
||
export type IptcTemplate = z.infer<typeof IptcTemplate>;
|
||
|
||
/**
|
||
* Example: the template behind Peter's current pad ("ABC Braga x CDE Gil Eanes, em Braga, no Pavilhão ...").
|
||
* Organisations copy it and adjust; nothing in the app depends on these exact strings.
|
||
*/
|
||
export const NEWSROOM_TEMPLATE: IptcTemplate = {
|
||
title: "{players}",
|
||
caption: "{home} x {away}, em {city}, no {venue}",
|
||
headline: "{home} x {away}, em {city}, no {venue}",
|
||
event: "{home} x {away}",
|
||
location: "{venue}",
|
||
city: "{city}",
|
||
copyright: "{photographer} / PhotoReport.pt",
|
||
source: "{photographer} / PhotoReport.pt",
|
||
creator: "{photographer} / PhotoReport.pt",
|
||
keywords: ["{sport:upper}"],
|
||
supplementalCategories: ["{sport:upper}"],
|
||
personsShown: ["{players}"],
|
||
};
|
||
|
||
/**
|
||
* The default for generic events (press conferences, galas, presentations): nothing is guessed for the caption,
|
||
* headline or event; the editor writes them (the new event form, or the event's IPTC template later).
|
||
*/
|
||
export const GENERAL_TEMPLATE: IptcTemplate = {
|
||
title: "{players}",
|
||
location: "{venue}",
|
||
city: "{city}",
|
||
copyright: "{photographer} / PhotoReport.pt",
|
||
source: "{photographer} / PhotoReport.pt",
|
||
creator: "{photographer} / PhotoReport.pt",
|
||
personsShown: ["{players}"],
|
||
};
|
||
|
||
export interface IptcIssue {
|
||
field: IptcFieldKey;
|
||
kind: "missing_variable" | "unknown_code" | "bad_modifier";
|
||
detail: string;
|
||
}
|
||
|
||
export interface ApplyResult {
|
||
values: IptcValues;
|
||
issues: IptcIssue[];
|
||
}
|
||
|
||
function fill(template: string, vars: TemplateVars, codes: CodeList | undefined, field: IptcFieldKey, issues: IptcIssue[]): string {
|
||
let rendered;
|
||
try {
|
||
rendered = render(template, vars, { missing: "drop" });
|
||
} catch (err) {
|
||
issues.push({ field, kind: "bad_modifier", detail: err instanceof Error ? err.message : String(err) });
|
||
return template;
|
||
}
|
||
for (const name of rendered.missing) issues.push({ field, kind: "missing_variable", detail: name });
|
||
if (!codes) return rendered.text;
|
||
const expanded = expandCodes(rendered.text, codes);
|
||
for (const code of expanded.unknown) issues.push({ field, kind: "unknown_code", detail: code });
|
||
return expanded.text;
|
||
}
|
||
|
||
/** Collapse the spaces an empty variable leaves behind. Missing variables are always reported as issues. */
|
||
function tidy(value: string): string {
|
||
// A match template on an event without an away team: "Gala x , em Braga" → "Gala, em Braga".
|
||
return value
|
||
.replace(/\s{2,}/g, " ")
|
||
.replace(/\s+x\s*(?=,|$)/g, "")
|
||
.trim();
|
||
}
|
||
|
||
/**
|
||
* Fill a template for one photo. List variables (`{players}`) expand to one entry per item in list fields
|
||
* and to "A, B" in text fields. Fields whose result still holds an unresolved `{variable}` are reported.
|
||
*/
|
||
export function applyTemplate(template: IptcTemplate, vars: TemplateVars, codes?: CodeList): ApplyResult {
|
||
const values: IptcValues = {};
|
||
const issues: IptcIssue[] = [];
|
||
for (const field of IPTC_FIELDS) {
|
||
const source = template[field.key];
|
||
if (source === undefined) continue;
|
||
if (field.list) {
|
||
const items: string[] = [];
|
||
for (const entry of source as string[]) {
|
||
const whole = /^\{([a-zA-Z][a-zA-Z0-9_]*)\}$/.exec(entry);
|
||
const listVar = whole?.[1] ? lookup(vars, whole[1]) : undefined;
|
||
if (Array.isArray(listVar)) {
|
||
items.push(...listVar.map((v) => fill(v, {}, codes, field.key, issues)));
|
||
continue;
|
||
}
|
||
if (whole && (listVar === undefined || listVar === "")) continue; // empty list variable: no entry, no noise
|
||
const filled = tidy(fill(entry, vars, codes, field.key, issues));
|
||
if (filled) items.push(filled);
|
||
}
|
||
const unique = [...new Set(items.map(tidy).filter(Boolean))];
|
||
if (unique.length) (values as Record<string, string[]>)[field.key] = unique;
|
||
} else {
|
||
const filled = tidy(fill(source as string, vars, codes, field.key, issues));
|
||
if (filled) (values as Record<string, string>)[field.key] = filled;
|
||
}
|
||
}
|
||
return { values, issues };
|
||
}
|
||
|
||
/** When the photo was taken, as IPTC wants it: local date, local time with the UTC offset. */
|
||
export interface CreatedStamp {
|
||
date: string; // YYYY:MM:DD
|
||
time: string; // HH:MM:SS+hh:mm
|
||
iso: string; // YYYY-MM-DDTHH:MM:SS+hh:mm (XMP)
|
||
}
|
||
|
||
/**
|
||
* ExifTool arguments (`-TAG=value`) for the given values; list fields repeat the tag once per item.
|
||
* IIM is written as UTF-8 and flagged as such (CodedCharacterSet), so accents survive in every reader; files
|
||
* from Lightroom today carry no flag and show "Pavilh‹o" in some tools. `-m` keeps long values whole.
|
||
*/
|
||
export function toExiftoolArgs(values: IptcValues, created?: CreatedStamp): string[] {
|
||
const args = ["-m", "-charset", "iptc=UTF8", "-codedcharacterset=utf8"];
|
||
if (created) {
|
||
args.push(`-IPTC:DateCreated=${created.date}`, `-IPTC:TimeCreated=${created.time}`, `-XMP-photoshop:DateCreated=${created.iso}`);
|
||
}
|
||
for (const field of IPTC_FIELDS) {
|
||
const value = values[field.key];
|
||
if (value === undefined) continue;
|
||
for (const tag of field.tags) {
|
||
if (Array.isArray(value)) {
|
||
args.push(`-${tag}=`); // clear, then add each item
|
||
for (const item of value) args.push(`-${tag}+=${item}`);
|
||
} else {
|
||
args.push(`-${tag}=${value}`);
|
||
}
|
||
}
|
||
}
|
||
return args;
|
||
}
|