UNPKG

react-native-executorch

Version:

An easy way to run AI models in react native with ExecuTorch

67 lines (66 loc) 2.73 kB
"use strict"; import { symbols } from '../constants/ocr/symbols'; import { ETError, getError } from '../Error'; import { _OCRModule } from '../native/RnExecutorchModules'; import { fetchResource, calculateDownloadProgres } from '../utils/fetchResource'; export class OCRController { isReady = false; isGenerating = false; error = null; constructor({ modelDownloadProgressCallback = _downloadProgress => {}, isReadyCallback = _isReady => {}, isGeneratingCallback = _isGenerating => {}, errorCallback = _error => {} }) { this.nativeModule = new _OCRModule(); this.modelDownloadProgressCallback = modelDownloadProgressCallback; this.isReadyCallback = isReadyCallback; this.isGeneratingCallback = isGeneratingCallback; this.errorCallback = errorCallback; } loadModel = async (detectorSource, recognizerSources, language) => { try { if (!detectorSource || Object.keys(recognizerSources).length !== 3) return; if (!symbols[language]) { throw new Error(getError(ETError.LanguageNotSupported)); } this.isReady = false; this.isReadyCallback(false); const detectorPath = await fetchResource(detectorSource, calculateDownloadProgres(4, 0, this.modelDownloadProgressCallback)); const recognizerPaths = { recognizerLarge: await fetchResource(recognizerSources.recognizerLarge, calculateDownloadProgres(4, 1, this.modelDownloadProgressCallback)), recognizerMedium: await fetchResource(recognizerSources.recognizerMedium, calculateDownloadProgres(4, 2, this.modelDownloadProgressCallback)), recognizerSmall: await fetchResource(recognizerSources.recognizerSmall, calculateDownloadProgres(4, 3, this.modelDownloadProgressCallback)) }; await this.nativeModule.loadModule(detectorPath, recognizerPaths.recognizerLarge, recognizerPaths.recognizerMedium, recognizerPaths.recognizerSmall, symbols[language]); this.isReady = true; this.isReadyCallback(this.isReady); } catch (e) { if (this.errorCallback) { this.errorCallback(getError(e)); } else { throw new Error(getError(e)); } } }; forward = async input => { if (!this.isReady) { throw new Error(getError(ETError.ModuleNotLoaded)); } if (this.isGenerating) { throw new Error(getError(ETError.ModelGenerating)); } try { this.isGenerating = true; this.isGeneratingCallback(this.isGenerating); return await this.nativeModule.forward(input); } catch (e) { throw new Error(getError(e)); } finally { this.isGenerating = false; this.isGeneratingCallback(this.isGenerating); } }; } //# sourceMappingURL=OCRController.js.map