-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_app.html
More file actions
692 lines (632 loc) · 25.7 KB
/
Copy pathexample_app.html
File metadata and controls
692 lines (632 loc) · 25.7 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ONNX 画像処理デモ</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
<style>
/* JS 動的生成要素 — モデル選択リスト */
#model-select details { margin-bottom: 2px; }
#model-select details summary {
cursor: pointer; font-size: 12px; font-weight: 600;
padding: 6px 8px; border-radius: 6px; user-select: none;
color: #6b7280; list-style: none; transition: background 0.1s, color 0.1s;
}
#model-select details summary::-webkit-details-marker { display: none; }
#model-select details summary::before {
content: "▶"; margin-right: 6px; font-size: 9px;
display: inline-block; transition: transform 0.15s;
}
#model-select details[open] summary::before { transform: rotate(90deg); }
#model-select details summary:hover { background: #f3f4f6; color: #374151; }
#model-select details[open] > summary { color: #4f46e5; }
#model-select details label {
display: block; padding: 4px 8px 4px 26px;
font-size: 12px; cursor: pointer; color: #6b7280;
border-radius: 5px; margin: 1px 4px; transition: background 0.1s, color 0.1s;
}
#model-select details label:hover { background: #f9fafb; color: #374151; }
#model-select details label:has(input:checked) {
background: #eef2ff; color: #4f46e5; font-weight: 500;
}
#model-select input[type="radio"] { margin-right: 6px; accent-color: #6366f1; }
/* JS 動的生成要素 — パラメータスライダー */
.slider-group { flex: 1; min-width: 0; }
.slider-group > label {
display: block; font-size: 11px; font-weight: 600;
color: #9ca3af; text-transform: uppercase;
letter-spacing: 0.06em; margin-bottom: 8px;
}
.slider-value {
font-size: 13px; font-weight: 700; color: #4f46e5;
text-align: right; margin-top: 4px;
}
input[type="range"] {
-webkit-appearance: none; appearance: none;
width: 100%; height: 4px; border-radius: 2px;
background: #e5e7eb; outline: none; cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none; width: 16px; height: 16px;
border-radius: 50%; background: #6366f1; cursor: pointer;
box-shadow: 0 1px 4px rgba(99,102,241,0.4); transition: transform 0.1s;
}
input[type="range"]::-webkit-slider-thumb:hover { transform: scale(1.2); }
input[type="range"]::-moz-range-thumb {
width: 16px; height: 16px; border-radius: 50%;
background: #6366f1; cursor: pointer; border: none;
box-shadow: 0 1px 4px rgba(99,102,241,0.4);
}
/* グラフモーダル — JS が .active を付け外しする */
#graph-modal, #image-modal { display: none; }
#graph-modal.active, #image-modal.active { display: flex; }
/* 空要素の非表示 */
#param-sliders:empty { display: none; }
#timing:empty { display: none; }
/* canvas レスポンシブ */
canvas { max-width: 100%; height: auto; display: block; }
</style>
</head>
<body class="flex h-screen bg-gray-100 font-sans overflow-hidden">
<!-- ============ サイドバー ============ -->
<aside id="sidebar" class="w-72 min-w-[288px] bg-white border-r border-gray-200 flex flex-col">
<!-- ブランド + アップロード -->
<div class="px-4 pt-5 pb-4 border-b border-gray-100 space-y-4">
<!-- ロゴ -->
<!-- ファイルアップロード -->
<div id="file-upload">
<label class="block cursor-pointer group">
<input type="file" id="image-file" accept="image/*" class="hidden">
<div class="border-2 border-dashed border-gray-200 rounded-xl p-4 text-center
transition-all duration-200
group-hover:border-indigo-400 group-hover:bg-indigo-50">
<div class="text-gray-300 group-hover:text-indigo-400 transition-colors mb-1.5">
<svg class="w-6 h-6 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
</svg>
</div>
<p class="text-xs font-medium text-gray-400 group-hover:text-indigo-600 transition-colors">
画像をアップロード
</p>
</div>
</label>
</div>
</div>
<!-- 検索窓 -->
<div class="px-3 py-2 border-b border-gray-100">
<div class="relative">
<svg class="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none"
fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z"/>
</svg>
<input id="model-search" type="search" placeholder="検索..."
class="w-full pl-8 pr-3 py-1.5 text-xs rounded-lg border border-gray-200
bg-gray-50 text-gray-700 placeholder-gray-400
focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400
transition-all duration-150">
</div>
</div>
<!-- モデル選択リスト -->
<div class="flex-1 overflow-y-auto py-3 px-3">
<div id="model-select"></div>
</div>
</aside>
<!-- ============ メインエリア ============ -->
<div id="main" class="flex-1 flex flex-col min-w-0 overflow-hidden">
<!-- トップバー -->
<header class="bg-white border-b border-gray-200 px-6 py-3 flex items-center gap-4 flex-shrink-0">
<h1 class="text-sm font-semibold text-gray-700">
ONNX 画像処理デモ
<span class="font-normal text-gray-400 ml-1">(onnxruntime-web)</span>
</h1>
<div id="info" class="text-xs text-gray-400 flex-1"></div>
<div id="timing"
class="text-xs font-semibold text-indigo-600 bg-indigo-50 border border-indigo-100 px-3 py-1 rounded-full">
</div>
<div id="status" class="text-xs text-gray-400"></div>
</header>
<!-- スクロール可能なコンテンツ -->
<div class="flex-1 overflow-y-auto p-5 space-y-5">
<!-- グラフ + 画像 -->
<div id="content" class="grid grid-cols-3 gap-5">
<!-- グラフパネル -->
<div id="graph-panel" class="space-y-2">
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Graph</p>
<iframe id="graph-frame" src=""
class="w-full rounded-xl border border-gray-200 shadow-sm bg-white"
style="height: 420px;">
</iframe>
<button id="expand-graph-btn" onclick="openGraphModal()"
class="w-full text-xs text-gray-500 bg-white border border-gray-200 rounded-lg
py-1.5 px-3 flex items-center justify-center gap-1.5
hover:bg-indigo-50 hover:text-indigo-600 hover:border-indigo-200
transition-all duration-150">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"/>
</svg>
拡大表示
</button>
</div>
<!-- Before / After 画像 -->
<div id="images" class="col-span-2 flex gap-5">
<div class="flex-1 min-w-0 space-y-2">
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Before</p>
<div class="bg-white rounded-xl border border-gray-200 shadow-sm
flex items-center justify-center p-3 overflow-hidden"
style="min-height: 180px;">
<canvas id="before"></canvas>
</div>
<button onclick="openImageModal('before')"
class="w-full text-xs text-gray-500 bg-white border border-gray-200 rounded-lg
py-1.5 px-3 flex items-center justify-center gap-1.5
hover:bg-indigo-50 hover:text-indigo-600 hover:border-indigo-200
transition-all duration-150">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"/>
</svg>
拡大表示
</button>
</div>
<div class="flex-1 min-w-0 space-y-2">
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider">After</p>
<div class="bg-white rounded-xl border border-gray-200 shadow-sm
flex items-center justify-center p-3 overflow-hidden"
style="min-height: 180px;">
<canvas id="after"></canvas>
</div>
<button onclick="openImageModal('after')"
class="w-full text-xs text-gray-500 bg-white border border-gray-200 rounded-lg
py-1.5 px-3 flex items-center justify-center gap-1.5
hover:bg-indigo-50 hover:text-indigo-600 hover:border-indigo-200
transition-all duration-150">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"/>
</svg>
拡大表示
</button>
</div>
</div>
</div>
<!-- パラメータスライダー -->
<div id="param-sliders"
class="bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex gap-6">
</div>
</div>
</div>
<!-- ============ 画像拡大モーダル ============ -->
<div id="image-modal" onclick="closeImageModal(event)"
class="fixed inset-0 z-50 bg-black/70 items-center justify-center">
<div class="relative max-w-[90vw] max-h-[90vh] flex items-center justify-center">
<button id="image-modal-close" onclick="closeImageModal()"
class="absolute top-3 right-3 z-10 w-8 h-8 flex items-center justify-center
bg-white/90 backdrop-blur rounded-lg border border-gray-200
text-gray-500 hover:bg-gray-100 text-lg leading-none shadow-sm">
×
</button>
<img id="image-modal-img" src="" alt=""
class="max-w-[90vw] max-h-[90vh] rounded-xl shadow-2xl object-contain">
</div>
</div>
<!-- ============ グラフ拡大モーダル ============ -->
<div id="graph-modal" onclick="closeGraphModal(event)"
class="fixed inset-0 z-50 bg-black/50 items-center justify-center">
<div id="graph-modal-inner"
class="relative bg-white rounded-2xl overflow-hidden shadow-2xl"
style="width: 90vw; height: 85vh;">
<button id="graph-modal-close" onclick="closeGraphModal()"
class="absolute top-3 right-3 z-10 w-8 h-8 flex items-center justify-center
bg-white/90 backdrop-blur rounded-lg border border-gray-200
text-gray-500 hover:bg-gray-100 text-lg leading-none shadow-sm">
×
</button>
<iframe id="graph-modal-frame" src="" class="w-full h-full border-none"></iframe>
</div>
</div>
<script>
const MODELS_BASE = "models";
const ASSETS_BASE = "assets";
let modelsMeta = {}; // モデル名 → パラメータ情報
let modelsCategories = []; // カテゴリ配列
let modelToCategory = {}; // モデル名 → カテゴリ ID の逆引き
let currentSession = null;
let currentModelName = null;
let isFirstRun = true;
let imgTensor = null; // {data: Float32Array, dims: [1,3,H,W]}
let imgWidth = 0;
let imgHeight = 0;
// --- メタデータ読み込み ---
async function loadModelsMeta() {
try {
const res = await fetch(`${MODELS_BASE}/models_meta.json`);
if (res.ok) {
const data = await res.json();
// 新形式 (categories + params) と旧形式 (フラット) の両方に対応
if (data.categories) {
modelsCategories = data.categories.filter(c => !c.hidden);
modelsMeta = data.params || {};
// モデル名 → カテゴリ ID の逆引きマップを構築
for (const cat of modelsCategories) {
for (const name of cat.models) {
modelToCategory[name] = cat.id;
}
}
} else {
modelsMeta = data;
}
}
} catch (e) {
console.warn("models_meta.json の読み込みに失敗。フォールバック値を使用します。", e);
}
}
// --- モデル読み込み ---
async function loadModel(name) {
setStatus(`${name}.onnx を読み込み中...`);
const catId = modelToCategory[name] || "";
const modelUrl = catId ? `${MODELS_BASE}/${catId}/${name}.onnx` : `${MODELS_BASE}/${name}.onnx`;
const session = await ort.InferenceSession.create(modelUrl);
setStatus(`${name} 読み込み完了`);
return session;
}
// --- 画像読み込み → NCHW Float32Array ---
function loadImageFromElement(imgElem) {
const canvas = document.createElement("canvas");
canvas.width = imgElem.naturalWidth || imgElem.width;
canvas.height = imgElem.naturalHeight || imgElem.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return imageDataToNCHW(imageData, canvas.width, canvas.height);
}
function imageDataToNCHW(imageData, w, h) {
const rgba = imageData.data; // Uint8ClampedArray, RGBA HWC
const chw = new Float32Array(3 * h * w);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const srcIdx = (y * w + x) * 4;
const dstBase = y * w + x;
chw[0 * h * w + dstBase] = rgba[srcIdx] / 255.0; // R
chw[1 * h * w + dstBase] = rgba[srcIdx + 1] / 255.0; // G
chw[2 * h * w + dstBase] = rgba[srcIdx + 2] / 255.0; // B
}
}
return chw;
}
async function loadDefaultImage() {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
const chw = loadImageFromElement(img);
imgWidth = img.naturalWidth;
imgHeight = img.naturalHeight;
imgTensor = new ort.Tensor("float32", chw, [1, 3, imgHeight, imgWidth]);
// Before 表示
drawBefore(img);
updateInfo();
resolve();
};
img.onerror = () => reject(new Error("sample.jpg の読み込みに失敗しました"));
img.src = "assets/sample.jpg";
});
}
function drawBefore(imgElem) {
const canvas = document.getElementById("before");
canvas.width = imgElem.naturalWidth || imgElem.width;
canvas.height = imgElem.naturalHeight || imgElem.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
}
// --- パラメータスライダー生成 ---
function buildParamSliders(session, meta) {
const container = document.getElementById("param-sliders");
container.innerHTML = "";
const inputs = session.inputNames;
// 画像入力 (rank 4) 以外を検出
// onnxruntime-web では inputNames のみ使えるので、名前で判別
const paramNames = inputs.filter(n => n !== "input" && n !== "input2");
for (const name of paramNames) {
const paramInfo = (meta && meta[name]) ? meta[name] : [0.0, 1.0, 0.5];
const [lo, hi, def] = paramInfo;
const step = (hi - lo) / 100;
const group = document.createElement("div");
group.className = "slider-group";
const label = document.createElement("label");
label.textContent = name;
group.appendChild(label);
const slider = document.createElement("input");
slider.type = "range";
slider.min = lo;
slider.max = hi;
slider.step = step;
slider.value = def;
slider.dataset.paramName = name;
group.appendChild(slider);
const valueDisplay = document.createElement("div");
valueDisplay.className = "slider-value";
valueDisplay.textContent = Number(def).toFixed(2);
group.appendChild(valueDisplay);
slider.addEventListener("input", () => {
valueDisplay.textContent = Number(slider.value).toFixed(2);
onParamChange();
});
container.appendChild(group);
}
}
function getParamValues() {
const params = {};
const sliders = document.querySelectorAll("#param-sliders input[type=range]");
for (const s of sliders) {
params[s.dataset.paramName] = new ort.Tensor("float32", new Float32Array([parseFloat(s.value)]), [1]);
}
return params;
}
// --- 推論実行 ---
async function runInference(session, imgTensor, params) {
const feeds = { input: imgTensor, ...params };
const t0 = performance.now();
const results = await session.run(feeds);
const elapsed = performance.now() - t0;
// 最初の出力を取得
const outputName = session.outputNames[0];
return { output: results[outputName], elapsed };
}
// --- 出力→Canvas に描画 ---
function displayResult(outputTensor, canvas) {
const [, c, h, w] = outputTensor.dims;
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
const imageData = ctx.createImageData(w, h);
const data = outputTensor.data; // Float32Array, NCHW
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const srcBase = y * w + x;
const dstIdx = (y * w + x) * 4;
imageData.data[dstIdx] = Math.round(Math.min(1, Math.max(0, data[0 * h * w + srcBase])) * 255); // R
imageData.data[dstIdx + 1] = Math.round(Math.min(1, Math.max(0, data[1 * h * w + srcBase])) * 255); // G
imageData.data[dstIdx + 2] = Math.round(Math.min(1, Math.max(0, data[2 * h * w + srcBase])) * 255); // B
imageData.data[dstIdx + 3] = 255; // A
}
}
ctx.putImageData(imageData, 0, 0);
}
// --- UI 制御 ---
function updateInfo() {
document.getElementById("info").innerHTML =
`入力画像サイズ: ${imgWidth} x ${imgHeight}`;
}
function setStatus(msg) {
document.getElementById("status").textContent = msg;
}
async function onModelChange() {
const selected = document.querySelector('input[name="model"]:checked');
if (!selected) return;
const name = selected.value;
if (name === currentModelName && currentSession) {
return;
}
currentModelName = name;
// 選択モデルのカテゴリだけ開き、他を閉じる
const activeCatId = modelToCategory[name] || "";
document.querySelectorAll("#model-select details").forEach(d => {
d.open = (d.dataset.catId === activeCatId);
});
// グラフ表示を更新
const graphCatId = activeCatId;
document.getElementById("graph-frame").src = graphCatId
? `${ASSETS_BASE}/${graphCatId}/${name}_graph.html`
: `${ASSETS_BASE}/${name}_graph.html`;
try {
currentSession = await loadModel(name);
const meta = modelsMeta[name] || {};
buildParamSliders(currentSession, meta);
if (imgTensor) {
await runAndDisplay();
}
} catch (e) {
setStatus(`エラー: ${e.message}`);
console.error(e);
}
}
// スライダードラッグ中の推論を間引く (デバウンス + 排他制御)
let _paramTimer = null;
let _inferenceRunning = false;
let _pendingParam = false;
function onParamChange() {
if (!currentSession || !imgTensor) return;
if (_paramTimer) clearTimeout(_paramTimer);
_paramTimer = setTimeout(async () => {
_paramTimer = null;
if (_inferenceRunning) { _pendingParam = true; return; }
_inferenceRunning = true;
try {
await runAndDisplay();
} finally {
_inferenceRunning = false;
if (_pendingParam) { _pendingParam = false; onParamChange(); }
}
}, 30);
}
const BENCH_RUNS = 5;
let _benchTimer = null;
async function runAndDisplay() {
try {
const params = getParamValues();
const { output, elapsed } = await runInference(currentSession, imgTensor, params);
displayResult(output, document.getElementById("after"));
if (isFirstRun) {
document.getElementById("timing").textContent = "処理時間: 計測中...";
isFirstRun = false;
}
// 初回描画後にベンチマーク開始
startBench();
setStatus("");
} catch (e) {
setStatus(`推論エラー: ${e.message}`);
console.error(e);
}
}
function startBench() {
if (_benchTimer) clearTimeout(_benchTimer);
_benchTimer = setTimeout(() => runBench(), 50);
}
async function runBench() {
if (!currentSession || !imgTensor) return;
const params = getParamValues();
const times = [];
for (let i = 0; i < BENCH_RUNS; i++) {
const { elapsed } = await runInference(currentSession, imgTensor, params);
times.push(elapsed);
}
const avg = times.reduce((a, b) => a + b, 0) / times.length;
document.getElementById("timing").textContent =
`処理時間: ${avg.toFixed(2)} ms (${BENCH_RUNS}回平均)`;
}
// --- ファイルアップロード ---
document.getElementById("image-file").addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file) return;
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = async () => {
const chw = loadImageFromElement(img);
imgWidth = img.naturalWidth;
imgHeight = img.naturalHeight;
imgTensor = new ort.Tensor("float32", chw, [1, 3, imgHeight, imgWidth]);
drawBefore(img);
updateInfo();
URL.revokeObjectURL(url);
if (currentSession) {
await runAndDisplay();
}
};
img.src = url;
});
// --- モデル選択ラジオボタン生成 (カテゴリ別折りたたみ) ---
function buildModelSelect() {
const container = document.getElementById("model-select");
container.innerHTML = "";
if (modelsCategories.length > 0) {
// カテゴリ構造がある場合: <details> で折りたたみ表示
for (let ci = 0; ci < modelsCategories.length; ci++) {
const cat = modelsCategories[ci];
const details = document.createElement("details");
details.dataset.catId = cat.id;
// 最初のカテゴリはデフォルト開き
if (ci === 0) details.open = true;
const summary = document.createElement("summary");
// 日英2行表示
const jaSpan = document.createElement("span");
jaSpan.textContent = cat.label_ja || "";
const enSpan = document.createElement("span");
enSpan.textContent = cat.label_en || "";
enSpan.style.cssText = "display:block; font-size:11px; font-weight:normal; color:#888;";
summary.appendChild(jaSpan);
summary.appendChild(enSpan);
details.appendChild(summary);
for (const name of cat.models) {
const label = document.createElement("label");
const radio = document.createElement("input");
radio.type = "radio";
radio.name = "model";
radio.value = name;
radio.addEventListener("change", onModelChange);
label.appendChild(radio);
label.appendChild(document.createTextNode(name));
details.appendChild(label);
}
container.appendChild(details);
}
} else {
// フォールバック: フラットなラジオボタンリスト
for (const name of Object.keys(modelsMeta)) {
const label = document.createElement("label");
const radio = document.createElement("input");
radio.type = "radio";
radio.name = "model";
radio.value = name;
radio.addEventListener("change", onModelChange);
label.appendChild(radio);
label.appendChild(document.createTextNode(name));
container.appendChild(label);
}
}
}
// --- 初期化 ---
async function init() {
await loadModelsMeta();
buildModelSelect();
try {
await loadDefaultImage();
} catch (e) {
setStatus("sample.jpg が見つかりません。画像をアップロードしてください。");
console.warn(e);
}
// 最初のモデルを選択
const first = document.querySelector('input[name="model"]');
if (first) {
first.checked = true;
await onModelChange();
}
}
// --- モデル検索 ---
document.getElementById("model-search").addEventListener("input", (e) => {
const q = e.target.value.trim().toLowerCase();
document.querySelectorAll("#model-select details").forEach(details => {
let anyVisible = false;
details.querySelectorAll("label").forEach(label => {
const name = label.textContent.trim().toLowerCase();
const match = !q || name.includes(q);
label.style.display = match ? "" : "none";
if (match) anyVisible = true;
});
details.style.display = anyVisible ? "" : "none";
if (q && anyVisible) details.open = true;
});
});
init();
// --- 画像拡大モーダル ---
function openImageModal(canvasId) {
const canvas = document.getElementById(canvasId);
if (!canvas || canvas.width === 0) return;
document.getElementById("image-modal-img").src = canvas.toDataURL();
document.getElementById("image-modal").classList.add("active");
}
function closeImageModal(e) {
if (e && e.target !== document.getElementById("image-modal") && e.target !== document.getElementById("image-modal-close")) return;
document.getElementById("image-modal").classList.remove("active");
document.getElementById("image-modal-img").src = "";
}
// --- グラフ拡大モーダル ---
function openGraphModal() {
const src = document.getElementById("graph-frame").src;
if (!src) return;
const modalFrame = document.getElementById("graph-modal-frame");
modalFrame.src = src;
// iframe 内の pyvis 固定高さを親いっぱいに上書き
modalFrame.onload = () => {
try {
const innerDoc = modalFrame.contentDocument || modalFrame.contentWindow.document;
const canvas = innerDoc.getElementById("mynetwork");
if (canvas) canvas.style.height = "100%";
innerDoc.documentElement.style.height = "100%";
innerDoc.body.style.height = "100%";
} catch (e) { /* 同一オリジン制限時は無視 */ }
};
document.getElementById("graph-modal").classList.add("active");
}
function closeGraphModal(e) {
if (e && e.target !== document.getElementById("graph-modal") && e.target !== document.getElementById("graph-modal-close")) return;
document.getElementById("graph-modal").classList.remove("active");
document.getElementById("graph-modal-frame").src = "";
}
</script>
</body>
</html>