Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: clear instances when page hidden #329

Merged
merged 1 commit into from
Jan 19, 2025
Merged
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
2 changes: 1 addition & 1 deletion src/components/icon-font/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createFromIconfontCN } from '@ant-design/icons';
// import './iconfont/iconfont.js';

const IconFont = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_4613488_pz4284jx1rq.js'
scriptUrl: '//at.alicdn.com/t/c/font_4613488_6x6w1c4c2c.js'
});

export default IconFont;
64 changes: 56 additions & 8 deletions src/components/image-editor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const CanvasImageEditor: React.FC<CanvasImageEditorProps> = ({
const strokeCache = useRef<any>({});
const preImguid = useRef<string | number>('');
const [activeScale, setActiveScale] = useState<number>(1);
const negativeMaskRef = useRef<boolean>(false);

const getTransformedPoint = useCallback(
(offsetX: number, offsetY: number) => {
Expand Down Expand Up @@ -159,6 +160,41 @@ const CanvasImageEditor: React.FC<CanvasImageEditorProps> = ({
strokesRef.current = strokes;
};

const inpaintArea = useCallback(
(data: Uint8ClampedArray<ArrayBufferLike>) => {
for (let i = 0; i < data.length; i += 4) {
const alpha = data[i + 3];
if (alpha > 0) {
data[i] = 255; // Red
data[i + 1] = 255; // Green
data[i + 2] = 255; // Blue
data[i + 3] = 255; // Alpha
}
}
},
[]
);

const inpaintBackground = useCallback(
(data: Uint8ClampedArray<ArrayBufferLike>) => {
for (let i = 0; i < data.length; i += 4) {
const alpha = data[i + 3];
if (alpha > 0) {
data[i] = 0; // Red
data[i + 1] = 0; // Green
data[i + 2] = 0; // Blue
data[i + 3] = 255; // Alpha
} else {
data[i] = 255;
data[i + 1] = 255;
data[i + 2] = 255;
data[i + 3] = 255;
}
}
},
[]
);

const generateMask = useCallback(() => {
if (strokesRef.current.length === 0) {
return null;
Expand All @@ -178,15 +214,12 @@ const CanvasImageEditor: React.FC<CanvasImageEditorProps> = ({
);
const data = imageData.data;

for (let i = 0; i < data.length; i += 4) {
const alpha = data[i + 3];
if (alpha > 0) {
data[i] = 255; // Red
data[i + 1] = 255; // Green
data[i + 2] = 255; // Blue
data[i + 3] = 255; // Alpha
}
if (negativeMaskRef.current) {
inpaintBackground(data);
} else {
inpaintArea(data);
}

maskCtx.putImageData(imageData, 0, 0);

maskCtx.globalCompositeOperation = 'destination-over';
Expand Down Expand Up @@ -620,6 +653,12 @@ const CanvasImageEditor: React.FC<CanvasImageEditorProps> = ({
cursorRef.current!.style.width = `${value}px`;
cursorRef.current!.style.height = `${value}px`;
};

const handleOnChangeMask = (e: any) => {
negativeMaskRef.current = e.target.checked;
saveImage();
};

useEffect(() => {
initializeImage();
}, [initializeImage]);
Expand Down Expand Up @@ -719,6 +758,15 @@ const CanvasImageEditor: React.FC<CanvasImageEditorProps> = ({
</Tooltip>
</div>
<div className="tools">
{/* <Checkbox
onChange={handleOnChangeMask}
className="flex-center"
value={negativeMaskRef.current}
>
<span className="font-size-12">
{intl.formatMessage({ id: 'playground.image.negativeMask' })}
</span>
</Checkbox> */}
<Tooltip
title={intl.formatMessage({ id: 'playground.image.saveMask' })}
>
Expand Down
5 changes: 1 addition & 4 deletions src/components/seal-table/components/table-row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ const TableRow: React.FC<
const handleVisibilityChange = async () => {
if (document.visibilityState === 'hidden') {
cacheDataListRef.current = [];
setChildrenData([]);
}
};

Expand All @@ -218,10 +219,6 @@ const TableRow: React.FC<
};
}, [firstLoad, expanded, tableContext.allChildren]);

useEffect(() => {
console.log('allSubChildren===', tableContext.allSubChildren);
}, [tableContext.allSubChildren]);

const renderRowPrefix = () => {
if (expandable && rowSelection) {
return (
Expand Down
1 change: 1 addition & 0 deletions src/locales/en-US/playground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export default {
'The higher the value, the greater the modification to the original image.',
'playground.image.edit.tips': 'Click or drag image to this area to upload',
'playground.image.saveMask': 'Save Mask',
'playground.image.negativeMask': 'Negative Mask',
'playground.image.brushSize': 'Brush Size',
'playground.image.download': 'Download Image',
'playground.image.generate': 'Generate',
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh-CN/playground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export default {
'playground.image.strength.tip': '值越高,它对原图的修改越大',
'playground.image.edit.tips': '点击或拖动图片到此区域上传',
'playground.image.saveMask': '保存遮罩',
'playground.image.negativeMask': '反向遮罩',
'playground.image.brushSize': '画笔大小',
'playground.image.download': '下载图片',
'playground.image.generate': '生成图片',
Expand Down
30 changes: 3 additions & 27 deletions src/pages/llmodels/components/table-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ interface ModelsProps {
handleCategoryChange: (val: any) => void;
onViewLogs: () => void;
onCancelViewLogs: () => void;
allInstances: ModelInstanceListItem[];
queryParams: {
page: number;
perPage: number;
Expand Down Expand Up @@ -120,7 +119,6 @@ const Models: React.FC<ModelsProps> = ({
onViewLogs,
onCancelViewLogs,
handleCategoryChange,
allInstances,
deleteIds,
dataSource,
gpuDeviceList,
Expand All @@ -144,7 +142,6 @@ const Models: React.FC<ModelsProps> = ({
defaultSortOrder: 'descend'
});

const updateRef = useRef(false);
const [openLogModal, setOpenLogModal] = useState(false);
const [openAddModal, setOpenAddModal] = useState(false);
const [openDeployModal, setOpenDeployModal] = useState<any>({
Expand Down Expand Up @@ -673,24 +670,17 @@ const Models: React.FC<ModelsProps> = ({

const renderChildren = useCallback(
(list: any, parent?: any) => {
let childList = list;
if (allInstances.length && !updateRef.current) {
childList = list.filter((item: any) => {
return allInstances.some((instance) => instance.id === item.id);
});
updateRef.current = true;
}
return (
<InstanceItem
list={childList}
list={list}
modelData={parent}
gpuDeviceList={gpuDeviceList}
gpuDeviceList={[]}
workerList={workerList}
handleChildSelect={handleChildSelect}
></InstanceItem>
);
},
[workerList, allInstances]
[workerList]
);

const generateSource = useCallback((record: ListItem) => {
Expand Down Expand Up @@ -746,20 +736,6 @@ const Models: React.FC<ModelsProps> = ({
}
};

useEffect(() => {
const handleVisibilityChange = async () => {
if (document.visibilityState === 'hidden') {
updateRef.current = false;
}
};

document.addEventListener('visibilitychange', handleVisibilityChange);

return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);

return (
<>
<PageContainer
Expand Down
1 change: 1 addition & 0 deletions src/pages/llmodels/components/update-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const sourceOptions = [
{
label: 'models.form.localPath',
value: modelSourceMap.local_path_value,
locale: true,
key: 'local_path'
}
];
Expand Down
35 changes: 3 additions & 32 deletions src/pages/llmodels/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import TableContext from '@/components/seal-table/table-context';
import useSetChunkRequest, {
createAxiosToken as generateAxiosToken
} from '@/hooks/use-chunk-request';
import useSetChunkRequest from '@/hooks/use-chunk-request';
import useUpdateChunkedList from '@/hooks/use-update-chunk-list';
import { queryWorkersList } from '@/pages/resources/apis';
import {
Expand All @@ -11,17 +9,10 @@ import {
import _ from 'lodash';
import qs from 'query-string';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import {
MODELS_API,
MODEL_INSTANCE_API,
queryModelsInstances,
queryModelsList
} from './apis';
import { MODELS_API, MODEL_INSTANCE_API, queryModelsList } from './apis';
import TableList from './components/table-list';
import { ListItem } from './config/types';

const INSTANCE_SYNC = 'instance_sync';

const Models: React.FC = () => {
const { setChunkRequest, createAxiosToken } = useSetChunkRequest();
const { setChunkRequest: setModelInstanceChunkRequest } =
Expand All @@ -39,7 +30,6 @@ const Models: React.FC = () => {
total: 0
});

const [allInstances, setAllInstances] = useState<any[]>([]);
const [gpuDeviceList, setGpuDeviceList] = useState<GPUDeviceItem[]>([]);
const [workerList, setWorkerList] = useState<WokerListItem[]>([]);
const chunkRequedtRef = useRef<any>();
Expand Down Expand Up @@ -69,24 +59,6 @@ const Models: React.FC = () => {
}
});

const fetchModelsInstances = async () => {
try {
instancesToken.current?.cancel?.();
instancesToken.current = generateAxiosToken();
const params = {
page: 1,
perPage: 100
};
const data: any = await queryModelsInstances(params, {
token: instancesToken.current?.token
});
setAllInstances(data.items || []);
} catch (error) {
// ignore
setAllInstances([]);
}
};

const getWorkerList = async () => {
try {
const data = await queryWorkersList({ page: 1, perPage: 100 });
Expand Down Expand Up @@ -249,7 +221,7 @@ const Models: React.FC = () => {
const handleVisibilityChange = async () => {
if (document.visibilityState === 'visible') {
isPageHidden.current = false;
await fetchModelsInstances();
// await fetchModelsInstances();
await Promise.all([
createModelsChunkRequest(),
createModelsInstanceChunkRequest()
Expand Down Expand Up @@ -284,7 +256,6 @@ const Models: React.FC = () => {
handlePageChange={handlePageChange}
handleDeleteSuccess={fetchData}
onViewLogs={handleOnViewLogs}
allInstances={allInstances}
onCancelViewLogs={handleOnCancelViewLogs}
queryParams={queryParams}
loading={dataSource.loading}
Expand Down
5 changes: 2 additions & 3 deletions src/pages/playground/components/ground-images.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import React, {
useState
} from 'react';
import { CREAT_IMAGE_API } from '../apis';
import { promptList } from '../config';
import { extractErrorMessage, promptList } from '../config';
import {
ImageAdvancedParamsConfig,
ImageCustomSizeConfig,
Expand Down Expand Up @@ -336,8 +336,7 @@ const GroundImages: React.FC<MessageProps> = forwardRef((props, ref) => {
if (result.error) {
setTokenResult({
error: true,
errorMessage:
result?.data?.error?.message || result?.data?.error || ''
errorMessage: extractErrorMessage(result)
});
setImageList([]);
return;
Expand Down
7 changes: 2 additions & 5 deletions src/pages/playground/components/image-edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import React, {
useState
} from 'react';
import { EDIT_IMAGE_API } from '../apis';
import { extractErrorMessage } from '../config';
import {
ImageAdvancedParamsConfig,
ImageCustomSizeConfig,
Expand Down Expand Up @@ -369,11 +370,7 @@ const GroundImages: React.FC<MessageProps> = forwardRef((props, ref) => {
if (result.error) {
setTokenResult({
error: true,
errorMessage:
result?.data?.data?.detail ||
result?.data?.error?.message ||
result?.data?.error ||
''
errorMessage: extractErrorMessage(result)
});
setImageList([]);
return;
Expand Down
10 changes: 10 additions & 0 deletions src/pages/playground/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,13 @@ export const promptList = [
'A full shot of two people jogging at sunset, featuring a vibrant, warm color palette shifting from twilight blues to peachy-orange tones, with visible sun rays and lens flares, conveying a sense of leisure and athleticism.',
'A close-up portrait of a golden retriever wearing black-framed glasses, exhibiting a rich golden-brown coat with a fluffy texture, and a neutral, light gray background.'
];

export const extractErrorMessage = (result: any) => {
return (
result?.data?.data?.detail ||
result?.data?.data?.message ||
result?.data?.error?.message ||
result?.data?.error ||
''
);
};
4 changes: 2 additions & 2 deletions src/pages/playground/config/params-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ export const ImageCustomSizeConfig: ParamsSchema[] = [
min: 256,
max: 3200,
step: 64,
inputnumber: true
inputnumber: false
},
rules: [
{
Expand All @@ -471,7 +471,7 @@ export const ImageCustomSizeConfig: ParamsSchema[] = [
min: 256,
max: 3200,
step: 64,
inputnumber: true
inputnumber: false
},
rules: [
{
Expand Down