UNPKG

react-native-executorch

Version:

An easy way to run AI models in React Native with ExecuTorch

69 lines (68 loc) 2.42 kB
"use strict"; import { symbols } from '../constants/ocr/symbols'; import { ETError, getError } from '../Error'; import { ResourceFetcher } from '../utils/ResourceFetcher'; export class OCRController { isReady = false; isGenerating = false; error = null; constructor({ isReadyCallback = _isReady => {}, isGeneratingCallback = _isGenerating => {}, errorCallback = _error => {} } = {}) { this.isReadyCallback = isReadyCallback; this.isGeneratingCallback = isGeneratingCallback; this.errorCallback = errorCallback; } load = async (detectorSource, recognizerSources, language, onDownloadProgressCallback) => { 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 paths = await ResourceFetcher.fetch(onDownloadProgressCallback, detectorSource, recognizerSources.recognizerLarge, recognizerSources.recognizerMedium, recognizerSources.recognizerSmall); if (paths === null || paths?.length < 4) { throw new Error('Download interrupted!'); } this.nativeModule = global.loadOCR(paths[0], paths[1], paths[2], paths[3], 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 imageSource => { 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.generate(imageSource); } catch (e) { throw new Error(getError(e)); } finally { this.isGenerating = false; this.isGeneratingCallback(this.isGenerating); } }; delete() { if (this.isGenerating) { throw new Error(getError(ETError.ModelGenerating) + ', You cannot delete the model. You must wait until the generating is finished.'); } this.nativeModule.unload(); this.isReadyCallback(false); this.isGeneratingCallback(false); } } //# sourceMappingURL=OCRController.js.map