-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2181 lines (1968 loc) · 236 KB
/
Copy pathapp.js
File metadata and controls
2181 lines (1968 loc) · 236 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
#!/usr/bin/env node
/**
* Monjoy.AI — WSI Annotation Platform (Node.js / Express)
* =========================================================
* Fully JavaScript-based replacement of the Python/Flask version.
* Zero Python dependency — uses koffi to call libOpenSlide natively.
*
* Quick Start
* -----------
* npm install
* node app.js → http://localhost:5000
*
* OpenSlide C library must be installed:
* macOS: brew install openslide
* Linux: sudo apt install openslide-tools
* conda: conda install -c conda-forge openslide
*
* Features
* --------
* · Zero-copy slide access — originals never moved
* · All annotation tools (Polygon, Rectangle, Ellipse, Freehand, Point)
* · JSON annotation export/import (QuPath / ASAP / PathML compatible)
* · Patch extraction with ROI overlap enforcement
* · Blurriness detection
* · Native OS file-picker (osascript on macOS, tkinter subprocess on Linux/Win)
* · Cloud: Google Drive / Box / OneDrive shared-link download
* · TCGA / NCI GDC direct data access with project browser & download manager
*/
'use strict';
const express = require('express');
const fs = require('fs');
const fsp = fs.promises;
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const multer = require('multer');
const { execFile, spawnSync } = require('child_process');
const { Readable } = require('stream');
const { pipeline } = require('stream/promises');
const http = require('http');
const https = require('https');
const { v4: uuidv4 } = require('uuid');
// ── sharp ────────────────────────────────────────────────────────────────────
let sharp = null;
try { sharp = require('sharp'); }
catch(e) { console.warn(' sharp: ✗ npm install sharp'); }
// Remote registry defined below after BASE_DIR
// ── Simple BigTIFF Range-request tile fetcher ─────────────────────────────────
// Fetches ~50 KB per visible tile instead of downloading the full file.
const _streamCache = new Map(); // sid → {offsets, counts, dims, levels, tileW, tileH, jpegTables}
const _tileCache = new Map(); // 'sid:lv:c:r' → jpeg Buffer (LRU max 600)
const _TILE_LRU_MAX = 600;
async function _rangeGet(url, start, end, token) {
const headers = { Range: `bytes=${start}-${end}`, 'User-Agent': 'Monjoy.HistoAI/2.0' };
if (token) headers['X-Auth-Token'] = token;
const r = await fetch(url, { headers, redirect: 'follow', signal: AbortSignal.timeout(30000) });
if (r.status !== 206 && r.status !== 200)
throw new Error(`HTTP ${r.status} for range request`);
return Buffer.from(await r.arrayBuffer());
}
function _u16LE(b, o) { return b[o] | (b[o+1]<<8); }
function _u32LE(b, o) { return (b[o]|(b[o+1]<<8)|(b[o+2]<<16)|(b[o+3]<<24))>>>0; }
function _u64LE(b, o) { return _u32LE(b,o) + _u32LE(b,o+4)*0x100000000; }
async function openRemote(sid, url, token) {
if (_streamCache.has(sid)) return _streamCache.get(sid);
// Fetch first 4 MB — enough for IFDs in typical SVS
const hdr = await _rangeGet(url, 0, 4*1024*1024-1, token);
const magic = _u16LE(hdr, 0);
if (magic !== 0x4949 && magic !== 0x4D4D) throw new Error('Not a TIFF/BigTIFF file');
const le = magic === 0x4949;
const u16 = (o) => le ? _u16LE(hdr,o) : hdr.readUInt16BE(o);
const u32 = (o) => le ? _u32LE(hdr,o) : hdr.readUInt32BE(o);
const u64 = (o) => le ? _u64LE(hdr,o) : (hdr.readUInt32BE(o)*0x100000000+hdr.readUInt32BE(o+4));
const ver = u16(2);
const big = ver === 43;
if (ver !== 42 && ver !== 43) throw new Error(`Unknown TIFF version ${ver}`);
let ifdOff = big ? u64(8) : u32(4);
const TYPE_SZ = [0,1,1,2,4,8,1,1,2,4,8,4,8];
const levels = [];
while (ifdOff && ifdOff < hdr.length - 8) {
const nE = big ? u64(ifdOff) : u16(ifdOff);
const eBase = ifdOff + (big ? 8 : 2);
const eSz = big ? 20 : 12;
if (eBase + nE * eSz > hdr.length) break;
const tags = {};
for (let i = 0; i < nE; i++) {
const p = eBase + i*eSz;
const tag = u16(p), type = u16(p+2);
const cnt = big ? u64(p+4) : u32(p+4);
const vp = p + (big ? 12 : 8);
const tsz = TYPE_SZ[type]||4;
let val;
if (cnt === 1 && tsz <= (big?8:4)) {
val = type===3 ? u16(vp) : type===16 ? u64(vp) : u32(vp);
} else {
val = { off: big?u64(vp):u32(vp), cnt, type };
}
tags[tag] = val;
}
const nxtPos = eBase + nE*eSz;
const nextIfd = big ? u64(nxtPos) : u32(nxtPos);
const W = typeof tags[256]==='number'?tags[256]:0;
const H = typeof tags[257]==='number'?tags[257]:0;
const tW = typeof tags[322]==='number'?tags[322]:256;
const tH = typeof tags[323]==='number'?tags[323]:256;
const offRef = tags[324], cntRef = tags[325];
if (W && H && offRef) {
const readArr = (ref, n) => {
if (typeof ref === 'number') return [ref];
const { off, type } = ref;
const tsz2 = TYPE_SZ[type]||4;
if (off + n*tsz2 > hdr.length) return null;
const a = [];
for (let i=0;i<n;i++) {
const p2 = off+i*tsz2;
a.push(type===16?u64(p2):type===4?u32(p2):u16(p2));
}
return a;
};
const nTiles = typeof offRef==='object'?Number(offRef.cnt):1;
const offs = readArr(offRef, nTiles);
const cnts = cntRef ? readArr(cntRef, nTiles) : null;
if (offs) {
let jpegTables = null;
const jt = tags[347];
if (jt && typeof jt==='object' && jt.off+jt.cnt <= hdr.length)
jpegTables = hdr.slice(jt.off, jt.off+jt.cnt);
levels.push({ W, H, tW, tH, offs, cnts, jpegTables });
}
}
ifdOff = nextIfd;
}
if (!levels.length) throw new Error('No tiled pyramid levels found in BigTIFF');
levels.sort((a,b)=>b.W-a.W);
// Count DZ levels
let w=levels[0].W, h=levels[0].H, nDz=1;
while(w>1||h>1){w=Math.max(1,Math.ceil(w/2));h=Math.max(1,Math.ceil(h/2));nDz++;}
const meta = { levels, nDz, W:levels[0].W, H:levels[0].H, url, token };
_streamCache.set(sid, meta);
return meta;
}
async function getStreamTile(sid, url, token, dzLv, col, row) {
const ck = `${sid}:${dzLv}:${col}:${row}`;
if (_tileCache.has(ck)) return _tileCache.get(ck);
const meta = await openRemote(sid, url, token);
const { levels, nDz, W, H } = meta;
// Map DZ level to image dimension
const dzW = Math.max(1, Math.ceil(W / Math.pow(2, nDz-1-dzLv)));
let best = levels[0];
for (const lv of levels) { if (Math.abs(lv.W-dzW) < Math.abs(best.W-dzW)) best=lv; }
const scale = best.W/Math.max(1,dzW);
const tilesX = Math.ceil(best.W/best.tW);
const tilesY = Math.ceil(best.H/best.tH);
const svsCol = Math.min(tilesX-1, Math.floor(col*scale));
const svsRow = Math.min(tilesY-1, Math.floor(row*scale));
const idx = svsRow*tilesX+svsCol;
const white1x1 = Buffer.from('/9j/4AAQSkZJRgABAQEASABIAAD/wAARCAABAAEDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAACBP/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AoABn/9k=','base64');
if (!best.offs||idx>=best.offs.length||!best.offs[idx]) {
_tileCache.set(ck, white1x1);
return white1x1;
}
const byteOff = best.offs[idx];
const byteCnt = best.cnts ? best.cnts[idx] : 65536;
if (!byteOff || !byteCnt) { _tileCache.set(ck,white1x1); return white1x1; }
let tileBuf = await _rangeGet(url, byteOff, byteOff+byteCnt-1, token);
// Inject JPEG tables if needed
if (best.jpegTables && tileBuf[0]===0xFF && tileBuf[1]!==0xD8)
tileBuf = Buffer.concat([best.jpegTables.slice(0,-2), tileBuf]);
if (_tileCache.size >= _TILE_LRU_MAX) _tileCache.delete(_tileCache.keys().next().value);
_tileCache.set(ck, tileBuf);
return tileBuf;
}
// ── koffi + OpenSlide FFI ────────────────────────────────────────────────────
let OSL = null; // OpenSlide function table (populated below)
function findOpenSlideLib() {
const plat = process.platform;
const conda = process.env.CONDA_PREFIX || '';
const brew = '/opt/homebrew';
if (plat === 'darwin') {
return [
conda && path.join(conda, 'lib/libopenslide.dylib'),
brew + '/lib/libopenslide.dylib',
'/usr/local/lib/libopenslide.dylib',
'/opt/local/lib/libopenslide.dylib',
].filter(Boolean).find(p => { try { return fs.existsSync(p); } catch{ return false; }})
|| (brew + '/lib/libopenslide.dylib');
}
if (plat === 'linux') {
return [
conda && path.join(conda, 'lib/libopenslide.so.0'),
'/usr/lib/x86_64-linux-gnu/libopenslide.so.0',
'/usr/lib/libopenslide.so.0',
'/usr/local/lib/libopenslide.so.0',
'libopenslide.so.0',
].filter(Boolean).find(p => { try { return fs.existsSync(p); } catch{ return false; }})
|| 'libopenslide.so.0';
}
// Windows
return ['openslide-0.dll',
'C:\\Program Files\\OpenSlide\\bin\\openslide-0.dll']
.find(p => { try { return fs.existsSync(p); } catch{ return false; }}) || 'openslide-0.dll';
}
try {
const koffi = require('koffi');
const libPath = findOpenSlideLib();
const lib = koffi.load(libPath);
OSL = {
open: lib.func('void* openslide_open(const char* filename)'),
close: lib.func('void openslide_close(void* osr)'),
getError: lib.func('const char* openslide_get_error(void* osr)'),
levelCount:lib.func('int32 openslide_get_level_count(void* osr)'),
levelDims: lib.func('void openslide_get_level_dimensions(void* osr, int32 level, _Out_ int64* w, _Out_ int64* h)'),
levelDS: lib.func('double openslide_get_level_downsample(void* osr, int32 level)'),
bestLevel: lib.func('int32 openslide_get_best_level_for_downsample(void* osr, double ds)'),
readRegion:lib.func('void openslide_read_region(void* osr, uint8* dest, int64 x, int64 y, int32 level, int64 w, int64 h)'),
getProp: lib.func('const char* openslide_get_property_value(void* osr, const char* name)'),
detectVendor: lib.func('const char* openslide_detect_vendor(const char* filename)'),
};
console.log(` openslide: ✓ (${libPath})`);
} catch(e) {
console.warn(` openslide: ✗ ${e.message}`);
console.warn(' Install: brew install openslide OR conda install -c conda-forge openslide');
}
// ── Directories & Config ─────────────────────────────────────────────────────
const BASE_DIR = __dirname;
const ANNOTATIONS_DIR = path.join(BASE_DIR, 'annotations');
const PATCHES_DIR = path.join(BASE_DIR, 'patches');
const THUMBNAILS_DIR = path.join(BASE_DIR, 'static', 'thumbnails');
const CACHE_DIR = path.join(os.homedir(), '.monjoyai', 'cache'); // cloud + TCGA downloads
const REGISTRY_FILE = path.join(BASE_DIR, 'slide_registry.json');
const CONFIG_FILE = path.join(BASE_DIR, 'config.json');
[ANNOTATIONS_DIR, PATCHES_DIR, THUMBNAILS_DIR, CACHE_DIR].forEach(d => {
fs.mkdirSync(d, { recursive: true });
});
// ── Remote (URL-based streaming) registry ─────────────────────────────────────
const REMOTE_REG_FILE = path.join(BASE_DIR, 'remote_slide_registry.json');
function loadRemoteReg() { try { return JSON.parse(fs.readFileSync(REMOTE_REG_FILE,'utf8')); } catch { return {}; } }
function saveRemoteReg(r) { fs.writeFileSync(REMOTE_REG_FILE, JSON.stringify(r,null,2)); }
function remoteId(url) { return require('crypto').createHash('sha256').update(url).digest('hex').slice(0,12); }
const SUPPORTED_EXT = new Set(['.svs','.ndpi','.scn','.czi','.tiff','.tif','.mrxs','.vms','.vmu','.svslide']);
const TILE_SIZE = 254;
const TILE_OVERLAP = 1;
const DEFAULT_CLASSES = [
{ id:'nuclei', name:'Nuclei', color:'#7c3aed', shortcut:'1' },
{ id:'stroma', name:'Stroma', color:'#3b82f6', shortcut:'2' },
{ id:'fat', name:'Fat', color:'#fbbf24', shortcut:'3' },
{ id:'necrosis', name:'Necrosis', color:'#f97316', shortcut:'4' },
{ id:'mitosis', name:'Mitosis', color:'#f59e0b', shortcut:'5' },
{ id:'other', name:'Other', color:'#10b981', shortcut:'6' },
];
// ── Config & Registry helpers ────────────────────────────────────────────────
function loadConfig() {
try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); }
catch { return { watch_dirs: [] }; }
}
function saveConfig(cfg) { fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2)); }
function loadRegistry() {
try { return JSON.parse(fs.readFileSync(REGISTRY_FILE, 'utf8')); }
catch { return {}; }
}
function saveRegistry(reg) { fs.writeFileSync(REGISTRY_FILE, JSON.stringify(reg, null, 2)); }
function pathToId(filePath) {
return crypto.createHash('sha256').update(path.resolve(filePath)).digest('hex').slice(0, 12);
}
// ── Slide discovery ──────────────────────────────────────────────────────────
function discoverSlides() {
const slides = {};
// 1. Registered files
const reg = loadRegistry();
for (const [sid, info] of Object.entries(reg)) {
try {
if (fs.existsSync(info.path) && SUPPORTED_EXT.has(path.extname(info.path).toLowerCase())) {
slides[sid] = { id: sid, name: info.name || path.basename(info.path),
path: info.path, source: info.source || 'local' };
}
} catch {}
}
// 2. Watch directories
const cfg = loadConfig();
for (const wd of (cfg.watch_dirs || [])) {
try {
for (const f of fs.readdirSync(wd).sort()) {
const fp = path.join(wd, f);
if (SUPPORTED_EXT.has(path.extname(f).toLowerCase()) && fs.statSync(fp).isFile()) {
const sid = pathToId(fp);
if (!slides[sid]) slides[sid] = { id: sid, name: f, path: fp, source: 'watch_dir' };
}
}
} catch {}
}
// 3. Cloud/TCGA cache
try {
for (const f of fs.readdirSync(CACHE_DIR).sort()) {
const fp = path.join(CACHE_DIR, f);
if (SUPPORTED_EXT.has(path.extname(f).toLowerCase()) && fs.statSync(fp).isFile()) {
const sid = pathToId(fp);
if (!slides[sid]) slides[sid] = { id: sid, name: f, path: fp, source: 'cloud_cache' };
}
}
} catch {}
// Remote (streaming) slides
try {
const rem = loadRemoteReg();
for (const [sid, info] of Object.entries(rem)) {
if (!slides[sid]) {
slides[sid] = { id: sid, name: info.name, path: info.url,
source: info.source||'stream', is_remote: true, url: info.url };
}
}
} catch(e) {}
return Object.values(slides);
}
function resolveSlide(sid) {
const reg = loadRegistry();
if (reg[sid] && fs.existsSync(reg[sid].path)) return reg[sid].path;
const cfg = loadConfig();
for (const wd of (cfg.watch_dirs || [])) {
try {
for (const f of fs.readdirSync(wd)) {
const fp = path.join(wd, f);
if (SUPPORTED_EXT.has(path.extname(f).toLowerCase()) && pathToId(fp) === sid)
return fp;
}
} catch {}
}
try {
for (const f of fs.readdirSync(CACHE_DIR)) {
const fp = path.join(CACHE_DIR, f);
if (SUPPORTED_EXT.has(path.extname(f).toLowerCase()) && pathToId(fp) === sid)
return fp;
}
} catch {}
return null;
}
// ── Slide cache (open handles) ───────────────────────────────────────────────
const _slideCache = new Map(); // sid → { osr, meta, dz }
function openOsr(sid) {
if (_slideCache.has(sid)) return _slideCache.get(sid);
if (!OSL) throw new Error('OpenSlide C library not loaded');
const filePath = resolveSlide(sid);
if (!filePath) throw new Error(`Slide not found: ${sid}`);
const osr = OSL.open(filePath);
if (!osr) throw new Error(`openslide_open failed for ${filePath}`);
const err = OSL.getError(osr);
if (err) throw new Error(`OpenSlide error: ${err}`);
const meta = buildMeta(sid, osr, filePath);
const dz = new DeepZoomGen(meta);
_slideCache.set(sid, { osr, meta, dz });
return { osr, meta, dz };
}
function closeOsr(sid) {
if (_slideCache.has(sid)) {
try { OSL && OSL.close(_slideCache.get(sid).osr); } catch {}
_slideCache.delete(sid);
}
}
// ── Slide metadata ───────────────────────────────────────────────────────────
const KNOWN_PROPS = {
mpp_x: 'openslide.mpp-x',
mpp_y: 'openslide.mpp-y',
objective_power: 'openslide.objective-power',
vendor: 'openslide.vendor',
};
function buildMeta(sid, osr, filePath) {
const nLevels = OSL.levelCount(osr);
const levelDims = [], levelDS = [];
for (let i = 0; i < nLevels; i++) {
const w = [0n], h = [0n];
OSL.levelDims(osr, i, w, h);
levelDims.push([Number(w[0]), Number(h[0])]);
levelDS.push(OSL.levelDS(osr, i));
}
const props = {};
for (const [k, pname] of Object.entries(KNOWN_PROPS)) {
try { props[k] = OSL.getProp(osr, pname); } catch {}
}
const stat = fs.statSync(filePath);
const annData = loadAnn(sid);
return {
id: sid,
name: loadRegistry()[sid]?.name || path.basename(filePath),
dimensions: levelDims[0] || [0, 0],
level_count: nLevels,
level_dimensions: levelDims,
level_downsamples: levelDS,
mpp_x: props.mpp_x || null,
mpp_y: props.mpp_y || null,
objective_power: props.objective_power || null,
vendor: props.vendor || 'unknown',
annotation_count: (annData.annotations || []).length,
file_size_mb: Math.round(stat.size / 1048576 * 10) / 10,
real_path: filePath,
source: loadRegistry()[sid]?.source || 'local',
};
}
// ── DeepZoom generator ───────────────────────────────────────────────────────
// Mirrors openslide-python's DeepZoomGenerator logic exactly.
class DeepZoomGen {
constructor(meta) {
const [w0, h0] = meta.dimensions;
this.w0 = w0; this.h0 = h0;
this.levelDims = meta.level_dimensions;
this.levelDS = meta.level_downsamples;
this.tileSize = TILE_SIZE;
this.overlap = TILE_OVERLAP;
// Build DZ level list: halve until 1×1
const zDims = [];
let zw = w0, zh = h0;
while (zw > 1 || zh > 1) {
zDims.push([zw, zh]);
zw = Math.max(1, Math.ceil(zw / 2));
zh = Math.max(1, Math.ceil(zh / 2));
}
zDims.push([1, 1]);
this._zDims = zDims.reverse(); // index 0 = 1×1 thumbnail
this.nLevels = this._zDims.length;
// For each DZ level, map to best native slide level
this._slideLevel = this._zDims.map(([zw, zh]) => {
const ds = Math.max(w0 / zw, h0 / zh);
return this._bestLevel(ds);
});
}
_bestLevel(ds) {
let best = 0;
for (let i = 0; i < this.levelDS.length; i++) {
if (this.levelDS[i] <= ds + 0.001) best = i;
}
return best;
}
getDziXml() {
return `<?xml version="1.0" encoding="UTF-8"?><Image xmlns="http://schemas.microsoft.com/deepzoom/2008" Format="jpeg" Overlap="${this.overlap}" TileSize="${this.tileSize}"><Size Width="${this.w0}" Height="${this.h0}"/></Image>`;
}
// Returns {l0x, l0y, slideLevel, readW, readH, outW, outH}
getTileInfo(dzLevel, col, row) {
const [dzW, dzH] = this._zDims[dzLevel];
const ts = this.tileSize;
// Tile bounds in DZ space (no overlap for edge math)
const x0 = col * ts, y0 = row * ts;
const x1 = Math.min(x0 + ts, dzW);
const y1 = Math.min(y0 + ts, dzH);
const outW = x1 - x0, outH = y1 - y0;
// Map to level-0 coordinates
const l0Scale = this.w0 / dzW;
const l0x = Math.round(x0 * l0Scale);
const l0y = Math.round(y0 * l0Scale);
// Native slide level to read from
const slideLevel = this._slideLevel[dzLevel];
const nativeDS = this.levelDS[slideLevel];
const dzDS = l0Scale; // how many l0 px per DZ px
// Read size at native level
const readW = Math.max(1, Math.round(outW * dzDS / nativeDS));
const readH = Math.max(1, Math.round(outH * dzDS / nativeDS));
return { l0x, l0y, slideLevel, readW, readH, outW, outH };
}
}
// ── Tile rendering ───────────────────────────────────────────────────────────
async function renderTile(sid, dzLevel, col, row) {
if (!OSL) throw new Error('OpenSlide not available');
if (!sharp) throw new Error('sharp not available');
const { osr, dz } = openOsr(sid);
const { l0x, l0y, slideLevel, readW, readH, outW, outH } = dz.getTileInfo(dzLevel, col, row);
// Read raw ARGB pixels from OpenSlide
const nPx = readW * readH;
const buf = Buffer.alloc(nPx * 4, 0xff);
OSL.readRegion(osr, buf, BigInt(l0x), BigInt(l0y), slideLevel, BigInt(readW), BigInt(readH));
// Check error
const err = OSL.getError(osr);
if (err) throw new Error(`OpenSlide: ${err}`);
// Convert premultiplied ARGB (LE: B G R A) → RGB for JPEG
const rgb = Buffer.allocUnsafe(nPx * 3);
for (let i = 0; i < nPx; i++) {
const b = buf[i*4];
const g = buf[i*4+1];
const r = buf[i*4+2];
const a = buf[i*4+3];
// Unpremultiply; transparent → white
const inv = a === 0 ? 0 : 255 / a;
rgb[i*3] = Math.min(255, Math.round(r * inv));
rgb[i*3+1] = Math.min(255, Math.round(g * inv));
rgb[i*3+2] = Math.min(255, Math.round(b * inv));
}
// Resize to output dimensions if needed, then encode JPEG
let img = sharp(rgb, { raw: { width: readW, height: readH, channels: 3 } });
if (readW !== outW || readH !== outH) {
img = img.resize(outW, outH, { fit: 'fill', kernel: 'lanczos2' });
}
return img.jpeg({ quality: 85 }).toBuffer();
}
// ── Thumbnail ────────────────────────────────────────────────────────────────
async function getThumbnail(sid, sz = 256) {
if (!OSL || !sharp) throw new Error('OpenSlide or sharp unavailable');
const safe = sid.replace(/[/\\]/g, '_');
const thumb = path.join(THUMBNAILS_DIR, `${safe}_${sz}.jpg`);
if (fs.existsSync(thumb)) return thumb;
const { osr, meta } = openOsr(sid);
// Find level whose smaller dim is closest to sz
let bestLv = meta.level_count - 1;
for (let i = 0; i < meta.level_count; i++) {
const [w, h] = meta.level_dimensions[i];
if (Math.min(w, h) <= sz * 2) { bestLv = i; break; }
}
const [lw, lh] = meta.level_dimensions[bestLv];
const rW = Math.min(lw, 2048), rH = Math.min(lh, 2048);
const nPx = rW * rH;
const buf = Buffer.alloc(nPx * 4, 0xff);
OSL.readRegion(osr, buf, 0n, 0n, bestLv, BigInt(rW), BigInt(rH));
const rgb = Buffer.allocUnsafe(nPx * 3);
for (let i = 0; i < nPx; i++) {
const a = buf[i*4+3];
const inv = a === 0 ? 0 : 255 / a;
rgb[i*3] = Math.min(255, Math.round(buf[i*4+2] * inv));
rgb[i*3+1] = Math.min(255, Math.round(buf[i*4+1] * inv));
rgb[i*3+2] = Math.min(255, Math.round(buf[i*4] * inv));
}
await sharp(rgb, { raw: { width: rW, height: rH, channels: 3 } })
.resize(sz, sz, { fit: 'inside' })
.jpeg({ quality: 85 })
.toFile(thumb);
return thumb;
}
// ── Annotations I/O ──────────────────────────────────────────────────────────
function annFile(sid) {
return path.join(ANNOTATIONS_DIR, sid.replace(/[/\\]/g, '_') + '.json');
}
function loadAnn(sid) {
try {
const data = JSON.parse(fs.readFileSync(annFile(sid), 'utf8'));
data.classes = data.classes || DEFAULT_CLASSES;
return data;
} catch {
return { slide_id: sid, annotations: [], classes: DEFAULT_CLASSES };
}
}
function saveAnn(sid, data) {
fs.writeFileSync(annFile(sid), JSON.stringify(data, null, 2));
}
// ── GeoJSON export ───────────────────────────────────────────────────────────
function toGeoJson(annData) {
const feats = (annData.annotations || []).map(a => {
const coords = a.coordinates || [];
if (!coords.length) return null;
let geom;
if (a.type === 'point') {
geom = { type: 'Point', coordinates: coords[0] };
} else if (a.type === 'rectangle' && a.rect) {
const [x, y, w, h] = a.rect;
geom = { type: 'Polygon', coordinates: [[[x,y],[x+w,y],[x+w,y+h],[x,y+h],[x,y]]] };
} else {
const ring = coords.map(c => [c[0], c[1]]);
if (ring[0][0] !== ring[ring.length-1][0] || ring[0][1] !== ring[ring.length-1][1])
ring.push(ring[0]);
geom = { type: 'Polygon', coordinates: [ring] };
}
return { type: 'Feature', geometry: geom,
properties: { id: a.id, label: a.label, color: a.color,
area_px: a.area_px || 0, notes: a.notes || '',
created: a.created || '' }};
}).filter(Boolean);
return { type: 'FeatureCollection', features: feats };
}
// ── Blur detection ───────────────────────────────────────────────────────────
async function checkBlur(sid, threshold = 100) {
if (!OSL || !sharp) return { error: 'OpenSlide or sharp unavailable' };
const { osr, meta } = openOsr(sid);
const lv = Math.min(2, meta.level_count - 1);
const [lw, lh] = meta.level_dimensions[lv];
const MAX = 2048;
const scale = Math.min(1, MAX / Math.max(lw, lh));
const rW = Math.max(1, Math.round(lw * scale));
const rH = Math.max(1, Math.round(lh * scale));
const nPx = rW * rH;
const buf = Buffer.alloc(nPx * 4, 0xff);
OSL.readRegion(osr, buf, 0n, 0n, lv, BigInt(rW), BigInt(rH));
// Convert to greyscale
const gray = Buffer.allocUnsafe(nPx);
for (let i = 0; i < nPx; i++) {
gray[i] = Math.round(0.299 * buf[i*4+2] + 0.587 * buf[i*4+1] + 0.114 * buf[i*4]);
}
// Laplacian variance
let sum = 0, sum2 = 0;
for (let y = 1; y < rH - 1; y++) {
for (let x = 1; x < rW - 1; x++) {
const idx = y * rW + x;
const lap = (4 * gray[idx]
- gray[idx-1] - gray[idx+1]
- gray[idx-rW] - gray[idx+rW]);
sum += lap;
sum2 += lap * lap;
}
}
const n = (rH - 2) * (rW - 2);
const mean = sum / n;
const variance = sum2 / n - mean * mean;
return { variance: Math.round(variance * 100) / 100, threshold,
is_blurry: variance < threshold,
quality: variance < threshold ? 'BLURRY' : 'SHARP',
level_used: lv };
}
function sanitizeOutputSubdir(name, fallback = 'patches') {
const cleaned = path.basename(String(name || '').trim().replace(/\\/g, '/'))
.replace(/\.\.+/g, '_')
.replace(/[^a-zA-Z0-9._-]/g, '_')
.replace(/^_+|_+$/g, '');
return cleaned || fallback;
}
function sanitizePatchImageFormat(fmt) {
const v = String(fmt || 'jpg').trim().toLowerCase();
return (v === 'jpg' || v === 'jpeg') ? 'jpg' : 'jpg';
}
function getSlideLabel(sid) {
try {
const rem = loadRemoteReg();
if (rem[sid]) return rem[sid].name || sid;
} catch {}
try {
const found = discoverSlides().find(s => s.id === sid);
if (found) return found.name || sid;
} catch {}
return sid;
}
// ── Patch extraction ─────────────────────────────────────────────────────────
async function extractPatches(sid, {
patch_size = 256,
level = 0,
out_subdir = null,
output_dir = null,
label_filter = null,
overlap_threshold = 0.3,
slide_subdir = null,
image_format = 'jpg',
jpeg_quality = 92,
} = {}) {
if (!OSL || !sharp) return { error: 'OpenSlide or sharp unavailable' };
const remoteReg = loadRemoteReg();
if (remoteReg[sid]) {
return { error: 'Patch extraction is currently available for local or cached slides only. Please download/cache the slide first.' };
}
const { osr, meta } = openOsr(sid);
const ann = loadAnn(sid);
let anns = ann.annotations || [];
if (label_filter && label_filter.length) anns = anns.filter(a => label_filter.includes(a.label));
const safeLv = Math.min(Math.max(parseInt(level, 10) || 0, 0), meta.level_count - 1);
const ds = meta.level_downsamples[safeLv];
const stepL0 = Math.max(1, Math.round(patch_size * ds));
const mpp = meta.mpp_x ? parseFloat(meta.mpp_x) : null;
const objPow = meta.objective_power || null;
const patchFormat = sanitizePatchImageFormat(image_format);
const jpegQuality = Math.max(1, Math.min(100, parseInt(jpeg_quality, 10) || 92));
const slideBase = (meta.name || sid)
.replace(/\.[^.]+$/, '')
.replace(/[^a-zA-Z0-9_\-]/g, '_')
.slice(0, 32) || 'slide';
const safeOutSubdir = sanitizeOutputSubdir(out_subdir || output_dir || 'patches');
const rootOutDir = path.join(PATCHES_DIR, safeOutSubdir);
const safeSlideSubdir = slide_subdir ? sanitizeOutputSubdir(slide_subdir, slideBase) : null;
const outDir = safeSlideSubdir ? path.join(rootOutDir, safeSlideSubdir) : rootOutDir;
fs.mkdirSync(outDir, { recursive: true });
let count = 0;
let skippedAnnotations = 0;
const errors = [];
const manifestPatches = [];
for (const annItem of anns.filter(a => a.coordinates && a.coordinates.length)) {
const coords = annItem.coordinates;
const xs = coords.map(p => p[0]);
const ys = coords.map(p => p[1]);
const xMin = Math.round(Math.min(...xs));
const yMin = Math.round(Math.min(...ys));
const xMax = Math.round(Math.max(...xs));
const yMax = Math.round(Math.max(...ys));
const label = annItem.label || 'unknown';
const safeLabel = sanitizeOutputSubdir(label, 'unknown');
const lDir = path.join(outDir, safeLabel);
fs.mkdirSync(lDir, { recursive: true });
const maskH = yMax - yMin + stepL0;
const maskW = xMax - xMin + stepL0;
const mask = new Uint8Array(maskH * maskW);
fillPoly(mask, maskW, coords, xMin, yMin);
let savedForAnnotation = 0;
try {
for (let y0 = yMin; y0 < yMax; y0 += stepL0) {
for (let x0 = xMin; x0 < xMax; x0 += stepL0) {
const ly = y0 - yMin;
const lx = x0 - xMin;
let covered = 0;
let total = 0;
for (let dy = 0; dy < stepL0 && ly + dy < maskH; dy++) {
for (let dx = 0; dx < stepL0 && lx + dx < maskW; dx++) {
if (mask[(ly + dy) * maskW + (lx + dx)]) covered++;
total++;
}
}
if (total === 0 || covered / total < overlap_threshold) continue;
const nPx = patch_size * patch_size;
const buf = Buffer.alloc(nPx * 4, 0xff);
OSL.readRegion(osr, buf, BigInt(x0), BigInt(y0), safeLv,
BigInt(patch_size), BigInt(patch_size));
const rgb = Buffer.allocUnsafe(nPx * 3);
for (let i = 0; i < nPx; i++) {
const a = buf[i*4+3];
const inv = a === 0 ? 0 : 255 / a;
rgb[i*3] = Math.min(255, Math.round(buf[i*4+2] * inv));
rgb[i*3+1] = Math.min(255, Math.round(buf[i*4+1] * inv));
rgb[i*3+2] = Math.min(255, Math.round(buf[i*4] * inv));
}
const fname = `${slideBase}_x${x0}_y${y0}_s${patch_size}_L${safeLv}_${safeLabel}.jpg`;
const fpath = path.join(lDir, fname);
await sharp(rgb, { raw: { width: patch_size, height: patch_size, channels: 3 }})
.jpeg({ quality: jpegQuality, mozjpeg: true })
.toFile(fpath);
manifestPatches.push({
filename: fname,
relative_path: path.posix.join(safeSlideSubdir || '', safeLabel, fname).replace(/^\/+/, ''),
slide_name: meta.name || sid,
slide_id: sid,
annotation_id: annItem.id,
annotation_type: annItem.type,
annotation_label: annItem.label_name || annItem.label,
annotation_color: annItem.color,
annotation_notes: annItem.notes || '',
annotation_coordinates: annItem.coordinates,
annotation_area_px2: annItem.area_px || 0,
x_topleft: x0,
y_topleft: y0,
patch_size_px: patch_size,
resolution_level: safeLv,
downsample_factor: ds,
mpp_x: mpp,
objective_power: objPow,
image_format: patchFormat,
extracted_at: new Date().toISOString(),
});
count++;
savedForAnnotation++;
}
}
if (!savedForAnnotation) skippedAnnotations++;
} catch (e) {
errors.push(`${String(annItem.id || 'annotation').slice(0, 12)}: ${e.message}`);
}
}
const manifest = {
monjoy_histoai_version: '2.1',
generated_at: new Date().toISOString(),
image_format: patchFormat,
slide: {
name: meta.name || sid,
id: sid,
dimensions: meta.dimensions,
level_count: meta.level_count,
level_dimensions: meta.level_dimensions,
level_downsamples: meta.level_downsamples,
mpp_x: meta.mpp_x,
mpp_y: meta.mpp_y,
objective_power: meta.objective_power,
vendor: meta.vendor,
source: meta.source,
real_path: meta.real_path,
},
extraction_params: {
patch_size_px: patch_size,
resolution_level: safeLv,
downsample_factor: ds,
overlap_threshold,
label_filter: label_filter || 'all',
output_directory: outDir,
output_root_directory: rootOutDir,
slide_output_subdir: safeSlideSubdir,
image_format: patchFormat,
jpeg_quality: jpegQuality,
},
annotations: anns.map(a => ({
id: a.id,
type: a.type,
label: a.label,
label_name: a.label_name,
color: a.color,
coordinates: a.coordinates,
area_px2: a.area_px,
notes: a.notes,
created: a.created,
})),
patches: manifestPatches,
total_patches_extracted: count,
skipped_annotations: skippedAnnotations,
errors,
};
const manifestPath = path.join(outDir, `${slideBase}_manifest.json`);
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
return {
extracted: count,
skipped: skippedAnnotations,
errors,
output_dir: rootOutDir,
slide_output_dir: outDir,
output_subdir: safeOutSubdir,
slide_subdir: safeSlideSubdir,
manifest_file: manifestPath,
annotations_processed: anns.length,
image_format: patchFormat,
};
}
async function extractPatchesBatch(slideIds, opts = {}) {
const ids = Array.from(new Set((Array.isArray(slideIds) ? slideIds : []).filter(Boolean)));
if (!ids.length) return { error: 'No slides selected' };
const safeOutSubdir = sanitizeOutputSubdir(opts.out_subdir || opts.output_dir || 'patches');
const batchRoot = path.join(PATCHES_DIR, safeOutSubdir);
fs.mkdirSync(batchRoot, { recursive: true });
const results = [];
const batchErrors = [];
let totalExtracted = 0;
let totalSkipped = 0;
for (let i = 0; i < ids.length; i++) {
const sid = ids[i];
const slideName = getSlideLabel(sid);
const slideStem = String(slideName || sid).replace(/\.[^.]+$/, '');
const safeSlideDir = `${String(i + 1).padStart(2, '0')}_${sanitizeOutputSubdir(slideStem, 'slide_' + (i + 1))}`;
try {
const one = await extractPatches(sid, {
...opts,
out_subdir: safeOutSubdir,
output_dir: safeOutSubdir,
slide_subdir: safeSlideDir,
image_format: 'jpg',
});
if (one && one.error) throw new Error(one.error);
totalExtracted += one.extracted || 0;
totalSkipped += one.skipped || 0;
if (Array.isArray(one.errors) && one.errors.length) {
batchErrors.push(...one.errors.map(e => `${slideName}: ${e}`));
}
results.push({
slide_id: sid,
slide_name: slideName,
slide_subdir: one.slide_subdir || safeSlideDir,
output_dir: one.slide_output_dir || one.output_dir,
extracted: one.extracted || 0,
skipped: one.skipped || 0,
annotations_processed: one.annotations_processed || 0,
manifest_file: one.manifest_file,
errors: one.errors || [],
image_format: one.image_format || 'jpg',
});
} catch (e) {
const msg = e && e.message ? e.message : String(e);
batchErrors.push(`${slideName}: ${msg}`);
results.push({
slide_id: sid,
slide_name: slideName,
slide_subdir: safeSlideDir,
output_dir: path.join(batchRoot, safeSlideDir),
extracted: 0,
skipped: 0,
annotations_processed: 0,
manifest_file: null,
error: msg,
errors: [msg],
image_format: 'jpg',
});
}
}
const batchManifest = {
monjoy_histoai_version: '2.1',
generated_at: new Date().toISOString(),
image_format: 'jpg',
output_directory: batchRoot,
output_subdir: safeOutSubdir,
selected_slide_ids: ids,
extraction_params: {
patch_size_px: opts.patch_size || 256,
resolution_level: opts.level || 0,
overlap_threshold: opts.overlap_threshold == null ? 0.3 : opts.overlap_threshold,
label_filter: opts.label_filter || 'all',
image_format: 'jpg',
jpeg_quality: opts.jpeg_quality || 92,
},
totals: {
slides_selected: ids.length,
slides_processed: results.length,
slides_with_errors: results.filter(r => r.error).length,
total_patches_extracted: totalExtracted,
total_skipped_annotations: totalSkipped,
},
slides: results.map(r => ({
slide_id: r.slide_id,
slide_name: r.slide_name,
slide_subdir: r.slide_subdir,
output_dir: r.output_dir,
extracted: r.extracted,
skipped: r.skipped,
annotations_processed: r.annotations_processed,
manifest_file: r.manifest_file,
error: r.error || null,
errors: r.errors || [],
image_format: r.image_format || 'jpg',
})),