Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 | import type { Types } from '@cornerstonejs/core'; import { utilities, eventTarget, Enums, triggerEvent, cache, } from '@cornerstonejs/core'; import * as cornerstoneTools from '@cornerstonejs/tools'; import type { Types as cstTypes } from '@cornerstonejs/tools'; import { segmentation as cstSegmentation, LabelmapBaseTool, } from '@cornerstonejs/tools'; import { Events as aiEvents } from './enums'; const { strategies } = cstSegmentation; const { fillInsideCircle } = strategies; // @ts-ignore import ort from 'onnxruntime-web/webgpu'; import { vec3 } from 'gl-matrix'; const { annotation } = cornerstoneTools; const { state: annotationState } = annotation; const { Events } = Enums; const { Events: toolsEvents } = cornerstoneTools.Enums; const { segmentation } = cornerstoneTools; const { filterAnnotationsForDisplay } = cornerstoneTools.utilities.planar; const { IslandRemoval } = cornerstoneTools.utilities; const { triggerSegmentationDataModified } = segmentation.triggerSegmentationEvents; export type ModelType = { name: string; key: string; url: string; size: number; opt?: Record<string, unknown>; }; /** * clone tensor */ function cloneTensor(t) { return new ort.Tensor(t.type, Float32Array.from(t.data), t.dims); } /* * create feed for the original facebook model */ function feedForSam(emb, points, labels, modelSize = [1024, 1024]) { const maskInput = new ort.Tensor( new Float32Array(256 * 256), [1, 1, 256, 256] ); const hasMask = new ort.Tensor(new Float32Array([0]), [1]); const originalImageSize = new ort.Tensor(new Float32Array(modelSize), [2]); const pointCoords = new ort.Tensor(new Float32Array(points), [ 1, points.length / 2, 2, ]); const pointLabels = new ort.Tensor(new Float32Array(labels), [ 1, labels.length, ]); const key = (emb.image_embeddings && 'image_embeddings') || 'embeddings'; return { image_embeddings: cloneTensor(emb[key]), point_coords: pointCoords, point_labels: pointLabels, mask_input: maskInput, has_mask_input: hasMask, orig_im_size: originalImageSize, }; } /* Create a function which will be passed to the promise and resolve it when FileReader has finished loading the file. */ function getBuffer(fileData) { return new Promise((resolve) => { const reader = new FileReader(); reader.readAsArrayBuffer(fileData); reader.onload = function () { const arrayBuffer = reader.result as ArrayBuffer; const bytes = new Float32Array(arrayBuffer); resolve(bytes); }; }); } export enum Loggers { Log = 'status', Encoder = 'encoder', Decoder = 'decoder', } /** * The ONNXController handles the interaction between CS3D viewports and ONNX segmentation * models to allow segmentation of volume and stack viewports using browser local * data models. The process is that a particular view of the viewport is rendered * using the loadImageToCanvas to generate the required model size. This will render * without annotations/segmentation. Then, this view is passed to the encoder model which * transforms the data into a set of information about the overall image. This encoding * can take a while, so it is cached. * * To generate segmentations, the encoded model data is combined with information from the * user in the form of annotations on the image to include or exclude regions from the segmentation, * and allow the segmentation to be guided. * * Once the segmentation data has been generated, it is converted from the overlay/bitmap model into * a CS3D segmentation map, in the segment index currently being worked on. * * The encoded model data is stored in browser local storage, and each model * typically consumes about 4 mb per frame. The path for the storage is * based on the target id and the study/series/instance attributes. That * path is: * * `<modelName>/<studyUID>/<seriesUID>/<filePath>` * where the file path is the instance UID, or a made up name based on the * slice index and view normal for orthographic images. * * For encoding images, there are two sessions to consider. The currently * displaying session has information about the image being worked on, while a * second session allows encoding images not being currently viewed. This allows * for background encoding of images. However, note the library does NOT allow * encoding two images at the same time, it is merely that two images can be * queued up for encoding at the same time and can have non-overlapping results. */ export default class ONNXSegmentationController { /** Default name for a tool for inclusion points */ public static MarkerInclude = 'MarkerInclude'; /** Default name for a tool for exclusion points */ public static MarkerExclude = 'MarkerExclude'; /** Default name for a tool for box prompt */ public static BoxPrompt = 'BoxPrompt'; /** Some viewport options for loadImageToCanvas */ public static viewportOptions = { displayArea: { storeAsInitialCamera: true, // Use nearest neighbour for better results on the model interpolationType: Enums.InterpolationType.NEAREST, imageArea: [1, 1], imageCanvasPoint: { // TODO - fix this so top left corner works imagePoint: [0.5, 0.5], canvasPoint: [0.5, 0.5], }, } as Types.DisplayArea, background: <Types.Point3>[0, 0, 0.2], }; // the image size on canvas maxWidth = 1024; maxHeight = 1024; // the image size supported by the model modelWidth = 1024; modelHeight = 1024; tool; /** * Defines the URL endpoints and render sizes/setup for the various models that * can be used. */ static MODELS = { sam_l: [ { name: 'sam-l-encoder', url: '/sam_l/vit_l_encoder.onnx', size: 1224, key: 'encoder', feedType: 'images', }, { name: 'sam-l-decoder', url: '/sam_l/vit_l_decoder.onnx', size: 17, key: 'decoder', }, ], sam_h: [ { name: 'sam-h-encoder', url: '/sam_h/vit_h_encoder.onnx', size: 18, key: 'encoder', feedType: 'images', }, { name: 'sam-h-decoder', url: '/sam_h/vit_h_decoder.onnx', size: 1, key: 'decoder', }, ], }; public canvas = document.createElement('canvas'); public canvasMask = document.createElement('canvas'); /** Store other sessions to be used for next images. */ private sessions = []; private config; private points = []; private labels = []; private worldPoints = new Array<Types.Point3>(); private randomPoints; private _searchBreadth = 3; private loadingAI: Promise<unknown>; protected viewport; protected excludeTool = ONNXSegmentationController.MarkerExclude; protected currentImage; private listeners = [console.log]; protected desiredImage = { imageId: null, sampleImageId: null, imageIndex: -1, decoder: null, encoder: null, }; protected imageEncodings = new Map(); protected sharedImageEncoding; protected boxRadius = 5; protected imageImageData; protected isGpuInUse = false; protected annotationsNeedUpdating = false; protected maskImageData; protected promptAnnotationTypes = [ ONNXSegmentationController.MarkerInclude, ONNXSegmentationController.MarkerExclude, ONNXSegmentationController.BoxPrompt, ]; protected _cachedPromptAnnotations; // autoSegment mode properties protected _enabled = false; protected _autoSegmentMode = false; protected imageIdsRunAgainst = new Map(); protected numRandomPoints = 25; // Default number of random points to sample /** * Fill internal islands by size, and consider islands at the edge to * be included as internal. */ protected islandFillOptions: { maxInternalRemove: number; fillInternalEdge: boolean; } = { maxInternalRemove: 16, fillInternalEdge: true, }; /** * The p cutoff to apply, values p and above are included. * The values are pixel values, so 0 means everything, while 255 means * only certainly included. A value of 64 seems reasonable as it omits low probability areas, * but most areas are >190 in actual practice. */ protected pCutoff = 64; /** * Configure the ML Controller. No parameters are required, and will default * to the basic set of controls using MarkerInclude/Exclude and the default SAM * model for segmentation. * * The plan is to add additional prompt types and default models which can be * applied, but this version is a simple/basic version. * * @param options - a set of options to configure this with * * listeners - a set of functions to call to get log type feedback on the status of the segmentation * * getPromptAnnotations - a function to get the annotations which are used as input to the AI segmentation * * promptAnnotationTypes - a list of annotation type names to use to generate the prompts. This is an * alternate to the getPromptAnnotations * * models - a set of model configurations to run - note these are added globally to the static models * * modelName - the specific model name to choose. Must exist in models. * * autoSegmentMode - whether to enable autoSegment mode by default * * numRandomPoints - the number of random points to sample for autoSegment mode */ constructor( options: { listeners?: Array<(message: string) => void>; getPromptAnnotations?: ( viewport?: Types.IViewport ) => cornerstoneTools.Types.Annotation[]; promptAnnotationTypes?: string[]; models?: Record<string, ModelType[]>; modelName?: string; islandFillOptions?: { maxInternalRemove?: number; fillInternalEdge?: boolean; }; autoSegmentMode?: boolean; numRandomPoints?: number; searchBreadth?: number; } = { listeners: null, getPromptAnnotations: null, promptAnnotationTypes: null, models: null, modelName: null, islandFillOptions: { maxInternalRemove: 16, fillInternalEdge: true, }, autoSegmentMode: false, numRandomPoints: 2, searchBreadth: 3, } ) { if (options.listeners) { this.listeners = [...options.listeners]; } if (options.getPromptAnnotations) { this.getPromptAnnotations = options.getPromptAnnotations; } this.promptAnnotationTypes = options.promptAnnotationTypes || this.promptAnnotationTypes; if (options.models) { Object.assign(ONNXSegmentationController.MODELS, options.models); } this.config = this.getConfig(options.modelName); // Ensure we have non-optional properties when assigning if (options.islandFillOptions) { this.islandFillOptions = { maxInternalRemove: options.islandFillOptions.maxInternalRemove ?? this.islandFillOptions.maxInternalRemove, fillInternalEdge: options.islandFillOptions.fillInternalEdge ?? this.islandFillOptions.fillInternalEdge, }; } // Initialize autoSegment mode this._autoSegmentMode = options.autoSegmentMode || false; this.numRandomPoints = options.numRandomPoints || this.numRandomPoints; // Set search breadth for neighbor slices this._searchBreadth = options.searchBreadth || this._searchBreadth; } /** * Enable or disable the controller */ public set enabled(enabled: boolean) { this._enabled = enabled; } public get enabled() { return this._enabled; } /** * Enable or disable autoSegment mode */ public set autoSegmentMode(enabled: boolean) { this._autoSegmentMode = enabled; // Automatically enable the controller when autoSegment mode is enabled if (enabled) { this._enabled = true; } } public get autoSegmentMode() { return this._autoSegmentMode; } /** * Set the number of random points to sample in autoSegment mode */ public set numSamplePoints(num: number) { this.numRandomPoints = num; } /** * Loads the AI model. This can take a while and will return a promise * which resolves when the model is completed. If the model is already loaded, * then the promise returned will be resolved already. Can safely be called multiple * times to allow starting the model load early, and then waiting for it when done. */ public initModel(): Promise<unknown> { if (!this.loadingAI) { this.loadingAI = this.load(); } return this.loadingAI; } public setPCutoff(cutoff: number) { this.pCutoff = cutoff; this.annotationsNeedUpdating = true; this.tryLoad(); } /** * Connects a viewport up to get annotations and updates * Note that only one viewport at a time is permitted as the model needs to * load data about the active viewport. This method will disconnect a previous * viewport automatically. * * The viewport must have a labelmap segmentation registered, as well as a * tool which extends LabelmapBaseTool to use for setting the preview view * once the decode is completed. This is provided as toolForPreview * * @param viewport - a viewport to listen for annotations and rendered events * @param toolForPreview - this tool is used to access the preview object and * create a new preview instance. */ public initViewport(viewport) { const { desiredImage } = this; if (this.viewport) { this.disconnectViewport(this.viewport); } this.currentImage = null; this.viewport = viewport; const brushInstance = new LabelmapBaseTool( {}, { configuration: { strategies: { FILL_INSIDE_CIRCLE: fillInsideCircle, }, activeStrategy: 'FILL_INSIDE_CIRCLE', preview: { enabled: true, }, }, } ); this.tool = brushInstance; desiredImage.imageId = viewport.getCurrentImageId?.() || viewport.getViewReferenceId(); if (desiredImage.imageId.startsWith('volumeId:')) { desiredImage.sampleImageId = viewport.getImageIds( viewport.getVolumeId() )[0]; } else { desiredImage.sampleImageId = desiredImage.imageId; } viewport.element.addEventListener( Events.IMAGE_RENDERED, this.viewportRenderedListener ); const boundListener = this.annotationModifiedListener; eventTarget.addEventListener(toolsEvents.ANNOTATION_ADDED, boundListener); eventTarget.addEventListener( toolsEvents.ANNOTATION_MODIFIED, boundListener ); eventTarget.addEventListener( toolsEvents.ANNOTATION_COMPLETED, boundListener ); if (desiredImage.imageId) { this.tryLoad(); } } public acceptPreview(element) { this.tool.acceptPreview(element); } public rejectPreview(element) { this.tool.rejectPreview(element); } restoreCachedPromptAnnotations(viewport: Types.IViewport) { if (!this._cachedPromptAnnotations) { return []; } const annotations = []; const { include, exclude } = this._cachedPromptAnnotations; if (include) { const newInclude = cornerstoneTools.utilities.moveAnnotationToViewPlane( include, viewport ); annotations.push(newInclude); } if (exclude) { const newExclude = cornerstoneTools.utilities.moveAnnotationToViewPlane( exclude, viewport ); annotations.push(newExclude); } return annotations; } /** * Removes all prompt annotations but caches one positive (include) and one negative (exclude) * annotation. These cached annotations can be re-added later (for example, after an interpolateScroll). * * @param viewport - The viewport element on which annotations are rendered. */ removePromptAnnotationsWithCache(viewport: Types.IViewport) { const toolNames = [ ONNXSegmentationController.MarkerInclude, ONNXSegmentationController.MarkerExclude, ONNXSegmentationController.BoxPrompt, ]; let cachedInclude = null; let cachedExclude = null; // Get all annotations once const allAnnotations = cornerstoneTools.annotation.state.getAllAnnotations(); // Single loop to filter, cache, and remove prompt annotations for (const annotation of allAnnotations) { const toolName = annotation.metadata.toolName; if (toolNames.includes(toolName)) { // Cache first found include/exclude annotations if ( toolName === ONNXSegmentationController.MarkerInclude && !cachedInclude ) { cachedInclude = annotation; } else if ( toolName === ONNXSegmentationController.MarkerExclude && !cachedExclude ) { cachedExclude = annotation; } // Remove the annotation cornerstoneTools.annotation.state.removeAnnotation( annotation.annotationUID ); } } // Store cached annotations this._cachedPromptAnnotations = { include: cachedInclude, exclude: cachedExclude, }; viewport.render(); } /** * The interpolateScroll checks to see if there are any annotations on the * current image in the specified viewport, and if so, scrolls in the given * direction and copies the annotations to the new image displayed. * It will not copy any annotations onto a viewport already containing * prompt annotations, nor will it do anything if there are no annotations * on the current viewport. * * Assumes the current and next viewports have the same viewport normal, and * that the difference between positions is entirely contained by the difference * in the focal point between viewports. This difference is added to each * point in the annotations. */ public async interpolateScroll(viewport = this.viewport, dir = 1) { const { element } = viewport; this.tool.acceptPreview(element); const promptAnnotations = this.getPromptAnnotations(viewport); const currentSliceIndex = viewport.getCurrentImageIdIndex(); const viewRef = viewport.getViewReference({ sliceIndex: currentSliceIndex + dir, }); if (!viewRef || viewRef.sliceIndex === currentSliceIndex) { console.warn('No next image in direction', dir, currentSliceIndex); return; } viewport.scroll(dir); // Wait for the scroll to complete await new Promise((resolve) => window.setTimeout(resolve, 250)); let annotations = []; if (!promptAnnotations.length) { annotations = this.restoreCachedPromptAnnotations(viewport); } else { // Add the difference between the new and old focal point as being the // position difference between images. Does not account for any // rotational differences between frames that may occur on stacks for (const annotation of promptAnnotations) { const newAnnotation = <cstTypes.Annotation>structuredClone(annotation); // remove the old annotation cornerstoneTools.annotation.state.removeAnnotation( annotation.annotationUID ); Object.assign(newAnnotation.metadata, viewRef); cornerstoneTools.utilities.moveAnnotationToViewPlane( newAnnotation, viewport ); annotations.push(newAnnotation); } } for (const annotation of annotations) { annotationState.addAnnotation(annotation, viewport.element); } viewport.render(); } /** * Logs the message to the given log level */ protected log(logger: Loggers, ...args) { for (const listener of this.listeners) { listener(logger, ...args); } } /** * Gets a list of the include/exclude orientation annotations applying to the * current image id. */ protected getPromptAnnotations = (viewport = this.viewport) => { const annotations = []; const { element } = viewport; for (const annotationName of this.promptAnnotationTypes) { annotations.push( ...annotationState.getAnnotations(annotationName, element) ); } const currentAnnotations = filterAnnotationsForDisplay( this.viewport, annotations ); return currentAnnotations; }; /** * A listener for viewport being rendered that tried loading/encoding the * new image if it is different from the previous image. Will return before * the image is encoded. Can be called without binding as it is already * bound to the this object. * The behaviour of the callback is that if the image has changed in terms * of which image (new view reference), then that image is set as the * currently desired encoded image, and a new encoding will be read from * cache or one will be created and stored in cache. * * This does not need to be manually bound, the initViewport will bind * this to the correct rendering messages. */ protected viewportRenderedListener = (_event) => { const { viewport, currentImage, desiredImage } = this; desiredImage.imageId = viewport.getCurrentImageId() || viewport.getViewReferenceId(); desiredImage.imageIndex = viewport.getCurrentImageIdIndex(); if (!desiredImage.imageId) { return; } if (desiredImage.imageId.startsWith('volumeId:')) { desiredImage.sampleImageId = viewport.getImageIds( viewport.getVolumeId() )[0]; } else { desiredImage.sampleImageId = desiredImage.imageId; } if (desiredImage.imageId === currentImage?.imageId) { return; } if (this._enabled && this._autoSegmentMode) { if ( 'isInAcquisitionPlane' in viewport && !viewport.isInAcquisitionPlane() ) { console.warn( 'Non acquisition plane viewports and auto segment mode is not yet supported' ); return; } const segmentation = cornerstoneTools.segmentation.activeSegmentation.getActiveSegmentation( viewport.id ); const segmentIndex = cornerstoneTools.segmentation.segmentIndex.getActiveSegmentIndex( segmentation.segmentationId ); // Get all image IDs const imageIds = viewport.getImageIds(); const currentImageIdIndex = viewport.getCurrentImageIdIndex(); const pointLists = []; let foundPrevious = false; let foundNext = false; // Check slices with increasing offset until we find points or reach max breadth for (let offset = 1; offset <= this._searchBreadth; offset++) { if (!foundPrevious) { const previousImageIdIndex = currentImageIdIndex - offset; if (previousImageIdIndex >= 0) { const previousImageId = imageIds[previousImageIdIndex]; const previousLabelmapImage = cache.getImageByReferencedImageId(previousImageId); const previousLabelmapVoxelManager = previousLabelmapImage?.voxelManager; if (previousLabelmapVoxelManager) { let foundInThisSlice = false; previousLabelmapVoxelManager.forEach(({ value, pointIJK }) => { if (value === segmentIndex) { const worldCoords = utilities.imageToWorldCoords( previousLabelmapImage.imageId, [pointIJK[0], pointIJK[1]] ); pointLists.push(worldCoords); foundInThisSlice = true; } }); if (foundInThisSlice) { foundPrevious = true; } } } } // Check next slice if we haven't found points in that direction yet if (!foundNext) { const nextImageIdIndex = currentImageIdIndex + offset; if (nextImageIdIndex < imageIds.length) { const nextImageId = imageIds[nextImageIdIndex]; const nextLabelmapImage = cache.getImageByReferencedImageId(nextImageId); const nextLabelmapVoxelManager = nextLabelmapImage?.voxelManager; if (nextLabelmapVoxelManager) { let foundInThisSlice = false; nextLabelmapVoxelManager.forEach(({ value, pointIJK }) => { if (value === segmentIndex) { const worldCoords = utilities.imageToWorldCoords( nextLabelmapImage.imageId, [pointIJK[0], pointIJK[1]] ); pointLists.push(worldCoords); foundInThisSlice = true; } }); if (foundInThisSlice) { foundNext = true; } } } } // If we have found points in both directions, we can stop if (foundPrevious && foundNext) { break; } } // Pick random points from the pointLists this.randomPoints = pointLists.length > 0 ? pointLists .sort(() => Math.random() - 0.5) .slice(0, Math.min(pointLists.length, this.numRandomPoints)) : []; } const { canvasMask } = this; const ctxMask = canvasMask.getContext('2d'); ctxMask.clearRect(0, 0, canvasMask.width, canvasMask.height); this.tryLoad({ resetImage: true }); }; /** * This is an already bound annotation modified listener, that is added/removed * from the viewport by the initViewport method. * This listener does the following: * * Gets the annotations, returning immediately if there are no annotations * * Marks the annotations as needing an update * * Starts an encoding on the current image if it is not already encoded * * When the image is encoded, runs the decoder * * Once the decoder has completed, converts the results into a CS3D segmentation preview * * Note that the decoder run will not occur if the image is changed before the * decoder starts running, and that encoding a new image may not start until * an ongoing decoder operations has completed. */ protected annotationModifiedListener = cornerstoneTools.utilities.debounce( (_event?) => { const currentAnnotations = this.getPromptAnnotations(); if (!currentAnnotations.length) { return; } this.annotationsNeedUpdating = true; this.tryLoad(); }, 300 ); /** * Disconnects the given viewport, removing the listeners. */ public disconnectViewport(viewport) { viewport.element.removeEventListener( Events.IMAGE_RENDERED, this.viewportRenderedListener ); const boundListener = this.annotationModifiedListener; eventTarget.removeEventListener( toolsEvents.ANNOTATION_MODIFIED, boundListener ); eventTarget.removeEventListener( toolsEvents.ANNOTATION_COMPLETED, boundListener ); } /** * Does the actual load, separated from the public method to allow starting * the AI to load and then waiting for it once other things are also ready. * This is done internally so that only a single load/setup is created, allowing * for the load to be started and only waited for when other things are ready. */ protected async load() { const { sessions } = this; this.canvas.style.cursor = 'wait'; let loader; // Create two sessions, one for the current images, and a second session // for caching non-visible images. This doesn't create two GPU sessions, // but does create two sessions for storage of encoded results. for (let i = 0; i < 2; i++) { sessions.push({ sessionIndex: i, encoder: null, decoder: null, imageEmbeddings: null, isLoading: false, canvas: i === 0 ? this.canvas : document.createElement('canvas'), }); if (i === 0) { loader = this.loadModels( ONNXSegmentationController.MODELS[this.config.model], sessions[i] ).catch((e) => { this.log(Loggers.Log, "Couldn't load models", e); }); await loader; } else { // Only the encoder is needed otherwise sessions[i].encoder = sessions[0].encoder; } sessions[i].loader = loader; } } /** * Clears the points, labels and annotations related to the ML model from the * viewport. */ public clear(viewport) { this.points = []; this.labels = []; this.getPromptAnnotations(viewport).forEach((annotation) => annotationState.removeAnnotation(annotation.annotationUID) ); if (this.tool) { this.tool.rejectPreview(this.viewport.element); } } /** * Cache the next image encoded. This will start at the current image id, * and will keep on fetching additional images, wrapping round to the 0...current * position-1 so as to fetch all images. * Works with both volume (orthographic) and stack viewports. * This will interfere with any image navigation * * @param current - the starting image near which other images should be cached. * @param offset - what offset to the current image should be used, that is, * for 125 images, if the current was 5, and the offset is 6, then the * image at sliceIndex 5+6+1 will be used. * @param length - the number of images. This will be determined dynamically * based on when the view reference for the next slice returns undefined. * Defaults to 1,000,000 to start with. */ public async cacheImageEncodings( current = this.viewport.getCurrentImageIdIndex(), offset = 0, length = 1000_000 ) { const { viewport, imageEncodings } = this; if (offset >= length) { // We are done. return; } const index = (offset + current) % length; const view = viewport.getViewReference({ sliceIndex: index }); if (!view) { length = index; return this.cacheImageEncodings(current, offset, length); } const imageId = view.referencedImageId || viewport.getViewReferenceId({ sliceIndex: index }); if (!imageEncodings.has(imageId)) { // Try loading from storage await this.loadStorageImageEncoding(current, imageId, index); } if (imageEncodings.has(imageId)) { this.cacheImageEncodings(current, offset + 1, length); return; } // Try doing a load, so that UI has priority this.tryLoad(); if (this.isGpuInUse) { setTimeout(() => this.cacheImageEncodings(current, offset), 500); return; } this.log(Loggers.Log, 'Caching', index, imageId); const sampleImageId = viewport.getImageIds()[0]; this.handleImage({ imageId, sampleImageId }, this.sessions[1]).then(() => { this.cacheImageEncodings(current, offset + 1, length); }); } /** * Handles a new image. This will render the image to a separate canvas * using the load image to canvas, and then will load or generate encoder * values into the imageSession provided. * If there is already an image being handled or worked on, returns immediately. * * At the end of the handle, tries calling the tryLoad method to see if there * are other high priority tasks to complete. */ protected async handleImage({ imageId, sampleImageId }, imageSession) { if (imageId === imageSession.imageId || this.isGpuInUse || !this.enabled) { return; } const { viewport, desiredImage } = this; this.isGpuInUse = true; imageSession.imageId = imageId; imageSession.sampleImageId = sampleImageId; try { const isCurrent = desiredImage.imageId === imageId; const { canvas } = imageSession; if (isCurrent) { this.log( Loggers.Encoder, `Loading image on ${imageSession.sessionIndex}` ); this.log(Loggers.Decoder, 'Awaiting image'); canvas.style.cursor = 'wait'; } this.points = []; this.labels = []; const width = this.maxWidth; const height = this.maxHeight; canvas.width = width; canvas.height = height; imageSession.imageEmbeddings = undefined; const size = canvas.style.width; const ctx = canvas.getContext('2d', { willReadFrequently: true }); ctx.clearRect(0, 0, width, height); const renderArguments = { canvas, imageId, viewportOptions: { ...viewport.defaultOptions, ...ONNXSegmentationController.viewportOptions, }, viewReference: null, renderingEngineId: viewport.getRenderingEngine().id, }; if (imageId.startsWith('volumeId:')) { const viewRef = viewport.getViewReference(); renderArguments.viewReference = viewRef; renderArguments.imageId = null; } imageSession.canvasPosition = await utilities.loadImageToCanvas(renderArguments); canvas.style.width = size; canvas.style.height = size; if (isCurrent) { this.log( Loggers.Encoder, `Rendered image on ${imageSession.sessionIndex}` ); } this.imageImageData = ctx.getImageData(0, 0, width, height); const data = await this.restoreImageEncoding(imageSession, imageId); if (data) { imageSession.imageEmbeddings = data; if (desiredImage.imageId === imageId) { this.log(Loggers.Encoder, 'Cached Image'); canvas.style.cursor = 'default'; } } else { const t = await ort.Tensor.fromImage(this.imageImageData, { resizedWidth: this.modelWidth, resizedHeight: this.modelHeight, }); const { feedType = 'input_image' } = this.config.encoder; const feed = (feedType === 'images' && { images: t }) || (feedType === 'pixelValues' && { pixel_values: t }) || { input_image: t, }; await imageSession.loader; const session = await imageSession.encoder; if (!session) { this.log(Loggers.Log, '****** No session'); return; } const start = performance.now(); imageSession.imageEmbeddings = session.run(feed); const data = await imageSession.imageEmbeddings; this.storeImageEncoding(imageSession, imageId, data); if (desiredImage.imageId === imageId) { this.log( Loggers.Encoder, `Image Ready ${imageSession.sessionIndex} ${( performance.now() - start ).toFixed(1)} ms` ); canvas.style.cursor = 'default'; } } } finally { this.isGpuInUse = false; } this.tryLoad(); } /** * This method tries to run the decode that wraps the decode operation in * checks for whether hte GPU is in use, whether the decode has otherwise completed, * and a general try/catch around the decode. */ protected async runDecode() { const { canvas } = this; if (this.isGpuInUse || !this.currentImage?.imageEmbeddings) { return; } this.isGpuInUse = true; try { this.canvas.style.cursor = 'wait'; await this.decode(this.points, this.labels); } finally { canvas.style.cursor = 'default'; this.isGpuInUse = false; } } /** * This function will try setting the current image to the desired loading image * if it isn't already the desired one, and invoke the handleImage. * If the desired image is already the right one, then it will try to run * and outstanding decoder task. * This sequence allows out of order decodes to happen and to start the latest * encode/decode at the time the last operation has completed. If the user * performs multiple operations, then only the last set is handled. */ public tryLoad(options = { resetImage: false }) { const { viewport, desiredImage } = this; if (!desiredImage.imageId || options.resetImage) { desiredImage.imageId = viewport.getCurrentImageId() || viewport.getViewReferenceId(); this.currentImage = null; } // Always use session 0 for the current session const [session] = this.sessions; if (session?.imageId === desiredImage.imageId) { if (this.currentImage !== session) { this.currentImage = session; } if (this._enabled && this._autoSegmentMode) { this.points = []; this.labels = []; // Process random points from previous segmentation if available if (this.randomPoints?.length) { this.randomPoints.forEach((point) => { const mappedPoint = this.mapAnnotationPoint( point, this.currentImage.canvasPosition ); this.points.push(...mappedPoint); this.labels.push(1); }); this.runDecode(); } } else { // Regular mode - process annotations this.updateAnnotations(); } return; } this.handleImage(desiredImage, session); } /** * Maps world points to destination points. * Assumes the destination canvas is defined by the canvasPosition value */ mapAnnotationPoint(worldPoint, canvasPosition) { const { origin, downVector, rightVector } = canvasPosition; // Vectors are scaled to unit vectors in canvas index space const deltaOrigin = vec3.sub([0, 0, 0], worldPoint, origin); const x = Math.round( vec3.dot(deltaOrigin, rightVector) / vec3.sqrLen(rightVector) ); const y = Math.round( vec3.dot(deltaOrigin, downVector) / vec3.sqrLen(downVector) ); return [x, y]; } /** * Updates annotations when they have changed in some way, running the decoder. * This will mark the annotations as needing update, so that if the * encoding of the image isn't ready yet, or the encoder is otherwise busy, * it will run the update again once the tryLoad is done at the end of the task. */ updateAnnotations(useSession = this.currentImage) { if ( this.isGpuInUse || !this.annotationsNeedUpdating || !this.currentImage ) { return; } const promptAnnotations = this.getPromptAnnotations(); this.annotationsNeedUpdating = false; this.points = []; this.labels = []; this.worldPoints = []; if (!promptAnnotations?.length || !useSession?.canvasPosition) { return; } for (const annotation of promptAnnotations) { const handle = annotation.data.handles.points[0]; const point = this.mapAnnotationPoint(handle, useSession.canvasPosition); this.points.push(...point); if ( annotation.metadata.toolName === ONNXSegmentationController.BoxPrompt ) { // 2 and 3 are the codes for the handles on a box prompt this.labels.push(2, 3); this.points.push( ...this.mapAnnotationPoint( annotation.data.handles.points[3], useSession.canvasPosition ) ); } else { const label = annotation.metadata.toolName === this.excludeTool ? 0 : 1; if (label) { this.worldPoints.push(handle); } this.labels.push(label); } } this.runDecode(); } /** * Restores a stored image encoding from memory cache first, and from * the browser storage secondly. This is much faster than re-generating it * all the time. */ async restoreImageEncoding(session, imageId) { if (!this.sharedImageEncoding) { return; } if (!this.imageEncodings.has(imageId)) { await this.loadStorageImageEncoding(session, imageId); } const floatData = this.imageEncodings.get(imageId); if (floatData) { const key = (this.sharedImageEncoding.image_embeddings && 'image_embeddings') || 'embeddings'; this.sharedImageEncoding[key].cpuData.set(floatData); return this.sharedImageEncoding; } } /** * Loads the image encoding from browser storage. */ async loadStorageImageEncoding(session, imageId, index = null) { try { const root = await this.getDirectoryForImageId(session, imageId); const name = this.getFileNameForImageId(imageId, this.config.model); if (!root || !name) { return null; } const fileHandle = await findFileEntry(root, name); if (!fileHandle) { return null; } this.log(Loggers.Log, 'Loading from storage', index || imageId, name); const file = await fileHandle.getFile(); if (file) { const buffer = await getBuffer(file); this.imageEncodings.set(imageId, buffer); } } catch (e) { this.log(Loggers.Log, 'Unable to fetch file', imageId, e); } } /** * Stores the image encoding to both memory cache and browser storage. */ async storeImageEncoding(session, imageId, data) { if (!this.sharedImageEncoding) { this.sharedImageEncoding = data; } const storeData = (data.image_embeddings || data.embeddings)?.cpuData; if (!storeData) { console.log('Unable to store data', data); return; } const writeData = new Float32Array(storeData); this.imageEncodings.set(imageId, writeData); try { const root = await this.getDirectoryForImageId(session, imageId); const name = this.getFileNameForImageId(imageId, this.config.model); if (!root || !name) { return; } const fileHandle = await root.getFileHandle(name, { create: true }); const writable = await fileHandle.createWritable(); await writable.write(writeData); await writable.close(); // Note, this data is not considered for persistence as it is assumed multiple // series are being worked on. See the persistence model for adding ahead of // time caching. } catch (e) { this.log(Loggers.Log, 'Unable to write', imageId, e); } } /** * Given the mask created by the AI model, assigns the data to a new preview * instance of a labelmap and triggers the modified event so that the new * segmentation data is visible. Replaces existing segmentation on that * image. */ createLabelmap(mask, canvasPosition, _points, _labels) { const { canvas, viewport } = this; const preview = this.tool.addPreview(viewport.element); const { previewSegmentIndex, memo, segmentationId, segmentIndex, segmentationVoxelManager, } = preview; const previewVoxelManager = memo?.voxelManager; const { dimensions } = previewVoxelManager; const { data } = mask; const { origin, rightVector, downVector } = canvasPosition; const worldPointJ = vec3.create(); const worldPoint = vec3.create(); const imageData = viewport.getDefaultImageData(); // Assumes that the load to canvas size is bigger than the destination // size - if that isn't true, then this should super-sample the data for (let j = 0; j < canvas.height; j++) { vec3.scaleAndAdd(worldPointJ, origin, downVector, j); for (let i = 0; i < canvas.width; i++) { vec3.scaleAndAdd(worldPoint, worldPointJ, rightVector, i); const ijkPoint = imageData.worldToIndex(worldPoint).map(Math.round); if ( ijkPoint.findIndex((v, index) => v < 0 || v >= dimensions[index]) !== -1 ) { continue; } // 4 values - RGBA - per pixel const maskIndex = 4 * (i + j * this.maxWidth); const v = data[maskIndex]; const segmentValue = segmentationVoxelManager.getAtIJKPoint(ijkPoint); if (segmentValue !== 0 && segmentValue !== 255) { continue; } if (v > this.pCutoff) { previewVoxelManager.setAtIJKPoint(ijkPoint, previewSegmentIndex); } else { previewVoxelManager.setAtIJKPoint(ijkPoint, null); } } } if (this._autoSegmentMode) { this.tool.doneEditMemo(); } this.tool._previewData.isDrag = true; const voxelManager = previewVoxelManager.sourceVoxelManager || previewVoxelManager; if (this.islandFillOptions) { const islandRemoval = new IslandRemoval(this.islandFillOptions); if ( islandRemoval.initialize(viewport, voxelManager, { previewSegmentIndex, segmentIndex, points: this.worldPoints.map((point) => imageData.worldToIndex(point).map(Math.round) ), }) ) { islandRemoval.floodFillSegmentIsland(); islandRemoval.removeExternalIslands(); islandRemoval.removeInternalIslands(); } } triggerSegmentationDataModified(segmentationId); } /** * Runs the GPU decoder operation itself. */ async decode(points, labels, useSession = this.currentImage) { const { canvas, canvasMask, imageImageData, desiredImage, boxRadius } = this; const ctx = canvas.getContext('2d', { willReadFrequently: true }); ctx.clearRect(0, 0, canvas.width, canvas.height); canvas.width = imageImageData.width; canvas.height = imageImageData.height; canvasMask.width = imageImageData.width; canvasMask.height = imageImageData.height; if (!useSession || useSession.imageId !== desiredImage.imageId) { this.log( Loggers.Log, '***** Image not current, need to wait for current image' ); return; } // Comment this line out to draw just the overlay mask data ctx.putImageData(imageImageData, 0, 0); if (points.length) { // need to wait for encoder to be ready if (!useSession.imageEmbeddings) { await useSession.encoder; } // wait for encoder to deliver embeddings const emb = await useSession.imageEmbeddings; // the decoder const session = useSession.decoder; const feed = feedForSam(emb, points, labels); const res = await session.run(feed); for (let i = 0; i < points.length; i += 2) { const label = labels[i / 2]; ctx.fillStyle = label ? 'blue' : 'pink'; ctx.fillRect( points[i] - boxRadius, points[i + 1] - boxRadius, 2 * boxRadius, 2 * boxRadius ); } const mask = res.masks; this.maskImageData = mask.toImageData(); this.createLabelmap( this.maskImageData, useSession.canvasPosition, points, labels ); ctx.globalAlpha = 0.3; const { data } = this.maskImageData; const counts = []; for (let i = 0; i < data.length; i += 4) { const v = data[i]; if (v > 0) { if (v < 255) { data[i] = 0; if (v > 192) { data[i + 1] = 255; } else { data[i + 2] = v + 64; } } counts[v] = 1 + (counts[v] || 0); } } const bitmap = await createImageBitmap(this.maskImageData); ctx.drawImage(bitmap, 0, 0); const ctxMask = canvasMask.getContext('2d'); ctxMask.globalAlpha = 0.9; ctxMask.drawImage(bitmap, 0, 0); } } /* * fetch and cache the ONNX model at the given url/name. */ async fetchAndCacheModel(url, name) { try { const cache = await caches.open('onnx'); let cachedResponse = await cache.match(url); if (cachedResponse == undefined) { // Trigger event when model component starts loading from network triggerEvent(eventTarget, aiEvents.MODEL_COMPONENT_LOADED, { name, url, status: 'loading', source: 'network', }); await cache.add(url); cachedResponse = await cache.match(url); this.log(Loggers.Log, `${name} (network)`); } else { // Trigger event when model component is loaded from cache triggerEvent(eventTarget, aiEvents.MODEL_COMPONENT_LOADED, { name, url, status: 'loaded', source: 'cache', }); this.log(Loggers.Log, `${name} (cached)`); } const data = await cachedResponse.arrayBuffer(); return data; } catch (error) { this.log(Loggers.Log, `${name} (network)`); // Trigger event when model component has an error triggerEvent(eventTarget, aiEvents.MODEL_COMPONENT_LOADED, { name, url, status: 'error', error, }); return await fetch(url).then((response) => response.arrayBuffer()); } } /* * load model cache data and creates an instance. This calls fetchAndCacheModle * once for the decoder and encoder, and then instantiates an instance. */ async loadModels(models, imageSession = this.currentImage) { const cache = await caches.open('onnx'); let missing = 0; const urls = []; // Get the list of urls to download // eslint-disable-next-line @typescript-eslint/no-explicit-any for (const model of Object.values(models) as ModelType[]) { const cachedResponse = await cache.match(model.url); if (cachedResponse === undefined) { missing += model.size; } urls.push(model.url); } // Trigger event for model loading started triggerEvent(eventTarget, aiEvents.MODEL_LOADING_STARTED, { modelConfig: this.config.model, totalSize: missing, urls, }); if (missing > 0) { this.log( Loggers.Log, `downloading ${missing} MB from network ... it might take a while` ); } else { this.log(Loggers.Log, 'loading...'); } const start = performance.now(); for (const model of Object.values(models) as ModelType[]) { const opt = { executionProviders: [this.config.provider], enableMemPattern: false, enableCpuMemArena: false, extra: { session: { disable_prepacking: '1', use_device_allocator_for_initializers: '1', use_ort_model_bytes_directly: '1', use_ort_model_bytes_for_initializers: '1', }, }, interOpNumThreads: 4, intraOpNumThreads: 2, }; const model_bytes = await this.fetchAndCacheModel(model.url, model.name); const extra_opt = model.opt || {}; const sessionOptions = { ...opt, ...extra_opt }; this.config[model.key] = model; imageSession[model.key] = await ort.InferenceSession.create( model_bytes, sessionOptions ); } const stop = performance.now(); const loadTime = stop - start; // Trigger event for model loading completed triggerEvent(eventTarget, aiEvents.MODEL_LOADING_COMPLETED, { modelConfig: this.config.model, loadTimeMs: loadTime, urls, }); this.log(Loggers.Log, `ready, ${loadTime.toFixed(1)}ms`, urls.join(', ')); } /** * Gets the storage directory for storing the given image id */ async getDirectoryForImageId(session, imageId) { if ( imageId.indexOf('/studies/') === -1 || imageId.indexOf('/instances/') === -1 ) { imageId = session.sampleImageId; if ( !imageId || imageId.indexOf('/studies/') === -1 || imageId.indexOf('/instances/') === -1 ) { return null; } } const studySeriesUids = imageId .split('/studies/')[1] .split('/instances/')[0] .split('/'); const [studyUID, _series, seriesUID] = studySeriesUids; const root = await window.navigator.storage.getDirectory(); const modelRoot = await getOrCreateDir(root, this.config.model); const studyRoot = await getOrCreateDir(modelRoot, studyUID); const seriesRoot = await getOrCreateDir(studyRoot, seriesUID); return seriesRoot; } /** * Gets the storage file name for the given imageId */ getFileNameForImageId(imageId, extension) { if (imageId.startsWith('volumeId:')) { const sliceIndex = imageId.indexOf('sliceIndex='); const focalPoint = imageId.indexOf('&focalPoint='); const name = imageId .substring(sliceIndex, focalPoint) .replace('&', '.') .replace('sliceIndex=', 'volume.'); return name + extension; } const instancesLocation = imageId.indexOf('/instances/'); if (instancesLocation != -1) { const sopLocation = instancesLocation + 11; const nextSlash = imageId.indexOf('/', sopLocation); return imageId.substring(sopLocation, nextSlash) + extension; } } /** * Creates a configuration for which encoder/decoder to run. TODO - move * this into the constructor. */ getConfig(modelName = 'sam_b') { if (this.config) { return this.config; } const query = window.location.search.substring(1); const config = { model: modelName, provider: 'webgpu', device: 'gpu', threads: 4, local: null, isSlimSam: false, }; const vars = query.split('&'); for (let i = 0; i < vars.length; i++) { const pair = vars[i].split('='); if (pair[0] in config) { config[pair[0]] = decodeURIComponent(pair[1]); } } config.threads = parseInt(String(config.threads)); config.local = parseInt(config.local); ort.env.wasm.wasmPaths = 'ort/'; ort.env.wasm.numThreads = config.threads; ort.env.wasm.proxy = config.provider == 'wasm'; this.config = config; return config; } } /** Gets or creates a storage directory */ async function getOrCreateDir(dir, name) { return ( (await findFileEntry(dir, name)) || dir.getDirectoryHandle(name, { create: true }) ); } /** Finds a file entry in the given directory. */ async function findFileEntry(dir, name) { for await (const [key, value] of dir) { if (key === name) { return value; } } } |