Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

np. we need to call this only when isOme is true

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have the same for frames, we also have it on images. I believe, if the cache value did not change, this costs 0

'/api/projects/{project_id}/dataset/media/{media_id}/planes',
{ params: { path: { project_id: projectId, media_id: mediaItem.id } } },
],
],
},
onSuccess: async () => {
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -134,6 +134,7 @@ const MediaPreviewContent = ({
device: selectedDevice,
confidenceThreshold,
range: getMediaItemPredictionRange(mediaItem),
planeRange: getMediaItemPredictionPlaneRange(mediaItem),
});

const isCurrentMediaReviewed = annotationsData?.user_reviewed ?? false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -21,6 +21,7 @@ export const useNextPredictionPrefetch = (nextMediaItem: Media) => {
device: selectedDevice,
confidenceThreshold,
range: getMediaItemPredictionRange(nextMediaItem),
planeRange: getMediaItemPredictionPlaneRange(nextMediaItem),
})
);
};
Original file line number Diff line number Diff line change
@@ -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<typeof options.queryKey>);

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);
});
});
87 changes: 32 additions & 55 deletions application/ui/src/modules/annotator/api/use-media-predictions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -18,21 +18,32 @@ 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,
mediaId,
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),
Expand All @@ -41,6 +52,7 @@ export const mediaPredictionsQueryOptions = ({
selectedModel,
confidenceThreshold,
range,
planeRange,
],
queryFn: async ({ signal }) => {
if (selectedModel === undefined) return [];
Expand All @@ -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 },
],
},
});

Expand Down Expand Up @@ -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;
};
Expand Down Expand Up @@ -169,6 +145,7 @@ const useIsFetchingCurrentFramePredictions = (mediaId: string) => {
device: selectedDevice,
confidenceThreshold,
range: getMediaItemPredictionRange(mediaItem),
planeRange: getMediaItemPredictionPlaneRange(mediaItem),
});
};

Expand Down
Loading
Loading