From 6a3e9da705ed10d1508410806fb9bda11ee22398 Mon Sep 17 00:00:00 2001 From: Joao Vilaca Date: Thu, 3 Dec 2026 14:19:25 +0100 Subject: [PATCH 1/4] feat(ui): wire OME annotator predictions, navigation, prefetching, and tools --- .../api/use-submit-annotations.test.tsx | 52 ++++++++++- .../api/use-submit-annotations.ts | 17 ++-- .../media-preview/media-preview.component.tsx | 3 +- .../use-next-prediction-prefetch.hook.ts | 3 +- .../api/use-media-predictions.test.ts | 63 ++++++++++++++ .../annotator/api/use-media-predictions.ts | 87 +++++++------------ .../use-prefetch-media-item.hook.test.tsx | 67 ++++++++++++-- .../hooks/use-prefetch-media-item.hook.ts | 16 +++- .../src/modules/annotator/shell/utils.test.ts | 28 +++++- .../ui/src/modules/annotator/shell/utils.ts | 13 ++- .../use-available-tools.test.ts | 55 ++++++++++++ .../annotator-tools/use-available-tools.ts | 7 ++ 12 files changed, 336 insertions(+), 75 deletions(-) create mode 100644 application/ui/src/modules/annotator/api/use-media-predictions.test.ts create mode 100644 application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts diff --git a/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.test.tsx b/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.test.tsx index e562ca0d624..dacb761c974 100644 --- a/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.test.tsx +++ b/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.test.tsx @@ -8,7 +8,13 @@ import { InfiniteData, QueryClient } from '@tanstack/react-query'; import { act, waitFor } from '@testing-library/react'; import { getMockedShape } from 'mocks/mock-annotation'; import { getMockedAnnotationLabelRef, getMockedLabel } from 'mocks/mock-labels'; -import { getMockedMediaImage, getMockedVideo, getMockedVideoFrame } from 'mocks/mock-media'; +import { + getMockedMediaImage, + getMockedOmeImage, + getMockedOmePlane, + getMockedVideo, + getMockedVideoFrame, +} from 'mocks/mock-media'; import { getMockedProject } from 'mocks/mock-project'; import { delay, HttpResponse } from 'msw'; @@ -184,6 +190,50 @@ describe('dataset media cache after submitting', () => { expect(getCachedMedia(queryClient)).toEqual([video]); }); + + it('submits OME plane annotations with z/t params, refreshes the container count, and invalidates /planes', async () => { + const omeImage = getMockedOmeImage({ + id: 'ome-1', + annotation_status: { has_annotations: false, annotated_ome_planes: 0 }, + }); + const refreshedOmeImage = { + ...omeImage, + annotation_status: { has_annotations: true, annotated_ome_planes: 1 }, + }; + const queryClient = createQueryClientWithMedia([omeImage]); + const planesQueryKey = [ + 'get', + '/api/projects/{project_id}/dataset/media/{media_id}/planes', + { params: { path: { project_id: '123', media_id: omeImage.id } } }, + ] as const; + queryClient.setQueryData(planesQueryKey, { items: [], total: 0 }); + + let requestUrl = ''; + server.use( + http.post('/api/projects/{project_id}/dataset/media/{media_id}/annotations', ({ request }) => { + requestUrl = request.url; + + return HttpResponse.json({}); + }), + http.get('/api/projects/{project_id}/dataset/media/{media_id}', () => HttpResponse.json(refreshedOmeImage)) + ); + + const { result } = renderSubmitAnnotations({ + mediaItem: getMockedOmePlane({ id: omeImage.id, z_index: 4, t_index: 2 }), + mode: 'annotation', + labels: [], + queryClient, + }); + + await waitFor(() => expect(result.current).not.toBeNull()); + await act(() => result.current.submit('unassigned')); + + const params = new URL(requestUrl).searchParams; + expect(params.get('z')).toBe('4'); + expect(params.get('t')).toBe('2'); + expect(getCachedMedia(queryClient)).toEqual([refreshedOmeImage]); + expect(queryClient.getQueryState(planesQueryKey)?.isInvalidated).toBe(true); + }); }); describe('submit in prediction mode', () => { diff --git a/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.ts b/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.ts index 550d654ddc8..1c563bed4dd 100644 --- a/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.ts +++ b/application/ui/src/features/dataset/media-preview/api/use-submit-annotations.ts @@ -18,7 +18,7 @@ import { mapServerAnnotationsToLocal, } from '../../../../modules/annotator/annotation-mappers'; import { isEmptyLabel, isNonEmptyLabel, useProjectLabelsWithEmptyLabel } from '../../../../shared/labels'; -import { getMediaItemQueryParams, isVideoFrame } from '../../../../shared/media-item-utils'; +import { getMediaItemQueryParams, isOmePlane, isVideoFrame } from '../../../../shared/media-item-utils'; import type { Annotation } from '../../../../shared/types'; import { isNonEmptyArray } from '../../../../shared/util'; import { @@ -53,6 +53,11 @@ const useSaveAnnotationsMutation = (mediaItem: Media) => { '/api/projects/{project_id}/dataset/media/{media_id}/frames', { params: { path: { project_id: projectId, media_id: mediaItem.id } } }, ], + [ + 'get', + '/api/projects/{project_id}/dataset/media/{media_id}/planes', + { params: { path: { project_id: projectId, media_id: mediaItem.id } } }, + ], ], }, onSuccess: async () => { @@ -61,11 +66,11 @@ const useSaveAnnotationsMutation = (mediaItem: Media) => { // The dataset media listing backs the gallery and sidebar annotation-status badges. Instead of // invalidating it (which would refetch every page already scrolled through), patch the cached media. - if (isVideoFrame(mediaItem)) { - // Frames share their video's id. Whether this frame was annotated before is unknown, so the video's - // annotated frame count is fetched again. Awaited, so that saving stays pending (and the next save - // disabled) until then: refreshes cannot overlap and resolve out of order. A failed refresh does not - // fail the (successful) save: the count is only stale until the next listing. + if (isVideoFrame(mediaItem) || isOmePlane(mediaItem)) { + // Video frames and OME planes share their container's id. Whether this frame/plane was annotated before + // is unknown, so the container's annotated count is fetched again. Awaited, so that saving stays + // pending (and the next save disabled) until then: refreshes cannot overlap and resolve out of order. + // A failed refresh does not fail the (successful) save: the count is only stale until the next listing. await refreshCachedMedia(queryClient, projectId, mediaItem.id).catch(() => undefined); } else { markCachedMediaAsAnnotated(queryClient, projectId, mediaItem.id); diff --git a/application/ui/src/features/dataset/media-preview/media-preview.component.tsx b/application/ui/src/features/dataset/media-preview/media-preview.component.tsx index 5ea2084691b..327039f4b8a 100644 --- a/application/ui/src/features/dataset/media-preview/media-preview.component.tsx +++ b/application/ui/src/features/dataset/media-preview/media-preview.component.tsx @@ -27,7 +27,7 @@ import { useAnnotationsQuery } from '../../../modules/annotator/shell/api/use-an import { getInitialAnnotations, useAnnotatorMode } from '../../../modules/annotator/shell/utils'; import { ToolProvider } from '../../../modules/annotator/tool-provider.component'; import { SEGMENT_ANYTHING_ENCODING_QUERY_KEY_PREFIX } from '../../../modules/annotator/tools/segment-anything-tool/use-segment-anything.hook'; -import { getMediaItemPredictionRange } from '../../../shared/media-item-utils'; +import { getMediaItemPredictionPlaneRange, getMediaItemPredictionRange } from '../../../shared/media-item-utils'; import { useSelectDatasetItem } from '../gallery/hooks/use-select-dataset-item.hook'; import { AnnotatorContainer } from './annotator.component'; import { SIDEBAR_WIDTH } from './constants'; @@ -134,6 +134,7 @@ const MediaPreviewContent = ({ device: selectedDevice, confidenceThreshold, range: getMediaItemPredictionRange(mediaItem), + planeRange: getMediaItemPredictionPlaneRange(mediaItem), }); const isCurrentMediaReviewed = annotationsData?.user_reviewed ?? false; diff --git a/application/ui/src/features/dataset/media-preview/use-next-prediction-prefetch.hook.ts b/application/ui/src/features/dataset/media-preview/use-next-prediction-prefetch.hook.ts index 0c36ceaf958..705f0d1727b 100644 --- a/application/ui/src/features/dataset/media-preview/use-next-prediction-prefetch.hook.ts +++ b/application/ui/src/features/dataset/media-preview/use-next-prediction-prefetch.hook.ts @@ -7,7 +7,7 @@ import { useProjectIdentifier } from 'hooks/use-project-identifier.hook'; import { mediaPredictionsQueryOptions } from '../../../modules/annotator/api/use-media-predictions'; import { usePredictionSetup } from '../../../modules/annotator/predictions-setup-provider.component'; -import { getMediaItemPredictionRange } from '../../../shared/media-item-utils'; +import { getMediaItemPredictionPlaneRange, getMediaItemPredictionRange } from '../../../shared/media-item-utils'; export const useNextPredictionPrefetch = (nextMediaItem: Media) => { const projectId = useProjectIdentifier(); @@ -21,6 +21,7 @@ export const useNextPredictionPrefetch = (nextMediaItem: Media) => { device: selectedDevice, confidenceThreshold, range: getMediaItemPredictionRange(nextMediaItem), + planeRange: getMediaItemPredictionPlaneRange(nextMediaItem), }) ); }; diff --git a/application/ui/src/modules/annotator/api/use-media-predictions.test.ts b/application/ui/src/modules/annotator/api/use-media-predictions.test.ts new file mode 100644 index 00000000000..446df4b1142 --- /dev/null +++ b/application/ui/src/modules/annotator/api/use-media-predictions.test.ts @@ -0,0 +1,63 @@ +// Copyright (C) 2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 + +import type { QueryFunctionContext } from '@tanstack/react-query'; +import { HttpResponse } from 'msw'; + +import { http } from '../../../api/utils'; +import { server } from '../../../msw-node-setup'; +import { mediaPredictionsQueryOptions } from './use-media-predictions'; + +describe('mediaPredictionsQueryOptions', () => { + it('sends plane_range without range for OME prediction requests', async () => { + let receivedBody: unknown; + + server.use( + http.post('/api/projects/{project_id}/dataset/media:predict', async ({ request }) => { + receivedBody = await request.json(); + + return HttpResponse.json({ + predictions: [ + { + media: { id: 'ome-1', z_index: 3, t_index: 1 }, + prediction: [], + }, + ], + }); + }) + ); + + const options = mediaPredictionsQueryOptions({ + projectId: 'project-123', + selectedModel: { + modelId: 'model-1', + modelVariantId: 'variant-1', + name: 'Model 1 [FP16]', + optimalConfidenceThreshold: 0.5, + }, + mediaId: 'ome-1', + device: 'cpu', + confidenceThreshold: 0.5, + planeRange: { z: { start: 3, end: 3, stride: 1 }, t: { start: 1, end: 1, stride: 1 } }, + }); + + const result = await options.queryFn?.({ + queryKey: options.queryKey, + signal: new AbortController().signal, + } as QueryFunctionContext); + + expect(receivedBody).toEqual({ + model_id: 'model-1', + model_variant_id: 'variant-1', + device: 'cpu', + confidence_threshold: 0.5, + media: [ + { + media_id: 'ome-1', + plane_range: { z: { start: 3, end: 3, stride: 1 }, t: { start: 1, end: 1, stride: 1 } }, + }, + ], + }); + expect(result).toHaveLength(1); + }); +}); diff --git a/application/ui/src/modules/annotator/api/use-media-predictions.ts b/application/ui/src/modules/annotator/api/use-media-predictions.ts index cc9b6678f0c..880e9ed6241 100644 --- a/application/ui/src/modules/annotator/api/use-media-predictions.ts +++ b/application/ui/src/modules/annotator/api/use-media-predictions.ts @@ -2,12 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { fetchClient } from '@/api'; -import type { PredictionDTO, PredictionVideoRangePayload } from '@/api/types'; +import type { PredictionDTO, PredictionPlaneRangePayload, PredictionVideoRangePayload } from '@/api/types'; import { queryOptions, useIsFetching, useQuery } from '@tanstack/react-query'; import { useProjectIdentifier } from 'hooks/use-project-identifier.hook'; import { EMPTY_LABEL_ID } from '../../../shared/labels'; -import { getMediaItemPredictionRange } from '../../../shared/media-item-utils'; +import { getMediaItemPredictionPlaneRange, getMediaItemPredictionRange } from '../../../shared/media-item-utils'; import { getModelIdentifierPayload, SelectableModel } from '../../../shared/selectable-model'; import { usePredictionSetup } from '../predictions-setup-provider.component'; import { useSelectedMediaItem } from '../selected-media-item-provider.component'; @@ -18,6 +18,23 @@ import { useVideoPlayerContext } from '../video-player/video-player-provider.com // Prefix matching every prediction query of a project, so callers can cancel them all at once. export const getMediaPredictionsQueryKeyPrefix = (projectId: string) => [projectId, 'media-predictions']; +interface MediaPredictionsParams { + mediaId: string; + selectedModel: SelectableModel | undefined; + device: string; + confidenceThreshold: number | null; + range?: PredictionVideoRangePayload | null; + planeRange?: PredictionPlaneRangePayload | null; +} + +interface MediaPredictionsQueryOptionsParams extends MediaPredictionsParams { + projectId: string; +} + +interface UseMediaPredictionsParams extends MediaPredictionsParams { + enabled?: boolean; +} + export const mediaPredictionsQueryOptions = ({ projectId, selectedModel, @@ -25,14 +42,8 @@ export const mediaPredictionsQueryOptions = ({ device, confidenceThreshold, range = null, -}: { - projectId: string; - selectedModel: SelectableModel | undefined; - mediaId: string; - device: string; - confidenceThreshold: number | null; - range?: PredictionVideoRangePayload | null; -}) => + planeRange = null, +}: MediaPredictionsQueryOptionsParams) => queryOptions({ queryKey: [ ...getMediaPredictionsQueryKeyPrefix(projectId), @@ -41,6 +52,7 @@ export const mediaPredictionsQueryOptions = ({ selectedModel, confidenceThreshold, range, + planeRange, ], queryFn: async ({ signal }) => { if (selectedModel === undefined) return []; @@ -52,7 +64,11 @@ export const mediaPredictionsQueryOptions = ({ ...getModelIdentifierPayload(selectedModel), device, confidence_threshold: confidenceThreshold, - media: [{ media_id: mediaId, range }], + media: [ + planeRange !== null + ? { media_id: mediaId, plane_range: planeRange } + : { media_id: mediaId, range }, + ], }, }); @@ -81,56 +97,16 @@ export const mediaPredictionsQueryOptions = ({ enabled: selectedModel !== undefined, }); -export const useMediaPredictions = ({ - mediaId, - selectedModel, - range, - device, - confidenceThreshold, - enabled = true, -}: { - mediaId: string; - selectedModel: SelectableModel | undefined; - range?: PredictionVideoRangePayload | null; - device: string; - confidenceThreshold: number | null; - enabled?: boolean; -}) => { +export const useMediaPredictions = ({ enabled = true, ...params }: UseMediaPredictionsParams) => { const projectId = useProjectIdentifier(); - const options = mediaPredictionsQueryOptions({ - projectId, - selectedModel, - mediaId, - range, - device, - confidenceThreshold, - }); + const options = mediaPredictionsQueryOptions({ projectId, ...params }); return useQuery({ ...options, enabled: options.enabled && enabled }); }; -export const useIsFetchingMediaPredictions = ({ - mediaId, - selectedModel, - device, - confidenceThreshold, - range = null, -}: { - mediaId: string; - selectedModel: SelectableModel | undefined; - device: string; - confidenceThreshold: number | null; - range?: PredictionVideoRangePayload | null; -}) => { +export const useIsFetchingMediaPredictions = (params: MediaPredictionsParams) => { const projectId = useProjectIdentifier(); - const { queryKey } = mediaPredictionsQueryOptions({ - projectId, - selectedModel, - mediaId, - device, - confidenceThreshold, - range, - }); + const { queryKey } = mediaPredictionsQueryOptions({ projectId, ...params }); return useIsFetching({ queryKey, exact: true }) > 0; }; @@ -169,6 +145,7 @@ const useIsFetchingCurrentFramePredictions = (mediaId: string) => { device: selectedDevice, confidenceThreshold, range: getMediaItemPredictionRange(mediaItem), + planeRange: getMediaItemPredictionPlaneRange(mediaItem), }); }; diff --git a/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.test.tsx b/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.test.tsx index fe8ebebcc43..9e1b3fd0ac1 100644 --- a/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.test.tsx +++ b/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.test.tsx @@ -2,7 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { waitFor } from '@testing-library/react'; -import { getMockedMediaImage } from 'mocks/mock-media'; +import { getMockedMediaImage, getMockedOmeImage, getMockedOmePlane } from 'mocks/mock-media'; +import { getMockedOmeImageMetadata } from 'mocks/mock-ome'; import { HttpResponse } from 'msw'; import { renderHook } from 'test-utils/render'; @@ -14,11 +15,11 @@ const mediaItem = getMockedMediaImage({ id: 'media-2' }); describe('usePrefetchMediaItem', () => { const setupAnnotationsHandler = () => { - const requestedPaths: string[] = []; + const requestedUrls: string[] = []; server.use( http.get('/api/projects/{project_id}/dataset/media/{media_id}/annotations', ({ request }) => { - requestedPaths.push(new URL(request.url).pathname); + requestedUrls.push(request.url); return HttpResponse.json({ media_id: mediaItem.id, @@ -30,26 +31,76 @@ describe('usePrefetchMediaItem', () => { }) ); - return requestedPaths; + return requestedUrls; }; it('fetches the annotations of the media item ahead of time', async () => { - const requestedPaths = setupAnnotationsHandler(); + const requestedUrls = setupAnnotationsHandler(); renderHook(() => usePrefetchMediaItem(mediaItem)); await waitFor(() => { - expect(requestedPaths).toEqual([expect.stringContaining(mediaItem.id)]); + expect(requestedUrls).toEqual([expect.stringContaining(mediaItem.id)]); }); }); + it('prefetches OME metadata, channel view, and (z=0, t=0) annotations for an OME image container', async () => { + const requestedUrls = setupAnnotationsHandler(); + const omeRequests: string[] = []; + const omeImage = getMockedOmeImage({ id: 'ome-2' }); + + server.use( + http.get('/api/projects/{project_id}/dataset/media/{media_id}/ome', ({ request }) => { + omeRequests.push(new URL(request.url).pathname); + + return HttpResponse.json(getMockedOmeImageMetadata()); + }), + http.get('/api/projects/{project_id}/dataset/media/{media_id}/channel-view', ({ request }) => { + omeRequests.push(new URL(request.url).pathname); + + return HttpResponse.json({ settings: [], is_default: true }); + }) + ); + + renderHook(() => usePrefetchMediaItem(omeImage)); + + await waitFor(() => { + expect(omeRequests).toEqual( + expect.arrayContaining([ + expect.stringContaining('/ome-2/ome'), + expect.stringContaining('/ome-2/channel-view'), + ]) + ); + expect(requestedUrls).toHaveLength(1); + }); + + const annotationParams = new URL(requestedUrls[0]).searchParams; + expect(annotationParams.get('z')).toBe('0'); + expect(annotationParams.get('t')).toBe('0'); + }); + + it('prefetches plane-specific annotations for an OME plane', async () => { + const requestedUrls = setupAnnotationsHandler(); + const omePlane = getMockedOmePlane({ id: 'ome-3', z_index: 5, t_index: 2 }); + + renderHook(() => usePrefetchMediaItem(omePlane)); + + await waitFor(() => { + expect(requestedUrls).toHaveLength(1); + }); + + const annotationParams = new URL(requestedUrls[0]).searchParams; + expect(annotationParams.get('z')).toBe('5'); + expect(annotationParams.get('t')).toBe('2'); + }); + it('does not fetch anything when there is no media item to prefetch', async () => { - const requestedPaths = setupAnnotationsHandler(); + const requestedUrls = setupAnnotationsHandler(); renderHook(() => usePrefetchMediaItem(undefined)); await waitFor(() => { - expect(requestedPaths).toHaveLength(0); + expect(requestedUrls).toHaveLength(0); }); }); }); diff --git a/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.ts b/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.ts index 54f66602ef6..21c85f94bb6 100644 --- a/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.ts +++ b/application/ui/src/modules/annotator/hooks/use-prefetch-media-item.hook.ts @@ -7,6 +7,8 @@ import type { Media } from '@/api/types'; import { useQueryClient } from '@tanstack/react-query'; import { useProjectIdentifier } from 'hooks/use-project-identifier.hook'; +import { isOmeImage, isOmePlane } from '../../../shared/media-item-utils'; +import { omeChannelViewQueryOptions, omeImageInfoQueryOptions } from '../ome/api/use-ome-queries'; import { annotationsQueryOptions } from '../shell/api/use-annotations-query'; import { loadImageQueryOptions } from './use-load-image-query.hook'; @@ -20,7 +22,19 @@ export const usePrefetchMediaItem = (mediaItem: Media | undefined) => { return; } + if (isOmeImage(mediaItem)) { + void queryClient.prefetchQuery(omeImageInfoQueryOptions(projectId, mediaItem.id)); + void queryClient.prefetchQuery(omeChannelViewQueryOptions(projectId, mediaItem.id)); + void queryClient.prefetchQuery( + annotationsQueryOptions(projectId, { ...mediaItem, type: 'ome_plane', z_index: 0, t_index: 0 }) + ); + return; + } + void queryClient.prefetchQuery(annotationsQueryOptions(projectId, mediaItem)); - void queryClient.prefetchQuery(loadImageQueryOptions(projectId, mediaItem)); + + if (!isOmePlane(mediaItem)) { + void queryClient.prefetchQuery(loadImageQueryOptions(projectId, mediaItem)); + } }, [mediaItem, projectId, queryClient]); }; diff --git a/application/ui/src/modules/annotator/shell/utils.test.ts b/application/ui/src/modules/annotator/shell/utils.test.ts index 1e43f1a4615..fa8de8710f9 100644 --- a/application/ui/src/modules/annotator/shell/utils.test.ts +++ b/application/ui/src/modules/annotator/shell/utils.test.ts @@ -3,7 +3,12 @@ import type { AnnotationDTO } from '@/api/types'; import { act } from '@testing-library/react'; -import { getMockedMediaImage, getMockedVideoFrame, getMultipleMockedMediaImage } from 'mocks/mock-media'; +import { + getMockedMediaImage, + getMockedOmePlane, + getMockedVideoFrame, + getMultipleMockedMediaImage, +} from 'mocks/mock-media'; import { renderHook } from 'test-utils/render'; import { useVideoPlayerContext } from '../video-player/video-player-provider.component'; @@ -117,6 +122,27 @@ describe('getNextMediaItem', () => { expect(result).toEqual({ ...frame, frame_number: 6 }); }); }); + + describe('OME plane media items', () => { + it('advances Z slice by slice within the same time point', () => { + const plane = getMockedOmePlane({ id: 'ome-1', size_z: 3, size_t: 2, z_index: 1, t_index: 0 }); + + expect(getNextMediaItem(plane, [plane], 1)).toEqual({ ...plane, z_index: 2, t_index: 0 }); + }); + + it('wraps Z back to 0 and increments T after the last Z slice', () => { + const plane = getMockedOmePlane({ id: 'ome-1', size_z: 3, size_t: 2, z_index: 2, t_index: 0 }); + + expect(getNextMediaItem(plane, [plane], 1)).toEqual({ ...plane, z_index: 0, t_index: 1 }); + }); + + it('advances to the next media item after the final (Z, T) plane', () => { + const plane = getMockedOmePlane({ id: 'ome-1', size_z: 3, size_t: 2, z_index: 2, t_index: 1 }); + const nextImage = getMockedMediaImage({ id: 'image-1' }); + + expect(getNextMediaItem(plane, [plane, nextImage], 1)).toEqual(nextImage); + }); + }); }); describe('useNextMediaItem', () => { diff --git a/application/ui/src/modules/annotator/shell/utils.ts b/application/ui/src/modules/annotator/shell/utils.ts index 11a10496aef..1d35a3ee6b7 100644 --- a/application/ui/src/modules/annotator/shell/utils.ts +++ b/application/ui/src/modules/annotator/shell/utils.ts @@ -8,7 +8,7 @@ import { useProjectIdentifier } from 'hooks/use-project-identifier.hook'; import { range } from 'lodash-es'; import { useLocalStorage } from 'usehooks-ts'; -import { isVideoFrame } from '../../../shared/media-item-utils'; +import { isOmePlane, isVideoFrame } from '../../../shared/media-item-utils'; import type { AnnotatorMode } from '../annotator-mode'; import { usePrefetchMediaItem } from '../hooks/use-prefetch-media-item.hook'; import { useVideoPlayerContext } from '../video-player/video-player-provider.component'; @@ -39,6 +39,17 @@ export const getNextMediaItem = (currentMediaItem: Media, allMediaItems: Media[] } } + // Z-stacks are annotated slice by slice, then time point by time point. + if (isOmePlane(currentMediaItem)) { + if (currentMediaItem.z_index < currentMediaItem.size_z - 1) { + return { ...currentMediaItem, z_index: currentMediaItem.z_index + 1 }; + } + + if (currentMediaItem.t_index < currentMediaItem.size_t - 1) { + return { ...currentMediaItem, z_index: 0, t_index: currentMediaItem.t_index + 1 }; + } + } + const currentIndex = allMediaItems.findIndex(({ id }) => id === currentMediaItem.id); if (currentIndex < 0) { diff --git a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts new file mode 100644 index 00000000000..2331934c68b --- /dev/null +++ b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts @@ -0,0 +1,55 @@ +// Copyright (C) 2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 + +import { getMockedMediaImage, getMockedOmePlane } from 'mocks/mock-media'; +import { renderHook } from 'test-utils/render'; + +import { useProjectTask } from '../../../../hooks/use-project-task.hook'; +import { useSelectedMediaItem } from '../../selected-media-item-provider.component'; +import { useAvailableTools } from './use-available-tools'; + +rs.mock('../../../../hooks/use-project-task.hook', () => ({ + useProjectTask: rs.fn(() => 'instance_segmentation'), +})); + +rs.mock('../../selected-media-item-provider.component', () => ({ + useSelectedMediaItem: rs.fn(), +})); + +describe('useAvailableTools', () => { + beforeEach(() => { + rs.mocked(useProjectTask).mockReturnValue('instance_segmentation'); + }); + + it('keeps smart tools enabled for a standard image within canvas limits', () => { + rs.mocked(useSelectedMediaItem).mockReturnValue({ + mediaItem: getMockedMediaImage({ width: 1024, height: 768 }), + } as ReturnType); + + const { result } = renderHook(() => useAvailableTools()); + + expect(result.current.map(({ type }) => type)).toContain('sam'); + expect(result.current.map(({ type }) => type)).toContain('magnetic-lasso'); + expect(result.current.map(({ type }) => type)).toContain('ssim'); + }); + + it('disables pixel-based smart tools for an OME plane while keeping SAM and manual tools', () => { + rs.mocked(useSelectedMediaItem).mockReturnValue({ + mediaItem: getMockedOmePlane({ width: 1024, height: 768 }), + } as ReturnType); + + const { result } = renderHook(() => useAvailableTools()); + + expect(result.current.map(({ type }) => type)).toEqual(['selection', 'polygon', 'sam']); + }); + + it('disables all smart tools including SAM for an oversized OME plane', () => { + rs.mocked(useSelectedMediaItem).mockReturnValue({ + mediaItem: getMockedOmePlane({ width: 20000, height: 20000 }), + } as ReturnType); + + const { result } = renderHook(() => useAvailableTools()); + + expect(result.current.map(({ type }) => type)).toEqual(['selection', 'polygon']); + }); +}); diff --git a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts index 402cb93509d..13e18fdfbbe 100644 --- a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts +++ b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts @@ -16,6 +16,7 @@ import { BoundingBox, DetectionTool, Polygon, SegmentAnythingIcon, Selector } fr import { FEATURE_FLAGS } from '../../../../constants/feature-flags'; import { useProjectTask } from '../../../../hooks/use-project-task.hook'; import { HOTKEYS } from '../../../../shared/hotkeys-definition'; +import { isOme } from '../../../../shared/media-item-utils'; import { useSelectedMediaItem } from '../../selected-media-item-provider.component'; import { ToolConfig } from '../interface'; import { canRasteriseAtFullSize } from '../utils'; @@ -133,5 +134,11 @@ export const useAvailableTools = (): ToolConfig[] => { ); } + // OME planes are rendered server-side without client ImageData, so pixel-based smart tools are unavailable + // while server-backed SAM remains enabled. + if (isOme(mediaItem)) { + return taskTools.filter((tool) => tool.type !== 'magnetic-lasso' && tool.type !== 'ssim'); + } + return taskTools; }; From b510e65c0cfbefd9f35f22d55e718a454519b8d9 Mon Sep 17 00:00:00 2001 From: Joao Vilaca Date: Thu, 3 Dec 2026 15:37:58 +0100 Subject: [PATCH 2/4] Enable SSIM for OME images --- .../annotator/ome/api/use-ome-queries.ts | 6 +-- .../annotator/ome/use-ome-render-url.hook.ts | 15 +++--- .../use-available-tools.test.ts | 10 ++-- .../annotator-tools/use-available-tools.ts | 14 +++--- .../tools/ssim-tool/ssim-tool.component.tsx | 29 +++++++++-- .../tools/ssim-tool/use-ssim.hook.test.ts | 37 ++++++++++++++ .../tools/ssim-tool/use-ssim.hook.ts | 7 +-- .../annotator/tools/ssim-tool/utils.test.ts | 31 ++++++++++++ .../annotator/tools/ssim-tool/utils.ts | 50 ++++++++++++++++--- 9 files changed, 164 insertions(+), 35 deletions(-) diff --git a/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts b/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts index 7c14bb2b764..d9c4be3459b 100644 --- a/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts +++ b/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts @@ -27,10 +27,10 @@ export const omeChannelViewQueryOptions = (projectId: string, mediaId: string) = { staleTime: Infinity } ); -export const useOmeChannelView = (mediaId: string) => { +export const useOmeChannelView = (mediaId: string, enabled = true) => { const projectId = useProjectIdentifier(); - const infoQuery = useQuery(omeImageInfoQueryOptions(projectId, mediaId)); - const channelViewQuery = useQuery(omeChannelViewQueryOptions(projectId, mediaId)); + const infoQuery = useQuery({ ...omeImageInfoQueryOptions(projectId, mediaId), enabled }); + const channelViewQuery = useQuery({ ...omeChannelViewQueryOptions(projectId, mediaId), enabled }); const omeInfo = infoQuery.data; const savedSettings = diff --git a/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts b/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts index cd584db6d21..1739ed568bf 100644 --- a/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts +++ b/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts @@ -1,24 +1,25 @@ // Copyright (C) 2026 Intel Corporation // SPDX-License-Identifier: Apache-2.0 -import type { MediaOmeImage, MediaOmePlane } from '@/api/types'; +import type { Media } from '@/api/types'; import { useProjectIdentifier } from 'hooks/use-project-identifier.hook'; -import { isOmePlane } from '../../../shared/media-item-utils'; +import { isOme, isOmePlane } from '../../../shared/media-item-utils'; import { getOmeRenderUrl } from '../../../shared/media-url.utils'; import { useOmeChannelView } from './api/use-ome-queries'; import { isFloatOmePixelType } from './ome-metadata.utils'; import { selectOmeRenderTarget } from './ome-render.utils'; -export const useOmeRenderUrl = (mediaItem: MediaOmeImage | MediaOmePlane) => { +export const useOmeRenderUrl = (mediaItem: Media) => { const projectId = useProjectIdentifier(); - const { omeInfo, savedSettings, isPending, isError } = useOmeChannelView(mediaItem.id); + const isOmeMedia = isOme(mediaItem); + const { omeInfo, savedSettings, isPending, isError } = useOmeChannelView(mediaItem.id, isOmeMedia); - if (omeInfo === undefined || savedSettings === undefined) { + if (!isOmeMedia || omeInfo === undefined || savedSettings === undefined) { return { renderUrl: null, - isLoadingMetadata: isPending, - hasMetadataError: isError, + isLoadingMetadata: isOmeMedia && isPending, + hasMetadataError: isOmeMedia && isError, }; } diff --git a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts index 2331934c68b..da4981b4307 100644 --- a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts +++ b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.test.ts @@ -33,19 +33,19 @@ describe('useAvailableTools', () => { expect(result.current.map(({ type }) => type)).toContain('ssim'); }); - it('disables pixel-based smart tools for an OME plane while keeping SAM and manual tools', () => { + it('disables magnetic lasso for an OME plane (even pyramidal slides) while keeping SAM, SSIM, and manual tools', () => { rs.mocked(useSelectedMediaItem).mockReturnValue({ - mediaItem: getMockedOmePlane({ width: 1024, height: 768 }), + mediaItem: getMockedOmePlane({ width: 20000, height: 20000 }), } as ReturnType); const { result } = renderHook(() => useAvailableTools()); - expect(result.current.map(({ type }) => type)).toEqual(['selection', 'polygon', 'sam']); + expect(result.current.map(({ type }) => type)).toEqual(['selection', 'polygon', 'sam', 'ssim']); }); - it('disables all smart tools including SAM for an oversized OME plane', () => { + it('disables all smart tools for an oversized standard image', () => { rs.mocked(useSelectedMediaItem).mockReturnValue({ - mediaItem: getMockedOmePlane({ width: 20000, height: 20000 }), + mediaItem: getMockedMediaImage({ width: 20000, height: 20000 }), } as ReturnType); const { result } = renderHook(() => useAvailableTools()); diff --git a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts index 13e18fdfbbe..6c9eb8894b9 100644 --- a/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts +++ b/application/ui/src/modules/annotator/tools/annotator-tools/use-available-tools.ts @@ -127,18 +127,18 @@ export const useAvailableTools = (): ToolConfig[] => { const taskTools = useTaskTools(); const { mediaItem } = useSelectedMediaItem(); - // Disable smart tools (SAM, magnetic lasso, SSIM) for oversized media. + // OME planes are rendered server-side at a safe pyramid level without full-resolution client ImageData, + // so Magnetic Lasso is unavailable while server-backed SAM and render-backed SSIM work at any slide size. + if (isOme(mediaItem)) { + return taskTools.filter((tool) => tool.type !== 'magnetic-lasso'); + } + + // Disable smart tools (SAM, magnetic lasso, SSIM) for oversized standard media. if (!canRasteriseAtFullSize(mediaItem.width, mediaItem.height)) { return taskTools.filter( (tool) => tool.type !== 'sam' && tool.type !== 'magnetic-lasso' && tool.type !== 'ssim' ); } - // OME planes are rendered server-side without client ImageData, so pixel-based smart tools are unavailable - // while server-backed SAM remains enabled. - if (isOme(mediaItem)) { - return taskTools.filter((tool) => tool.type !== 'magnetic-lasso' && tool.type !== 'ssim'); - } - return taskTools; }; diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx b/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx index ac2c434be3d..d309c73eccb 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx +++ b/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx @@ -3,26 +3,48 @@ import { useEffect } from 'react'; +import type { Media } from '@/api/types'; import { toast } from '@/components/toast/toast.component'; import { useZoom } from '@/components/zoom/zoom.provider'; import { useTranslation } from '@/i18n'; +import { skipToken, useQuery } from '@tanstack/react-query'; +import { isOme } from '../../../../shared/media-item-utils'; import { useAnnotations } from '../../annotation-document-provider.component'; import { getFormattedPoints } from '../../annotations/utils'; import { useAnnotatorLabels } from '../../annotator-labels-provider.component'; +import { useOmeRenderUrl } from '../../ome/use-ome-render-url.hook'; import { useSelectedMediaItem } from '../../selected-media-item-provider.component'; import { Rectangle } from '../../shapes/rectangle.component'; import { DEFAULT_ANNOTATION_STYLES } from '../../utils'; import { DrawingBox } from '../drawing-box-tool/drawing-box.component'; import { ToolLoading } from '../tool-loading.component'; +import { loadImageData } from '../utils'; import { useSSIMState } from './ssim-state-provider.component'; import classes from './ssim-tool.module.scss'; +// OME planes skip full-resolution client rasterization; load the active `/render` composite on demand for SSIM. +const useSSIMImageData = (mediaItem: Media, fallbackImage: ImageData): ImageData | undefined => { + const isOmeMedia = isOme(mediaItem); + const { renderUrl } = useOmeRenderUrl(mediaItem); + const { data } = useQuery({ + queryKey: ['omeRenderImageData', renderUrl], + queryFn: isOmeMedia && renderUrl !== null ? ({ signal }) => loadImageData(renderUrl, signal) : skipToken, + staleTime: Infinity, + // Drop the RGBA buffer as soon as the user switches planes/channels or leaves SSIM. + gcTime: 0, + retry: 0, + }); + + return isOmeMedia ? data : fallbackImage; +}; + export const SSIMTool = () => { const { t } = useTranslation(); const { scale: zoom } = useZoom(); const { roi, image, mediaItem } = useSelectedMediaItem(); + const imageData = useSSIMImageData(mediaItem, image); const { annotations } = useAnnotations(); const { selectedLabel } = useAnnotatorLabels(); const { runSSIM, toolState, isProcessing, isLoading, isError, error, autoMergeDuplicates } = useSSIMState(); @@ -95,16 +117,17 @@ export const SSIMTool = () => { zoom={zoom} selectedLabel={selectedLabel} // A second run would overwrite the in-flight one's results before they are added. - isDisabled={isProcessing} + isDisabled={isProcessing || imageData === undefined} onComplete={(shapes) => { const [template] = shapes; - if (template === undefined) { + if (template === undefined || imageData === undefined) { return []; } runSSIM({ - imageData: image, + imageData, + imageBounds: roi, template, existingAnnotations: annotations.map((annotation) => annotation.shape), autoMergeDuplicates, diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts index f35ade04408..bb3d883d86d 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts @@ -319,4 +319,41 @@ describe('useSSIM', () => { expect(result.current.toolState.shapes).toEqual([]); }); + + it('maps downsampled render coordinates back to media bounds', async () => { + const executeSSIM = rs + .fn() + .mockResolvedValue([ + { shape: { x: 60, y: 40, width: 10, height: 10, shapeType: 'rect' }, confidence: 0.95 }, + ]); + mockWorker(executeSSIM); + + const { result } = renderHook(() => useSSIM('rectangle')); + + await waitFor(() => expect(result.current.worker).toBeDefined()); + + const mediaTemplate = { type: 'rectangle' as const, x: 20, y: 20, width: 20, height: 20 }; + + act(() => { + result.current.runSSIM({ + imageData: { width: 100, height: 100 } as ImageData, + imageBounds: { x: 0, y: 0, width: 200, height: 200 }, + template: mediaTemplate, + existingAnnotations: [], + autoMergeDuplicates: true, + }); + }); + + await waitFor(() => expect(result.current.toolState.shapes).toHaveLength(2)); + + expect(executeSSIM).toHaveBeenCalledWith( + expect.objectContaining({ + template: { x: 10, y: 10, width: 10, height: 10, shapeType: 'rect' }, + }) + ); + expect(result.current.toolState.shapes).toEqual([ + mediaTemplate, + { type: 'rectangle', x: 120, y: 80, width: 20, height: 20 }, + ]); + }); }); diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts index 2a50383dcd5..af6fbed334b 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts @@ -106,10 +106,11 @@ export const useSSIM = (shapeType: SSIMShapeType, enabled = true) => { return; } - const { imageData, existingAnnotations, autoMergeDuplicates, template } = props; - const ssimMatches = convertToolMatchesToGetiMatches(matches); + const { imageData, imageBounds, existingAnnotations, autoMergeDuplicates, template } = props; + const bounds = imageBounds ?? roiFromImage(imageData); + const ssimMatches = convertToolMatchesToGetiMatches(matches, imageData, bounds); const existingRects = autoMergeDuplicates ? getExistingRects(existingAnnotations) : []; - const filteredMatches = filterSSIMResults(roiFromImage(imageData), ssimMatches, template, existingRects); + const filteredMatches = filterSSIMResults(bounds, ssimMatches, template, existingRects); setToolState((currentState) => { const threshold = keepNumberOfItems diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts b/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts index 56f47925dab..762993b7d6f 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts @@ -59,6 +59,27 @@ describe('SSIM utils', () => { shapeType: 'rect', }); }); + + it('scales template and existing annotations into imageData space when rendered at a lower resolution', () => { + const imageData = { width: 2000, height: 1500 } as ImageData; + + expect( + toToolRunSSIMProps({ + imageData, + imageBounds: { x: 0, y: 0, width: 4000, height: 3000 }, + template: rect(400, 300, 200, 150), + existingAnnotations: [rect(1000, 600, 100, 100)], + autoMergeDuplicates: true, + }) + ).toEqual({ + imageData, + roi: { x: 0, y: 0, width: 2000, height: 1500 }, + template: { x: 200, y: 150, width: 100, height: 75, shapeType: 'rect' }, + existingAnnotations: [{ x: 500, y: 300, width: 50, height: 50, shapeType: 'rect' }], + autoMergeDuplicates: true, + shapeType: 'rect', + }); + }); }); describe('convertToolMatchesToGetiMatches', () => { @@ -69,6 +90,16 @@ describe('SSIM utils', () => { ]) ).toEqual([match(rect(1, 2, 3, 4), 0.8)]); }); + + it('scales matches back to media coordinates when source and target dimensions differ', () => { + expect( + convertToolMatchesToGetiMatches( + [{ shape: { x: 600, y: 450, width: 100, height: 75, shapeType: 'rect' }, confidence: 0.9 }], + { width: 2000, height: 1500 }, + { width: 4000, height: 3000 } + ) + ).toEqual([match(rect(1200, 900, 200, 150), 0.9)]); + }); }); describe('filterSSIMResults', () => { diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts b/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts index 060e77eb010..c3e7b33a7a7 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts @@ -19,10 +19,33 @@ export type SSIMMatch = Omit & { export type SSIMShapeType = Extract; export type RunSSIMProps = Omit & { + imageBounds?: RegionOfInterest; template: Rect; existingAnnotations: Shape[]; }; +type Dimensions = { + width: number; + height: number; +}; + +const scaleRect = (rect: Rect, from: Dimensions, to: Dimensions): Rect => { + if (from.width === to.width && from.height === to.height) { + return rect; + } + + const scaleX = from.width > 0 ? to.width / from.width : 1; + const scaleY = from.height > 0 ? to.height / from.height : 1; + + return { + ...rect, + x: rect.x * scaleX, + y: rect.y * scaleY, + width: rect.width * scaleX, + height: rect.height * scaleY, + }; +}; + const toToolRect = (rect: Rect): ToolRunSSIMProps['template'] => { const { x, y, width, height } = rect; @@ -41,25 +64,38 @@ export const getExistingRects = (shapes: Shape[]): Rect[] => { export const toToolRunSSIMProps = ({ imageData, + imageBounds, template, existingAnnotations, autoMergeDuplicates, }: RunSSIMProps): ToolRunSSIMProps => { + const bounds = imageBounds ?? roiFromImage(imageData); + return { imageData, roi: roiFromImage(imageData), - template: toToolRect(template), - existingAnnotations: getExistingRects(existingAnnotations).map(toToolRect), + template: toToolRect(scaleRect(template, bounds, imageData)), + existingAnnotations: getExistingRects(existingAnnotations).map((rect) => + toToolRect(scaleRect(rect, bounds, imageData)) + ), autoMergeDuplicates, shapeType: 'rect', }; }; -export const convertToolMatchesToGetiMatches = (matches: ToolSSIMMatch[]): SSIMMatch[] => { - return matches.map((match) => ({ - ...match, - shape: convertToolShapeToGetiShape(match.shape), - })); +export const convertToolMatchesToGetiMatches = ( + matches: ToolSSIMMatch[], + from?: Dimensions, + to?: Dimensions +): SSIMMatch[] => { + return matches.map((match) => { + const shape = convertToolShapeToGetiShape(match.shape); + + return { + ...match, + shape: from && to ? scaleRect(shape, from, to) : shape, + }; + }); }; export const filterSSIMResults = ( From 9b859d3c46de8702cae0a9ad049eb06329d719f0 Mon Sep 17 00:00:00 2001 From: Joao Vilaca Date: Thu, 3 Dec 2026 16:03:18 +0100 Subject: [PATCH 3/4] Fix SSIM on very small bounding boxes --- .../annotator/tools/ssim-tool/utils.test.ts | 15 +++++++++ .../annotator/tools/ssim-tool/utils.ts | 33 +++++++++++++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts b/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts index 762993b7d6f..6925ecb26ce 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts @@ -80,6 +80,21 @@ describe('SSIM utils', () => { shapeType: 'rect', }); }); + + it('narrows the search ROI around small templates so they stay valid after SSIM downscaling', () => { + const imageData = { width: 2048, height: 2048 } as ImageData; + + const props = toToolRunSSIMProps({ + imageData, + imageBounds: { x: 0, y: 0, width: 2048, height: 2048 }, + template: rect(500, 600, 8, 8), + existingAnnotations: [], + autoMergeDuplicates: true, + }); + + expect(props.roi).toEqual({ x: 254, y: 354, width: 500, height: 500 }); + expect(props.template).toEqual({ x: 246, y: 246, width: 8, height: 8, shapeType: 'rect' }); + }); }); describe('convertToolMatchesToGetiMatches', () => { diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts b/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts index c3e7b33a7a7..e4a41b6eb9f 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts @@ -3,6 +3,7 @@ import type { RunSSIMProps as ToolRunSSIMProps, SSIMMatch as ToolSSIMMatch } from '@geti-ui/smart-tools'; import { clampBox, roiFromImage } from '@geti-ui/smart-tools/utils'; +import { clamp } from 'lodash-es'; import type { Rect, RegionOfInterest, Shape } from '../../../../shared/types'; import { convertToolShapeToGetiShape, getBoundingRectFromShape, intersectionOverUnion } from '../utils'; @@ -11,6 +12,10 @@ import { convertToolShapeToGetiShape, getBoundingRectFromShape, intersectionOver export const MAX_NUMBER_ITEMS = 100; // Scores are min-max normalised per run, so this is relative to the template's own score (1.0). export const DEFAULT_CONFIDENCE_THRESHOLD = 0.9; +// `@geti-ui/smart-tools` resizes the SSIM search ROI to 250×250. Templates narrower than 1px after +// downscaling crash OpenCV `matchTemplate`; keep them at least 4px wide/tall by narrowing the search ROI. +const SSIM_SCALE_PX = 250; +const MIN_SSIM_TEMPLATE_PX = 4; export type SSIMMatch = Omit & { shape: Rect; @@ -62,6 +67,21 @@ export const getExistingRects = (shapes: Shape[]): Rect[] => { return shapes.map(getBoundingRectFromShape).filter((shape): shape is Rect => shape !== null); }; +const getAxisRoi = (start: number, length: number, limit: number): [offset: number, size: number] => { + if (limit <= 0 || length <= 0 || (length * SSIM_SCALE_PX) / limit >= MIN_SSIM_TEMPLATE_PX) { + return [0, limit]; + } + + const minSize = Math.max(1, Math.ceil(start + length) - Math.floor(start)); + const targetSize = Math.floor((length * SSIM_SCALE_PX) / MIN_SSIM_TEMPLATE_PX); + const size = Math.min(limit, Math.max(minSize, targetSize)); + const minOffset = Math.max(0, Math.ceil(start + length) - size); + const maxOffset = Math.min(Math.floor(start), limit - size); + const offset = clamp(Math.round(start + length / 2 - size / 2), minOffset, maxOffset); + + return [offset, size]; +}; + export const toToolRunSSIMProps = ({ imageData, imageBounds, @@ -70,11 +90,20 @@ export const toToolRunSSIMProps = ({ autoMergeDuplicates, }: RunSSIMProps): ToolRunSSIMProps => { const bounds = imageBounds ?? roiFromImage(imageData); + const scaledTemplate = scaleRect(template, bounds, imageData); + const [roiX, roiWidth] = getAxisRoi(scaledTemplate.x, scaledTemplate.width, imageData.width); + const [roiY, roiHeight] = getAxisRoi(scaledTemplate.y, scaledTemplate.height, imageData.height); + const roi = { x: roiX, y: roiY, width: roiWidth, height: roiHeight }; + const roiTemplate: Rect = { + ...scaledTemplate, + x: scaledTemplate.x - roi.x, + y: scaledTemplate.y - roi.y, + }; return { imageData, - roi: roiFromImage(imageData), - template: toToolRect(scaleRect(template, bounds, imageData)), + roi, + template: toToolRect(roiTemplate), existingAnnotations: getExistingRects(existingAnnotations).map((rect) => toToolRect(scaleRect(rect, bounds, imageData)) ), From 1dad9b1962992dd6ac495cb4b5f994fb6d4657e9 Mon Sep 17 00:00:00 2001 From: Joao Vilaca Date: Thu, 3 Dec 2026 16:31:35 +0100 Subject: [PATCH 4/4] Minor refactor; Add more tests --- .../annotator/ome/api/use-ome-queries.ts | 6 +-- .../annotator/ome/use-ome-render-url.hook.ts | 15 +++--- .../tools/ssim-tool/ssim-tool.component.tsx | 46 ++++++++-------- .../tools/ssim-tool/use-ssim.hook.test.ts | 5 +- .../tools/ssim-tool/use-ssim.hook.ts | 8 ++- .../annotator/tools/ssim-tool/utils.test.ts | 53 ++++++++++++++++--- .../annotator/tools/ssim-tool/utils.ts | 38 +++++++------ 7 files changed, 106 insertions(+), 65 deletions(-) diff --git a/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts b/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts index d9c4be3459b..7c14bb2b764 100644 --- a/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts +++ b/application/ui/src/modules/annotator/ome/api/use-ome-queries.ts @@ -27,10 +27,10 @@ export const omeChannelViewQueryOptions = (projectId: string, mediaId: string) = { staleTime: Infinity } ); -export const useOmeChannelView = (mediaId: string, enabled = true) => { +export const useOmeChannelView = (mediaId: string) => { const projectId = useProjectIdentifier(); - const infoQuery = useQuery({ ...omeImageInfoQueryOptions(projectId, mediaId), enabled }); - const channelViewQuery = useQuery({ ...omeChannelViewQueryOptions(projectId, mediaId), enabled }); + const infoQuery = useQuery(omeImageInfoQueryOptions(projectId, mediaId)); + const channelViewQuery = useQuery(omeChannelViewQueryOptions(projectId, mediaId)); const omeInfo = infoQuery.data; const savedSettings = diff --git a/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts b/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts index 1739ed568bf..cd584db6d21 100644 --- a/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts +++ b/application/ui/src/modules/annotator/ome/use-ome-render-url.hook.ts @@ -1,25 +1,24 @@ // Copyright (C) 2026 Intel Corporation // SPDX-License-Identifier: Apache-2.0 -import type { Media } from '@/api/types'; +import type { MediaOmeImage, MediaOmePlane } from '@/api/types'; import { useProjectIdentifier } from 'hooks/use-project-identifier.hook'; -import { isOme, isOmePlane } from '../../../shared/media-item-utils'; +import { isOmePlane } from '../../../shared/media-item-utils'; import { getOmeRenderUrl } from '../../../shared/media-url.utils'; import { useOmeChannelView } from './api/use-ome-queries'; import { isFloatOmePixelType } from './ome-metadata.utils'; import { selectOmeRenderTarget } from './ome-render.utils'; -export const useOmeRenderUrl = (mediaItem: Media) => { +export const useOmeRenderUrl = (mediaItem: MediaOmeImage | MediaOmePlane) => { const projectId = useProjectIdentifier(); - const isOmeMedia = isOme(mediaItem); - const { omeInfo, savedSettings, isPending, isError } = useOmeChannelView(mediaItem.id, isOmeMedia); + const { omeInfo, savedSettings, isPending, isError } = useOmeChannelView(mediaItem.id); - if (!isOmeMedia || omeInfo === undefined || savedSettings === undefined) { + if (omeInfo === undefined || savedSettings === undefined) { return { renderUrl: null, - isLoadingMetadata: isOmeMedia && isPending, - hasMetadataError: isOmeMedia && isError, + isLoadingMetadata: isPending, + hasMetadataError: isError, }; } diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx b/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx index d309c73eccb..86f55fcf11a 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx +++ b/application/ui/src/modules/annotator/tools/ssim-tool/ssim-tool.component.tsx @@ -3,7 +3,7 @@ import { useEffect } from 'react'; -import type { Media } from '@/api/types'; +import type { MediaOmeImage, MediaOmePlane } from '@/api/types'; import { toast } from '@/components/toast/toast.component'; import { useZoom } from '@/components/zoom/zoom.provider'; import { useTranslation } from '@/i18n'; @@ -24,27 +24,10 @@ import { useSSIMState } from './ssim-state-provider.component'; import classes from './ssim-tool.module.scss'; -// OME planes skip full-resolution client rasterization; load the active `/render` composite on demand for SSIM. -const useSSIMImageData = (mediaItem: Media, fallbackImage: ImageData): ImageData | undefined => { - const isOmeMedia = isOme(mediaItem); - const { renderUrl } = useOmeRenderUrl(mediaItem); - const { data } = useQuery({ - queryKey: ['omeRenderImageData', renderUrl], - queryFn: isOmeMedia && renderUrl !== null ? ({ signal }) => loadImageData(renderUrl, signal) : skipToken, - staleTime: Infinity, - // Drop the RGBA buffer as soon as the user switches planes/channels or leaves SSIM. - gcTime: 0, - retry: 0, - }); - - return isOmeMedia ? data : fallbackImage; -}; - -export const SSIMTool = () => { +const SSIMToolContent = ({ imageData }: { imageData: ImageData | undefined }) => { const { t } = useTranslation(); const { scale: zoom } = useZoom(); - const { roi, image, mediaItem } = useSelectedMediaItem(); - const imageData = useSSIMImageData(mediaItem, image); + const { roi, mediaItem } = useSelectedMediaItem(); const { annotations } = useAnnotations(); const { selectedLabel } = useAnnotatorLabels(); const { runSSIM, toolState, isProcessing, isLoading, isError, error, autoMergeDuplicates } = useSSIMState(); @@ -127,7 +110,7 @@ export const SSIMTool = () => { runSSIM({ imageData, - imageBounds: roi, + roi, template, existingAnnotations: annotations.map((annotation) => annotation.shape), autoMergeDuplicates, @@ -139,3 +122,24 @@ export const SSIMTool = () => { ); }; + +// OME planes skip full-resolution client rasterization; load the active `/render` composite on demand for SSIM. +const OmeSSIMTool = ({ mediaItem }: { mediaItem: MediaOmeImage | MediaOmePlane }) => { + const { renderUrl } = useOmeRenderUrl(mediaItem); + const { data: imageData } = useQuery({ + queryKey: ['omeRenderImageData', renderUrl], + queryFn: renderUrl !== null ? ({ signal }) => loadImageData(renderUrl, signal) : skipToken, + staleTime: Infinity, + // Drop the RGBA buffer as soon as the user switches planes/channels or leaves SSIM. + gcTime: 0, + retry: 0, + }); + + return ; +}; + +export const SSIMTool = () => { + const { image, mediaItem } = useSelectedMediaItem(); + + return isOme(mediaItem) ? : ; +}; diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts index bb3d883d86d..8b96f53604f 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.test.ts @@ -24,7 +24,8 @@ class FakeWorker { const template = { type: 'rectangle' as const, x: 10, y: 10, width: 20, height: 20 }; const imageData = { width: 100, height: 100 } as ImageData; -const runProps = { imageData, template, existingAnnotations: [], autoMergeDuplicates: true }; +const roi = { x: 0, y: 0, width: 100, height: 100 }; +const runProps = { imageData, roi, template, existingAnnotations: [], autoMergeDuplicates: true }; const toolMatch = (x: number, y: number) => ({ shape: { x, y, width: 20, height: 20, shapeType: 'rect' as const }, @@ -337,7 +338,7 @@ describe('useSSIM', () => { act(() => { result.current.runSSIM({ imageData: { width: 100, height: 100 } as ImageData, - imageBounds: { x: 0, y: 0, width: 200, height: 200 }, + roi: { x: 0, y: 0, width: 200, height: 200 }, template: mediaTemplate, existingAnnotations: [], autoMergeDuplicates: true, diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts index af6fbed334b..8d0856de085 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/use-ssim.hook.ts @@ -4,7 +4,6 @@ import { useCallback, useMemo, useRef, useState } from 'react'; import { i18n } from '@/i18n'; -import { roiFromImage } from '@geti-ui/smart-tools/utils'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import type { Remote } from 'comlink'; import { clamp } from 'lodash-es'; @@ -106,11 +105,10 @@ export const useSSIM = (shapeType: SSIMShapeType, enabled = true) => { return; } - const { imageData, imageBounds, existingAnnotations, autoMergeDuplicates, template } = props; - const bounds = imageBounds ?? roiFromImage(imageData); - const ssimMatches = convertToolMatchesToGetiMatches(matches, imageData, bounds); + const { imageData, roi, existingAnnotations, autoMergeDuplicates, template } = props; + const ssimMatches = convertToolMatchesToGetiMatches(matches, imageData, roi); const existingRects = autoMergeDuplicates ? getExistingRects(existingAnnotations) : []; - const filteredMatches = filterSSIMResults(bounds, ssimMatches, template, existingRects); + const filteredMatches = filterSSIMResults(roi, ssimMatches, template, existingRects); setToolState((currentState) => { const threshold = keepNumberOfItems diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts b/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts index 6925ecb26ce..d4edd4f7261 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/utils.test.ts @@ -41,20 +41,21 @@ describe('SSIM utils', () => { describe('toToolRunSSIMProps', () => { it('converts the template and existing annotations to smart-tools rects', () => { - const imageData = { width: 1, height: 1 } as ImageData; + const imageData = { width: 100, height: 100 } as ImageData; expect( toToolRunSSIMProps({ imageData, + roi: { x: 0, y: 0, width: 100, height: 100 }, template: rect(5, 5, 20, 20), - existingAnnotations: [rect(100, 100), { type: 'full_image' }], + existingAnnotations: [rect(60, 60), { type: 'full_image' }], autoMergeDuplicates: true, }) ).toEqual({ imageData, - roi: { x: 0, y: 0, width: 1, height: 1 }, + roi: { x: 0, y: 0, width: 100, height: 100 }, template: { x: 5, y: 5, width: 20, height: 20, shapeType: 'rect' }, - existingAnnotations: [{ x: 100, y: 100, width: 10, height: 10, shapeType: 'rect' }], + existingAnnotations: [{ x: 60, y: 60, width: 10, height: 10, shapeType: 'rect' }], autoMergeDuplicates: true, shapeType: 'rect', }); @@ -66,7 +67,7 @@ describe('SSIM utils', () => { expect( toToolRunSSIMProps({ imageData, - imageBounds: { x: 0, y: 0, width: 4000, height: 3000 }, + roi: { x: 0, y: 0, width: 4000, height: 3000 }, template: rect(400, 300, 200, 150), existingAnnotations: [rect(1000, 600, 100, 100)], autoMergeDuplicates: true, @@ -86,7 +87,7 @@ describe('SSIM utils', () => { const props = toToolRunSSIMProps({ imageData, - imageBounds: { x: 0, y: 0, width: 2048, height: 2048 }, + roi: { x: 0, y: 0, width: 2048, height: 2048 }, template: rect(500, 600, 8, 8), existingAnnotations: [], autoMergeDuplicates: true, @@ -95,6 +96,46 @@ describe('SSIM utils', () => { expect(props.roi).toEqual({ x: 254, y: 354, width: 500, height: 500 }); expect(props.template).toEqual({ x: 246, y: 246, width: 8, height: 8, shapeType: 'rect' }); }); + + it('clamps narrowed search ROIs to image edges while keeping the template inside', () => { + const imageData = { width: 2048, height: 2048 } as ImageData; + const roi = { x: 0, y: 0, width: 2048, height: 2048 }; + + const topLeft = toToolRunSSIMProps({ + imageData, + roi, + template: rect(2, 4, 8, 8), + existingAnnotations: [], + autoMergeDuplicates: true, + }); + expect(topLeft.roi).toEqual({ x: 0, y: 0, width: 500, height: 500 }); + expect(topLeft.template).toEqual({ x: 2, y: 4, width: 8, height: 8, shapeType: 'rect' }); + + const bottomRight = toToolRunSSIMProps({ + imageData, + roi, + template: rect(2040, 2040, 8, 8), + existingAnnotations: [], + autoMergeDuplicates: true, + }); + expect(bottomRight.roi).toEqual({ x: 1548, y: 1548, width: 500, height: 500 }); + expect(bottomRight.template).toEqual({ x: 492, y: 492, width: 8, height: 8, shapeType: 'rect' }); + }); + + it('only narrows axes where the template is too small for the full image', () => { + const imageData = { width: 2048, height: 2048 } as ImageData; + + const props = toToolRunSSIMProps({ + imageData, + roi: { x: 0, y: 0, width: 2048, height: 2048 }, + template: rect(500, 600, 8, 100), + existingAnnotations: [], + autoMergeDuplicates: true, + }); + + expect(props.roi).toEqual({ x: 254, y: 0, width: 500, height: 2048 }); + expect(props.template).toEqual({ x: 246, y: 600, width: 8, height: 100, shapeType: 'rect' }); + }); }); describe('convertToolMatchesToGetiMatches', () => { diff --git a/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts b/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts index e4a41b6eb9f..7b59cf652fc 100644 --- a/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts +++ b/application/ui/src/modules/annotator/tools/ssim-tool/utils.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { RunSSIMProps as ToolRunSSIMProps, SSIMMatch as ToolSSIMMatch } from '@geti-ui/smart-tools'; -import { clampBox, roiFromImage } from '@geti-ui/smart-tools/utils'; +import { clampBox } from '@geti-ui/smart-tools/utils'; import { clamp } from 'lodash-es'; import type { Rect, RegionOfInterest, Shape } from '../../../../shared/types'; @@ -24,7 +24,7 @@ export type SSIMMatch = Omit & { export type SSIMShapeType = Extract; export type RunSSIMProps = Omit & { - imageBounds?: RegionOfInterest; + roi: RegionOfInterest; template: Rect; existingAnnotations: Shape[]; }; @@ -67,45 +67,43 @@ export const getExistingRects = (shapes: Shape[]): Rect[] => { return shapes.map(getBoundingRectFromShape).filter((shape): shape is Rect => shape !== null); }; -const getAxisRoi = (start: number, length: number, limit: number): [offset: number, size: number] => { - if (limit <= 0 || length <= 0 || (length * SSIM_SCALE_PX) / limit >= MIN_SSIM_TEMPLATE_PX) { +// Returns a 1D search window `[offset, size]` within `[0, limit]` centered on `[start, start + length]`. +// Keeps the full axis unless the template would shrink below `MIN_SSIM_TEMPLATE_PX` on SSIM's 250×250 grid. +const getSearchWindow = (start: number, length: number, limit: number): [offset: number, size: number] => { + const maxWindow = Math.floor((length * SSIM_SCALE_PX) / MIN_SSIM_TEMPLATE_PX); + if (length <= 0 || maxWindow >= limit) { return [0, limit]; } - const minSize = Math.max(1, Math.ceil(start + length) - Math.floor(start)); - const targetSize = Math.floor((length * SSIM_SCALE_PX) / MIN_SSIM_TEMPLATE_PX); - const size = Math.min(limit, Math.max(minSize, targetSize)); - const minOffset = Math.max(0, Math.ceil(start + length) - size); - const maxOffset = Math.min(Math.floor(start), limit - size); - const offset = clamp(Math.round(start + length / 2 - size / 2), minOffset, maxOffset); + const size = Math.min(limit, Math.max(Math.ceil(length) + 1, maxWindow)); + const offset = clamp(Math.round(start + (length - size) / 2), 0, limit - size); return [offset, size]; }; export const toToolRunSSIMProps = ({ imageData, - imageBounds, + roi, template, existingAnnotations, autoMergeDuplicates, }: RunSSIMProps): ToolRunSSIMProps => { - const bounds = imageBounds ?? roiFromImage(imageData); - const scaledTemplate = scaleRect(template, bounds, imageData); - const [roiX, roiWidth] = getAxisRoi(scaledTemplate.x, scaledTemplate.width, imageData.width); - const [roiY, roiHeight] = getAxisRoi(scaledTemplate.y, scaledTemplate.height, imageData.height); - const roi = { x: roiX, y: roiY, width: roiWidth, height: roiHeight }; + const scaledTemplate = scaleRect(template, roi, imageData); + const [searchX, searchWidth] = getSearchWindow(scaledTemplate.x, scaledTemplate.width, imageData.width); + const [searchY, searchHeight] = getSearchWindow(scaledTemplate.y, scaledTemplate.height, imageData.height); + const searchRoi = { x: searchX, y: searchY, width: searchWidth, height: searchHeight }; const roiTemplate: Rect = { ...scaledTemplate, - x: scaledTemplate.x - roi.x, - y: scaledTemplate.y - roi.y, + x: scaledTemplate.x - searchRoi.x, + y: scaledTemplate.y - searchRoi.y, }; return { imageData, - roi, + roi: searchRoi, template: toToolRect(roiTemplate), existingAnnotations: getExistingRects(existingAnnotations).map((rect) => - toToolRect(scaleRect(rect, bounds, imageData)) + toToolRect(scaleRect(rect, roi, imageData)) ), autoMergeDuplicates, shapeType: 'rect',