import { Tensor } from '@tensorflow/tfjs' ; import { onnx } from 'onnx-proto' ; import { parseTensor } from './onnx_util' ; export function normalizeArrayToObj < T > ( array , indexKey ) { const normalizedObject = { } ; for ( let i = 0 ; i < array . length ; i ++ ) { const key = array [ i ] [ indexKey ] ; normalizedObject [ key ] = array [ i ] ; } return normalizedObject as { [ key ] : T ; } ; } export function joinArraysToObj < T > ( keys , values ) { const normalizedObject = { } ; for ( let i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; normalizedObject [ key ] = values [ i ] ; } return normalizedObject as { [ key ] : T ; } ; } export function isNotNull ( val ) { return val !== undefined && val !== null ; } export function fetchText ( uri ) { return fetch ( new Request ( uri ) ) . then ( handleFetchErrors ) . then ( ( res ) => res . text ( ) ) ; } export function fetchArrayBuffer ( uri ) { return fetch ( new Request ( uri ) ) . then ( handleFetchErrors ) . then ( ( res ) => res . arrayBuffer ( ) ) ; } function handleFetchErrors ( response ) { if ( ! response . ok ) { throw Error ( response . statusText ) ; } return response ; } export function parseOnnxModel ( data ) { return onnx . ModelProto . decode ( new Uint8Array ( data ) ) ; } export function getNamedAttrs < T > ( attrs ? ) { return < any > normalizeArrayToObj ( attrs , 'name' ) as T ; } export async function loadOnnxModel ( modelUrl ) { const buffer = await fetchArrayBuffer ( modelUrl ) ; return await parseOnnxModel ( buffer ) ; } export function getBlobValues ( graph ) { const blobs = graph . initializer ; const weights = blobs . map ( ( d ) => parseTensor ( d ) ) ; const names = blobs . map ( getLayerName ) ; return joinArraysToObj ( names , weights ) ; } export function getValueInfo ( valueInfo ) { const getDimValues = ( shape ) => shape . dim . map ( d => d . dimValue ) as number [ ] ; const shapes = valueInfo . map ( d => d . type . tensorType . shape ) . map ( getDimValues ) ; const names = valueInfo . map ( getLayerName ) ; return joinArraysToObj ( names , shapes ) ; } export function getBlobShapes ( graph ) { const inputShapes = getValueInfo ( graph . input ) ; const outputShapes = getValueInfo ( graph . output ) ; return Object . assign ( { } , inputShapes , outputShapes ) ; } export function getLayerName ( node ) { return node . name ? node . name : node . output [ 0 ] ; } export function getNodes ( graph ) { const nodes = graph . node ; const names = nodes . map ( getLayerName ) ; return joinArraysToObj ( names , nodes ) ; } export function loadImageData ( url ) { const img = new Image ( ) ; return new Promise ( ( resolve , reject ) => { img . crossOrigin = 'anonymous' ; img . src = url ; img . onload = ( ) => resolve ( img ) ; img . onerror = reject ; } ) ; }