Ошибка: невозможно прочитать как файл при загрузке модели - PullRequest
1 голос
/ 25 апреля 2020

Я думаю, что я делаю ошибку новичка, но у меня возникают проблемы с выяснением, что идет не так.

Ошибка:

C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing>node classify rlc.jpg (node:38620) UnhandledPromiseRejectionWarning: Error: cannot read as File: "model.json" at readFile (C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\filereader\FileReader.js:266:15) at FileReader.self.readAsText (C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\filereader\FileReader.js:295:7) at C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@tensorflow\tfjs-core\dist\io\browser_files.js:226:36 at new Promise (<anonymous>) at BrowserFiles.<anonymous> (C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@tensorflow\tfjs-core\dist\io\browser_files.js:159:39) at step (C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@tensorflow\tfjs-core\dist\io\browser_files.js:48:23) at Object.next (C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@tensorflow\tfjs-core\dist\io\browser_files.js:29:53) at C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@tensorflow\tfjs-core\dist\io\browser_files.js:23:71 at new Promise (<anonymous>) at __awaiter (C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@tensorflow\tfjs-core\dist\io\browser_files.js:19:12) (node:38620) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag - необработанные отклонения = строгий (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2) (node:38620) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Код:

const tf = require('@tensorflow/tfjs');
const tfnode = require('@tensorflow/tfjs-node');
const tmImage = require('@teachablemachine/image');
const fs = require('fs');
global.FileReader = require('filereader');
const uploadModel =  "model.json"
const uploadWeights = "weights.bin"
const uploadMetadata = "metadata.json"

const readImage = path => {
    const imageBuffer = fs.readFileSync(path);
    const tfimage = tfnode.node.decodeImage(imageBuffer);
    return tfimage;
}

const imageClassification = async path => {
    const image = readImage(path);
    const model = await tmImage.loadFromFiles(uploadModel,uploadWeights,uploadMetadata);
    const predictions = await model.predict(image);
    console.log('Classification Results:', predictions);
}

if (process.argv.length !== 3) throw new Error('Incorrect arguments: node classify.js <IMAGE_FILE>');

imageClassification(process.argv[2]);

Структура файла:

/Testing
  /node_modules
  classify.js
  metadata.json
  model.json
  package-lock.json
  rlc.jpg
  weights.bin

Справочная информация: попытка взять то, что я узнал, с использованием модели классификации изображений, встроенной в обучаемую машину с собственным javascript и адаптировать его к node js. Я новичок и спотыкаюсь об отличиях среды между узлом и браузером, на которых основаны все учебники, на которых я следую.

Обучающие программы Я следующие:

1 Ответ

1 голос
/ 25 апреля 2020

Библиотека ожидает файл в функции loadFromFiles, документация в github . Файл API браузера , который вы не можете использовать в узле по умолчанию. Поэтому вам нужно каким-то образом заполнить это в среде узлов, посмотрите эти библиотеки node-fetch / fetch-blob node-file-api / file-api

Пример использование с file-api:

const fs = require('fs');
const path = require('path');
const FileAPI = require('file-api');

const uploadModel =  "model.json"
const uploadModelPath = path.join(process.cwd(), uploadModel);

// polyfill
Object.keys(FileApi).forEach(key => { 
    process[key] = FileApi[key];
})

const uploadModelFile = new File({ 
  buffer: fs.readFileSync(uploadModelPath)
});

Эта библиотека довольно старая и может не работать, вы можете попробовать поискать другие библиотеки polyfill или написать свою. Вы можете увидеть, как файл читается в исходном коде тензорного потока , или вы можете разветвить и добавить возможность работать с файлами узлов.

...