react-native-executorch
Version:
An easy way to run AI models in React Native with ExecuTorch
71 lines (70 loc) • 2.88 kB
JavaScript
import { symbols } from '../constants/ocr/symbols';
import { ETError, getError } from '../Error';
import { VerticalOCRNativeModule } from '../native/RnExecutorchModules';
import { ResourceFetcher } from '../utils/ResourceFetcher';
export class VerticalOCRController {
ocrNativeModule;
isReady = false;
isGenerating = false;
error = null;
modelDownloadProgressCallback;
isReadyCallback;
isGeneratingCallback;
errorCallback;
constructor({ modelDownloadProgressCallback = (_downloadProgress) => { }, isReadyCallback = (_isReady) => { }, isGeneratingCallback = (_isGenerating) => { }, errorCallback = (_error) => { }, }) {
this.ocrNativeModule = VerticalOCRNativeModule;
this.modelDownloadProgressCallback = modelDownloadProgressCallback;
this.isReadyCallback = isReadyCallback;
this.isGeneratingCallback = isGeneratingCallback;
this.errorCallback = errorCallback;
}
loadModel = async (detectorSources, recognizerSources, language, independentCharacters) => {
try {
if (Object.keys(detectorSources).length !== 2 ||
Object.keys(recognizerSources).length !== 2)
return;
if (!symbols[language]) {
throw new Error(getError(ETError.LanguageNotSupported));
}
this.isReady = false;
this.isReadyCallback(this.isReady);
const paths = await ResourceFetcher.fetch(this.modelDownloadProgressCallback, detectorSources.detectorLarge, detectorSources.detectorNarrow, independentCharacters
? recognizerSources.recognizerSmall
: recognizerSources.recognizerLarge);
if (paths === null || paths.length < 3) {
throw new Error('Download interrupted');
}
await this.ocrNativeModule.loadModule(paths[0], paths[1], paths[2], symbols[language], independentCharacters);
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.ocrNativeModule.forward(input);
}
catch (e) {
throw new Error(getError(e));
}
finally {
this.isGenerating = false;
this.isGeneratingCallback(this.isGenerating);
}
};
}