createOrtValue method
Creates an OrtValue from data
sourceType
is the source data type (e.g., 'float32', 'int32')
data
is the data to create the tensor from
shape
is the shape of the tensor
Implementation
@override
Future<Map<String, dynamic>> createOrtValue(String sourceType, dynamic data, List<int> shape) async {
try {
// Convert shape to JavaScript array
final jsShape = jsArrayFrom(shape);
// Map the source type to onnxruntime-web data type
final dataType = _mapSourceTypeToOrtType(sourceType);
// Handle different data types
JSObject tensor;
switch (sourceType) {
case 'float32':
// Convert data to Float32Array
final jsData = _convertToTypedArray(data, 'Float32Array');
tensor = tensorConstructor.callAsConstructorVarArgs([dataType.toJS, jsData, jsShape]);
break;
case 'int32':
// Convert data to Int32Array
final jsData = _convertToTypedArray(data, 'Int32Array');
tensor = tensorConstructor.callAsConstructorVarArgs([dataType.toJS, jsData, jsShape]);
break;
case 'int64':
// Note: JavaScript doesn't have Int64Array, so using BigInt64Array
// This might require special handling depending on browser support
final jsData = _convertToTypedArray(data, 'BigInt64Array');
tensor = tensorConstructor.callAsConstructorVarArgs([dataType.toJS, jsData, jsShape]);
break;
case 'uint8':
// Convert data to Uint8Array
final jsData = _convertToTypedArray(data, 'Uint8Array');
tensor = tensorConstructor.callAsConstructorVarArgs([dataType.toJS, jsData, jsShape]);
break;
case 'bool':
// For boolean tensors, ONNX Runtime uses a Uint8Array with 0/1 values
// Make sure we properly handle all possible incoming bool representations
final boolArray =
(data as List).map((value) {
if (value is bool) {
return value ? 1 : 0;
} else if (value is num) {
return value != 0 ? 1 : 0;
} else {
return value == true ? 1 : 0;
}
}).toList();
final jsData = _convertToTypedArray(boolArray, 'Uint8Array');
tensor = tensorConstructor.callAsConstructorVarArgs([dataType.toJS, jsData, jsShape]);
break;
case 'string':
// For string tensors, we use the standard JavaScript Array
// ONNX Runtime JS API accepts string arrays for string tensors
final stringArray = jsArrayFrom((data as List<String>).toList());
tensor = tensorConstructor.callAsConstructorVarArgs([dataType.toJS, stringArray, jsShape]);
break;
default:
throw PlatformException(
code: "UNSUPPORTED_TYPE",
message: "Unsupported data type: $sourceType",
details: null,
);
}
// Generate a unique ID for this tensor
final valueId = '${DateTime.now().millisecondsSinceEpoch}_${math.Random().nextInt(10000)}';
// Store the tensor
_ortValues[valueId] = tensor;
// Return the tensor information
return {'valueId': valueId, 'dataType': sourceType, 'shape': shape};
} catch (e) {
if (e is PlatformException) {
rethrow;
}
throw PlatformException(code: "TENSOR_CREATION_ERROR", message: "Failed to create OrtValue: $e", details: null);
}
}