Spaces:
Running

File size: 33,338 Bytes
f78cf71
4fbfe0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f78cf71
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
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>LoRA メタデータエディター</title>
<style>
  :root{color-scheme:light;--ink:#182932;--muted:#506671;--border:#bbcbd0;--teal:#006859;--pale:#e9f5f1;--paper:#fff;--mono:ui-monospace,Consolas,monospace}
  *{box-sizing:border-box}
  body{margin:0;background:#f4f6f4;color:var(--ink);font-family:"Inter","Yu Gothic UI",Meiryo,sans-serif;line-height:1.55}
  main{max-width:1060px;margin:auto;padding:clamp(18px,4vw,54px) clamp(14px,3.5vw,40px) 36px}
  header,.row,.section-head,.actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
  header{border-top:4px solid var(--ink);padding-top:18px;margin-bottom:24px;justify-content:space-between}
  h1,h2,h3,p{margin:0} h1{font-size:clamp(22px,3.5vw,33px);letter-spacing:-.035em} h2{font-size:17px} h3{font-size:14px}
  .hint,.status{font-size:13px;color:var(--muted)} .hint{margin-top:5px} .mono,code{font-family:var(--mono)}
  .button,button{display:inline-flex;justify-content:center;align-items:center;min-height:38px;background:#fff;color:var(--ink);border:1px solid var(--border);border-radius:7px;padding:7px 13px;font:600 14px/1.4 inherit;font-family:inherit;font-size:14px;font-weight:600;cursor:pointer}
  button:hover,.button:hover{background:#edf4f2;border-color:#76968e} button:disabled{opacity:.55;cursor:default}
  .primary{background:var(--teal);border-color:var(--teal);color:white}.primary:hover{background:#005448;color:white}
  :focus-visible{outline:3px solid #008f82;outline-offset:3px} [hidden]{display:none!important}
  .drop{border:2px dashed #96b4ac;background:#f9fcfa;border-radius:14px;padding:clamp(42px,9vw,100px) 20px;text-align:center}
  .drop h2{font-size:clamp(18px,3vw,24px);margin:17px 0 4px}.drop button{margin-top:20px}
  .file-icon{display:inline-grid;place-items:center;width:58px;height:66px;background:var(--pale);border:1px solid #87b1a8;border-radius:7px;color:var(--teal);font:700 22px var(--mono);box-shadow:4px 4px 0 #cfdfd8}
  .dragging .drop,.dragging .filebar{outline:3px solid var(--teal);outline-offset:3px;background:#e4f4ed}
  .filebar,.card,details{background:var(--paper);border:1px solid var(--border);border-radius:10px}
  .filebar{padding:12px 17px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:12px}.filename{overflow-wrap:anywhere;font-size:14px;font-weight:650}.filebar button{flex:none}
  .columns{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(240px,1fr);gap:16px;align-items:start}
  .card{padding:clamp(16px,2.4vw,24px);min-width:0}.card h2{margin-bottom:13px}
  .side{display:grid;gap:16px;min-width:0}.field{display:block;margin-top:16px}.label,label{font-size:14px;font-weight:650}
  .key{font:12px var(--mono);color:var(--muted);overflow-wrap:anywhere}.section-head{justify-content:space-between;gap:6px}
  input,textarea,select{border:1px solid var(--border);border-radius:6px;background:#fff;color:var(--ink);font:inherit;width:100%;padding:8px 10px}
  input,textarea{margin-top:5px}textarea{resize:vertical;min-height:62px;line-height:1.55} .alias{font-family:var(--mono);font-size:17px}
  .tagbox{margin:16px 0 0;background:var(--pale);border-left:3px solid var(--teal);border-radius:4px;padding:12px 15px}.tagbox code{display:block;overflow-wrap:anywhere;color:#005647;margin-top:4px;font-size:16px}
  .tagbox small{color:#45665d}.warn{color:#8b420a}.save-card .primary{width:100%;margin-top:14px}
  details{margin-top:16px}summary{cursor:pointer;font-weight:650;padding:14px 18px} summary span{color:var(--muted);font-size:13px;margin-left:8px}
  .advanced{padding:0 18px 18px}.browse{display:grid;grid-template-columns:minmax(195px,1fr) minmax(0,1.65fr);gap:14px;margin-top:12px}
  select{font:13px/1.5 var(--mono);height:175px;padding:4px}option{padding:3px} .inspect textarea{height:146px;font:13px/1.55 var(--mono)}
  .status{margin-top:10px;overflow-wrap:anywhere}.status:empty{display:none}.error{color:#a1281c;font-weight:600}
  .lang{display:flex;gap:4px}.lang button[aria-pressed="true"]{background:var(--ink);color:white;border-color:var(--ink)}
  .pair{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(210px,100%),1fr));gap:12px 18px}
  .section-head label,.inspect label{overflow-wrap:anywhere}
  .inspect select{height:auto;min-height:36px;font:inherit;margin-top:5px}
  .key-help{min-height:1.5em;margin:4px 0}.save-card>button{width:100%;margin-top:8px}
  #jsonHelp,#jsonInfo{overflow-wrap:anywhere} .minor{min-height:30px;padding:4px 8px;font-size:12px}
  #weight{width:8em}.subsection{margin-top:16px;padding-top:13px;border-top:1px solid var(--border)}
  @media(max-width:700px){.columns,.browse{grid-template-columns:1fr}.side{gap:12px}.filebar{align-items:flex-start}.filebar button{min-height:32px;padding:5px 8px}select{height:116px}header{margin-bottom:16px}.drop{padding-block:42px}}
</style>
</head>
<body>
<main>
  <header><h1 data-en="LoRA Metadata Editor">LoRA メタデータエディター</h1><div class="lang" role="group" aria-label="日本語 / English"><button type="button" id="ja" lang="ja">日本語</button><button type="button" id="en" lang="en">English</button></div></header>
  <input id="file" type="file" accept=".safetensors,.json" multiple hidden>
  <input id="jsonFile" type="file" accept=".json" hidden>
  <section class="drop" id="drop">
    <span class="file-icon" aria-hidden="true">{ }</span>
    <h2 data-en="Drop a LoRA file here">LoRAファイルをここにドロップ</h2>
    <p class="hint" data-en="Open a .safetensors file locally. You can include its Forge settings .json file.">.safetensors をこの端末で開きます。Forgeの設定JSONも一緒に選べます。</p>
    <button type="button" class="primary" id="open" data-en="Choose files">ファイルを選択</button>
  </section>
  <p id="loadStatus" class="status" role="status"></p>
  <div id="editor" hidden>
    <section class="filebar" aria-labelledby="sourceLabel">
      <div><div class="key" id="sourceLabel" data-en="Source file">読み込み元</div><div class="filename" id="sourceName"></div><div class="hint" id="fileInfo"></div></div>
      <button type="button" id="change" data-en="Open another file">別のファイルを開く</button>
    </section>
    <div class="columns">
      <section class="card">
        <div class="section-head"><h2><label for="alias" style="font:inherit" data-en="LoRA name in prompt">プロンプトに入る名前</label></h2><span class="key">ss_output_name</span></div>
        <input id="alias" class="alias" autocomplete="off" spellcheck="false">
        <div class="actions" style="margin-top:8px"><button type="button" id="useFilename" data-en="Use source filename">ファイル名から入力</button></div>
        <div class="subsection"><label for="weight" data-en="Default strength">初期強度</label>
          <input id="weight" type="number" step="any" placeholder="0.7" aria-describedby="weightHelp">
          <p class="hint" id="weightHelp" data-en="Saved in the Forge settings JSON. Leave blank or enter 0 to use your Forge default (shown here as 1).">Forge設定JSONに保存します。空欄または0でForgeの既定値を使います(プレビューでは1)。</p>
        </div>
        <div class="tagbox"><small data-en="Forge Neo prompt preview">Forge Neo のタグプレビュー</small><code id="tag"></code></div>
        <p id="tagNote" class="hint"></p>
      </section>
      <div class="side">
        <section class="card save-card">
          <h2 data-en="Save your changes">編集内容を保存</h2>
          <div class="section-head"><label for="exportName" data-en="Output filename">保存ファイル名</label><button class="minor" type="button" id="originalName" data-en="Use original name">元の名前を使う</button></div>
          <input id="exportName" autocomplete="off" spellcheck="false">
          <button type="button" class="primary" id="save" data-en="Save LoRA as…">LoRAを別名で保存</button>
          <button type="button" id="saveJson" data-en="Save Forge settings (.json)">Forge設定を保存(.json)</button>
          <p class="hint" id="jsonHelp"></p>
          <p id="saveStatus" class="status" role="status"></p>
        </section>
      </div>
    </div>
    <section class="card" style="margin-top:16px">
      <h2 data-en="Model information">モデル情報</h2>
      <div id="modelFields" class="pair"></div>
      <div class="subsection">
        <div class="section-head"><h3 data-en="Forge card settings">Forgeカードの設定</h3><button id="loadJson" type="button" data-en="Load settings JSON">設定JSONを読み込む</button></div>
        <p id="jsonInfo" class="hint"></p>
        <div class="pair" id="forgeFields"></div>
      </div>
    </section>
    <details id="details">
      <summary><b data-en="Other metadata">その他のメタデータ</b><span id="keyCount"></span></summary>
      <div class="advanced">
        <label for="query" data-en="Find a field">項目を検索</label><input id="query" type="search" placeholder="ss_epoch" spellcheck="false">
        <div class="browse">
          <div><label for="keys" data-en="Field">項目</label><select id="keys" size="7"></select></div>
          <div class="inspect"><label for="value" id="valueLabel"></label><p class="hint key-help" id="keyHelp"></p><textarea id="value" spellcheck="false" aria-describedby="keyHelp"></textarea><select id="boolValue" aria-describedby="keyHelp" hidden></select><input id="suggestedValue" list="choices" spellcheck="false" aria-describedby="keyHelp" hidden><datalist id="choices"></datalist></div>
        </div>
      </div>
    </details>
  </div>
</main>
<script>
"use strict";
const el = id => document.getElementById(id);
let language = "ja";
try { if (localStorage.getItem("lora-editor-language") === "en") language = "en"; } catch {}
const t = (ja, en) => language === "ja" ? ja : en;
// id, on-disk key, label (ja/en), help (ja/en), multiline
const modelFields = [
  ["title","modelspec.title","タイトル","Title","一覧などに表示するモデル名です。","Display title for model listings."],
  ["author","modelspec.author","作者","Author","作者名やチーム名です。","Name of the creator or team."],
  ["description","modelspec.description","説明","Description","モデルの用途や使い方を記録します。","Describe what this LoRA does and how to use it.",true],
  ["tags","modelspec.tags","分類タグ","Tags","分類や検索に使うキーワードです。","Keywords for organizing and finding the model."],
  ["notes","notes","メモ","Notes","LoRA本体に保存する自由記入欄です。","Free-form notes stored inside the LoRA file.",true]
];
const forgeFields = [
  ["trigger","activation text","トリガーワード","Activation text","カード選択時にポジティブプロンプトへ追加する語句です。","Words appended to the positive prompt when you select the card."],
  ["negative","negative text","ネガティブ用の語句","Negative prompt text","カードのネガティブプロンプト用に登録する語句です。","Words registered for the card’s negative prompt."]
];
const basic = {alias:"ss_output_name", ...Object.fromEntries(modelFields.map(([id,key]) => [id,key]))};
const mainKeys = new Set(Object.values(basic));
const help = {
  "format":["学習ツールが記録したファイル形式です。","File format recorded by the training tool."],
  "modelspec.architecture":["モデルの構造を示す識別子です。","Identifier for the model architecture."],
  "modelspec.date":["モデルに記録された日付です。","Date recorded for this model."],
  "modelspec.implementation":["モデルの実装を示す参照先です。","Reference to the implementation of the model."],
  "modelspec.resolution":["モデルに記録された基準解像度です。","Reference image resolution recorded for the model."],
  "modelspec.sai_model_spec":["メタデータが従うModelSpecのバージョンです。","Version of the ModelSpec metadata format."],
  "modelspec.license":["モデルに付けられたライセンスの表記です。","License recorded for this model."],
  "modelspec.trigger_phrase":["作者がモデル内に記録したトリガー語句です。","Trigger phrase embedded in the model by its author."],
  name:["作成ツールが記録した名前です。","Name recorded by the creation tool."],
  software:["作成に使ったソフトウェアの情報です。","Software used to create the model."],
  version:["作成ツールが記録したバージョンです。","Version recorded by the creation tool."],
  training_info:["作成ツールがまとめた学習情報です。","Training details recorded by the creation tool."],
  civitai_gpu_architecture:["学習に使用したGPUのアーキテクチャです。","GPU architecture used during training."],
  civitai_gpu_vram_gb:["学習に使用したGPUのVRAM容量(GB)です。","Training GPU memory in GB."],
  ss_base_model_version:["学習元のモデル系列・バージョンです。","Family or version of the training base model."],
  ss_sd_model_name:["学習元チェックポイントの名前です。","Name of the checkpoint used for training."],
  ss_batch_size:["学習時に1バッチで処理した件数です。","Number of samples per training batch."],
  ss_cache_latents:["学習時に潜在表現をキャッシュしたかを示します。","Whether latents were cached during training."],
  ss_caption_dropout_rate:["学習時にキャプションを省く確率です。","Probability of dropping a caption during training."],
  ss_dataset_dirs:["学習データのフォルダー別の情報です。","Training dataset information by folder."],
  ss_epoch:["このファイルを保存した時点の学習エポックです。","Training epoch recorded at the time of saving."],
  ss_full_fp16:["学習時にフルFP16設定を使用したかを示します。","Whether full FP16 training was enabled."],
  ss_gradient_accumulation_steps:["重みの更新前に勾配を累積する回数です。","Number of gradient accumulation steps per update."],
  ss_gradient_checkpointing:["学習中に中間結果を再計算してメモリを節約したかを示します。","Whether training recomputed intermediates to save memory."],
  ss_learning_rate:["学習時の基本学習率です。","Base learning rate used during training."],
  ss_lowram:["学習ツールの低RAM設定が有効だったかを示します。","Whether the trainer used its low-RAM setting."],
  ss_lr_scheduler:["学習率の変化を決める方式です。","Schedule used to adjust the learning rate."],
  ss_max_grad_norm:["学習時の勾配クリッピングに使う上限です。","Maximum gradient norm for clipping."],
  ss_max_train_steps:["設定された最大学習ステップ数です。","Maximum configured number of training steps."],
  ss_mixed_precision:["学習時に選んだ混合精度です。","Mixed-precision mode used during training."],
  ss_network_alpha:["学習時のネットワークのalpha設定です。","Network alpha recorded during training."],
  ss_network_dim:["学習時に設定したネットワークのランクです。","Network rank configured during training."],
  ss_network_module:["学習に使用したネットワークモジュール名です。","Network module used during training."],
  ss_noise_offset:["学習ノイズに加えたオフセットの設定です。","Noise offset configured during training."],
  ss_num_batches_per_epoch:["1エポックに含まれるバッチ数です。","Number of training batches per epoch."],
  ss_num_epochs:["学習で設定された総エポック数です。","Total number of training epochs configured."],
  ss_num_reg_images:["正則化に使用した画像の枚数です。","Number of regularization images."],
  ss_num_train_images:["記録された学習画像の枚数です。","Recorded number of training images."],
  ss_optimizer:["学習時に重みの更新に使った方式です。","Optimizer used to update weights during training."],
  ss_steps:["保存時点で記録された学習ステップ数です。","Training step count recorded at save time."],
  ss_tag_frequency:["学習キャプション内のタグとその出現回数です。","Tag counts from the training captions."],
  ss_text_encoder_lr:["テキストエンコーダーの学習率です。","Learning rate for the text encoder."],
  ss_unet_lr:["画像モデル側の学習率です。","Learning rate for the image model."],
  ss_v2:["学習ツールのStable Diffusion v2設定が有効だったかを示します。","Whether the trainer enabled its Stable Diffusion v2 mode."],
  sshs_model_hash:["学習ツールが記録したモデルの照合用ハッシュです。","Model verification hash recorded by the training tool."],
  sshs_legacy_hash:["旧形式の照合用ハッシュです。","Legacy verification hash recorded by the training tool."]
};
const extension = /\.safetensors$/i;
const maxHeader = 100_000_000; // safetensors format limit
let model = null, request = 0, edited = false, forgeEdited = false;
let forge = {}, forgeSource = "";
let advancedKeys = [];

function makeFields(container, fields) {
  for (const [id,key,ja,en,jaHelp,enHelp,multiline] of fields) {
    const wrapper = document.createElement("div");
    const head = document.createElement("div");
    head.className = "section-head";
    const label = document.createElement("label");
    label.htmlFor = id; label.textContent = ja; label.dataset.en = en;
    const keyLabel = document.createElement("span");
    keyLabel.className = "key"; keyLabel.textContent = key;
    head.append(label,keyLabel);
    const input = document.createElement(multiline ? "textarea" : "input");
    input.id = id; input.setAttribute("aria-describedby", id+"Help");
    if (multiline) input.rows = 2;
    const note = document.createElement("p");
    note.id = id+"Help"; note.className = "hint"; note.textContent = jaHelp; note.dataset.en = enHelp;
    wrapper.append(head,input,note); el(container).append(wrapper);
  }
}
makeFields("modelFields",modelFields);
makeFields("forgeFields",forgeFields);
const messages = {};
function status(id, ja, en = ja, error = false) {
  messages[id] = [ja,en,error];
  const box = el(id);
  box.textContent = t(ja,en);
  box.classList.toggle("error", error);
}
function record(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
async function readFile(file) {
  const first = await file.slice(0, 8).arrayBuffer();
  if (first.byteLength !== 8) throw Error("ファイルの先頭8バイトを読み取れません。");
  const length = new DataView(first).getBigUint64(0, true);
  if (!length || length > BigInt(Math.min(maxHeader, file.size - 8))) throw Error("ヘッダーの長さが不正です。");
  const start = 8 + Number(length);
  const bytes = await file.slice(8, start).arrayBuffer();
  const text = new TextDecoder("utf-8", {fatal:true}).decode(bytes);
  if (!text.startsWith("{")) throw Error("safetensors ヘッダーが見つかりません。");
  const header = JSON.parse(text);
  const meta = Object.hasOwn(header, "__metadata__") ? header.__metadata__ : {};
  if (!record(meta) || Object.values(meta).some(v => typeof v !== "string")) throw Error("メタデータの形式が不正です。");
  const ranges = [];
  for (const [key, t] of Object.entries(header)) {
    if (key === "__metadata__") continue;
    if (!record(t) || typeof t.dtype !== "string" || !Array.isArray(t.shape) ||
        !t.shape.every(n => Number.isSafeInteger(n) && n >= 0) ||
        !Array.isArray(t.data_offsets) || t.data_offsets.length !== 2 ||
        !t.data_offsets.every(Number.isSafeInteger)) throw Error("テンソル情報を読み取れません。");
    ranges.push(t.data_offsets);
  }
  ranges.sort((a,b) => a[0] - b[0] || a[1] - b[1]);
  let end = 0;
  for (const [from, to] of ranges) {
    if (from !== end || to < from) throw Error("テンソルの格納範囲が不正です。");
    end = to;
  }
  if (end !== file.size - start) throw Error("ファイルのサイズと重みデータの長さが一致しません。");
  return {file, header, start, meta:Object.assign(Object.create(null), meta), count:ranges.length};
}
function buildFile() {
  const header = {...model.header};
  if (Object.keys(model.meta).length || Object.hasOwn(header, "__metadata__")) header.__metadata__ = model.meta;
  const bytes = new TextEncoder().encode(JSON.stringify(header));
  const length = Math.ceil(bytes.length / 8) * 8;
  if (length > maxHeader) throw Error("メタデータが safetensors のヘッダー上限を超えています。");
  const prefix = new Uint8Array(8);
  new DataView(prefix.buffer).setBigUint64(0, BigInt(length), true);
  const spaces = new Uint8Array(length - bytes.length).fill(32);
  return new Blob([prefix, bytes, spaces, model.file.slice(model.start)], {type:"application/octet-stream"});
}
function outputName() {
  const name = el("exportName").value.trim();
  return !name || extension.test(name) ? name : name + ".safetensors";
}
function refreshLabels() {
  document.documentElement.lang = language;
  for (const node of document.querySelectorAll("[data-en]")) {
    node.dataset.ja ??= node.textContent;
    node.textContent = t(node.dataset.ja,node.dataset.en);
  }
  document.title = document.querySelector("h1").textContent;
  for (const code of ["ja","en"]) el(code).setAttribute("aria-pressed", String(language === code));
  for (const [id,args] of Object.entries(messages)) status(id,...args);
  if (model) {
    const size = (model.file.size / 1048576).toLocaleString(language,{maximumFractionDigits:1});
    const count = model.count.toLocaleString(language);
    el("fileInfo").textContent = size + " MiB · " + t("テンソル " + count + " 件",count + " tensors");
    el("keyCount").textContent = advancedKeys.length + t(" 件"," fields");
    selectKey(); preview(); refreshForgeInfo();
  }
}
for (const code of ["ja","en"]) {
  el(code).onclick = () => {
    language = code;
    try { localStorage.setItem("lora-editor-language",code); } catch {}
    refreshLabels();
  };
}
function refreshForgeInfo() {
  el("jsonHelp").textContent = t("設定JSONは同名のLoRAと同じフォルダーに置きます。","Place the settings JSON next to the LoRA with the same base filename.") +
    " " + outputName().replace(extension,".json");
  el("jsonInfo").textContent = forgeSource ? t("読み込み元 ","Loaded from ") + forgeSource :
    t("既存のJSONがある場合は読み込んでから編集してください。","If you already have a settings JSON, load it before editing.");
}
function preview() {
  const alias = model.meta.ss_output_name ?? outputName().replace(extension, "");
  const strength = el("weight");
  el("tag").textContent = alias && !strength.validity.badInput
    ? "<lora:" + alias + ":" + (strength.valueAsNumber || 1) + ">" +
      (forge["activation text"] ? " " + forge["activation text"] : "") : "—";
  const note = el("tagNote");
  note.classList.toggle("warn", !alias || /[:<>\r\n]/.test(alias));
  if (!alias) note.textContent = t("別名または保存ファイル名を入力してください。","Enter an alias or output filename.");
  else if (/[:<>\r\n]/.test(alias)) note.textContent = t("この名前にはタグの区切りに使う文字が含まれています。","This alias contains a character used as a tag delimiter.");
  else note.textContent = Object.hasOwn(model.meta, "ss_output_name")
    ? t("Forge Neo の「Alias from file」設定で使うタグです。","Shown for Forge Neo’s “Alias from file” setting.")
    : t("別名が未設定のため、保存ファイル名から表示しています。","No alias is set. The preview uses the output filename.");
}
function selectKey() {
  const key = el("keys").value;
  const chosen = el("keys").selectedIndex >= 0;
  const value = chosen ? model.meta[key] : "";
  const bool = /^(true|false)$/i.test(value);
  const options = key === "ss_mixed_precision" ? ["no","fp16","bf16"] : [];
  el("value").hidden = bool || options.length > 0; el("value").disabled = !chosen;
  el("boolValue").hidden = !bool;
  el("suggestedValue").hidden = bool || !options.length;
  el("valueLabel").htmlFor = bool ? "boolValue" : options.length ? "suggestedValue" : "value";
  el("valueLabel").textContent = chosen ? key : t("該当する項目はありません","No matching fields");
  el("keyHelp").textContent = !chosen ? "" : Object.hasOwn(help,key) ? t(...help[key]) :
    t("作成ツール独自の項目です。値を文字列として編集できます。","Producer-specific field. Its stored value is a string.");
  if (bool) {
    const variants = value === value.toUpperCase() ? ["TRUE","FALSE"] :
      value === value.toLowerCase() ? ["true","false"] : ["True","False"];
    variants[value.toLowerCase() === "true" ? 0 : 1] = value;
    el("boolValue").replaceChildren(...variants.map((v,i) => new Option(v + t(i ? "(いいえ)" : "(はい)",i ? " (no)" : " (yes)"),v)));
    el("boolValue").value = value;
  } else if (options.length) {
    el("choices").replaceChildren(...options.map(v => new Option(v,v)));
    el("suggestedValue").value = value;
  } else el("value").value = value;
}
function filterKeys() {
  const select = el("keys"), previous = select.value;
  const query = el("query").value.trim().toLowerCase();
  const keys = advancedKeys.filter(k => k.toLowerCase().includes(query));
  select.replaceChildren(...keys.map(k => new Option(k, k)));
  select.selectedIndex = keys.includes(previous) ? keys.indexOf(previous) : keys.length ? 0 : -1;
  selectKey();
}
function showFile() {
  const {file, meta} = model;
  el("drop").hidden = true;
  el("editor").hidden = false;
  el("sourceName").textContent = file.name;
  for (const [id, key] of Object.entries(basic)) el(id).value = meta[key] ?? "";
  el("exportName").value = file.name.replace(extension, "") + "-edited.safetensors";
  advancedKeys = Object.keys(meta).filter(k => !mainKeys.has(k)).sort();
  el("details").open = false;
  el("query").value = "";
  filterKeys();
  showForge();
  refreshLabels();
  status("saveStatus", "");
  el("alias").focus();
}
function showForge() {
  el("weight").value = forge["preferred weight"] ?? "";
  for (const [id,key] of forgeFields) el(id).value = forge[key] ?? "";
  refreshForgeInfo(); preview();
}
const errorsEn = {
  "ファイルの先頭8バイトを読み取れません。":"The first eight file bytes could not be read.",
  "ヘッダーの長さが不正です。":"Invalid header length.",
  "safetensors ヘッダーが見つかりません。":"Missing safetensors header.",
  "メタデータの形式が不正です。":"Invalid metadata format.",
  "テンソル情報を読み取れません。":"Invalid tensor information.",
  "テンソルの格納範囲が不正です。":"Invalid tensor data offsets.",
  "ファイルのサイズと重みデータの長さが一致しません。":"File size does not match the tensor data length.",
  "メタデータが safetensors のヘッダー上限を超えています。":"Metadata exceeds the safetensors header limit.",
  "設定JSONにはオブジェクトを指定してください。":"The settings JSON must contain an object."
};
async function openFiles(files) {
  if (!files.length) return;
  const current = ++request;
  const filesJson = files.filter(f => /\.json$/i.test(f.name));
  const models = files.filter(f => !filesJson.includes(f));
  const file = models[0], json = filesJson[0];
  if (models.length > 1 || filesJson.length > 1 || (!file && !model)) {
    status("loadStatus","LoRAを1つ選んでください。設定JSONを1つ一緒に開けます。","Select one LoRA file, optionally with one settings JSON.",true);
    return;
  }
  status("loadStatus", "読み込み中…","Reading files…");
  try {
    const loaded = file ? await readFile(file) : null;
    const settings = json ? JSON.parse((await json.text()).replace(/^\uFEFF/,"")) : {};
    if (!record(settings)) throw Error("設定JSONにはオブジェクトを指定してください。");
    if (current !== request) return;
    const discardsChanges = forgeEdited || (file && edited);
    if (discardsChanges && !confirm(file
        ? t("未保存の編集を破棄して別のLoRAを開きますか?","Discard unsaved edits and open another LoRA?")
        : t("未保存のForge設定を読み込んだJSONで置き換えますか?","Replace unsaved Forge settings with this JSON?"))) {
      status("loadStatus", "");
      return;
    }
    forge = settings; forgeSource = json?.name || ""; forgeEdited = false;
    if (loaded) { model = loaded; edited = false; showFile(); }
    else { showForge(); updateStatus(); }
    status("loadStatus", "");
  } catch (err) {
    if (current === request) status("loadStatus","開けませんでした。 " + err.message,"Could not open file. " + (errorsEn[err.message] ?? err.message),true);
  }
}
el("open").onclick = el("change").onclick = () => el("file").click();
el("loadJson").onclick = () => el("jsonFile").click();
el("file").onchange = el("jsonFile").onchange = event => {
  const files = Array.from(event.target.files);
  event.target.value = "";
  openFiles(files);
};
let dragDepth = 0;
for (const type of ["dragenter","dragover","dragleave","drop"]) {
  window.addEventListener(type, event => {
    if (!event.dataTransfer.types.includes("Files")) return;
    event.preventDefault();
    if (type === "dragenter") dragDepth++;
    if (type === "dragleave") dragDepth = Math.max(0, dragDepth - 1);
    if (type === "drop") {
      dragDepth = 0;
      openFiles(Array.from(event.dataTransfer.files));
    }
    document.body.classList.toggle("dragging", dragDepth > 0);
  });
}
function updateStatus(saved = "") {
  const pending = edited && forgeEdited ? ["LoRA・Forge設定が未保存です。","LoRA and Forge settings have unsaved changes."] :
    edited ? ["LoRAの変更が未保存です。","LoRA changes are unsaved."] :
    forgeEdited ? ["Forge設定が未保存です。","Forge settings are unsaved."] : ["",""];
  status("saveStatus", (saved ? saved + " のダウンロードを開始しました。 " : "") + pending[0],
    (saved ? "Download started for " + saved + ". " : "") + pending[1]);
}
function markEdit() {
  edited = true;
  updateStatus();
}
for (const [id, key] of Object.entries(basic)) {
  el(id).oninput = () => {
    const value = el(id).value;
    if (id === "alias" && !value) delete model.meta[key];
    else model.meta[key] = value;
    if (id === "alias") preview();
    markEdit();
  };
}
el("useFilename").onclick = () => {
  el("alias").value = model.file.name.replace(extension, "");
  el("alias").dispatchEvent(new Event("input"));
  el("alias").focus();
};
el("query").oninput = filterKeys;
el("keys").onchange = selectKey;
el("value").oninput = el("suggestedValue").oninput = el("boolValue").onchange = event => {
  if (el("keys").selectedIndex < 0) return;
  model.meta[el("keys").value] = event.target.value;
  markEdit();
};
el("weight").oninput = () => {
  const weight = el("weight");
  if (!weight.validity.badInput) {
    if (weight.value === "") delete forge["preferred weight"];
    else forge["preferred weight"] = weight.valueAsNumber;
  }
  forgeEdited = true; preview(); updateStatus();
};
for (const [id,key] of forgeFields) {
  el(id).oninput = () => {
    forge[key] = el(id).value;
    forgeEdited = true; preview(); updateStatus();
  };
}
el("exportName").oninput = () => { preview(); refreshForgeInfo(); updateStatus(); };
el("originalName").onclick = () => {
  el("exportName").value = model.file.name;
  el("exportName").dispatchEvent(new Event("input"));
};
function saveFile(asJson) {
  let name = outputName();
  if (!name || /[<>:"/\\|?*\u0000-\u001f]/.test(name)) {
    status("saveStatus","保存に使えるファイル名を入力してください。","Enter a valid output filename.",true);
    el("exportName").focus();
    return;
  }
  if (asJson && !el("weight").reportValidity()) return;
  try {
    if (asJson) name = name.replace(extension,".json");
    const blob = asJson ? new Blob([JSON.stringify(forge,null,2)+"\n"],{type:"application/json"}) : buildFile();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = name;
    document.body.append(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
    if (asJson) forgeEdited = false; else edited = false;
    updateStatus(name);
  } catch (err) {
    status("saveStatus","書き出せませんでした。 " + err.message,"Could not export. " + (errorsEn[err.message] ?? err.message),true);
  }
}
el("save").onclick = () => saveFile(false);
el("saveJson").onclick = () => saveFile(true);
window.addEventListener("beforeunload", event => {
  if (edited || forgeEdited) { event.preventDefault(); event.returnValue = ""; }
});
refreshLabels();
</script>
</body>
</html>