Fixed model pagination (#5674)

<!-- Raise an issue to propose your change
(https://github.com/opencv/cvat/issues).
It helps to avoid duplication of efforts from multiple independent
contributors.
Discuss your ideas with maintainers to be sure that changes will be
approved and merged.
Read the [Contribution
guide](https://opencv.github.io/cvat/docs/contributing/). -->

<!-- Provide a general summary of your changes in the Title above -->

### Motivation and context
<!-- Why is this change required? What problem does it solve? If it
fixes an open
issue, please link to the issue here. Describe your changes in detail,
add
screenshots. -->

### How has this been tested?
<!-- Please describe in detail how you tested your changes.
Include details of your testing environment, and the tests you ran to
see how your change affects other areas of the code, etc. -->

### Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply.
If an item isn't applicable for some reason, then ~~explicitly
strikethrough~~ the whole
line. If you don't do that, GitHub will show incorrect progress for the
pull request.
If you're unsure about any of these, don't hesitate to ask. We're here
to help! -->
- [ ] I submit my changes into the `develop` branch
- [ ] I have added a description of my changes into the
[CHANGELOG](https://github.com/opencv/cvat/blob/develop/CHANGELOG.md)
file
- [ ] I have updated the documentation accordingly
- [ ] I have added tests to cover my changes
- [ ] I have linked related issues (see [GitHub docs](

https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword))
- [ ] I have increased versions of npm packages if it is necessary

([cvat-canvas](https://github.com/opencv/cvat/tree/develop/cvat-canvas#versioning),

[cvat-core](https://github.com/opencv/cvat/tree/develop/cvat-core#versioning),

[cvat-data](https://github.com/opencv/cvat/tree/develop/cvat-data#versioning)
and

[cvat-ui](https://github.com/opencv/cvat/tree/develop/cvat-ui#versioning))

### License

- [ ] I submit _my code changes_ under the same [MIT License](
https://github.com/opencv/cvat/blob/develop/LICENSE) that covers the
project.
  Feel free to contact the maintainers if that's a concern.
main
Kirill Lakhov 3 years ago committed by GitHub
parent e194f5b8e0
commit e24bacede2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,49 @@
// Copyright (C) 2023 CVAT.ai Corporation
//
// SPDX-License-Identifier: MIT
import { ModelKind, ModelReturnType } from './enums';
export interface ModelAttribute {
name: string;
values: string[];
input_type: 'select' | 'number' | 'checkbox' | 'radio' | 'text';
}
export interface ModelParams {
canvas: {
minPosVertices?: number;
minNegVertices?: number;
startWithBox?: boolean;
onChangeToolsBlockerState?: (event: string) => void;
};
}
export interface ModelTip {
message: string;
gif: string;
}
export interface SerializedModel {
id?: string | number;
name?: string;
labels?: string[];
version?: number;
attributes?: Record<string, ModelAttribute>;
framework?: string;
description?: string;
kind?: ModelKind;
type?: string;
return_type?: ModelReturnType;
owner?: any;
provider?: string;
api_key?: string;
url?: string;
help_message?: string;
animated_gif?: string;
min_pos_points?: number;
min_neg_points?: number;
startswith_box?: boolean;
created_date?: string;
updated_date?: string;
}

@ -30,9 +30,11 @@ class LambdaManager {
this.cachedList = null; this.cachedList = null;
} }
async list(): Promise<MLModel[]> { async list(): Promise<{ models: MLModel[], count: number }> {
const lambdaFunctions = await serverProxy.lambda.list(); const lambdaFunctions = await serverProxy.lambda.list();
const functions = await serverProxy.functions.list();
const functionsResult = await serverProxy.functions.list();
const { results: functions, count: functionsCount } = functionsResult;
const result = [...lambdaFunctions, ...functions]; const result = [...lambdaFunctions, ...functions];
const models = []; const models = [];
@ -46,7 +48,7 @@ class LambdaManager {
} }
this.cachedList = models; this.cachedList = models;
return models; return { models, count: lambdaFunctions.length + functionsCount };
} }
async run(taskID: number, model: MLModel, args: any) { async run(taskID: number, model: MLModel, args: any) {

@ -7,50 +7,9 @@ import { isBrowser, isNode } from 'browser-or-node';
import serverProxy from './server-proxy'; import serverProxy from './server-proxy';
import PluginRegistry from './plugins'; import PluginRegistry from './plugins';
import { ModelProviders, ModelKind, ModelReturnType } from './enums'; import { ModelProviders, ModelKind, ModelReturnType } from './enums';
import {
interface ModelAttribute { SerializedModel, ModelAttribute, ModelParams, ModelTip,
name: string; } from './core-types';
values: string[];
input_type: 'select' | 'number' | 'checkbox' | 'radio' | 'text';
}
interface ModelParams {
canvas: {
minPosVertices?: number;
minNegVertices?: number;
startWithBox?: boolean;
onChangeToolsBlockerState?: (event: string) => void;
};
}
interface ModelTip {
message: string;
gif: string;
}
interface SerializedModel {
id?: string | number;
name?: string;
labels?: string[];
version?: number;
attributes?: Record<string, ModelAttribute>;
framework?: string;
description?: string;
kind?: ModelKind;
type?: string;
return_type?: ModelReturnType;
owner?: any;
provider?: string;
api_key?: string;
url?: string;
help_message?: string;
animated_gif?: string;
min_pos_points?: number;
min_neg_points?: number;
startswith_box?: boolean;
created_date?: string;
updated_date?: string;
}
export default class MLModel { export default class MLModel {
private serialized: SerializedModel; private serialized: SerializedModel;

@ -13,6 +13,7 @@ import { isEmail } from './common';
import config from './config'; import config from './config';
import DownloadWorker from './download.worker'; import DownloadWorker from './download.worker';
import { ServerError } from './exceptions'; import { ServerError } from './exceptions';
import { FunctionsResponseBody } from './server-response-types';
type Params = { type Params = {
org: number | string, org: number | string,
@ -1604,17 +1605,20 @@ async function getAnnotations(session, id) {
return response.data; return response.data;
} }
async function getFunctions() { async function getFunctions(): Promise<FunctionsResponseBody> {
const { backendAPI } = config; const { backendAPI } = config;
try { try {
const response = await Axios.get(`${backendAPI}/functions`, { const response = await Axios.get(`${backendAPI}/functions`, {
proxy: config.proxy, proxy: config.proxy,
}); });
return response.data.results; return response.data;
} catch (errorData) { } catch (errorData) {
if (errorData.response.status === 404) { if (errorData.response.status === 404) {
return []; return {
results: [],
count: 0,
};
} }
throw generateError(errorData); throw generateError(errorData);
} }

@ -0,0 +1,10 @@
// Copyright (C) 2023 CVAT.ai Corporation
//
// SPDX-License-Identifier: MIT
import { SerializedModel } from 'core-types';
export interface FunctionsResponseBody {
results: SerializedModel[];
count: number;
}

@ -40,8 +40,8 @@ export enum ModelsActionTypes {
export const modelsActions = { export const modelsActions = {
getModels: (query?: ModelsQuery) => createAction(ModelsActionTypes.GET_MODELS, { query }), getModels: (query?: ModelsQuery) => createAction(ModelsActionTypes.GET_MODELS, { query }),
getModelsSuccess: (models: MLModel[]) => createAction(ModelsActionTypes.GET_MODELS_SUCCESS, { getModelsSuccess: (models: MLModel[], count: number) => createAction(ModelsActionTypes.GET_MODELS_SUCCESS, {
models, models, count,
}), }),
getModelsFailed: (error: any) => createAction(ModelsActionTypes.GET_MODELS_FAILED, { getModelsFailed: (error: any) => createAction(ModelsActionTypes.GET_MODELS_FAILED, {
error, error,
@ -113,14 +113,15 @@ export type ModelsActions = ActionUnion<typeof modelsActions>;
const core = getCore(); const core = getCore();
export function getModelsAsync(query: ModelsQuery): ThunkAction { export function getModelsAsync(query?: ModelsQuery): ThunkAction {
return async (dispatch): Promise<void> => { return async (dispatch, getState): Promise<void> => {
dispatch(modelsActions.getModels(query)); dispatch(modelsActions.getModels(query));
const filteredQuery = filterNull(query); const filteredQuery = filterNull(query || getState().models.query);
try { try {
const models = await core.lambda.list(filteredQuery); const result = await core.lambda.list(filteredQuery);
dispatch(modelsActions.getModelsSuccess(models)); const { models, count } = result;
dispatch(modelsActions.getModelsSuccess(models, count));
} catch (error) { } catch (error) {
dispatch(modelsActions.getModelsFailed(error)); dispatch(modelsActions.getModelsFailed(error));
} }

@ -3,17 +3,22 @@
// //
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
import React, { useState } from 'react'; import React from 'react';
import moment from 'moment'; import moment from 'moment';
import { useSelector } from 'react-redux'; import { useSelector, useDispatch } from 'react-redux';
import { Row, Col } from 'antd/lib/grid'; import { Row, Col } from 'antd/lib/grid';
import Pagination from 'antd/lib/pagination'; import Pagination from 'antd/lib/pagination';
import { CombinedState } from 'reducers'; import { CombinedState, ModelsQuery } from 'reducers';
import { MLModel } from 'cvat-core-wrapper'; import { MLModel } from 'cvat-core-wrapper';
import { ModelProviders } from 'cvat-core/src/enums'; import { ModelProviders } from 'cvat-core/src/enums';
import { getModelsAsync } from 'actions/models-actions';
import DeployedModelItem from './deployed-model-item'; import DeployedModelItem from './deployed-model-item';
const PAGE_SIZE = 12; export const PAGE_SIZE = 12;
interface Props {
query: ModelsQuery;
}
function setUpModelsList(models: MLModel[], newPage: number): MLModel[] { function setUpModelsList(models: MLModel[], newPage: number): MLModel[] {
const builtInModels = models.filter((model: MLModel) => model.provider === ModelProviders.CVAT); const builtInModels = models.filter((model: MLModel) => model.provider === ModelProviders.CVAT);
@ -23,14 +28,17 @@ function setUpModelsList(models: MLModel[], newPage: number): MLModel[] {
return renderModels.slice((newPage - 1) * PAGE_SIZE, newPage * PAGE_SIZE); return renderModels.slice((newPage - 1) * PAGE_SIZE, newPage * PAGE_SIZE);
} }
export default function DeployedModelsListComponent(): JSX.Element { export default function DeployedModelsListComponent(props: Props): JSX.Element {
const interactors = useSelector((state: CombinedState) => state.models.interactors); const interactors = useSelector((state: CombinedState) => state.models.interactors);
const detectors = useSelector((state: CombinedState) => state.models.detectors); const detectors = useSelector((state: CombinedState) => state.models.detectors);
const trackers = useSelector((state: CombinedState) => state.models.trackers); const trackers = useSelector((state: CombinedState) => state.models.trackers);
const reid = useSelector((state: CombinedState) => state.models.reid); const reid = useSelector((state: CombinedState) => state.models.reid);
const classifiers = useSelector((state: CombinedState) => state.models.classifiers); const classifiers = useSelector((state: CombinedState) => state.models.classifiers);
const totalCount = useSelector((state: CombinedState) => state.models.totalCount); const totalCount = useSelector((state: CombinedState) => state.models.totalCount);
const [page, setPage] = useState(1);
const dispatch = useDispatch();
const { query } = props;
const { page } = query;
const models = [...interactors, ...detectors, ...trackers, ...reid, ...classifiers]; const models = [...interactors, ...detectors, ...trackers, ...reid, ...classifiers];
const items = setUpModelsList(models, page) const items = setUpModelsList(models, page)
.map((model): JSX.Element => <DeployedModelItem key={model.id} model={model} />); .map((model): JSX.Element => <DeployedModelItem key={model.id} model={model} />);
@ -46,7 +54,10 @@ export default function DeployedModelsListComponent(): JSX.Element {
<Pagination <Pagination
className='cvat-tasks-pagination' className='cvat-tasks-pagination'
onChange={(newPage: number) => { onChange={(newPage: number) => {
setPage(newPage); dispatch(getModelsAsync({
...query,
page: newPage,
}));
}} }}
showSizeChanger={false} showSizeChanger={false}
total={totalCount} total={totalCount}

@ -10,11 +10,12 @@ import { useDispatch, useSelector } from 'react-redux';
import { getModelProvidersAsync, getModelsAsync } from 'actions/models-actions'; import { getModelProvidersAsync, getModelsAsync } from 'actions/models-actions';
import { updateHistoryFromQuery } from 'components/resource-sorting-filtering'; import { updateHistoryFromQuery } from 'components/resource-sorting-filtering';
import Spin from 'antd/lib/spin'; import Spin from 'antd/lib/spin';
import notification from 'antd/lib/notification';
import DeployedModelsList from './deployed-models-list'; import { CombinedState, Indexable } from 'reducers';
import DeployedModelsList, { PAGE_SIZE } from './deployed-models-list';
import EmptyListComponent from './empty-list'; import EmptyListComponent from './empty-list';
import FeedbackComponent from '../feedback/feedback'; import FeedbackComponent from '../feedback/feedback';
import { CombinedState } from '../../reducers';
import TopBar from './top-bar'; import TopBar from './top-bar';
function ModelsPageComponent(): JSX.Element { function ModelsPageComponent(): JSX.Element {
@ -29,19 +30,33 @@ function ModelsPageComponent(): JSX.Element {
}, []); }, []);
const updatedQuery = { ...query }; const updatedQuery = { ...query };
const queryParams = new URLSearchParams(history.location.search);
for (const key of Object.keys(updatedQuery)) {
(updatedQuery as Indexable)[key] = queryParams.get(key) || null;
if (key === 'page') {
updatedQuery.page = updatedQuery.page ? +updatedQuery.page : 1;
}
}
useEffect(() => { useEffect(() => {
history.replace({ history.replace({
search: updateHistoryFromQuery(query), search: updateHistoryFromQuery(query),
}); });
}, [query]); }, [query]);
const pageOutOfBounds = updatedQuery.page > Math.ceil(totalCount / PAGE_SIZE);
useEffect(() => { useEffect(() => {
dispatch(getModelProvidersAsync()); dispatch(getModelProvidersAsync());
dispatch(getModelsAsync(updatedQuery)); dispatch(getModelsAsync(updatedQuery));
if (pageOutOfBounds) {
notification.error({
message: 'Could not fetch models',
description: 'Invalid page',
});
}
}, []); }, []);
const content = totalCount ? ( const content = (totalCount && !pageOutOfBounds) ? (
<DeployedModelsList /> <DeployedModelsList query={updatedQuery} />
) : <EmptyListComponent />; ) : <EmptyListComponent />;
return ( return (

@ -42,6 +42,10 @@ export default function (state = defaultState, action: ModelsActions | AuthActio
return { return {
...state, ...state,
fetching: true, fetching: true,
query: {
...state.query,
...action.payload.query,
},
}; };
} }
case ModelsActionTypes.GET_MODELS_SUCCESS: { case ModelsActionTypes.GET_MODELS_SUCCESS: {
@ -62,7 +66,7 @@ export default function (state = defaultState, action: ModelsActions | AuthActio
classifiers: action.payload.models.filter((model: MLModel) => ( classifiers: action.payload.models.filter((model: MLModel) => (
model.kind === ModelKind.CLASSIFIER model.kind === ModelKind.CLASSIFIER
)), )),
totalCount: action.payload.models.length, totalCount: action.payload.count,
initialized: true, initialized: true,
fetching: false, fetching: false,
}; };

Loading…
Cancel
Save