Spaces:
Running
on
Zero
Running
on
Zero
File size: 10,182 Bytes
46861c5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
// Copyright (c) Meta Platforms, Inc. and affiliates.
// All rights reserved.
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
import { InferenceSession, Tensor } from "onnxruntime-web";
import React, { useContext, useEffect, useState, useRef } from "react";
import axios from "axios";
import "./assets/scss/App.scss";
import { handleImageScale } from "./components/helpers/scaleHelper";
import { modelScaleProps, QueueStatus } from "./components/helpers/Interfaces";
import { onnxMaskToImage, arrayToImageData, imageDataToURL } from "./components/helpers/maskUtils";
import { modelData } from "./components/helpers/onnxModelAPI";
import Stage, { DescriptionState } from "./components/Stage";
import AppContext from "./components/hooks/createContext";
import { imageToSamEmbedding } from "./services/maskApi";
import LoadingOverlay from "./components/LoadingOverlay";
import ErrorModal from './components/ErrorModal';
import QueueStatusIndicator from "./components/QueueStatusIndicator";
const ort = require("onnxruntime-web");
// Define image and model paths
const MODEL_DIR = "/model/sam_onnx_quantized_example.onnx";
const App = () => {
const {
clicks: [clicks, setClicks],
image: [image, setImage],
maskImg: [maskImg, setMaskImg],
maskImgData: [maskImgData, setMaskImgData],
isClicked: [isClicked, setIsClicked]
} = useContext(AppContext)!;
const [model, setModel] = useState<InferenceSession | null>(null);
const [tensor, setTensor] = useState<Tensor | null>(null);
const [modelScale, setModelScale] = useState<modelScaleProps | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const [descriptionState, setDescriptionState] = useState<DescriptionState>({
state: 'ready',
description: ''
});
const [queueStatus, setQueueStatus] = useState<QueueStatus>({ inQueue: false });
// Initialize the ONNX model
useEffect(() => {
const initModel = async () => {
try {
if (MODEL_DIR === undefined) return;
const URL: string = MODEL_DIR;
const model = await InferenceSession.create(URL);
setModel(model);
} catch (e) {
console.log(e);
}
};
initModel();
}, []);
const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
try {
const url = URL.createObjectURL(file);
await loadImage(new URL(url));
} catch (error) {
setError('Failed to load image. Please try again with a different image.');
console.error('Error loading image:', error);
}
};
const loadImage = async (url: URL) => {
try {
setIsLoading(true);
const img = new Image();
img.src = url.href;
img.onload = async () => {
const { height, width, samScale } = handleImageScale(img);
setModelScale({
height: height,
width: width,
samScale: samScale,
});
img.width = width;
img.height = height;
setImage(img);
// After image is loaded, fetch its embedding from Gradio
await fetchImageEmbedding(img);
setIsLoading(false);
};
} catch (error) {
console.log(error);
setIsLoading(false);
}
};
const fetchImageEmbedding = async (img: HTMLImageElement) => {
try {
// Create a canvas to convert the image to base64
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0);
// Convert image to base64 data URL and extract the base64 string
const base64Image = canvas.toDataURL('image/jpeg').split(',')[1];
// Make request to Gradio API
const samEmbedding = await imageToSamEmbedding(
base64Image,
(status: QueueStatus) => {
setQueueStatus(status);
}
);
// Convert base64 embedding back to array buffer
const binaryString = window.atob(samEmbedding);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Create tensor from the embedding
const embedding = new ort.Tensor(
'float32',
new Float32Array(bytes.buffer), // Convert to Float32Array
[1, 256, 64, 64] // SAM embedding shape
);
setTensor(embedding);
} catch (error) {
setQueueStatus({ inQueue: false }); // Reset queue status on error
let errorMessage = 'Failed to process image. Please try again.';
if (axios.isAxiosError(error)) {
errorMessage = error.response?.data?.message || errorMessage;
}
setError(errorMessage);
console.error('Error fetching embedding:', error);
}
};
useEffect(() => {
const handleMaskUpdate = async () => {
await runONNX();
};
handleMaskUpdate();
}, [clicks]);
const runONNX = async () => {
try {
// Don't run if already described or is describing
if (descriptionState.state !== 'ready') return;
console.log('Running ONNX model with:', {
modelLoaded: model !== null,
hasClicks: clicks !== null,
hasTensor: tensor !== null,
hasModelScale: modelScale !== null
});
if (
model === null ||
clicks === null ||
tensor === null ||
modelScale === null
) {
console.log('Missing required inputs, returning early');
return;
}
else {
console.log('Preparing model feeds with:', {
clicks,
tensorShape: tensor.dims,
modelScale
});
const feeds = modelData({
clicks,
tensor,
modelScale,
});
if (feeds === undefined) {
console.log('Model feeds undefined, returning early');
return;
}
console.log('Running model with feeds:', feeds);
const results = await model.run(feeds);
console.log('Model run complete, got results:', results);
const output = results[model.outputNames[0]];
console.log('Processing output with dims:', output.dims);
// Calculate and log the mask area (number of non-zero values)
const maskArray = Array.from(output.data as Uint8Array);
const maskArea = maskArray.filter(val => val > 0).length;
console.log('Mask area (number of non-zero pixels):', maskArea);
// Double check that the state is ready before processing the mask since the state may have changed
if (descriptionState.state !== 'ready') return;
// If clicked, we only handle the first mask (note that mask will be cleared after clicking before handling to let us know if it's the first mask).
if (isClicked && maskImgData != null) return;
if (maskArea > 0) {
setMaskImg(onnxMaskToImage(output.data, output.dims[2], output.dims[3], false));
setMaskImgData(imageDataToURL(arrayToImageData(output.data, output.dims[2], output.dims[3], true)));
} else {
console.warn('No mask area detected, clearing mask');
setMaskImg(null);
// setMaskImgData(null);
}
console.log('Mask processing complete');
}
} catch (e) {
setError('Failed to process the image. Please try again.');
console.error('Error running ONNX model:', e);
}
};
const handleNewRegion = () => {
setDescriptionState({
state: 'ready',
description: ''
} as DescriptionState);
setMaskImg(null);
// setMaskImgData(null);
setIsClicked(false);
};
const handleCopyDescription = () => {
navigator.clipboard.writeText(descriptionState.description);
};
const handleReset = () => {
// Clear all states
setDescriptionState({
state: 'ready',
description: ''
} as DescriptionState);
setMaskImg(null);
// setMaskImgData(null);
setImage(null);
setClicks(null);
setIsClicked(false);
};
return (
<div className="flex flex-col h-screen">
{isLoading && <LoadingOverlay />}
{error && <ErrorModal message={error} onClose={() => setError(null)} />}
<QueueStatusIndicator queueStatus={queueStatus} />
<div className="flex-1">
<Stage
onImageUpload={handleImageUpload}
descriptionState={descriptionState}
setDescriptionState={setDescriptionState}
queueStatus={queueStatus}
setQueueStatus={setQueueStatus}
/>
</div>
<div className="description-container">
<div className={`description-box ${descriptionState.state !== 'described' ? descriptionState.state : ''}`}>
{descriptionState.description ? (
descriptionState.description + (descriptionState.state === 'describing' ? '...' : '')
) : descriptionState.state === 'describing' ? (
<em>Describing the region... (this may take a while if compute resources are busy)</em>
) : (
image ? (
<em>Click on the image to describe the region</em>
) : (
<em>Upload an image to describe the region</em>
)
)}
</div>
<div className="description-controls">
<button
onClick={handleCopyDescription}
disabled={descriptionState.state !== 'described'}
>
Copy description
</button>
<button
onClick={handleNewRegion}
disabled={descriptionState.state !== 'described'}
>
Describe a new region
</button>
<button
onClick={handleReset}
className="reset-button"
disabled={descriptionState.state === 'describing' || !image}
>
Try a new image
</button>
</div>
</div>
</div>
);
};
export default App;
|