-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
535 lines (458 loc) · 15.4 KB
/
Copy pathplugin.js
File metadata and controls
535 lines (458 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
const fs = require("fs");
const path = require("path");
const SETTINGS_KEY = "eagle-ct-classifier.settings";
const TAG_GROUP_NAME = "Camie Tagger";
const TAG_PREFIX = "CT/";
const DEFAULT_CATEGORIES = ["general", "character", "copyright", "artist", "meta"];
const LOG_FLUSH_INTERVAL_MS = 100;
const MAX_VISIBLE_LOG_LINES = 400;
const SUPPORTED_EXTENSIONS = new Set([
"jpg",
"jpeg",
"png",
"webp",
"bmp",
"gif",
"avif",
"tif",
"tiff",
]);
let pluginContext = null;
let isRunning = false;
let CamieTagger = null;
let resolveTaggerPaths = null;
let logFlushTimer = null;
let logLines = [];
let pendingLogLines = [];
const elements = {
repoPathInput: document.getElementById("repoPathInput"),
thresholdInput: document.getElementById("thresholdInput"),
topKInput: document.getElementById("topKInput"),
categoryGeneral: document.getElementById("categoryGeneral"),
categoryCharacter: document.getElementById("categoryCharacter"),
categoryCopyright: document.getElementById("categoryCopyright"),
categoryArtist: document.getElementById("categoryArtist"),
categoryMeta: document.getElementById("categoryMeta"),
browseRepoButton: document.getElementById("browseRepoButton"),
saveSettingsButton: document.getElementById("saveSettingsButton"),
runButton: document.getElementById("runButton"),
selectionCount: document.getElementById("selectionCount"),
statusTitle: document.getElementById("statusTitle"),
statusText: document.getElementById("statusText"),
statusCard: document.getElementById("statusCard"),
progressBar: document.getElementById("progressBar"),
logOutput: document.getElementById("logOutput"),
};
function readSettings() {
try {
const raw = localStorage.getItem(SETTINGS_KEY);
return raw ? JSON.parse(raw) : {};
} catch (error) {
console.error(error);
return {};
}
}
function writeSettings(settings) {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
}
function bundledRepoPath() {
if (!pluginContext?.path) {
return "";
}
const repoPath = path.join(pluginContext.path, "camie-tagger-v2");
return fs.existsSync(repoPath) ? repoPath : "";
}
function currentSettings() {
const categories = [
elements.categoryGeneral,
elements.categoryCharacter,
elements.categoryCopyright,
elements.categoryArtist,
elements.categoryMeta,
]
.filter((element) => element.checked)
.map((element) => element.value);
return {
repoPath: elements.repoPathInput.value.trim() || bundledRepoPath(),
threshold: Number(elements.thresholdInput.value),
topK: Number(elements.topKInput.value),
categories,
};
}
function appendLog(message) {
const timestamp = new Date().toLocaleTimeString("ja-JP", { hour12: false });
pendingLogLines.push(`[${timestamp}] ${message}`);
scheduleLogFlush();
}
function scheduleLogFlush() {
if (logFlushTimer != null) {
return;
}
logFlushTimer = setTimeout(() => {
flushLogs();
}, LOG_FLUSH_INTERVAL_MS);
}
function flushLogs(force = false) {
if (logFlushTimer != null) {
clearTimeout(logFlushTimer);
logFlushTimer = null;
}
if (!force && pendingLogLines.length === 0) {
return;
}
if (pendingLogLines.length > 0) {
logLines.push(...pendingLogLines);
pendingLogLines = [];
}
if (logLines.length > MAX_VISIBLE_LOG_LINES) {
logLines = logLines.slice(-MAX_VISIBLE_LOG_LINES);
}
elements.logOutput.textContent = logLines.join("\n");
elements.logOutput.scrollTop = elements.logOutput.scrollHeight;
}
function resetLogs(initialMessage = "") {
if (logFlushTimer != null) {
clearTimeout(logFlushTimer);
logFlushTimer = null;
}
logLines = initialMessage ? [initialMessage] : [];
pendingLogLines = [];
elements.logOutput.textContent = initialMessage;
}
function setStatus(mode, title, text) {
elements.statusCard.className = `status-card ${mode}`;
elements.statusTitle.textContent = title;
elements.statusText.textContent = text;
}
function setProgress(percent) {
elements.progressBar.style.width = `${Math.max(0, Math.min(100, percent))}%`;
}
function setRunningState(running) {
isRunning = running;
elements.runButton.disabled = running;
elements.browseRepoButton.disabled = running;
elements.saveSettingsButton.disabled = running;
}
function normalizeTagName(tag) {
return `${TAG_PREFIX}${String(tag).trim()}`;
}
function uniqueStrings(values) {
return [...new Set(values.filter(Boolean))];
}
function isFiniteThreshold(value) {
return Number.isFinite(value) && value >= 0 && value <= 1;
}
function isFiniteTopK(value) {
return Number.isInteger(value) && value > 0;
}
function validateSettings(settings) {
if (!settings.repoPath) {
throw new Error("camie-tagger リポジトリパスを指定してください。");
}
if (!isFiniteThreshold(settings.threshold)) {
throw new Error("閾値は 0 から 1 の範囲で指定してください。");
}
if (!isFiniteTopK(settings.topK)) {
throw new Error("カテゴリごとの最大タグ数は 1 以上の整数で指定してください。");
}
if (!Array.isArray(settings.categories) || settings.categories.length === 0) {
throw new Error("少なくとも 1 つのタグカテゴリを選択してください。");
}
}
function validateTaggerPaths(repoPath) {
if (typeof resolveTaggerPaths !== "function") {
throw new Error("tagger モジュールが初期化されていません。");
}
const resolved = resolveTaggerPaths(repoPath);
const paths = [
{ label: "Python 実行ファイル", value: resolved.pythonPath },
{ label: "ONNX モデル", value: resolved.modelPath },
{ label: "メタデータ", value: resolved.metadataPath },
];
for (const entry of paths) {
if (!fs.existsSync(entry.value)) {
throw new Error(`${entry.label} が見つかりません: ${entry.value}`);
}
}
return resolved;
}
async function browseRepoPath() {
const result = await eagle.dialog.showOpenDialog({
title: "camie-tagger リポジトリを選択",
properties: ["openDirectory"],
});
if (!result.canceled && result.filePaths[0]) {
elements.repoPathInput.value = result.filePaths[0];
}
}
async function saveSettingsFromForm() {
const settings = currentSettings();
validateSettings(settings);
validateTaggerPaths(settings.repoPath);
writeSettings(settings);
appendLog(`設定を保存しました: ${settings.repoPath}`);
setStatus("success", "設定保存済み", "camie-tagger の実行環境を確認しました。");
}
async function refreshSelectionCount() {
if (!pluginContext) {
return;
}
try {
let count = 0;
if (typeof eagle.item.countSelected === "function") {
count = await eagle.item.countSelected();
} else {
const selectedItems = await eagle.item.getSelected();
count = selectedItems.length;
}
elements.selectionCount.textContent = `選択中 ${count} 件`;
} catch (error) {
console.error(error);
}
}
async function ensureTagGroup(tagNames) {
if (!pluginContext) {
throw new Error("プラグインの初期化前です。");
}
let groups = await eagle.tagGroup.get();
let group = groups.find((entry) => entry.name === TAG_GROUP_NAME);
if (!group) {
appendLog(`タググループ "${TAG_GROUP_NAME}" を作成します。`);
await eagle.tagGroup.create({
name: TAG_GROUP_NAME,
color: "orange",
tags: [],
});
groups = await eagle.tagGroup.get();
group = groups.find((entry) => entry.name === TAG_GROUP_NAME);
}
if (!group) {
throw new Error(`タググループ "${TAG_GROUP_NAME}" の取得に失敗しました。`);
}
if (tagNames.length > 0) {
const mergedTags = uniqueStrings([...(group.tags || []), ...tagNames]);
if (typeof group.addTags === "function") {
try {
await group.addTags({ tags: tagNames });
} catch (error) {
appendLog(`tagGroup.addTags に失敗したため save() にフォールバックします: ${error.message}`);
group.tags = mergedTags;
await group.save();
}
} else {
group.tags = mergedTags;
await group.save();
}
}
return group;
}
function collectTags(result, allowedCategories) {
const tags = [];
for (const [category, categoryTags] of Object.entries(result.tags || {})) {
if (!allowedCategories.has(category)) {
continue;
}
for (const entry of categoryTags) {
tags.push(normalizeTagName(entry.tag));
}
}
return uniqueStrings(tags);
}
async function applyTagsToItem(item, tags) {
if (tags.length === 0) {
return 0;
}
const existingTags = uniqueStrings(item.tags || []);
const existingTagSet = new Set(existingTags);
const tagsToAdd = tags.filter((tag) => !existingTagSet.has(tag));
if (tagsToAdd.length === 0) {
return 0;
}
item.tags = [...existingTags, ...tagsToAdd];
await item.save();
return tagsToAdd.length;
}
function getPluginScriptPath() {
if (!pluginContext?.path) {
throw new Error("プラグインパスを取得できません。");
}
return path.join(pluginContext.path, "src", "infer.py");
}
function createTagger(settings) {
if (!CamieTagger) {
throw new Error("tagger モジュールが初期化されていません。");
}
const resolved = validateTaggerPaths(settings.repoPath);
return new CamieTagger({
...resolved,
scriptPath: getPluginScriptPath(),
threshold: settings.threshold,
topK: settings.topK,
});
}
function loadTaggerModule() {
if (!pluginContext?.path) {
throw new Error("プラグインパスを取得できません。");
}
const taggerModulePath = path.join(pluginContext.path, "src", "tagger.js");
const taggerModule = require(taggerModulePath);
CamieTagger = taggerModule;
resolveTaggerPaths = taggerModule.resolveTaggerPaths;
}
async function getSelectedImageItems() {
if (!pluginContext) {
throw new Error("プラグインの初期化前です。");
}
const items = await eagle.item.getSelected();
return items.filter((item) => {
const ext = String(item.ext || "").toLowerCase();
return item.filePath && SUPPORTED_EXTENSIONS.has(ext);
});
}
async function runTagging() {
if (isRunning) {
return;
}
setRunningState(true);
setProgress(0);
try {
const settings = currentSettings();
validateSettings(settings);
writeSettings(settings);
const allowedCategories = new Set(settings.categories);
const selectedItems = await getSelectedImageItems();
await refreshSelectionCount();
if (selectedItems.length === 0) {
throw new Error("画像アイテムが選択されていません。PNG/JPG/WebP などを選択してください。");
}
setStatus("running", "初期化中", "camie-tagger を起動してモデルを読み込んでいます。");
appendLog(`${selectedItems.length} 件の画像を処理します。`);
const tagger = createTagger(settings);
let totalAppliedTags = 0;
const allTags = new Set();
let skippedItems = 0;
try {
const readyInfo = await tagger.initialize();
appendLog(`モデル初期化完了: provider=${readyInfo.provider}, total_tags=${readyInfo.total_tags}`);
for (let index = 0; index < selectedItems.length; index += 1) {
const item = selectedItems[index];
const progressText = `${index + 1}/${selectedItems.length}: ${item.name || path.basename(item.filePath)}`;
setStatus("running", "解析中", progressText);
let result;
try {
result = await tagger.infer(item.filePath, {
threshold: settings.threshold,
topK: settings.topK,
});
} catch (error) {
const message = error?.message || String(error);
if (message.includes("画像が見つかりません")) {
skippedItems += 1;
setProgress(((index + 1) / selectedItems.length) * 100);
appendLog(`スキップ: ${message}`);
continue;
}
throw error;
}
const tags = collectTags(result, allowedCategories);
const appliedTagCount = await applyTagsToItem(item, tags);
for (const tag of tags) {
allTags.add(tag);
}
totalAppliedTags += appliedTagCount;
setProgress(((index + 1) / selectedItems.length) * 100);
appendLog(
`推論完了: ${tags.length} タグ抽出, ${appliedTagCount} タグ追加, ${appliedTagCount > 0 ? "保存あり" : "保存なし"}, ${result.inference_time_ms} ms`,
);
}
} finally {
await tagger.shutdown().catch((error) => {
eagle.log.warn(error.stack || String(error));
});
}
await ensureTagGroup([...allTags]);
setStatus(
"success",
"完了",
`${selectedItems.length} 件を処理し、合計 ${totalAppliedTags} 件の CT タグを適用しました。` +
(skippedItems > 0 ? ` ${skippedItems} 件は画像未検出のためスキップしました。` : ""),
);
appendLog(`タググループ "${TAG_GROUP_NAME}" を同期しました。`);
await eagle.notification.show({
title: "Eagle CT Classifier",
body: `${selectedItems.length} 件のタグ付けが完了しました。`,
duration: 3000,
mute: true,
});
} catch (error) {
const message = error?.message || String(error);
setStatus("error", "エラー", message);
appendLog(`エラー: ${message}`);
eagle.log.error(error?.stack || message);
await eagle.dialog.showErrorBox("Eagle CT Classifier", message);
} finally {
flushLogs(true);
setRunningState(false);
await refreshSelectionCount();
}
}
function hydrateForm() {
const settings = readSettings();
const categories =
Array.isArray(settings.categories) && settings.categories.length > 0
? new Set(settings.categories)
: new Set(DEFAULT_CATEGORIES);
if (settings.repoPath) {
elements.repoPathInput.value = settings.repoPath;
} else {
const repoPath = bundledRepoPath();
if (repoPath) {
elements.repoPathInput.value = repoPath;
}
}
if (typeof settings.threshold === "number") {
elements.thresholdInput.value = String(settings.threshold);
}
if (typeof settings.topK === "number") {
elements.topKInput.value = String(settings.topK);
}
elements.categoryGeneral.checked = categories.has("general");
elements.categoryCharacter.checked = categories.has("character");
elements.categoryCopyright.checked = categories.has("copyright");
elements.categoryArtist.checked = categories.has("artist");
elements.categoryMeta.checked = categories.has("meta");
}
function bindEvents() {
elements.browseRepoButton.addEventListener("click", () => {
browseRepoPath().catch((error) => {
eagle.log.error(error.stack || String(error));
});
});
elements.saveSettingsButton.addEventListener("click", () => {
saveSettingsFromForm().catch(async (error) => {
const message = error?.message || String(error);
appendLog(`設定エラー: ${message}`);
setStatus("error", "設定エラー", message);
await eagle.dialog.showErrorBox("Eagle CT Classifier", message);
});
});
elements.runButton.addEventListener("click", () => {
runTagging().catch((error) => {
eagle.log.error(error.stack || String(error));
});
});
}
eagle.onPluginCreate((plugin) => {
pluginContext = plugin;
loadTaggerModule();
resetLogs("プラグインを初期化しました。");
hydrateForm();
bindEvents();
refreshSelectionCount();
});
eagle.onPluginRun(() => {
if (!pluginContext) {
return;
}
refreshSelectionCount();
});