2021-04-27 07:04:25 +00:00
|
|
|
// Copyright (c) Microsoft Corporation. All rights reserved.
|
|
|
|
|
// Licensed under the MIT License.
|
|
|
|
|
|
2021-11-24 22:14:42 +00:00
|
|
|
import * as base64 from 'base64-js';
|
2023-10-06 20:37:37 +00:00
|
|
|
import * as fs from 'node:fs/promises';
|
2021-04-27 07:04:25 +00:00
|
|
|
|
|
|
|
|
import {Attribute} from '../lib/onnxjs/attribute';
|
|
|
|
|
import {Graph} from '../lib/onnxjs/graph';
|
|
|
|
|
|
|
|
|
|
export function base64toBuffer(data: string): Uint8Array {
|
2021-11-24 22:14:42 +00:00
|
|
|
return base64.toByteArray(data);
|
2021-04-27 07:04:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function bufferToBase64(buffer: Uint8Array): string {
|
2021-11-24 22:14:42 +00:00
|
|
|
return base64.fromByteArray(buffer);
|
2021-04-27 07:04:25 +00:00
|
|
|
}
|
|
|
|
|
|
2024-03-27 04:35:49 +00:00
|
|
|
async function retry<T>(fn: () => Promise<T>, maxRetries = 3, delay = 100): Promise<T> {
|
|
|
|
|
let retries = maxRetries;
|
|
|
|
|
do {
|
|
|
|
|
try {
|
|
|
|
|
return await fn();
|
|
|
|
|
} catch (err) {
|
|
|
|
|
if (retries-- === 0) {
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
|
|
|
}
|
|
|
|
|
// eslint-disable-next-line no-constant-condition
|
|
|
|
|
} while (true);
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-20 07:20:58 +00:00
|
|
|
export async function readFile(file: string) {
|
|
|
|
|
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
|
2021-04-27 07:04:25 +00:00
|
|
|
// node
|
2023-10-06 20:37:37 +00:00
|
|
|
return fs.readFile(file);
|
2021-04-27 07:04:25 +00:00
|
|
|
} else {
|
|
|
|
|
// browser
|
2024-03-27 04:35:49 +00:00
|
|
|
//
|
|
|
|
|
// use "retry" to workaround the error "TypeError: Failed to fetch" in some test environments
|
|
|
|
|
return retry(async () => {
|
|
|
|
|
const response = await fetch(file);
|
|
|
|
|
return new Uint8Array(await response.arrayBuffer());
|
|
|
|
|
});
|
2021-04-27 07:04:25 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function readJsonFile(file: string): Promise<any> {
|
|
|
|
|
const content = await readFile(file);
|
2021-11-24 22:14:42 +00:00
|
|
|
return JSON.parse(new TextDecoder().decode(content));
|
2021-04-27 07:04:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* create a single-node graph for unit test purpose
|
|
|
|
|
*/
|
|
|
|
|
export function createMockGraph(opType: string, attributes: Attribute): Graph {
|
|
|
|
|
const node: Graph.Node = {name: '', opType, inputs: [], outputs: [], attributes};
|
|
|
|
|
return {
|
|
|
|
|
getInputIndices: () => [],
|
|
|
|
|
getInputNames: () => [],
|
|
|
|
|
getOutputIndices: () => [],
|
|
|
|
|
getOutputNames: () => [],
|
|
|
|
|
getNodes: () => [node],
|
|
|
|
|
getValues: () => []
|
|
|
|
|
};
|
|
|
|
|
}
|