toNetInput.js 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var tslib_1 = require("tslib");
  4. var utils_1 = require("../utils");
  5. var awaitMediaLoaded_1 = require("./awaitMediaLoaded");
  6. var isMediaElement_1 = require("./isMediaElement");
  7. var NetInput_1 = require("./NetInput");
  8. var resolveInput_1 = require("./resolveInput");
  9. /**
  10. * Validates the input to make sure, they are valid net inputs and awaits all media elements
  11. * to be finished loading.
  12. *
  13. * @param input The input, which can be a media element or an array of different media elements.
  14. * @returns A NetInput instance, which can be passed into one of the neural networks.
  15. */
  16. function toNetInput(inputs) {
  17. return tslib_1.__awaiter(this, void 0, void 0, function () {
  18. var inputArgArray, getIdxHint, inputArray;
  19. return tslib_1.__generator(this, function (_a) {
  20. switch (_a.label) {
  21. case 0:
  22. if (inputs instanceof NetInput_1.NetInput) {
  23. return [2 /*return*/, inputs];
  24. }
  25. inputArgArray = Array.isArray(inputs)
  26. ? inputs
  27. : [inputs];
  28. if (!inputArgArray.length) {
  29. throw new Error('toNetInput - empty array passed as input');
  30. }
  31. getIdxHint = function (idx) { return Array.isArray(inputs) ? " at input index " + idx + ":" : ''; };
  32. inputArray = inputArgArray.map(resolveInput_1.resolveInput);
  33. inputArray.forEach(function (input, i) {
  34. if (!isMediaElement_1.isMediaElement(input) && !utils_1.isTensor3D(input) && !utils_1.isTensor4D(input)) {
  35. if (typeof inputArgArray[i] === 'string') {
  36. throw new Error("toNetInput -" + getIdxHint(i) + " string passed, but could not resolve HTMLElement for element id " + inputArgArray[i]);
  37. }
  38. throw new Error("toNetInput -" + getIdxHint(i) + " expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id");
  39. }
  40. if (utils_1.isTensor4D(input)) {
  41. // if tf.Tensor4D is passed in the input array, the batch size has to be 1
  42. var batchSize = input.shape[0];
  43. if (batchSize !== 1) {
  44. throw new Error("toNetInput -" + getIdxHint(i) + " tf.Tensor4D with batchSize " + batchSize + " passed, but not supported in input array");
  45. }
  46. }
  47. });
  48. // wait for all media elements being loaded
  49. return [4 /*yield*/, Promise.all(inputArray.map(function (input) { return isMediaElement_1.isMediaElement(input) && awaitMediaLoaded_1.awaitMediaLoaded(input); }))];
  50. case 1:
  51. // wait for all media elements being loaded
  52. _a.sent();
  53. return [2 /*return*/, new NetInput_1.NetInput(inputArray, Array.isArray(inputs))];
  54. }
  55. });
  56. });
  57. }
  58. exports.toNetInput = toNetInput;
  59. //# sourceMappingURL=toNetInput.js.map