Spaces:
Running
Running
File size: 10,359 Bytes
9bd422a | 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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | # ONNX Model Explorer β API Reference
All modules are loaded as plain `<script>` tags and exposed on `window`. No import/export syntax is used at runtime.
---
## ModelLoader
**File:** `js/core/modelLoader.js`
**Global:** `window.ModelLoader`
Loads the model registry from `models/models.json` and fetches individual `.onnx` files. Also handles file uploads from the user.
### Constructor
```js
const loader = new ModelLoader();
```
### Methods
#### `loadModelList(configPath?)`
Fetches and parses `models/models.json`. Results are cached in memory after the first call.
| Parameter | Type | Default | Description |
|---|---|---|---|
| `configPath` | `string` | `CONFIG.MODELS_CONFIG_FILE` | Path to the JSON registry file |
**Returns:** `Promise<ModelInfo[]>`
```js
const models = await loader.loadModelList();
// [{ id, name, description, path, category, version, size, labelsFile }, ...]
```
On error (network failure, invalid JSON), logs to console and returns `[]`.
---
#### `loadModelFile(filePath)`
Fetches a `.onnx` file and returns its raw bytes.
| Parameter | Type | Description |
|---|---|---|
| `filePath` | `string` | Relative or absolute URL to the `.onnx` file |
**Returns:** `Promise<ArrayBuffer>`
**Throws:** `Error` if the HTTP request fails.
```js
const buffer = await loader.loadModelFile('models/ppe/model.onnx');
```
---
#### `handleFileUpload(file)`
Validates and reads a `File` object (from `<input type="file">` or drag-and-drop).
| Parameter | Type | Description |
|---|---|---|
| `file` | `File` | Browser `File` object |
**Returns:** `Promise<{ success: boolean, data?: ArrayBuffer, error?: string }>`
```js
const result = await loader.handleFileUpload(file);
if (result.success) {
// result.data is an ArrayBuffer
} else {
console.error(result.error);
}
```
Validation rules (from `CONFIG.FILE`):
- Extension must be `.onnx`
- File size must not exceed `CONFIG.FILE.MAX_FILE_SIZE`
---
### Types
```ts
interface ModelInfo {
id: string;
name: string;
description: string;
path: string;
category: string;
version: string;
size: number;
labelsFile: string | null;
}
```
---
## ONNXParser
**File:** `js/core/onnxParser.js`
**Global:** `window.ONNXParser`
Parses an ONNX model `ArrayBuffer` using the ONNX.js library (must be loaded from CDN before use).
### Constructor
```js
const parser = new ONNXParser();
```
### Methods
#### `parseModel(modelBuffer, options?)`
Decodes the protobuf and extracts all model information.
| Parameter | Type | Description |
|---|---|---|
| `modelBuffer` | `ArrayBuffer` | Raw bytes of the `.onnx` file |
| `options` | `object` | Optional overrides (e.g. `{ fileName, fileSize }`) |
**Returns:** `Promise<ParsedModel>`
**Throws:** `Error` if ONNX.js is not loaded, the buffer is empty, or parsing fails.
```js
const parsed = await parser.parseModel(buffer, { fileName: 'model.onnx' });
```
---
### Types
```ts
interface ParsedModel {
metadata: ModelMetadata;
graph: GraphStructure;
inputs: TensorInfo[];
outputs: TensorInfo[];
initializers: InitializerInfo[];
}
interface ModelMetadata {
producerName: string;
producerVersion: string;
opsetVersion: number;
irVersion: number;
customAttributes: Record<string, any>;
fileName: string;
fileSize: number;
loadedAt: number; // Unix timestamp (ms)
}
interface GraphStructure {
name: string;
nodes: NodeInfo[];
edges: EdgeInfo[];
initializers: InitializerInfo[];
}
interface NodeInfo {
id: string;
name: string;
opType: string;
attributes: Record<string, any>;
inputs: string[];
outputs: string[];
domain: string;
}
interface EdgeInfo {
source: string; // node id
target: string; // node id
label: string; // tensor name
}
interface TensorInfo {
name: string;
shape: (number | string)[];
dataType: string;
description?: string;
isOptional?: boolean;
}
interface InitializerInfo {
name: string;
shape: number[];
dataType: string;
size: number; // bytes
elementCount: number;
}
```
---
## GraphProcessor
**File:** `js/core/graphProcessor.js`
**Global:** `window.GraphProcessor`
Converts a `ParsedModel` into Cytoscape.js element descriptors. Automatically clusters nodes by `opType` when the graph exceeds `CONFIG.PERFORMANCE.LAZY_LOAD_THRESHOLD` nodes.
### Constructor
```js
const processor = new GraphProcessor();
```
### Methods
#### `processGraph(parsedModel)`
Builds the full list of Cytoscape elements (nodes + edges) from a parsed model.
| Parameter | Type | Description |
|---|---|---|
| `parsedModel` | `ParsedModel` | Output of `ONNXParser.parseModel()` |
**Returns:** `{ elements: CytoscapeElement[], stats: GraphStats }`
```js
const { elements, stats } = processor.processGraph(parsedModel);
// Pass elements directly to cytoscape({ elements })
```
Node classes assigned:
- `input-node` β model input tensors
- `output-node` β model output tensors
- `initializer-node` β constant weight tensors
- `op-node` β computation operators
- `op-node cluster-node` β clustered operators (large graphs)
---
### Types
```ts
interface GraphStats {
nodeCount: number;
edgeCount: number;
initializerCount: number;
inputCount: number;
outputCount: number;
clusterCount?: number; // present when isClustered is true
isClustered?: boolean;
}
```
---
## StateManager
**File:** `js/state/stateManager.js`
**Global:** `window.StateManager`
Singleton that holds all application state. Components read state via getters and react to changes via subscriptions.
### State Shape
```ts
interface AppState {
currentModel: ParsedModel | null;
modelList: ModelInfo[];
selectedNodeId: string | null;
zoomLevel: number;
viewMode: 'single' | 'comparison';
comparisonModel: ParsedModel | null;
searchQuery: string;
filteredModelList: ModelInfo[];
error: { message: string; type: 'error' | 'warning' | 'info'; timestamp: number } | null;
isLoading: boolean;
loadingProgress: number; // 0β100
}
```
### Getters
| Method | Returns | Description |
|---|---|---|
| `getState()` | `AppState` | Shallow copy of the full state |
| `getCurrentModel()` | `ParsedModel\|null` | Currently loaded model |
| `getModelList()` | `ModelInfo[]` | Full model registry |
| `getFilteredModelList()` | `ModelInfo[]` | Search-filtered model list |
| `getSearchQuery()` | `string` | Current search string |
| `getSelectedNodeId()` | `string\|null` | Selected graph node id |
| `getZoomLevel()` | `number` | Current zoom level |
| `getViewMode()` | `'single'\|'comparison'` | Current view mode |
| `getComparisonModel()` | `ParsedModel\|null` | Second model in comparison mode |
| `getError()` | `ErrorState\|null` | Current error, or null |
| `isLoading()` | `boolean` | Whether a load is in progress |
| `getLoadingProgress()` | `number` | Load progress 0β100 |
### Setters
Each setter updates the corresponding state key and notifies subscribers.
| Method | Parameter | Description |
|---|---|---|
| `setCurrentModel(model)` | `ParsedModel\|null` | Set current model; persists id to `localStorage` |
| `setModelList(list)` | `ModelInfo[]` | Replace the full model list |
| `setFilteredModelList(list)` | `ModelInfo[]` | Replace the filtered list |
| `setSearchQuery(query)` | `string` | Update search query |
| `setSelectedNodeId(id)` | `string\|null` | Update selected node |
| `setZoomLevel(level)` | `number` | Update zoom level |
| `setViewMode(mode)` | `'single'\|'comparison'` | Switch view mode |
| `setComparisonModel(model)` | `ParsedModel\|null` | Set comparison model |
| `setError(message, type?)` | `string, string` | Set error state (`type` defaults to `'error'`) |
| `clearError()` | β | Clear current error |
| `setLoading(loading)` | `boolean` | Toggle loading state |
| `setLoadingProgress(n)` | `number` | Update progress 0β100 |
### Subscription
#### `subscribe(key, callback)`
Subscribe to changes on a specific state key. Use `'*'` to receive all changes.
| Parameter | Type | Description |
|---|---|---|
| `key` | `string` | State key name, or `'*'` for all |
| `callback` | `(newValue, oldValue, key) => void` | Called on every change |
**Returns:** `Function` β call it to unsubscribe.
```js
const unsub = StateManager.subscribe('currentModel', (model) => {
console.log('Model changed:', model);
});
// Later:
unsub();
```
#### `unsubscribe(key, callback)`
Remove a specific callback without using the returned unsubscribe function.
#### `reset()`
Resets all state to initial values. Primarily used in tests.
#### `getPersistedSelectedModelId()`
Returns the model id stored in `localStorage` from the previous session, or `null`.
---
## EventBus
**File:** `js/core/eventBus.js`
**Global:** `window.EventBus`
Singleton pub/sub event bus for decoupled communication between components.
### Methods
#### `on(eventName, callback)`
Subscribe to an event.
| Parameter | Type | Description |
|---|---|---|
| `eventName` | `string` | Event name |
| `callback` | `(data: any) => void` | Handler |
**Returns:** `Function` β unsubscribe function.
```js
const off = EventBus.on('model:loaded', (model) => {
console.log('Loaded:', model.metadata.fileName);
});
```
#### `off(eventName, callback)`
Remove a specific handler.
#### `emit(eventName, data?)`
Emit an event to all subscribers. Errors thrown inside handlers are caught and logged.
```js
EventBus.emit('model:selected', { id: 'ppe' });
```
#### `once(eventName, callback)`
Subscribe for a single invocation, then auto-unsubscribe.
#### `clear(eventName?)`
Remove all listeners for `eventName`, or all listeners if omitted.
#### `listenerCount(eventName)`
Returns the number of active listeners for an event (useful for debugging).
### Standard Events
| Event | Payload | Description |
|---|---|---|
| `model:loaded` | `ParsedModel` | A model was successfully parsed |
| `model:selected` | `ModelInfo` | User selected a model from the list |
| `node:selected` | `string` (node id) | User clicked a graph node |
| `search:updated` | `string` (query) | Search field changed |
| `error:occurred` | `{ message, type }` | An error was raised |
| `export:requested` | `ParsedModel` | User clicked Export |
| `comparison:started` | `ParsedModel` | Comparison mode activated |
| `comparison:ended` | β | Comparison mode exited |
|