-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhome1.html
More file actions
2886 lines (2717 loc) · 151 KB
/
Copy pathhome1.html
File metadata and controls
2886 lines (2717 loc) · 151 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>KCAC Annotation Editor — Cloud (Drive) Edition</title>
<style>
:root {
--bg: #0e1116; --panel: #161b22; --panel-2: #1c2128; --border: #30363d;
--text: #e6edf3; --muted: #7d8590; --accent: #2f81f7; --accent-2: #1f6feb;
--danger: #f85149; --success: #3fb950; --warning: #d29922;
--line-color: #3fb950; --layout-color: #f78166; --selected: #ffd60a;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--bg); color: var(--text); }
body { display: flex; flex-direction: column; }
.topbar { display: flex; align-items: center; gap: 10px; padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--border); flex-shrink: 0; }
.topbar h1 { font-size: 13px; font-weight: 600; letter-spacing: 0.5px; color: var(--accent); white-space: nowrap; }
.topbar .sep { width: 1px; height: 24px; background: var(--border); }
.btn { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); padding: 6px 12px; font-size: 12px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; font-family: inherit; transition: all 0.15s; white-space: nowrap; }
.btn:hover { background: #2d333b; border-color: var(--accent); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.btn.primary { background: var(--accent-2); border-color: var(--accent-2); }
.btn.primary:hover { background: var(--accent); }
.btn.danger { color: var(--danger); }
.btn.danger:hover { background: rgba(248,81,73,0.1); border-color: var(--danger); }
.btn.success { color: var(--success); }
.btn.success:hover { background: rgba(63,185,80,0.1); border-color: var(--success); }
input[type="file"] { display: none; }
label.btn { cursor: pointer; }
.main { display: flex; flex: 1; overflow: hidden; }
.file-panel { width: 240px; background: var(--panel); border-right: 1px solid var(--border); display: flex; flex-direction: column; flex-shrink: 0; }
.file-panel-header { padding: 10px 12px; border-bottom: 1px solid var(--border); display: flex; flex-direction: column; gap: 6px; }
.file-panel-header .row { display: flex; gap: 6px; }
.file-panel-header .row .btn { flex: 1; padding: 5px 8px; font-size: 11px; justify-content: center; }
.folder-status { font-size: 10px; color: var(--muted); font-family: 'SF Mono', Consolas, monospace; word-break: break-all; }
.folder-status.ok { color: var(--success); }
.file-search { padding: 8px 10px; border-bottom: 1px solid var(--border); }
.file-search input { width: 100%; }
.file-list { flex: 1; overflow-y: auto; }
.file-item { padding: 8px 12px; font-size: 11px; cursor: pointer; display: flex; align-items: center; gap: 6px; border-bottom: 1px solid rgba(48,54,61,0.4); font-family: 'SF Mono', Consolas, monospace; transition: background 0.1s; }
.file-item:hover { background: var(--panel-2); }
.file-item.active { background: rgba(47,129,247,0.18); border-left: 3px solid var(--accent); padding-left: 9px; }
.file-item .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-item .badge { font-size: 9px; padding: 1px 5px; border-radius: 3px; flex-shrink: 0; }
.file-item .badge.ok { background: rgba(63,185,80,0.2); color: var(--success); }
.file-item .badge.miss { background: rgba(248,81,73,0.2); color: var(--danger); }
.file-item .badge.dirty { background: rgba(210,153,34,0.25); color: var(--warning); }
.file-item .badge.saved { background: rgba(63,185,80,0.15); color: var(--success); }
.nav-bar { padding: 8px 10px; border-top: 1px solid var(--border); display: flex; gap: 6px; background: var(--panel-2); }
.nav-bar .btn { flex: 1; justify-content: center; }
.nav-info { font-size: 10px; color: var(--muted); text-align: center; padding: 4px; font-family: 'SF Mono', Consolas, monospace; }
.canvas-area { flex: 1; background: #0a0d12; position: relative; overflow: hidden;
background-image: linear-gradient(45deg, #14181f 25%, transparent 25%), linear-gradient(-45deg, #14181f 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #14181f 75%), linear-gradient(-45deg, transparent 75%, #14181f 75%);
background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0px; }
#canvas { position: absolute; top: 0; left: 0; cursor: crosshair; }
.sidebar { width: 380px; background: var(--panel); border-left: 1px solid var(--border); overflow-y: auto; flex-shrink: 0; }
.section { border-bottom: 1px solid var(--border); padding: 12px 14px; }
.section h3 { font-size: 11px; text-transform: uppercase; color: var(--muted); margin-bottom: 8px; letter-spacing: 0.8px; }
details.section { padding: 0; }
details.section summary { list-style: none; cursor: pointer; padding: 12px 14px; border-bottom: 1px solid rgba(48,54,61,0.5); }
details.section summary::-webkit-details-marker { display: none; }
details.section summary h3 { margin: 0; }
details.section[open] summary { border-bottom-color: transparent; }
.section-body { padding: 0 14px 12px; }
.dropzone { position: absolute; inset: 20px; border: 2px dashed var(--border); border-radius: 12px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px; pointer-events: none; transition: all 0.2s; }
.dropzone.active { border-color: var(--accent); background: rgba(47,129,247,0.05); }
.dropzone.hidden { display: none; }
.dropzone .icon { font-size: 48px; opacity: 0.4; }
.dropzone p { color: var(--muted); font-size: 14px; max-width: 500px; text-align: center; line-height: 1.7; padding: 0 20px; }
.dropzone .hint { font-size: 12px; opacity: 0.7; }
.dropzone strong { color: var(--text); }
.dropzone code { background: var(--panel-2); padding: 2px 6px; border-radius: 3px; font-size: 11px; }
.statusbar { display: flex; gap: 12px; align-items: center; padding: 6px 16px; background: var(--panel); border-top: 1px solid var(--border); font-size: 11px; color: var(--muted); font-family: 'SF Mono', Consolas, monospace; flex-shrink: 0; }
.status-pill { padding: 2px 8px; border-radius: 4px; background: var(--panel-2); border: 1px solid var(--border); }
.status-pill.warn { color: var(--warning); border-color: var(--warning); }
.status-pill.success { color: var(--success); border-color: var(--success); }
.tool-row { display: flex; gap: 6px; flex-wrap: wrap; }
.tool-btn { background: var(--panel-2); border: 1px solid var(--border); color: var(--text); padding: 8px 10px; border-radius: 6px; cursor: pointer; font-size: 11px; flex: 1; min-width: 60px; font-family: inherit; transition: all 0.15s; }
.tool-btn:hover { background: #2d333b; }
.tool-btn.active { background: var(--accent-2); border-color: var(--accent-2); color: white; }
.filter-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.filter-row label { font-size: 12px; flex: 1; }
input[type="range"] { flex: 1; }
input[type="number"], input[type="text"], select, textarea { background: var(--bg); color: var(--text); border: 1px solid var(--border); padding: 5px 8px; border-radius: 4px; font-size: 12px; font-family: inherit; width: 100%; }
textarea { min-height: 58px; resize: vertical; line-height: 1.45; }
input:focus, select:focus { outline: none; border-color: var(--accent); }
textarea:focus { outline: none; border-color: var(--accent); }
.toolbar-select { width: auto; min-width: 142px; }
.field-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.field-grid.one { grid-template-columns: 1fr; }
.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.field label, label.field { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }
.field input, .field select { min-width: 0; }
.flag-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 10px; margin-top: 8px; }
.flag-grid label { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text); text-transform: none; letter-spacing: 0; }
.id-preview { margin-top: 8px; padding: 7px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--panel-2); color: var(--muted); font-size: 11px; font-family: 'SF Mono', Consolas, monospace; word-break: break-all; }
.issue-list { display: flex; flex-direction: column; gap: 6px; max-height: 150px; overflow-y: auto; }
.issue { border: 1px solid var(--border); border-radius: 6px; padding: 6px 8px; font-size: 11px; line-height: 1.35; }
.issue.ok { color: var(--success); border-color: rgba(63,185,80,0.45); }
.issue.warn { color: var(--warning); border-color: rgba(210,153,34,0.45); }
.issue.error { color: var(--danger); border-color: rgba(248,81,73,0.45); }
.ann-list { max-height: 220px; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px; }
.ann-item { padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 11px; display: flex; align-items: center; gap: 6px; cursor: pointer; font-family: 'SF Mono', Consolas, monospace; }
.ann-item:last-child { border-bottom: none; }
.ann-item:hover { background: var(--panel-2); }
.ann-item.selected { background: rgba(255,214,10,0.15); border-left: 3px solid var(--selected); padding-left: 7px; }
.ann-item .swatch { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
.ann-item .label { flex: 1; }
.ann-item .conf { color: var(--muted); }
.stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.stat { background: var(--panel-2); padding: 8px 10px; border-radius: 6px; border: 1px solid var(--border); }
.stat .label { font-size: 10px; color: var(--muted); text-transform: uppercase; }
.stat .value { font-size: 16px; font-weight: 600; margin-top: 2px; }
.class-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.class-btn { padding: 6px; font-size: 11px; border-radius: 4px; border: 1px solid var(--border); background: var(--panel-2); color: var(--text); cursor: pointer; font-family: inherit; }
.class-btn:hover { background: #2d333b; }
.toast { position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%); background: var(--panel-2); border: 1px solid var(--border); padding: 10px 18px; border-radius: 8px; font-size: 13px; box-shadow: 0 8px 24px rgba(0,0,0,0.5); z-index: 1000; opacity: 0; transition: opacity 0.2s; pointer-events: none; }
.toast.show { opacity: 1; }
.toast.success { border-color: var(--success); color: var(--success); }
.toast.error { border-color: var(--danger); color: var(--danger); }
.toast.warn { border-color: var(--warning); color: var(--warning); }
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.7); display: none; align-items: center; justify-content: center; z-index: 999; }
.modal-overlay.show { display: flex; }
.modal { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 24px; max-width: 540px; width: 90%; max-height: 85vh; overflow-y: auto; }
.modal h2 { font-size: 16px; margin-bottom: 16px; }
.modal h3 { font-size: 12px; color: var(--muted); margin: 16px 0 8px; text-transform: uppercase; }
.shortcut-list { display: grid; grid-template-columns: auto 1fr; gap: 6px 16px; font-size: 12px; }
.shortcut-list kbd { background: var(--bg); border: 1px solid var(--border); padding: 2px 7px; border-radius: 4px; font-family: 'SF Mono', Consolas, monospace; font-size: 11px; }
.modal .close-btn { margin-top: 16px; }
.modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; }
.smart-help { position: fixed; z-index: 1200; width: min(320px, calc(100vw - 24px)); background: #10151d; color: var(--text); border: 1px solid var(--accent); border-radius: 8px; padding: 10px 12px; font-size: 12px; line-height: 1.45; box-shadow: 0 10px 28px rgba(0,0,0,0.55); display: none; }
.smart-help.show { display: block; }
.smart-help .more { margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; }
.smart-help button { font-size: 11px; padding: 4px 8px; }
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: var(--bg); }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--muted); }
.autosave-toggle { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--muted); }
.autosave-toggle input { margin: 0; }
</style>
<script src="https://apis.google.com/js/api.js" defer></script>
<script src="https://accounts.google.com/gsi/client" defer></script>
</head>
<body>
<div class="topbar">
<h1>KCAC WORKBENCH</h1>
<div class="sep"></div>
<button class="btn primary" id="openImageFolderBtn" title="Open folder of images">📁 Image Folder</button>
<button class="btn primary" id="openJsonFolderBtn" title="Open folder of JSON files (writable)">📁 JSON Folder</button>
<div class="sep"></div>
<button class="btn primary" id="driveBtn" title="Connect to Google Drive and load a folder of pages/JSONs"><span id="driveBtnIcon">☁️</span> <span id="driveBtnLabel">Google Drive</span></button>
<span id="driveStatusPill" class="status-pill" style="display:none">Drive: —</span>
<div class="sep"></div>
<label class="btn" for="loadImage">Single Image</label>
<input type="file" id="loadImage" accept="image/*">
<label class="btn" for="loadJson">Single JSON</label>
<input type="file" id="loadJson" accept=".json">
<div class="sep"></div>
<button class="btn success" id="saveJsonBtn" title="Save KCAC JSON (Ctrl+S)">💾 Save</button>
<select id="exportFormat" class="toolbar-select" title="Standards export format">
<option value="bundle">Standards bundle</option>
<option value="page">PAGE XML</option>
<option value="alto">ALTO XML</option>
<option value="tei">TEI P5</option>
<option value="hf">HF JSONL</option>
<option value="mets">METS/MODS</option>
<option value="iiif">IIIF 3.0</option>
<option value="dataset-card">Dataset Card</option>
<option value="datasheet">Datasheet</option>
</select>
<button class="btn" id="exportStdBtn">Export</button>
<button class="btn" id="exportYoloBtn">📦 YOLO</button>
<div class="sep"></div>
<button class="btn" id="undoBtn" title="Undo (Ctrl+Z)">↶</button>
<button class="btn" id="redoBtn" title="Redo (Ctrl+Y)">↷</button>
<div style="flex:1"></div>
<label class="autosave-toggle"><input type="checkbox" id="autosaveChk" checked> Auto-save on switch</label>
<button class="btn" id="helpBtn">? Help</button>
</div>
<div class="main">
<div class="file-panel">
<div class="file-panel-header">
<div class="row">
<button class="btn" id="openImageFolderBtn2">📁 Images</button>
<button class="btn" id="openJsonFolderBtn2">📁 JSONs</button>
</div>
<div class="folder-status" id="imgFolderStatus">No image folder</div>
<div class="folder-status" id="jsonFolderStatus">No JSON folder</div>
</div>
<div class="file-search">
<input type="text" id="fileSearch" placeholder="Filter files...">
</div>
<div class="file-list" id="fileList">
<div style="padding:20px; text-align:center; color:var(--muted); font-size:11px;">
No files loaded.<br>Click <strong>Image Folder</strong> above.
</div>
</div>
<div class="nav-info" id="navInfo">— / —</div>
<div class="nav-bar">
<button class="btn" id="prevBtn" title="Previous (PageUp)">◀ Prev</button>
<button class="btn" id="nextBtn" title="Next (PageDown)">Next ▶</button>
</div>
</div>
<div class="canvas-area" id="canvasArea">
<canvas id="canvas"></canvas>
<div class="dropzone" id="dropzone">
<div class="icon">📁</div>
<p><strong>Open an image folder + JSON folder to start.</strong><br>
<span class="hint">Filenames are auto-paired: <code>page_009.jpg</code> ↔ <code>page_009.json</code>.<br>KCAC IDs, PAGE XML, ALTO, TEI, IIIF, METS, and HF JSONL export from the same corrected page.</span></p>
<p class="hint" id="apiSupportHint" style="font-size:11px"></p>
</div>
</div>
<div class="sidebar">
<div class="section">
<h3>Tools</h3>
<div class="tool-row">
<button class="tool-btn active" data-tool="select">▭ Select</button>
<button class="tool-btn" data-tool="draw-line">+ Line</button>
<button class="tool-btn" data-tool="draw-layout">+ Layout</button>
</div>
</div>
<div class="section">
<h3>Visibility</h3>
<div class="filter-row">
<input type="checkbox" id="showLines" checked>
<label for="showLines"><span style="color:var(--line-color)">●</span> Text Lines</label>
<span id="lineCount" class="status-pill">0</span>
</div>
<div class="filter-row">
<input type="checkbox" id="showLayout" checked>
<label for="showLayout"><span style="color:var(--layout-color)">●</span> Layout</label>
<span id="layoutCount" class="status-pill">0</span>
</div>
<div class="filter-row">
<input type="checkbox" id="showLabels" checked>
<label for="showLabels">Show labels</label>
</div>
<div class="filter-row" style="margin-top:8px">
<label>Min conf:</label>
<input type="range" id="confThreshold" min="0" max="1" step="0.01" value="0">
<span id="confValue" style="font-size:11px; min-width:30px; text-align:right">0.00</span>
</div>
</div>
<details class="section" open>
<summary><h3>KCAC Page</h3></summary>
<div class="section-body">
<div class="field-grid">
<label class="field">Book ID<input type="text" id="bookIdInput" data-meta="page" data-key="book_id" placeholder="kcac_000152"></label>
<label class="field">Page seq<input type="number" id="pageSeqInput" data-meta="page" data-key="page_number_sequence" min="1" step="1"></label>
<label class="field">Printed page<input type="text" id="pagePrintedInput" data-meta="page" data-key="page_number_printed"></label>
<label class="field">Split<select id="splitInput" data-meta="page" data-key="split">
<option value="train">train</option>
<option value="val">val</option>
<option value="test_general">test_general</option>
<option value="test_historical_hard">test_historical_hard</option>
<option value="test_low_quality_scans">test_low_quality_scans</option>
<option value="test_poetry_layout">test_poetry_layout</option>
<option value="test_multi_column">test_multi_column</option>
<option value="test_mixed_language">test_mixed_language</option>
<option value="test_long_tail_glyphs">test_long_tail_glyphs</option>
</select></label>
<label class="field">Page type<select id="pageTypeInput" data-meta="page" data-key="page_type">
<option value="cover">cover</option>
<option value="title">title</option>
<option value="toc">toc</option>
<option value="body">body</option>
<option value="plate">plate</option>
<option value="blank">blank</option>
<option value="advert">advert</option>
<option value="colophon">colophon</option>
<option value="index">index</option>
</select></label>
<label class="field">Layout<select id="layoutClassInput" data-meta="page" data-key="layout_class">
<option value="single-column">single-column</option>
<option value="two-column">two-column</option>
<option value="three-column">three-column</option>
<option value="dictionary">dictionary</option>
<option value="poetry-centred">poetry-centred</option>
</select></label>
<label class="field">Language<select id="languageInput" data-meta="page" data-key="language">
<option value="ckb-Arab">ckb-Arab (Sorani Kurdish)</option>
<option value="kmr-Latn">kmr-Latn (Kurmanji Kurdish)</option>
<option value="hac-Arab">hac-Arab (Hawrami Kurdish)</option>
<option value="ar-Arab">ar-Arab (Arabic)</option>
<option value="en-Latn">en-Latn (English)</option>
<option value="mixed">mixed</option>
</select></label>
<label class="field">Direction<select id="readingDirectionInput" data-meta="page" data-key="reading_direction">
<option value="rtl">rtl</option>
<option value="ltr">ltr</option>
</select></label>
<label class="field">Script<select id="scriptInput" data-meta="page" data-key="script">
<option value="sorani-arabic">sorani-arabic</option>
<option value="kurmanji-latin">kurmanji-latin</option>
<option value="hawrami">hawrami</option>
<option value="arabic">arabic</option>
<option value="english-latin">english-latin</option>
<option value="mixed">mixed</option>
</select></label>
<label class="field">Typography<select id="typographyInput" data-meta="page" data-key="era_typography">
<option value="typewriter">typewriter</option>
<option value="letterpress">letterpress</option>
<option value="offset">offset</option>
<option value="digital">digital</option>
</select></label>
<label class="field">Scan quality<select id="scanQualityInput" data-meta="page" data-key="scan_quality">
<option value="pristine">pristine</option>
<option value="good">good</option>
<option value="fair">fair</option>
<option value="poor">poor</option>
</select></label>
<label class="field">DPI<input type="number" id="dpiInput" data-meta="page" data-key="scan_resolution_dpi" min="0" step="1"></label>
<label class="field">Colour<select id="colourModeInput" data-meta="page" data-key="colour_mode">
<option value="colour">colour</option>
<option value="greyscale">greyscale</option>
<option value="bitonal">bitonal</option>
</select></label>
<label class="field">Damage<input type="text" id="damageInput" data-meta="page" data-key="damage_present" placeholder="foxing, tearing"></label>
<label class="field">Verification<select id="verificationInput" data-meta="page" data-key="verification_status">
<option value="raw">raw</option>
<option value="ocr_generated">ocr_generated</option>
<option value="single_verified">single_verified</option>
<option value="double_verified">double_verified</option>
<option value="adjudicated">adjudicated</option>
<option value="gold">gold</option>
</select></label>
</div>
<div class="flag-grid">
<label><input type="checkbox" id="hasIllustrationsInput" data-meta="page" data-key="has_illustrations"> illustrations</label>
<label><input type="checkbox" id="hasTableInput" data-meta="page" data-key="has_table"> table</label>
<label><input type="checkbox" id="hasMarginaliaInput" data-meta="page" data-key="has_marginalia"> marginalia</label>
<label><input type="checkbox" id="hasFootnoteInput" data-meta="page" data-key="has_footnote"> footnote</label>
<label><input type="checkbox" id="hasPoetryInput" data-meta="page" data-key="has_poetry"> poetry</label>
</div>
<div class="id-preview" id="stableIdPreview">Page ID: -</div>
</div>
</details>
<details class="section">
<summary><h3>Catalog</h3></summary>
<div class="section-body">
<div class="field-grid one">
<label class="field">Title original<input type="text" id="titleOriginalInput" data-meta="book" data-key="title_original"></label>
<label class="field">Title normalised<input type="text" id="titleNormalisedInput" data-meta="book" data-key="title_normalised"></label>
<label class="field">Authors<input type="text" id="authorsInput" data-meta="book" data-key="authors"></label>
</div>
<div class="field-grid" style="margin-top:8px">
<label class="field">Publisher<input type="text" id="publisherInput" data-meta="book" data-key="publisher"></label>
<label class="field">Place<input type="text" id="placeInput" data-meta="book" data-key="place_of_publication"></label>
<label class="field">Year printed<input type="text" id="yearPrintedInput" data-meta="book" data-key="publication_year_printed"></label>
<label class="field">Year gregorian<input type="number" id="yearGregorianInput" data-meta="book" data-key="publication_year_gregorian" min="0" step="1"></label>
<label class="field">Genre<input type="text" id="genreInput" data-meta="book" data-key="genre"></label>
<label class="field">Rights<select id="rightsInput" data-meta="book" data-key="rights_status">
<option value="unknown">unknown</option>
<option value="public_domain">public_domain</option>
<option value="permission_granted">permission_granted</option>
<option value="copyrighted">copyrighted</option>
</select></label>
<label class="field">SPDX<select id="spdxInput" data-meta="book" data-key="spdx_license">
<option value="NOASSERTION">NOASSERTION</option>
<option value="CC-BY-4.0">CC-BY-4.0</option>
<option value="CC-BY-SA-4.0">CC-BY-SA-4.0</option>
<option value="CC0-1.0">CC0-1.0</option>
<option value="LicenseRef-KCAC-Permission">LicenseRef-KCAC-Permission</option>
</select></label>
<label class="field">Source<input type="text" id="sourceCollectionInput" data-meta="book" data-key="source_collection"></label>
<label class="field">Source URL<input type="text" id="sourceUrlInput" data-meta="book" data-key="source_url"></label>
</div>
<button class="btn" id="applyBookDefaultsBtn" style="width:100%; justify-content:center; margin-top:8px">Apply Catalog To Folder</button>
</div>
</details>
<div class="section">
<h3>Selection (<span id="selCount">0</span>)</h3>
<div class="tool-row" style="margin-bottom:8px">
<button class="btn danger" id="deleteBtn" style="flex:1">🗑 Del</button>
<button class="btn" id="selectAllBtn" style="flex:1">All</button>
<button class="btn" id="deselectBtn" style="flex:1">None</button>
</div>
<div id="selectionEditor" style="display:none">
<div id="singleSelectionFields" style="display:none">
<div class="field-grid">
<label class="field">KCAC ID<input type="text" id="selectedStableId" readonly></label>
<label class="field">Reading order<input type="number" id="readingOrderInput" min="1" step="1"></label>
<label class="field">Accuracy<input type="number" id="annConfidenceInput" min="0" max="1" step="0.0001"></label>
<label class="field">Rotation deg<input type="number" id="rotationInput" min="-180" max="180" step="0.1"></label>
<label class="field">Kind<input type="text" id="annKindInput" readonly></label>
<label class="field">Language<select id="annLanguageInput">
<option value="">— inherit page —</option>
<option value="ckb-Arab">ckb-Arab (Sorani Kurdish)</option>
<option value="kmr-Latn">kmr-Latn (Kurmanji Kurdish)</option>
<option value="hac-Arab">hac-Arab (Hawrami Kurdish)</option>
<option value="ar-Arab">ar-Arab (Arabic)</option>
<option value="en-Latn">en-Latn (English)</option>
<option value="mixed">mixed</option>
</select></label>
</div>
<div class="field-grid one" style="margin-top:8px">
<label class="field">Raw transcription<textarea id="rawTextInput" dir="auto"></textarea></label>
<label class="field">Normalised<textarea id="normTextInput" dir="auto"></textarea></label>
<label class="field">Diacritic stripped<textarea id="plainTextInput" dir="auto"></textarea></label>
</div>
</div>
<h3 style="margin-top:8px">Change Class →</h3>
<div class="class-grid">
<button class="class-btn" data-class="TextLine">→ TextLine</button>
<button class="class-btn" data-class="TextRegion">→ TextRegion</button>
<button class="class-btn" data-class="HeadingH1">→ Heading H1</button>
<button class="class-btn" data-class="HeadingH2">→ Heading H2</button>
<button class="class-btn" data-class="HeadingH3">→ Heading H3</button>
<button class="class-btn" data-class="Caption">→ Caption</button>
<button class="class-btn" data-class="Footnote">→ Footnote</button>
<button class="class-btn" data-class="PageNumber">→ PageNumber</button>
<button class="class-btn" data-class="Header">→ Header</button>
<button class="class-btn" data-class="Footer">→ Footer</button>
<button class="class-btn" data-class="Marginalia">→ Marginalia</button>
<button class="class-btn" data-class="Illustration">→ Illustration</button>
<button class="class-btn" data-class="Figure">→ Figure</button>
<button class="class-btn" data-class="Table">→ Table</button>
<button class="class-btn" data-class="DecorativeElement">→ Decorative</button>
<button class="class-btn" data-class="Advertisement">→ Advert</button>
<button class="class-btn" data-class="Signature">→ Signature</button>
<button class="class-btn" data-class="Stamp">→ Stamp</button>
<button class="class-btn" data-class="MathRegion">→ MathRegion</button>
</div>
</div>
</div>
<div class="section">
<h3>Bulk</h3>
<div class="tool-row">
<button class="btn" id="deleteLowConfBtn" style="flex:1">Del < threshold</button>
<button class="btn" id="invertBtn" style="flex:1">Invert</button>
</div>
</div>
<div class="section">
<h3>Validation</h3>
<div class="issue-list" id="qcList">
<div class="issue warn">Not checked</div>
</div>
<button class="btn" id="runQcBtn" style="width:100%; justify-content:center; margin-top:8px">Check Page</button>
</div>
<div class="section">
<h3>Stats</h3>
<div class="stat-grid">
<div class="stat"><div class="label">Image</div><div class="value" id="statImg" style="font-size:11px; word-break:break-all">—</div></div>
<div class="stat"><div class="label">Size</div><div class="value" id="statSize" style="font-size:11px">—</div></div>
<div class="stat"><div class="label">Lines</div><div class="value" id="statLines">0</div></div>
<div class="stat"><div class="label">Layout</div><div class="value" id="statLayout">0</div></div>
</div>
</div>
<div class="section">
<h3>Annotations</h3>
<div class="ann-list" id="annList"></div>
</div>
</div>
</div>
<div class="statusbar">
<span id="statusMode">Mode: Select</span>
<span class="status-pill" id="statusZoom">100%</span>
<span class="status-pill" id="statusCoords">— , —</span>
<span class="status-pill" id="statusDirty"></span>
<div style="flex:1"></div>
<span id="statusHint" class="status-pill">PageUp/PageDown to navigate · Auto-save on switch</span>
</div>
<div class="toast" id="toast"></div>
<div class="modal-overlay" id="helpModal">
<div class="modal">
<h2>⌨ KCAC Annotation Workbench</h2>
<h3>Folder Workflow</h3>
<ol style="font-size:12px; line-height:1.7; padding-left:20px;">
<li>Click <strong>📁 Image Folder</strong> → pick the folder with all your <code>.jpg/.png</code> files.</li>
<li>Click <strong>📁 JSON Folder</strong> → pick the folder with Surya or KCAC <code>.json</code> output.</li>
<li>Files auto-pair by name (<code>page_009.jpg</code> ↔ <code>page_009.json</code>).</li>
<li>Click any image in the left list. Edit boxes, page metadata, verification status, and transcriptions. Click next image → previous edits auto-save.</li>
<li>The JSON folder needs <strong>read-write</strong> permission (browser will prompt).</li>
</ol>
<h3>KCAC Exports</h3>
<p style="font-size:12px; line-height:1.6; color:var(--muted)">Save keeps a KCAC JSON record with legacy <code>text_lines</code> and <code>layout</code> arrays. Export creates PAGE XML, ALTO XML, TEI P5, METS/MODS, IIIF 3.0, HuggingFace JSONL, Dataset Card, and Datasheet files.</p>
<h3>Shortcuts</h3>
<div class="shortcut-list">
<kbd>PageDown / PageUp</kbd><span>Next / previous file</span>
<kbd>Ctrl + S</kbd><span>Save current file</span>
<kbd>V / L / R</kbd><span>Select / draw-line / draw-layout</span>
<kbd>Del / Backspace</kbd><span>Delete selected</span>
<kbd>Ctrl + A</kbd><span>Select all</span>
<kbd>Ctrl + Z / Y</kbd><span>Undo / Redo</span>
<kbd>Esc</kbd><span>Deselect</span>
<kbd>Shift + Click</kbd><span>Add to selection</span>
<kbd>Drag empty area</kbd><span>Marquee select</span>
<kbd>Mouse wheel</kbd><span>Zoom</span>
<kbd>Space + drag</kbd><span>Pan canvas</span>
<kbd>Arrow keys</kbd><span>Nudge selected (Shift = 10px)</span>
<kbd>[ / ]</kbd><span>Rotate selected (Shift = 10deg)</span>
</div>
<h3>Browser Support</h3>
<p style="font-size:11px; color:var(--muted)">Folder auto-save needs the File System Access API — works in Chrome, Edge, Brave, Opera. In Firefox/Safari you can still load files but saves will download instead.</p>
<button class="btn primary close-btn" onclick="document.getElementById('helpModal').classList.remove('show')">Close</button>
</div>
</div>
<div class="modal-overlay" id="bookSetupModal">
<div class="modal">
<h2>Book Setup For This Folder</h2>
<p style="font-size:12px; line-height:1.6; color:var(--muted)">These values become the default catalog record for every image in the folder. Page sequence increases automatically by image order.</p>
<div class="field-grid" style="margin-top:12px">
<label class="field">Book ID<input type="text" id="setupBookId" placeholder="kcac_000152"></label>
<label class="field">Start page<input type="number" id="setupStartPage" min="1" step="1" value="1"></label>
<label class="field">Title<input type="text" id="setupTitle"></label>
<label class="field">Author<input type="text" id="setupAuthors"></label>
<label class="field">Rights<select id="setupRights">
<option value="unknown">unknown</option>
<option value="public_domain">public_domain</option>
<option value="permission_granted">permission_granted</option>
<option value="copyrighted">copyrighted</option>
</select></label>
<label class="field">SPDX<select id="setupSpdx">
<option value="NOASSERTION">NOASSERTION</option>
<option value="CC-BY-4.0">CC-BY-4.0</option>
<option value="CC-BY-SA-4.0">CC-BY-SA-4.0</option>
<option value="CC0-1.0">CC0-1.0</option>
<option value="LicenseRef-KCAC-Permission">LicenseRef-KCAC-Permission</option>
</select></label>
<label class="field">Source collection<input type="text" id="setupSource"></label>
<label class="field">Source URL<input type="text" id="setupSourceUrl"></label>
</div>
<div class="modal-actions">
<button class="btn" id="bookSetupLaterBtn">Later</button>
<button class="btn primary" id="bookSetupApplyBtn">Apply To Folder</button>
</div>
</div>
</div>
<div class="modal-overlay" id="infoModal">
<div class="modal">
<h2 id="infoModalTitle">More Info</h2>
<p id="infoModalText" style="font-size:12px; line-height:1.7; color:var(--muted)"></p>
<button class="btn primary close-btn" id="infoModalCloseBtn">Close</button>
</div>
</div>
<div class="smart-help" id="smartHelp">
<div id="smartHelpText"></div>
<div class="more"><button class="btn" id="smartHelpMoreBtn">More info</button></div>
</div>
<div class="modal-overlay" id="driveModal">
<div class="modal">
<h2>☁️ Google Drive — Connect Your Dataset</h2>
<p style="font-size:12px; line-height:1.6; color:var(--muted)">
Open a Google Drive folder of page images and JSON annotations directly in this editor. Edits save back to the same Drive folder.
You need to register one Google Cloud OAuth Client (free, one-time). See the help text below.
</p>
<div class="field-grid" style="margin-top:12px">
<label class="field">OAuth Client ID<input type="text" id="driveClientId" placeholder="xxxxxxxxxx.apps.googleusercontent.com"></label>
<label class="field">API key<input type="text" id="driveApiKey" placeholder="AIza..."></label>
<label class="field" style="grid-column: 1 / -1">Folder URL or ID<input type="text" id="driveFolderId" placeholder="https://drive.google.com/drive/folders/1lvJs5... or just the ID"></label>
</div>
<details style="margin-top:10px; font-size:11px; color:var(--muted); line-height:1.7">
<summary style="cursor:pointer; color:var(--accent)">▸ How to get the Client ID and API key (one-time, 5 minutes)</summary>
<div style="margin-top:8px; padding:10px; background:var(--panel-2); border-radius:6px;">
<ol style="padding-left:18px">
<li>Open <a href="https://console.cloud.google.com/" target="_blank" rel="noopener" style="color:var(--accent)">Google Cloud Console</a> and create or select a project.</li>
<li>Enable the <b>Google Drive API</b> at <code>APIs & Services → Library</code>.</li>
<li>Configure the OAuth consent screen (External, your email as test user) at <code>APIs & Services → OAuth consent screen</code>.</li>
<li>Under <code>APIs & Services → Credentials</code>:
<ul style="padding-left:14px">
<li>Create an <b>API key</b> → paste it above.</li>
<li>Create an <b>OAuth 2.0 Client ID</b> of type <b>Web application</b>. Add your page origin to <i>Authorized JavaScript origins</i>, e.g. <code>https://hiwakurdy.github.io</code> (GitHub Pages) or <code>http://localhost:8000</code> for local testing. Paste the Client ID above.</li>
</ul>
</li>
<li>For the folder, paste either the full URL <code>https://drive.google.com/drive/folders/<ID></code> or just the <code><ID></code>.</li>
<li>Click <b>Connect & Load Folder</b>. A Google sign-in popup will appear the first time.</li>
</ol>
<p style="margin-top:6px"><b>Scopes requested:</b> <code>drive.file</code> — only files this app creates or that you explicitly open through this app. Your other Drive files are <b>not</b> accessible. You can revoke access any time at <a href="https://myaccount.google.com/permissions" target="_blank" rel="noopener" style="color:var(--accent)">myaccount.google.com/permissions</a>.</p>
<p style="margin-top:6px"><b>Note:</b> Because <code>drive.file</code> only sees files the app touches, the very first time you open a folder, the app will request the folder by its ID. Pre-existing files inside that folder are listed via that ID. New JSONs the app saves are owned by the app scope.</p>
</div>
</details>
<div class="modal-actions" style="margin-top:12px">
<button class="btn" id="driveDisconnectBtn" style="margin-right:auto; display:none">Disconnect</button>
<button class="btn" id="driveCancelBtn">Close</button>
<button class="btn primary" id="driveConnectBtn">Connect & Load Folder</button>
</div>
</div>
</div>
<script>
const SCHEMA_NAME = 'kcac_document_understanding_annotation';
const SCHEMA_VERSION = '0.1';
const STANDARDS = ['PAGE XML', 'ALTO XML', 'METS/MODS', 'TEI P5', 'IIIF Presentation 3.0', 'HuggingFace datasets', 'BCP 47', 'SPDX', 'Datasheet for Datasets'];
const PUBLIC_VERIFICATION = new Set(['single_verified', 'double_verified', 'adjudicated', 'gold']);
const OLD_LABEL_MAP = {
Text: 'TextRegion',
Title: 'HeadingH1',
SectionHeader: 'HeadingH2',
PageHeader: 'Header',
PageFooter: 'Footer',
ListItem: 'TextRegion',
Formula: 'MathRegion',
text_line: 'TextLine'
};
function defaultPageMeta() {
return {
book_id: 'kcac_000000',
page_number_sequence: 1,
page_number_printed: '',
page_type: 'body',
layout_class: 'single-column',
reading_direction: 'rtl',
language: 'ckb-Arab',
script: 'sorani-arabic',
era_typography: 'letterpress',
scan_resolution_dpi: '',
colour_mode: 'colour',
scan_quality: 'good',
damage_present: '',
verification_status: 'raw',
split: 'train',
has_illustrations: false,
has_table: false,
has_marginalia: false,
has_footnote: false,
has_poetry: false
};
}
function defaultBookMeta() {
return {
title_original: '',
title_normalised: '',
authors: '',
authors_normalised: '',
editor: '',
compiler: '',
translator: '',
publisher: '',
place_of_publication: '',
publication_year_printed: '',
publication_year_gregorian: '',
publication_year_hijri: '',
publication_year_kurdish: '',
genre: '',
tags: '',
rights_status: 'unknown',
spdx_license: 'NOASSERTION',
source_collection: '',
source_url: '',
physical_condition: '',
missing_pages: '',
notes: ''
};
}
const state = {
image: null, imageName: '', jsonData: null, annotations: [],
pageMeta: defaultPageMeta(), bookMeta: defaultBookMeta(), validationIssues: [],
selectedIds: new Set(), hoverIds: new Set(), tool: 'select',
zoom: 1, panX: 0, panY: 0,
isPanning: false, isDragging: false, isDrawing: false, isResizing: false, isRotating: false,
resizeHandle: null, isMarquee: false, marqueeStart: null, marqueeEnd: null,
drawStart: null, dragStart: null, dragOrigBboxes: null,
history: [], historyIdx: -1,
showLines: true, showLayout: true, showLabels: true, confThreshold: 0,
nextId: 1, spaceDown: false, curMouse: null,
imageDirHandle: null, jsonDirHandle: null,
imageFiles: [], jsonFiles: new Map(),
folderDefaults: { active: false, folderName: '', bookId: 'kcac_000000', startPage: 1, bookMeta: defaultBookMeta() },
currentIndex: -1, currentJsonHandle: null, currentJsonName: null,
dirty: false, savedSet: new Set(), fileFilter: '',
};
const FS_API = !!window.showDirectoryPicker;
/* ============================================================
GOOGLE DRIVE INTEGRATION
------------------------------------------------------------
Lets you treat a Google Drive folder as the source of images +
JSONs (instead of, or in addition to, the local-folder mode).
Saves edited KCAC JSON back to the same folder.
Uses Google Identity Services (OAuth) + gapi Drive v3.
============================================================ */
const DRIVE_LS_KEY = 'kcac_drive_config_v1';
const DRIVE_SCOPES = 'https://www.googleapis.com/auth/drive.file';
const DRIVE_DISCOVERY = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
const drive = {
enabled: false,
clientId: '',
apiKey: '',
folderId: '',
folderName: '',
accessToken: '',
tokenClient: null,
gapiReady: false,
gisReady: false,
jsonIdByBase: new Map(), // basenameNoExt -> { id, name }
imageBlobCache: new Map(), // driveFileId -> Blob (memoized to avoid re-download on revisit)
};
function loadDriveConfig() {
try {
const raw = localStorage.getItem(DRIVE_LS_KEY);
if (!raw) return;
const cfg = JSON.parse(raw);
drive.clientId = cfg.clientId || '';
drive.apiKey = cfg.apiKey || '';
drive.folderId = cfg.folderId || '';
} catch {}
}
function saveDriveConfig() {
try {
localStorage.setItem(DRIVE_LS_KEY, JSON.stringify({
clientId: drive.clientId, apiKey: drive.apiKey, folderId: drive.folderId
}));
} catch {}
}
function parseDriveFolderId(input) {
if (!input) return '';
const trimmed = input.trim();
const m1 = trimmed.match(/\/folders\/([a-zA-Z0-9_-]+)/);
if (m1) return m1[1];
const m2 = trimmed.match(/[?&]id=([a-zA-Z0-9_-]+)/);
if (m2) return m2[1];
// assume raw ID
return trimmed.replace(/[^a-zA-Z0-9_-].*$/, '');
}
function setDriveStatus(text, ok) {
const pill = document.getElementById('driveStatusPill');
if (!pill) return;
pill.style.display = text ? 'inline-block' : 'none';
pill.textContent = text || '';
pill.classList.toggle('success', !!ok);
}
async function gapiLoadDrive() {
if (drive.gapiReady) return;
if (typeof gapi === 'undefined') throw new Error('gapi not loaded yet (check internet / blocked scripts)');
await new Promise((res, rej) => gapi.load('client', { callback: res, onerror: rej }));
await gapi.client.init({ apiKey: drive.apiKey, discoveryDocs: [DRIVE_DISCOVERY] });
drive.gapiReady = true;
}
function gisInitTokenClient() {
if (typeof google === 'undefined' || !google.accounts?.oauth2) {
throw new Error('Google Identity Services not loaded yet');
}
drive.tokenClient = google.accounts.oauth2.initTokenClient({
client_id: drive.clientId,
scope: DRIVE_SCOPES,
prompt: '',
callback: () => {}, // assigned per-request
});
drive.gisReady = true;
}
function requestDriveToken({ silent = false } = {}) {
return new Promise((resolve, reject) => {
if (!drive.tokenClient) { reject(new Error('Token client not ready')); return; }
drive.tokenClient.callback = (resp) => {
if (resp.error) { reject(new Error(resp.error)); return; }
drive.accessToken = resp.access_token;
gapi.client.setToken({ access_token: drive.accessToken });
resolve(resp);
};
try {
drive.tokenClient.requestAccessToken({ prompt: silent ? '' : 'consent' });
} catch (e) { reject(e); }
});
}
async function ensureDriveReady() {
if (!drive.clientId || !drive.apiKey || !drive.folderId) {
throw new Error('Set Client ID, API key, and Folder ID first');
}
await gapiLoadDrive();
if (!drive.gisReady) gisInitTokenClient();
if (!drive.accessToken) await requestDriveToken({ silent: false });
}
async function driveListFolder(folderId) {
// List all (non-trashed) files in the folder, paginated.
const out = [];
let pageToken = '';
do {
const resp = await gapi.client.drive.files.list({
q: `'${folderId}' in parents and trashed = false`,
fields: 'nextPageToken, files(id, name, mimeType, size, modifiedTime)',
pageSize: 1000,
pageToken: pageToken || undefined,
orderBy: 'name_natural',
supportsAllDrives: true,
includeItemsFromAllDrives: true,
});
out.push(...(resp.result.files || []));
pageToken = resp.result.nextPageToken || '';
} while (pageToken);
return out;
}
async function driveGetFolderName(folderId) {
try {
const resp = await gapi.client.drive.files.get({ fileId: folderId, fields: 'id, name' });
return resp.result.name || folderId;
} catch { return folderId; }
}
async function driveDownloadBlob(fileId, mimeHint) {
// Use raw fetch (gapi response body re-encodes binary). Auth via bearer.
const url = `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`;
const r = await fetch(url, { headers: { Authorization: `Bearer ${drive.accessToken}` } });
if (!r.ok) {
if (r.status === 401) {
await requestDriveToken({ silent: true });
const r2 = await fetch(url, { headers: { Authorization: `Bearer ${drive.accessToken}` } });
if (!r2.ok) throw new Error(`Drive download ${r2.status}`);
return await r2.blob();
}
throw new Error(`Drive download ${r.status}`);
}
return await r.blob();
}
async function driveUploadJson(fileName, content, existingId) {
// Multipart upload create OR media-only update.
const boundary = '-------kcac' + Math.random().toString(36).slice(2);
const delim = `\r\n--${boundary}\r\n`;
const closeDelim = `\r\n--${boundary}--`;
const metadata = existingId
? { name: fileName }
: { name: fileName, parents: [drive.folderId], mimeType: 'application/json' };
const body =
delim +
'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify(metadata) +
delim +
'Content-Type: application/json\r\n\r\n' +
content +
closeDelim;
const method = existingId ? 'PATCH' : 'POST';
const url = existingId
? `https://www.googleapis.com/upload/drive/v3/files/${encodeURIComponent(existingId)}?uploadType=multipart&supportsAllDrives=true&fields=id,name`
: `https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true&fields=id,name`;
const doFetch = async () => fetch(url, {
method,
headers: {
Authorization: `Bearer ${drive.accessToken}`,
'Content-Type': `multipart/related; boundary=${boundary}`,
},
body,
});
let r = await doFetch();
if (r.status === 401) {
await requestDriveToken({ silent: true });
r = await doFetch();
}
if (!r.ok) {
const txt = await r.text();
throw new Error(`Drive upload ${r.status}: ${txt.slice(0, 200)}`);
}
return await r.json();
}
function driveMakeImageHandle(file) {
// Adapter so existing loadByIndex pipeline (which calls entry.handle.getFile())
// works on Drive files. Returns an object that, when getFile() is called,
// yields a File-like Blob with a .name property.
return {
_driveId: file.id,
_driveName: file.name,
getFile: async () => {
let blob = drive.imageBlobCache.get(file.id);
if (!blob) {
blob = await driveDownloadBlob(file.id, file.mimeType);
// Bound cache size to ~10 most recent images
if (drive.imageBlobCache.size >= 10) {
const firstKey = drive.imageBlobCache.keys().next().value;
drive.imageBlobCache.delete(firstKey);
}
drive.imageBlobCache.set(file.id, blob);
}
// Wrap as a File-ish object: existing code uses .name and FileReader.readAsDataURL
const f = new File([blob], file.name, { type: file.mimeType || blob.type || 'application/octet-stream' });
return f;
}
};
}
function driveMakeJsonHandle(file) {
return {
_driveId: file.id,
_driveName: file.name,
getFile: async () => {
const blob = await driveDownloadBlob(file.id, 'application/json');
return new File([blob], file.name, { type: 'application/json' });
}
};
}
async function driveOpenFolderFlow() {
// Read inputs
drive.clientId = document.getElementById('driveClientId').value.trim();
drive.apiKey = document.getElementById('driveApiKey').value.trim();
drive.folderId = parseDriveFolderId(document.getElementById('driveFolderId').value);
if (!drive.clientId || !drive.apiKey || !drive.folderId) {
toast('Please fill all three fields', 'error'); return;
}
saveDriveConfig();
toast('Connecting to Drive…', 'success');
try {
await ensureDriveReady();
drive.folderName = await driveGetFolderName(drive.folderId);
const files = await driveListFolder(drive.folderId);
const imageMimes = /^image\/(jpeg|png|webp|tiff|bmp|gif)$/i;
const isImage = f => imageMimes.test(f.mimeType || '') || /\.(jpe?g|png|webp|tiff?|bmp)$/i.test(f.name);
const isJson = f => f.mimeType === 'application/json' || /\.json$/i.test(f.name);
const imageDriveFiles = files.filter(isImage).sort((a,b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
const jsonDriveFiles = files.filter(isJson);
state.imageFiles = imageDriveFiles.map(f => ({ handle: driveMakeImageHandle(f), name: f.name, _driveId: f.id }));
const jsonMap = new Map();
drive.jsonIdByBase = new Map();
for (const f of jsonDriveFiles) {
const base = basenameNoExt(f.name);
jsonMap.set(base, { handle: driveMakeJsonHandle(f), name: f.name, _driveId: f.id });
drive.jsonIdByBase.set(base, { id: f.id, name: f.name });
}
state.jsonFiles = jsonMap;
// Switch into Drive mode (disables FS-API save path)
drive.enabled = true;
state.imageDirHandle = null;
state.jsonDirHandle = null;
state.currentIndex = -1;
state.savedSet.clear();
prepareFolderDefaults(drive.folderName);
document.getElementById('imgFolderStatus').textContent = `☁️ ${drive.folderName} (${imageDriveFiles.length} img)`;
document.getElementById('imgFolderStatus').className = 'folder-status ok';
document.getElementById('jsonFolderStatus').textContent = `☁️ ${drive.folderName} (${jsonDriveFiles.length} json)`;
document.getElementById('jsonFolderStatus').className = 'folder-status ok';
setDriveStatus(`Drive: ${drive.folderName}`, true);
document.getElementById('driveBtnLabel').textContent = 'Drive: ' + drive.folderName;
document.getElementById('driveBtnIcon').textContent = '☁️✓';
document.getElementById('driveDisconnectBtn').style.display = 'inline-flex';
rebuildFileList();
if (state.imageFiles.length > 0) await loadByIndex(0);
if (state.imageFiles.length > 0 && needsBookSetup()) showBookSetupModal();
toast(`Drive: loaded ${imageDriveFiles.length} images, ${jsonDriveFiles.length} JSONs`, 'success');
document.getElementById('driveModal').classList.remove('show');
} catch (e) {
console.error(e);
toast('Drive error: ' + e.message, 'error');
}
}
async function driveSaveCurrent(jsonText, baseName) {
if (!drive.enabled) throw new Error('Drive not connected');
if (!drive.accessToken) await requestDriveToken({ silent: true });
const fileName = (baseName || basenameNoExt(state.imageName) || 'page') + '.json';
const existing = drive.jsonIdByBase.get(basenameNoExt(fileName));
const resp = await driveUploadJson(fileName, jsonText, existing?.id);
// Update local maps
drive.jsonIdByBase.set(basenameNoExt(resp.name || fileName), { id: resp.id, name: resp.name || fileName });
const entry = { handle: driveMakeJsonHandle({ id: resp.id, name: resp.name || fileName }), name: resp.name || fileName, _driveId: resp.id };
state.jsonFiles.set(basenameNoExt(resp.name || fileName), entry);
state.currentJsonName = resp.name || fileName;
return resp;
}
function driveDisconnect() {
drive.enabled = false;