@enslo/sd-metadata-lite 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,463 +1,534 @@
1
- // src/extract.ts
2
- var CT = "class_type";
3
- var PARAMS = "parameters";
4
- var EASY_DIFF_KEY = "use_stable_diffusion_model";
1
+ //#region src/extract.ts
2
+ const CT = "class_type";
3
+ const PARAMS = "parameters";
4
+ const EASY_DIFF_KEY = "use_stable_diffusion_model";
5
+ /**
6
+ * Channel tool-specific entry keys into `entries.parameters`.
7
+ *
8
+ * Each key string appears exactly once in this loop to minimize IIFE size
9
+ * (esbuild cannot mangle object property names).
10
+ *
11
+ * Matched keys and their tools:
12
+ * - "extraMetadata" → Civitai (JPEG UserComment JSON)
13
+ * - "invokeai_metadata" → InvokeAI (PNG tEXt / JPEG UserComment JSON)
14
+ * - "generation_data" → TensorArt (JPEG UserComment JSON)
15
+ *
16
+ * Returns a NEW Entries with the matched value routed to `parameters`.
17
+ * If no key matches, returns the original `entries` reference unchanged
18
+ * (enables identity check with `!==`).
19
+ */
5
20
  function channelKnownKeys(src, entries) {
6
- for (const key of ["extraMetadata", "invokeai_metadata", "generation_data"]) {
7
- if (src[key]) {
8
- const result = {
9
- ...entries,
10
- // PNG tEXt chunks can have trailing null bytes — strip them.
11
- [PARAMS]: entries[PARAMS] ?? stringifyValue(src[key]).replace(/\0+$/, "")
12
- };
13
- if (src.prompt) result.prompt ??= stringifyValue(src.prompt);
14
- return result;
15
- }
16
- }
17
- return entries;
21
+ for (const key of [
22
+ "extraMetadata",
23
+ "invokeai_metadata",
24
+ "generation_data"
25
+ ]) if (src[key]) {
26
+ const result = {
27
+ ...entries,
28
+ [PARAMS]: entries[PARAMS] ?? stringifyValue(src[key]).replace(/\0+$/, "")
29
+ };
30
+ if (src.prompt) result.prompt ??= stringifyValue(src.prompt);
31
+ return result;
32
+ }
33
+ return entries;
18
34
  }
35
+ /**
36
+ * Normalize heterogeneous entry formats into a uniform shape.
37
+ *
38
+ * Pure function — returns a new Entries without mutating the input.
39
+ * Only identifies WHERE data lives and channels it to `entries.parameters`.
40
+ * All actual parsing/extraction is deferred to extract().
41
+ *
42
+ * Entry points by image format:
43
+ * PNG → entries already has named keys (parameters, prompt, Comment, etc.)
44
+ * JPEG → metadata is in EXIF UserComment (plain text or JSON blob)
45
+ * WebP → same as JPEG (EXIF-based)
46
+ */
19
47
  function normalize(entries) {
20
- if (entries.Software?.startsWith("NovelAI"))
21
- return { ...entries, [PARAMS]: entries[PARAMS] ?? entries.Comment };
22
- const uc = entries.UserComment;
23
- if (!uc) return channelKnownKeys(entries, entries);
24
- if (!uc.startsWith("{")) {
25
- if (uc.includes("Steps:"))
26
- return { ...entries, [PARAMS]: entries[PARAMS] ?? uc };
27
- return entries;
28
- }
29
- const obj = parseJson(uc);
30
- if (!obj) return entries;
31
- const channeled = channelKnownKeys(obj, entries);
32
- if (channeled !== entries) return channeled;
33
- if ("prompt" in obj && "workflow" in obj)
34
- return { ...entries, prompt: entries.prompt ?? stringifyValue(obj.prompt) };
35
- if (PARAMS in obj)
36
- return {
37
- ...entries,
38
- [PARAMS]: entries[PARAMS] ?? stringifyValue(obj[PARAMS])
39
- };
40
- return { ...entries, [PARAMS]: entries[PARAMS] ?? uc };
48
+ if (entries.Software?.startsWith("NovelAI")) return {
49
+ ...entries,
50
+ [PARAMS]: entries[PARAMS] ?? entries.Comment
51
+ };
52
+ const uc = entries.UserComment;
53
+ if (!uc) return channelKnownKeys(entries, entries);
54
+ if (!uc.startsWith("{")) {
55
+ if (uc.includes("Steps:")) return {
56
+ ...entries,
57
+ [PARAMS]: entries[PARAMS] ?? uc
58
+ };
59
+ return entries;
60
+ }
61
+ const obj = parseJson(uc);
62
+ if (!obj) return entries;
63
+ const channeled = channelKnownKeys(obj, entries);
64
+ if (channeled !== entries) return channeled;
65
+ if ("prompt" in obj && "workflow" in obj) return {
66
+ ...entries,
67
+ prompt: entries.prompt ?? stringifyValue(obj.prompt)
68
+ };
69
+ if (PARAMS in obj) return {
70
+ ...entries,
71
+ [PARAMS]: entries[PARAMS] ?? stringifyValue(obj[PARAMS])
72
+ };
73
+ return {
74
+ ...entries,
75
+ [PARAMS]: entries[PARAMS] ?? uc
76
+ };
41
77
  }
78
+ /**
79
+ * Main entry point: detect the originating tool, extract metadata from
80
+ * normalized entries, and return human-readable A1111-format text.
81
+ */
42
82
  function extract(rawEntries) {
43
- const entries = normalize(rawEntries);
44
- const params = entries[PARAMS];
45
- const prompt = entries.prompt ?? entries.Prompt;
46
- if (params?.includes("sui_image_params")) {
47
- const obj = parseJson(params);
48
- return buildA1111(
49
- extractCommon(obj.sui_image_params ?? obj)
50
- );
51
- }
52
- if (params && !params.startsWith("{")) return params;
53
- if (params) {
54
- const raw = parseJson(params);
55
- const obj = typeof raw === "string" ? parseJson(raw) : raw;
56
- if (obj) {
57
- const result = tryJsonTool(obj, params);
58
- if (result) return result;
59
- if (params.includes(CT)) return buildA1111(flatScan(params));
60
- const base = extractCommon(obj);
61
- if (prompt?.includes(CT))
62
- return buildA1111({
63
- ...flatScan(prompt),
64
- p: base.p,
65
- n: base.n,
66
- md: base.md,
67
- mh: base.mh
68
- });
69
- return buildA1111(base);
70
- }
71
- }
72
- if (entries[EASY_DIFF_KEY]) return buildA1111(extractCommon(entries));
73
- if (prompt?.includes(CT)) return buildA1111(flatScan(prompt));
74
- return params ?? entries.UserComment ?? entries.Comment ?? entries.ImageDescription ?? "";
83
+ const entries = normalize(rawEntries);
84
+ const params = entries[PARAMS];
85
+ const prompt = entries.prompt ?? entries.Prompt;
86
+ if (params?.includes("sui_image_params")) {
87
+ const obj = parseJson(params);
88
+ return buildA1111(extractCommon(obj.sui_image_params ?? obj));
89
+ }
90
+ if (params && !params.startsWith("{")) return params;
91
+ if (params) {
92
+ const raw = parseJson(params);
93
+ const obj = typeof raw === "string" ? parseJson(raw) : raw;
94
+ if (obj) {
95
+ const result = tryJsonTool(obj, params);
96
+ if (result) return result;
97
+ if (params.includes(CT)) return buildA1111(flatScan(params));
98
+ const base = extractCommon(obj);
99
+ if (prompt?.includes(CT)) return buildA1111({
100
+ ...flatScan(prompt),
101
+ p: base.p,
102
+ n: base.n,
103
+ md: base.md,
104
+ mh: base.mh
105
+ });
106
+ return buildA1111(base);
107
+ }
108
+ }
109
+ if (entries[EASY_DIFF_KEY]) return buildA1111(extractCommon(entries));
110
+ if (prompt?.includes(CT)) return buildA1111(flatScan(prompt));
111
+ return params ?? entries.UserComment ?? entries.Comment ?? entries.ImageDescription ?? "";
75
112
  }
113
+ /**
114
+ * Attempt to identify specific tools from a parsed JSON object.
115
+ * Returns A1111-format text if a tool is recognized, null otherwise.
116
+ *
117
+ * Detection is ordered from most specific to least specific signatures.
118
+ */
76
119
  function tryJsonTool(obj, text) {
77
- if (asString(obj.software).includes("RuinedFooocus"))
78
- return buildA1111(extractCommon(obj));
79
- if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));
80
- if (text.includes('"Model"') && text.includes('"resolution"')) {
81
- const [w, h] = parseDimensions(
82
- asString(obj.resolution),
83
- /(\d+)\s*x\s*(\d+)/
84
- );
85
- const upscaler = obj.use_upscaler;
86
- return buildA1111({
87
- ...extractCommon(obj),
88
- w,
89
- h,
90
- hu: asString(upscaler?.upscale_method),
91
- hs: asNumber(upscaler?.upscale_by),
92
- hd: asNumber(upscaler?.upscaler_strength),
93
- ht: asNumber(upscaler?.upscale_steps)
94
- });
95
- }
96
- if ("base_model" in obj) {
97
- const [w, h] = parseDimensions(
98
- asString(obj.resolution),
99
- /\(\s*(\d+)\s*,\s*(\d+)\s*\)/
100
- );
101
- return buildA1111({ ...extractCommon(obj), w, h });
102
- }
103
- if ("noise_schedule" in obj) return buildNovelAI(obj);
104
- return null;
120
+ if (asString(obj.software).includes("RuinedFooocus")) return buildA1111(extractCommon(obj));
121
+ if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));
122
+ if (text.includes("\"Model\"") && text.includes("\"resolution\"")) {
123
+ const [w, h] = parseDimensions(asString(obj.resolution), /(\d+)\s*x\s*(\d+)/);
124
+ return buildA1111({
125
+ ...extractCommon(obj),
126
+ w,
127
+ h
128
+ });
129
+ }
130
+ if ("base_model" in obj) {
131
+ const [w, h] = parseDimensions(asString(obj.resolution), /\(\s*(\d+)\s*,\s*(\d+)\s*\)/);
132
+ return buildA1111({
133
+ ...extractCommon(obj),
134
+ w,
135
+ h
136
+ });
137
+ }
138
+ if ("noise_schedule" in obj) return buildNovelAI(obj);
139
+ return null;
105
140
  }
141
+ /**
142
+ * Extract GenerationParams from a JSON object using field name fallback chains.
143
+ *
144
+ * Each field tries multiple property names to cover all known JSON-based tools.
145
+ * The fallback order generally goes: most common name → tool-specific aliases.
146
+ *
147
+ * Covered tools: A1111, NovelAI, SwarmUI, InvokeAI, Civitai, TensorArt,
148
+ * Fooocus, RuinedFooocus, EasyDiffusion, HF Space.
149
+ */
106
150
  function extractCommon(obj) {
107
- const sa = asString(obj.sampler ?? obj.sampler_name);
108
- const sc = asString(obj.scheduler ?? obj.noise_schedule);
109
- const mod = obj.model;
110
- const base = obj.baseModel;
111
- return {
112
- // Prompt: "prompt" (most tools) → "Prompt" (Fooocus) → "positive_prompt" (RuinedFooocus)
113
- p: asString(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),
114
- // Negative: multiple naming conventions across tools
115
- // "uc" = NovelAI's "undesired content"
116
- n: asString(
117
- obj.negative_prompt ?? obj.Negative ?? obj.negativeprompt ?? obj.negativePrompt ?? obj.uc
118
- ),
119
- se: asNumber(obj.seed),
120
- // "num_inference_steps" = HF Space / Civitai generator
121
- st: asNumber(obj.steps ?? obj.num_inference_steps),
122
- // CFG: many naming variants across tools
123
- // "scale" = NovelAI, "guidance_scale" = HF Space
124
- cf: asNumber(
125
- obj.cfg ?? obj.cfg_scale ?? obj.cfgScale ?? obj.cfgscale ?? obj.guidance_scale ?? obj.scale
126
- ),
127
- // InvokeAI quirk: stores the sampler name in the "scheduler" field
128
- // and has no separate sampler field. If sa is empty, use sc as sa.
129
- sa: sa || sc,
130
- sc: sa ? sc : void 0,
131
- w: asNumber(obj.width),
132
- h: asNumber(obj.height),
133
- // Model name: extensive fallback chain covering all known patterns.
134
- // "model" (string) → InvokeAI, SwarmUI, Civitai
135
- // "Model" (capital) → Fooocus
136
- // "base_model" → HF Space
137
- // "base_model_name" → Civitai generator
138
- // "baseModel" (string) → TensorArt (when stored as string)
139
- // "model.name" → Civitai (nested object)
140
- // "baseModel.modelFileName" → TensorArt (nested object)
141
- // "use_stable_diffusion_model" → EasyDiffusion (full path, take filename)
142
- md: asString(mod) || asString(obj.Model) || asString(obj.base_model) || asString(obj.base_model_name) || asString(base) || asString(mod?.name) || asString(base?.modelFileName) || asString(obj[EASY_DIFF_KEY]).split(/[\\/]/).pop(),
143
- // Model hash: similar multi-tool fallback chain.
144
- // "Model hash" → Fooocus
145
- // "model.hash" → Civitai (nested)
146
- // "baseModel.hash" → TensorArt (nested)
147
- mh: asString(obj.base_model_hash) || asString(obj["Model hash"]) || asString(mod?.hash) || asString(base?.hash),
148
- cs: asNumber(obj.clip_skip ?? obj.clipSkip),
149
- // Fooocus hires/refiner fields (different naming than A1111)
150
- hs: asNumber(obj.refinerupscale),
151
- hu: asString(obj.refinerupscalemethod),
152
- hd: asNumber(obj.refinercontrolpercentage)
153
- };
151
+ const sa = asString(obj.sampler ?? obj.sampler_name);
152
+ const sc = asString(obj.scheduler ?? obj.noise_schedule);
153
+ const mod = obj.model;
154
+ const base = obj.baseModel;
155
+ const up = obj.use_upscaler;
156
+ return {
157
+ p: asString(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),
158
+ n: asString(obj.negative_prompt ?? obj.Negative ?? obj.negativeprompt ?? obj.negativePrompt ?? obj.uc),
159
+ se: asNumber(obj.seed),
160
+ st: asNumber(obj.steps ?? obj.num_inference_steps),
161
+ cf: asNumber(obj.cfg ?? obj.cfg_scale ?? obj.cfgScale ?? obj.cfgscale ?? obj.guidance_scale ?? obj.scale),
162
+ sa: sa || sc,
163
+ sc: sa ? sc : void 0,
164
+ w: asNumber(obj.width),
165
+ h: asNumber(obj.height),
166
+ md: asString(mod) || asString(obj.Model) || asString(obj.base_model) || asString(obj.base_model_name) || asString(base) || asString(mod?.name) || asString(base?.modelFileName) || asString(obj[EASY_DIFF_KEY]).split(/[\\/]/).pop(),
167
+ mh: asString(obj.base_model_hash) || asString(obj["Model hash"]) || asString(mod?.hash) || asString(base?.hash),
168
+ cs: asNumber(obj.clip_skip ?? obj.clipSkip),
169
+ hs: asNumber(up?.upscale_by) ?? asNumber(obj.refinerupscale),
170
+ hu: asString(up?.upscale_method) || asString(obj.refinerupscalemethod),
171
+ hd: asNumber(up?.upscaler_strength) ?? asNumber(obj.refinercontrolpercentage),
172
+ ht: asNumber(up?.upscale_steps)
173
+ };
154
174
  }
175
+ /**
176
+ * Build A1111 text from NovelAI JSON metadata.
177
+ *
178
+ * NovelAI v4+ uses a nested prompt structure:
179
+ * { v4_prompt: { caption: { base_caption: "..." } } }
180
+ * Falls back to flat "prompt" / "uc" fields for older versions.
181
+ */
155
182
  function buildNovelAI(obj) {
156
- const v4Caption = obj.v4_prompt?.caption;
157
- const v4NegCaption = obj.v4_negative_prompt?.caption;
158
- return buildA1111({
159
- ...extractCommon(obj),
160
- // Prefer v4 captions, fall back to legacy flat fields.
161
- p: asString(v4Caption?.base_caption) || asString(obj.prompt),
162
- n: asString(v4NegCaption?.base_caption) || asString(obj.uc)
163
- });
183
+ const v4Caption = obj.v4_prompt?.caption;
184
+ const v4NegCaption = obj.v4_negative_prompt?.caption;
185
+ return buildA1111({
186
+ ...extractCommon(obj),
187
+ p: asString(v4Caption?.base_caption) || asString(obj.prompt),
188
+ n: asString(v4NegCaption?.base_caption) || asString(obj.uc)
189
+ });
164
190
  }
191
+ /**
192
+ * Scan a ComfyUI node graph (flat JSON) and extract generation parameters.
193
+ *
194
+ * ComfyUI stores metadata as a dictionary of nodes, each with a "class_type"
195
+ * and "inputs" object. This function iterates all nodes and extracts
196
+ * relevant parameters based on the node's class type.
197
+ *
198
+ * The "first match wins" strategy (??= / ||=) ensures we pick the primary
199
+ * node when multiple nodes of the same type exist (e.g. two KSamplers).
200
+ */
165
201
  function flatScan(json) {
166
- const result = {};
167
- const nodes = parseJson(json.replace(/\0+$/, "").replace(/\bNaN\b/g, "null"));
168
- if (!nodes) return result;
169
- for (const key in nodes) {
170
- const node = nodes[key];
171
- if (!node || typeof node !== "object") continue;
172
- const classType = asString(node[CT]);
173
- const inputs = node.inputs;
174
- if (!inputs) continue;
175
- if (/Text(Encode|.?Box)/.test(classType)) {
176
- const txt = asString(inputs.text) || asString(inputs.prompt) || asString(inputs.Text);
177
- if (txt) {
178
- if (/neg/i.test(classType)) {
179
- result.n ??= txt;
180
- } else {
181
- if (!result.p) result.p = txt;
182
- else if (!result.n) result.n = txt;
183
- }
184
- }
185
- }
186
- if (classType.includes("Sampler")) {
187
- result.se ??= asNumber(inputs.seed) ?? asNumber(inputs.noise_seed);
188
- result.st ??= asNumber(inputs.steps);
189
- result.cf ??= asNumber(inputs.cfg);
190
- result.sa ||= asString(inputs.sampler_name);
191
- result.sc ||= asString(inputs.scheduler);
192
- }
193
- result.md ||= asString(inputs.ckpt_name) || asString(inputs.unet_name);
194
- result.w ??= asNumber(inputs.width);
195
- result.h ??= asNumber(inputs.height);
196
- }
197
- return result;
202
+ const result = {};
203
+ const nodes = parseJson(json.replace(/\0+$/, "").replace(/\bNaN\b/g, "null"));
204
+ if (!nodes) return result;
205
+ for (const key in nodes) {
206
+ const node = nodes[key];
207
+ if (!node || typeof node !== "object") continue;
208
+ const classType = asString(node[CT]);
209
+ const inputs = node.inputs;
210
+ if (!inputs) continue;
211
+ if (/Text(Encode|.?Box)|ShowText|PromptStash/.test(classType)) {
212
+ const txt = asString(inputs.text) || asString(inputs.prompt) || asString(inputs.Text) || asString(inputs.prompt_text) || asString(inputs.text_0);
213
+ if (txt) {
214
+ if (/neg/i.test(classType)) result.n ??= txt;
215
+ else if (!result.p) result.p = txt;
216
+ else if (!result.n) result.n = txt;
217
+ }
218
+ }
219
+ if (classType.includes("Sampler")) {
220
+ result.se ??= asNumber(inputs.seed) ?? asNumber(inputs.noise_seed);
221
+ result.st ??= asNumber(inputs.steps);
222
+ result.cf ??= asNumber(inputs.cfg);
223
+ result.sa ||= asString(inputs.sampler_name);
224
+ result.sc ||= asString(inputs.scheduler);
225
+ }
226
+ result.md ||= asString(inputs.ckpt_name) || asString(inputs.unet_name);
227
+ result.w ??= asNumber(inputs.width);
228
+ result.h ??= asNumber(inputs.height);
229
+ }
230
+ return result;
198
231
  }
232
+ /**
233
+ * Build human-readable text in A1111 (Stable Diffusion WebUI) format.
234
+ *
235
+ * Output structure:
236
+ * Line 1: positive prompt
237
+ * Line 2: "Negative prompt: <negative prompt>"
238
+ * Line 3: comma-separated key-value pairs (Steps, Sampler, CFG, etc.)
239
+ */
199
240
  function buildA1111(params) {
200
- const lines = [];
201
- if (params.p) lines.push(params.p);
202
- if (params.n) lines.push(`Negative prompt: ${params.n}`);
203
- const fields = [];
204
- const addField = (key, value) => {
205
- if (value) fields.push(`${key}: ${value}`);
206
- };
207
- addField("Steps", params.st);
208
- addField("Sampler", params.sa);
209
- addField("Schedule type", params.sc);
210
- addField("CFG scale", params.cf);
211
- addField("Seed", params.se);
212
- if (params.w && params.h) addField("Size", `${params.w}x${params.h}`);
213
- addField("Model hash", params.mh);
214
- addField("Model", params.md);
215
- addField("Clip skip", params.cs);
216
- addField("Denoising strength", params.dn ?? params.hd);
217
- addField("Hires upscale", params.hs);
218
- addField("Hires steps", params.ht);
219
- addField("Hires upscaler", params.hu);
220
- if (fields.length) lines.push(fields.join(", "));
221
- return lines.join("\n");
241
+ const lines = [];
242
+ if (params.p) lines.push(params.p);
243
+ if (params.n) lines.push(`Negative prompt: ${params.n}`);
244
+ const fields = [];
245
+ const addField = (key, value) => {
246
+ if (value) fields.push(`${key}: ${value}`);
247
+ };
248
+ addField("Steps", params.st);
249
+ addField("Sampler", params.sa);
250
+ addField("Schedule type", params.sc);
251
+ addField("CFG scale", params.cf);
252
+ addField("Seed", params.se);
253
+ if (params.w && params.h) addField("Size", `${params.w}x${params.h}`);
254
+ addField("Model hash", params.mh);
255
+ addField("Model", params.md);
256
+ addField("Clip skip", params.cs);
257
+ addField("Denoising strength", params.dn ?? params.hd);
258
+ addField("Hires upscale", params.hs);
259
+ addField("Hires steps", params.ht);
260
+ addField("Hires upscaler", params.hu);
261
+ if (fields.length) lines.push(fields.join(", "));
262
+ return lines.join("\n");
222
263
  }
264
+ /** Safely parse JSON, returning null on failure. */
223
265
  function parseJson(text) {
224
- if (!text) return null;
225
- try {
226
- return JSON.parse(text);
227
- } catch {
228
- return null;
229
- }
266
+ if (!text) return null;
267
+ try {
268
+ return JSON.parse(text);
269
+ } catch {
270
+ return null;
271
+ }
230
272
  }
273
+ /**
274
+ * Coerce unknown value to string. Returns "" for non-strings.
275
+ * Returning "" (falsy) enables `||` fallback chains: `asString(a) || asString(b)`.
276
+ */
231
277
  function asString(v) {
232
- return typeof v === "string" ? v : "";
278
+ return typeof v === "string" ? v : "";
233
279
  }
280
+ /**
281
+ * Convert a value to its string representation for channeling.
282
+ * Strings pass through unchanged; objects are JSON-serialized.
283
+ * Used by channelKnownKeys to convert nested JSON objects to strings
284
+ * that extract() can later re-parse.
285
+ */
234
286
  function stringifyValue(v) {
235
- if (typeof v === "string") return v;
236
- if (v && typeof v === "object") return JSON.stringify(v);
237
- return "";
287
+ if (typeof v === "string") return v;
288
+ if (v && typeof v === "object") return JSON.stringify(v);
289
+ return "";
238
290
  }
291
+ /**
292
+ * Coerce unknown value to number. Returns undefined for non-numeric values.
293
+ * Accepts both number and numeric string inputs (e.g. "42" → 42).
294
+ * NaN values are filtered out and returned as undefined.
295
+ */
239
296
  function asNumber(v) {
240
- if (typeof v === "number") return v === v ? v : void 0;
241
- if (typeof v === "string") {
242
- const n = +v;
243
- return n === n ? n : void 0;
244
- }
245
- return void 0;
297
+ if (typeof v === "number") return v === v ? v : void 0;
298
+ if (typeof v === "string") {
299
+ const n = +v;
300
+ return n === n ? n : void 0;
301
+ }
246
302
  }
303
+ /**
304
+ * Extract width/height from a dimension string using the given regex.
305
+ * Different tools use different formats:
306
+ * - Fooocus: "1024x1024" → /(\d+)\s*x\s*(\d+)/
307
+ * - HF Space: "(1024, 1024)" → /\(\s*(\d+)\s*,\s*(\d+)\s*\)/
308
+ */
247
309
  function parseDimensions(text, pattern) {
248
- if (!text) return [];
249
- const match = text.match(pattern);
250
- return match ? [Number(match[1]), Number(match[2])] : [];
310
+ if (!text) return [];
311
+ const match = text.match(pattern);
312
+ return match ? [Number(match[1]), Number(match[2])] : [];
251
313
  }
252
-
253
- // src/read.ts
314
+ //#endregion
315
+ //#region src/read.ts
316
+ /**
317
+ * Extract text chunks from PNG data as keyword→text entries.
318
+ */
254
319
  function readPng(data) {
255
- const entries = {};
256
- const dv = dataview(data);
257
- let offset = 8;
258
- while (offset + 8 <= data.length) {
259
- const length = dv.getUint32(offset);
260
- const type = str(data, offset + 4, 4);
261
- offset += 8;
262
- if (offset + length > data.length) break;
263
- if (type === "tEXt" || type === "iTXt") {
264
- const nullIdx = data.indexOf(0, offset);
265
- if (nullIdx > offset && nullIdx < offset + length) {
266
- const keyword = str(data, offset, nullIdx - offset);
267
- if (type === "tEXt") {
268
- const textData = data.subarray(nullIdx + 1, offset + length);
269
- entries[keyword] = tryUtf8(textData) ?? str(data, nullIdx + 1, offset + length - nullIdx - 1);
270
- } else {
271
- const pos = nullIdx + 3;
272
- const langEnd = data.indexOf(0, pos);
273
- const transEnd = langEnd < 0 ? -1 : data.indexOf(0, langEnd + 1);
274
- if (langEnd < 0 || transEnd < 0) {
275
- offset += length + 4;
276
- continue;
277
- }
278
- entries[keyword] = tryUtf8(data.subarray(transEnd + 1, offset + length)) ?? "";
279
- }
280
- }
281
- }
282
- if (type === "IEND") break;
283
- offset += length + 4;
284
- }
285
- return entries;
320
+ const entries = {};
321
+ const dv = dataview(data);
322
+ let offset = 8;
323
+ while (offset + 8 <= data.length) {
324
+ const length = dv.getUint32(offset);
325
+ const type = str(data, offset + 4, 4);
326
+ offset += 8;
327
+ if (offset + length > data.length) break;
328
+ if (type === "tEXt" || type === "iTXt") {
329
+ const nullIdx = data.indexOf(0, offset);
330
+ if (nullIdx > offset && nullIdx < offset + length) {
331
+ const keyword = str(data, offset, nullIdx - offset);
332
+ if (type === "tEXt") entries[keyword] = tryUtf8(data.subarray(nullIdx + 1, offset + length)) ?? str(data, nullIdx + 1, offset + length - nullIdx - 1);
333
+ else {
334
+ const pos = nullIdx + 3;
335
+ const langEnd = data.indexOf(0, pos);
336
+ const transEnd = langEnd < 0 ? -1 : data.indexOf(0, langEnd + 1);
337
+ if (langEnd < 0 || transEnd < 0) {
338
+ offset += length + 4;
339
+ continue;
340
+ }
341
+ entries[keyword] = tryUtf8(data.subarray(transEnd + 1, offset + length)) ?? "";
342
+ }
343
+ }
344
+ }
345
+ if (type === "IEND") break;
346
+ offset += length + 4;
347
+ }
348
+ return entries;
286
349
  }
350
+ /**
351
+ * Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make + COM segment.
352
+ */
287
353
  function readJpeg(data) {
288
- const entries = {};
289
- let offset = 2;
290
- while (offset + 4 <= data.length) {
291
- const marker = data[offset + 1];
292
- if (data[offset] !== 255 || marker === 255) {
293
- offset++;
294
- continue;
295
- }
296
- if (marker > 216 && marker < 219) break;
297
- const segLen = data[offset + 2] << 8 | data[offset + 3];
298
- if (marker === 225 && offset + 10 <= data.length && str(data, offset + 4, 6) === "Exif\0\0") {
299
- Object.assign(
300
- entries,
301
- readExif(data.subarray(offset + 10, offset + 2 + segLen))
302
- );
303
- }
304
- if (marker === 254) {
305
- const comData = data.subarray(offset + 4, offset + 2 + segLen);
306
- const text = tryUtf8(comData);
307
- if (text) entries.Comment = text;
308
- }
309
- offset += 2 + segLen;
310
- }
311
- return entries;
354
+ const entries = {};
355
+ let offset = 2;
356
+ while (offset + 4 <= data.length) {
357
+ const marker = data[offset + 1];
358
+ if (data[offset] !== 255 || marker === 255) {
359
+ offset++;
360
+ continue;
361
+ }
362
+ if (marker > 216 && marker < 219) break;
363
+ const segLen = data[offset + 2] << 8 | data[offset + 3];
364
+ if (marker === 225 && offset + 10 <= data.length && str(data, offset + 4, 6) === "Exif\0\0") Object.assign(entries, readExif(data.subarray(offset + 10, offset + 2 + segLen)));
365
+ if (marker === 254) {
366
+ const text = tryUtf8(data.subarray(offset + 4, offset + 2 + segLen));
367
+ if (text) entries.Comment = text;
368
+ }
369
+ offset += 2 + segLen;
370
+ }
371
+ return entries;
312
372
  }
373
+ /**
374
+ * Extract metadata from WebP: EXIF chunk → same EXIF parsing as JPEG.
375
+ */
313
376
  function readWebp(data) {
314
- const dv = dataview(data);
315
- let offset = 12;
316
- while (offset + 8 <= data.length) {
317
- const type = str(data, offset, 4);
318
- const chunkSize = dv.getUint32(offset + 4, true);
319
- offset += 8;
320
- if (type === "EXIF" && offset + chunkSize <= data.length) {
321
- return readExif(data.subarray(offset, offset + chunkSize));
322
- }
323
- offset += chunkSize + chunkSize % 2;
324
- }
325
- return {};
377
+ const dv = dataview(data);
378
+ let offset = 12;
379
+ while (offset + 8 <= data.length) {
380
+ const type = str(data, offset, 4);
381
+ const chunkSize = dv.getUint32(offset + 4, true);
382
+ offset += 8;
383
+ if (type === "EXIF" && offset + chunkSize <= data.length) return readExif(data.subarray(offset, offset + chunkSize));
384
+ offset += chunkSize + chunkSize % 2;
385
+ }
386
+ return {};
326
387
  }
388
+ /**
389
+ * Parse EXIF/TIFF data and extract metadata entries.
390
+ */
327
391
  function readExif(data) {
328
- if (data.length < 8) return {};
329
- const firstByte = data[0];
330
- const le = firstByte === 73;
331
- if (!le && firstByte !== 77) return {};
332
- const dv = dataview(data);
333
- if (dv.getUint16(2, le) !== 42) return {};
334
- const entries = {};
335
- const ifd0 = dv.getUint32(4, le);
336
- let exifIfdOffset = 0;
337
- const handleUserComment = (tagData) => {
338
- const text = decodeUserComment(tagData);
339
- if (text) {
340
- if (text.startsWith("{")) {
341
- try {
342
- const obj = JSON.parse(text);
343
- const software = obj.Software;
344
- const comment = obj.Comment;
345
- if (typeof software === "string" && software.startsWith("NovelAI") && typeof comment === "string") {
346
- entries.Software = software;
347
- entries.Comment = comment;
348
- return;
349
- }
350
- } catch {
351
- }
352
- }
353
- entries.UserComment = text;
354
- }
355
- };
356
- scanIfd(data, dv, ifd0, le, (tag, tagData) => {
357
- if (tag === 270 || tag === 271) {
358
- const text = decodeAscii(tagData);
359
- if (text) {
360
- const prefixMatch = text.match(/^([A-Za-z]+):\s/);
361
- if (prefixMatch) {
362
- const key = prefixMatch[1];
363
- if (key) entries[key] = text.slice(prefixMatch[0].length);
364
- } else {
365
- entries[tag === 270 ? "ImageDescription" : "Make"] = text;
366
- }
367
- }
368
- } else if (tag === 37510) {
369
- handleUserComment(tagData);
370
- } else if (tag === 34665) {
371
- exifIfdOffset = dv.getUint32(tagData.byteOffset - data.byteOffset, le);
372
- }
373
- });
374
- if (exifIfdOffset && !entries.UserComment && !entries.Software) {
375
- scanIfd(data, dv, exifIfdOffset, le, (tag, tagData) => {
376
- if (tag === 37510) handleUserComment(tagData);
377
- });
378
- }
379
- return entries;
392
+ if (data.length < 8) return {};
393
+ const firstByte = data[0];
394
+ const le = firstByte === 73;
395
+ if (!le && firstByte !== 77) return {};
396
+ const dv = dataview(data);
397
+ if (dv.getUint16(2, le) !== 42) return {};
398
+ const entries = {};
399
+ const ifd0 = dv.getUint32(4, le);
400
+ let exifIfdOffset = 0;
401
+ const handleUserComment = (tagData) => {
402
+ const text = decodeUserComment(tagData);
403
+ if (text) {
404
+ if (text.startsWith("{")) try {
405
+ const obj = JSON.parse(text);
406
+ const software = obj.Software;
407
+ const comment = obj.Comment;
408
+ if (typeof software === "string" && software.startsWith("NovelAI") && typeof comment === "string") {
409
+ entries.Software = software;
410
+ entries.Comment = comment;
411
+ return;
412
+ }
413
+ } catch {}
414
+ entries.UserComment = text;
415
+ }
416
+ };
417
+ scanIfd(data, dv, ifd0, le, (tag, tagData) => {
418
+ if (tag === 270 || tag === 271) {
419
+ const text = decodeAscii(tagData);
420
+ if (text) {
421
+ const prefixMatch = text.match(/^([A-Za-z]+):\s/);
422
+ if (prefixMatch) {
423
+ const key = prefixMatch[1];
424
+ if (key) entries[key] = text.slice(prefixMatch[0].length);
425
+ } else entries[tag === 270 ? "ImageDescription" : "Make"] = text;
426
+ }
427
+ } else if (tag === 37510) handleUserComment(tagData);
428
+ else if (tag === 34665) exifIfdOffset = dv.getUint32(tagData.byteOffset - data.byteOffset, le);
429
+ });
430
+ if (exifIfdOffset && !entries.UserComment && !entries.Software) scanIfd(data, dv, exifIfdOffset, le, (tag, tagData) => {
431
+ if (tag === 37510) handleUserComment(tagData);
432
+ });
433
+ return entries;
380
434
  }
435
+ /**
436
+ * Scan IFD entries and call handler for each tag.
437
+ */
381
438
  function scanIfd(data, dv, ifdOffset, le, handler) {
382
- const u16 = (o) => dv.getUint16(o, le);
383
- const u32 = (o) => dv.getUint32(o, le);
384
- if (ifdOffset + 2 > data.length) return;
385
- const count = u16(ifdOffset);
386
- let pos = ifdOffset + 2;
387
- for (let i = 0; i < count; i++) {
388
- if (pos + 12 > data.length) return;
389
- const tag = u16(pos);
390
- const type = u16(pos + 2);
391
- const valueCount = u32(pos + 4);
392
- const typeSize = [0, 1, 1, 2, 4, 8, 0, 1][type] ?? 1;
393
- const size = valueCount * typeSize;
394
- const valOffset = size <= 4 ? pos + 8 : u32(pos + 8);
395
- if (valOffset + size <= data.length) {
396
- handler(tag, data.subarray(valOffset, valOffset + size));
397
- }
398
- pos += 12;
399
- }
439
+ const u16 = (o) => dv.getUint16(o, le);
440
+ const u32 = (o) => dv.getUint32(o, le);
441
+ if (ifdOffset + 2 > data.length) return;
442
+ const count = u16(ifdOffset);
443
+ let pos = ifdOffset + 2;
444
+ for (let i = 0; i < count; i++) {
445
+ if (pos + 12 > data.length) return;
446
+ const tag = u16(pos);
447
+ const type = u16(pos + 2);
448
+ const size = u32(pos + 4) * ([
449
+ 0,
450
+ 1,
451
+ 1,
452
+ 2,
453
+ 4,
454
+ 8,
455
+ 0,
456
+ 1
457
+ ][type] ?? 1);
458
+ const valOffset = size <= 4 ? pos + 8 : u32(pos + 8);
459
+ if (valOffset + size <= data.length) handler(tag, data.subarray(valOffset, valOffset + size));
460
+ pos += 12;
461
+ }
400
462
  }
401
463
  function dataview(data) {
402
- return new DataView(data.buffer, data.byteOffset, data.byteLength);
464
+ return new DataView(data.buffer, data.byteOffset, data.byteLength);
403
465
  }
404
- var utf8Dec = new TextDecoder("utf-8", { fatal: true });
405
- var fromCharCode = String.fromCharCode;
466
+ const utf8Dec = new TextDecoder("utf-8", { fatal: true });
467
+ const fromCharCode = String.fromCharCode;
406
468
  function str(data, offset, len) {
407
- let s = "";
408
- for (let i = 0; i < len; i++) s += fromCharCode(data[offset + i]);
409
- return s;
469
+ let s = "";
470
+ for (let i = 0; i < len; i++) s += fromCharCode(data[offset + i]);
471
+ return s;
410
472
  }
411
473
  function tryUtf8(data) {
412
- try {
413
- return utf8Dec.decode(data).replace(/\0$/, "");
414
- } catch {
415
- return null;
416
- }
474
+ try {
475
+ return utf8Dec.decode(data).replace(/\0$/, "");
476
+ } catch {
477
+ return null;
478
+ }
417
479
  }
418
480
  function decodeAscii(data) {
419
- const nullIdx = data.indexOf(0);
420
- return str(data, 0, nullIdx < 0 ? data.length : nullIdx).trim() || null;
481
+ const nullIdx = data.indexOf(0);
482
+ return str(data, 0, nullIdx < 0 ? data.length : nullIdx).trim() || null;
421
483
  }
484
+ /**
485
+ * Decode UserComment with encoding prefix detection.
486
+ */
422
487
  function decodeUserComment(data) {
423
- if (data.length < 8) return null;
424
- const prefix = str(data, 0, 8);
425
- const payload = data.subarray(8);
426
- if (prefix === "UNICODE\0") {
427
- if (payload.length < 2) return null;
428
- const isLE = payload[0] !== 0 && payload[1] === 0;
429
- return decodeUtf16(payload, isLE);
430
- }
431
- if (prefix === "ASCII\0\0\0") {
432
- return decodeAscii(payload);
433
- }
434
- return tryUtf8(data);
488
+ if (data.length < 8) return null;
489
+ const prefix = str(data, 0, 8);
490
+ const payload = data.subarray(8);
491
+ if (prefix === "UNICODE\0") {
492
+ if (payload.length < 2) return null;
493
+ return decodeUtf16(payload, payload[0] !== 0 && payload[1] === 0);
494
+ }
495
+ if (prefix === "ASCII\0\0\0") return decodeAscii(payload);
496
+ return tryUtf8(data);
435
497
  }
436
498
  function decodeUtf16(data, le) {
437
- let s = "";
438
- for (let i = 0; i + 1 < data.length; i += 2) {
439
- const code = le ? data[i] | data[i + 1] << 8 : data[i] << 8 | data[i + 1];
440
- if (!code) break;
441
- s += fromCharCode(code);
442
- }
443
- return s;
499
+ let s = "";
500
+ for (let i = 0; i + 1 < data.length; i += 2) {
501
+ const code = le ? data[i] | data[i + 1] << 8 : data[i] << 8 | data[i + 1];
502
+ if (!code) break;
503
+ s += fromCharCode(code);
504
+ }
505
+ return s;
444
506
  }
445
-
446
- // src/index.ts
507
+ //#endregion
508
+ //#region src/index.ts
509
+ /**
510
+ * @enslo/sd-metadata-lite
511
+ *
512
+ * Lightweight AI image metadata reader for bookmarklets.
513
+ * Reads PNG/JPEG/WebP files and returns A1111-format plain text.
514
+ */
515
+ /**
516
+ * Parse AI-generated image metadata and return A1111-format text.
517
+ *
518
+ * Supports PNG, JPEG, and WebP formats across 18+ generation tools.
519
+ * Returns empty string if no metadata is found.
520
+ *
521
+ * @param input - Image file data
522
+ * @returns A1111-format metadata text, or empty string
523
+ */
447
524
  function parse(input) {
448
- const data = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
449
- if (data[0] === 137 && data[1] === 80) {
450
- return extract(readPng(data));
451
- }
452
- if (data[0] === 255 && data[1] === 216) {
453
- return extract(readJpeg(data));
454
- }
455
- if (data[0] === 82 && data[1] === 73) {
456
- return extract(readWebp(data));
457
- }
458
- return "";
525
+ const data = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
526
+ if (data[0] === 137 && data[1] === 80) return extract(readPng(data));
527
+ if (data[0] === 255 && data[1] === 216) return extract(readJpeg(data));
528
+ if (data[0] === 82 && data[1] === 73) return extract(readWebp(data));
529
+ return "";
459
530
  }
460
- export {
461
- parse
462
- };
531
+ //#endregion
532
+ export { parse };
533
+
463
534
  //# sourceMappingURL=index.js.map