react-native-executorch 0.5.7 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/lib/Error.js +53 -0
  2. package/lib/ThreadPool.d.ts +10 -0
  3. package/lib/ThreadPool.js +28 -0
  4. package/lib/common/Logger.d.ts +8 -0
  5. package/lib/common/Logger.js +19 -0
  6. package/lib/constants/directories.js +2 -0
  7. package/lib/constants/llmDefaults.d.ts +6 -0
  8. package/lib/constants/llmDefaults.js +16 -0
  9. package/lib/constants/modelUrls.d.ts +223 -0
  10. package/lib/constants/modelUrls.js +322 -0
  11. package/lib/constants/ocr/models.d.ts +882 -0
  12. package/lib/constants/ocr/models.js +182 -0
  13. package/lib/constants/ocr/symbols.js +139 -0
  14. package/lib/constants/sttDefaults.d.ts +28 -0
  15. package/lib/constants/sttDefaults.js +68 -0
  16. package/lib/controllers/LLMController.d.ts +47 -0
  17. package/lib/controllers/LLMController.js +213 -0
  18. package/lib/controllers/OCRController.js +67 -0
  19. package/lib/controllers/SpeechToTextController.d.ts +56 -0
  20. package/lib/controllers/SpeechToTextController.js +349 -0
  21. package/lib/controllers/VerticalOCRController.js +70 -0
  22. package/lib/hooks/computer_vision/useClassification.d.ts +15 -0
  23. package/lib/hooks/computer_vision/useClassification.js +7 -0
  24. package/lib/hooks/computer_vision/useImageEmbeddings.d.ts +15 -0
  25. package/lib/hooks/computer_vision/useImageEmbeddings.js +7 -0
  26. package/lib/hooks/computer_vision/useImageSegmentation.d.ts +38 -0
  27. package/lib/hooks/computer_vision/useImageSegmentation.js +7 -0
  28. package/lib/hooks/computer_vision/useOCR.d.ts +20 -0
  29. package/lib/hooks/computer_vision/useOCR.js +41 -0
  30. package/lib/hooks/computer_vision/useObjectDetection.d.ts +15 -0
  31. package/lib/hooks/computer_vision/useObjectDetection.js +7 -0
  32. package/lib/hooks/computer_vision/useStyleTransfer.d.ts +15 -0
  33. package/lib/hooks/computer_vision/useStyleTransfer.js +7 -0
  34. package/lib/hooks/computer_vision/useVerticalOCR.d.ts +21 -0
  35. package/lib/hooks/computer_vision/useVerticalOCR.js +43 -0
  36. package/lib/hooks/general/useExecutorchModule.d.ts +13 -0
  37. package/lib/hooks/general/useExecutorchModule.js +7 -0
  38. package/lib/hooks/natural_language_processing/useLLM.d.ts +10 -0
  39. package/lib/hooks/natural_language_processing/useLLM.js +78 -0
  40. package/lib/hooks/natural_language_processing/useSpeechToText.d.ts +27 -0
  41. package/lib/hooks/natural_language_processing/useSpeechToText.js +49 -0
  42. package/lib/hooks/natural_language_processing/useTextEmbeddings.d.ts +16 -0
  43. package/lib/hooks/natural_language_processing/useTextEmbeddings.js +7 -0
  44. package/lib/hooks/natural_language_processing/useTokenizer.d.ts +17 -0
  45. package/lib/hooks/natural_language_processing/useTokenizer.js +52 -0
  46. package/lib/hooks/useModule.js +45 -0
  47. package/lib/hooks/useNonStaticModule.d.ts +20 -0
  48. package/lib/hooks/useNonStaticModule.js +49 -0
  49. package/lib/index.d.ts +48 -0
  50. package/lib/index.js +58 -0
  51. package/lib/module/modules/natural_language_processing/LLMModule.js +3 -0
  52. package/lib/module/modules/natural_language_processing/LLMModule.js.map +1 -1
  53. package/lib/modules/BaseModule.js +25 -0
  54. package/lib/modules/BaseNonStaticModule.js +14 -0
  55. package/lib/modules/computer_vision/ClassificationModule.d.ts +8 -0
  56. package/lib/modules/computer_vision/ClassificationModule.js +17 -0
  57. package/lib/modules/computer_vision/ImageEmbeddingsModule.d.ts +8 -0
  58. package/lib/modules/computer_vision/ImageEmbeddingsModule.js +17 -0
  59. package/lib/modules/computer_vision/ImageSegmentationModule.d.ts +11 -0
  60. package/lib/modules/computer_vision/ImageSegmentationModule.js +27 -0
  61. package/lib/modules/computer_vision/OCRModule.d.ts +14 -0
  62. package/lib/modules/computer_vision/OCRModule.js +17 -0
  63. package/lib/modules/computer_vision/ObjectDetectionModule.d.ts +9 -0
  64. package/lib/modules/computer_vision/ObjectDetectionModule.js +17 -0
  65. package/lib/modules/computer_vision/StyleTransferModule.d.ts +8 -0
  66. package/lib/modules/computer_vision/StyleTransferModule.js +17 -0
  67. package/lib/modules/computer_vision/VerticalOCRModule.d.ts +14 -0
  68. package/lib/modules/computer_vision/VerticalOCRModule.js +19 -0
  69. package/lib/modules/general/ExecutorchModule.d.ts +7 -0
  70. package/lib/modules/general/ExecutorchModule.js +14 -0
  71. package/lib/modules/natural_language_processing/LLMModule.d.ts +28 -0
  72. package/lib/modules/natural_language_processing/LLMModule.js +45 -0
  73. package/lib/modules/natural_language_processing/SpeechToTextModule.d.ts +24 -0
  74. package/lib/modules/natural_language_processing/SpeechToTextModule.js +36 -0
  75. package/lib/modules/natural_language_processing/TextEmbeddingsModule.d.ts +9 -0
  76. package/lib/modules/natural_language_processing/TextEmbeddingsModule.js +21 -0
  77. package/lib/modules/natural_language_processing/TokenizerModule.d.ts +12 -0
  78. package/lib/modules/natural_language_processing/TokenizerModule.js +30 -0
  79. package/lib/native/NativeETInstaller.js +2 -0
  80. package/lib/native/NativeOCR.js +2 -0
  81. package/lib/native/NativeVerticalOCR.js +2 -0
  82. package/lib/native/RnExecutorchModules.d.ts +7 -0
  83. package/lib/native/RnExecutorchModules.js +18 -0
  84. package/lib/tsconfig.tsbuildinfo +1 -0
  85. package/lib/types/common.d.ts +32 -0
  86. package/lib/types/common.js +25 -0
  87. package/lib/types/imageSegmentation.js +26 -0
  88. package/lib/types/llm.d.ts +46 -0
  89. package/lib/types/llm.js +9 -0
  90. package/lib/types/objectDetection.js +94 -0
  91. package/lib/types/ocr.js +1 -0
  92. package/lib/types/stt.d.ts +94 -0
  93. package/lib/types/stt.js +85 -0
  94. package/lib/typescript/modules/natural_language_processing/LLMModule.d.ts +1 -0
  95. package/lib/typescript/modules/natural_language_processing/LLMModule.d.ts.map +1 -1
  96. package/lib/typescript/types/llm.d.ts +1 -1
  97. package/lib/typescript/types/llm.d.ts.map +1 -1
  98. package/lib/utils/ResourceFetcher.d.ts +24 -0
  99. package/lib/utils/ResourceFetcher.js +305 -0
  100. package/lib/utils/ResourceFetcherUtils.d.ts +54 -0
  101. package/lib/utils/ResourceFetcherUtils.js +127 -0
  102. package/lib/utils/llm.d.ts +6 -0
  103. package/lib/utils/llm.js +72 -0
  104. package/lib/utils/stt.js +21 -0
  105. package/package.json +1 -1
  106. package/src/modules/natural_language_processing/LLMModule.ts +4 -0
  107. package/src/types/llm.ts +1 -1
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ import { DownloadResumable } from 'expo-file-system';
5
+ import { ResourceSource } from '../types/common';
6
+ export declare const enum HTTP_CODE {
7
+ OK = 200,
8
+ PARTIAL_CONTENT = 206
9
+ }
10
+ export declare const enum DownloadStatus {
11
+ ONGOING = 0,
12
+ PAUSED = 1
13
+ }
14
+ export declare const enum SourceType {
15
+ OBJECT = 0,
16
+ LOCAL_FILE = 1,
17
+ RELEASE_MODE_FILE = 2,
18
+ DEV_MODE_FILE = 3,
19
+ REMOTE_FILE = 4
20
+ }
21
+ export interface ResourceSourceExtended {
22
+ source: ResourceSource;
23
+ sourceType: SourceType;
24
+ callback?: (downloadProgress: number) => void;
25
+ results: string[];
26
+ uri?: string;
27
+ fileUri?: string;
28
+ cacheFileUri?: string;
29
+ next?: ResourceSourceExtended;
30
+ }
31
+ export interface DownloadResource {
32
+ downloadResumable: DownloadResumable;
33
+ status: DownloadStatus;
34
+ extendedInfo: ResourceSourceExtended;
35
+ }
36
+ export declare namespace ResourceFetcherUtils {
37
+ function getType(source: ResourceSource): SourceType;
38
+ function getFilesSizes(sources: ResourceSource[]): Promise<{
39
+ results: {
40
+ source: ResourceSource;
41
+ type: SourceType;
42
+ length: number;
43
+ previousFilesTotalLength: number;
44
+ }[];
45
+ totalLength: number;
46
+ }>;
47
+ function removeFilePrefix(uri: string): string;
48
+ function hashObject(jsonString: string): string;
49
+ function calculateDownloadProgress(totalLength: number, previousFilesTotalLength: number, currentFileLength: number, setProgress: (downloadProgress: number) => void): (progress: number) => void;
50
+ function triggerHuggingFaceDownloadCounter(uri: string): Promise<void>;
51
+ function createDirectoryIfNoExists(): Promise<void>;
52
+ function checkFileExists(fileUri: string): Promise<boolean>;
53
+ function getFilenameFromUri(uri: string): string;
54
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ import { getInfoAsync, makeDirectoryAsync, } from 'expo-file-system';
5
+ import { RNEDirectory } from '../constants/directories';
6
+ import { Asset } from 'expo-asset';
7
+ import { Logger } from '../common/Logger';
8
+ export var ResourceFetcherUtils;
9
+ (function (ResourceFetcherUtils) {
10
+ function getType(source) {
11
+ if (typeof source === 'object') {
12
+ return 0 /* SourceType.OBJECT */;
13
+ }
14
+ else if (typeof source === 'number') {
15
+ const uri = Asset.fromModule(source).uri;
16
+ if (!uri.includes('://')) {
17
+ return 2 /* SourceType.RELEASE_MODE_FILE */;
18
+ }
19
+ return 3 /* SourceType.DEV_MODE_FILE */;
20
+ }
21
+ else {
22
+ // typeof source == 'string'
23
+ if (source.startsWith('file://')) {
24
+ return 1 /* SourceType.LOCAL_FILE */;
25
+ }
26
+ return 4 /* SourceType.REMOTE_FILE */;
27
+ }
28
+ }
29
+ ResourceFetcherUtils.getType = getType;
30
+ async function getFilesSizes(sources) {
31
+ const results = [];
32
+ let totalLength = 0;
33
+ let previousFilesTotalLength = 0;
34
+ for (const source of sources) {
35
+ const type = await ResourceFetcherUtils.getType(source);
36
+ let length = 0;
37
+ if (type === 4 /* SourceType.REMOTE_FILE */ && typeof source === 'string') {
38
+ try {
39
+ const response = await fetch(source, { method: 'HEAD' });
40
+ if (!response.ok) {
41
+ Logger.warn(`Failed to fetch HEAD for ${source}: ${response.status}`);
42
+ continue;
43
+ }
44
+ const contentLength = response.headers.get('content-length');
45
+ if (!contentLength) {
46
+ Logger.warn(`No content-length header for ${source}`);
47
+ }
48
+ length = contentLength ? parseInt(contentLength, 10) : 0;
49
+ previousFilesTotalLength = totalLength;
50
+ totalLength += length;
51
+ }
52
+ catch (error) {
53
+ Logger.warn(`Error fetching HEAD for ${source}:`, error);
54
+ continue;
55
+ }
56
+ }
57
+ results.push({ source, type, length, previousFilesTotalLength });
58
+ }
59
+ return { results, totalLength };
60
+ }
61
+ ResourceFetcherUtils.getFilesSizes = getFilesSizes;
62
+ function removeFilePrefix(uri) {
63
+ return uri.startsWith('file://') ? uri.slice(7) : uri;
64
+ }
65
+ ResourceFetcherUtils.removeFilePrefix = removeFilePrefix;
66
+ function hashObject(jsonString) {
67
+ let hash = 0;
68
+ for (let i = 0; i < jsonString.length; i++) {
69
+ // eslint-disable-next-line no-bitwise
70
+ hash = (hash << 5) - hash + jsonString.charCodeAt(i);
71
+ // eslint-disable-next-line no-bitwise
72
+ hash |= 0;
73
+ }
74
+ // eslint-disable-next-line no-bitwise
75
+ return (hash >>> 0).toString();
76
+ }
77
+ ResourceFetcherUtils.hashObject = hashObject;
78
+ function calculateDownloadProgress(totalLength, previousFilesTotalLength, currentFileLength, setProgress) {
79
+ return (progress) => {
80
+ if (progress === 1 &&
81
+ previousFilesTotalLength === totalLength - currentFileLength) {
82
+ setProgress(1);
83
+ return;
84
+ }
85
+ // Avoid division by zero
86
+ if (totalLength === 0) {
87
+ setProgress(0);
88
+ return;
89
+ }
90
+ const baseProgress = previousFilesTotalLength / totalLength;
91
+ const scaledProgress = progress * (currentFileLength / totalLength);
92
+ const updatedProgress = baseProgress + scaledProgress;
93
+ setProgress(updatedProgress);
94
+ };
95
+ }
96
+ ResourceFetcherUtils.calculateDownloadProgress = calculateDownloadProgress;
97
+ /*
98
+ * Increments the Hugging Face download counter if the URI points to a Software Mansion Hugging Face repo.
99
+ * More information: https://huggingface.co/docs/hub/models-download-stats
100
+ */
101
+ async function triggerHuggingFaceDownloadCounter(uri) {
102
+ const url = new URL(uri);
103
+ if (url.host === 'huggingface.co' &&
104
+ url.pathname.startsWith('/software-mansion/')) {
105
+ const baseUrl = `${url.protocol}//${url.host}${url.pathname.split('resolve')[0]}`;
106
+ fetch(`${baseUrl}resolve/main/config.json`, { method: 'HEAD' });
107
+ }
108
+ }
109
+ ResourceFetcherUtils.triggerHuggingFaceDownloadCounter = triggerHuggingFaceDownloadCounter;
110
+ async function createDirectoryIfNoExists() {
111
+ if (!(await checkFileExists(RNEDirectory))) {
112
+ await makeDirectoryAsync(RNEDirectory, { intermediates: true });
113
+ }
114
+ }
115
+ ResourceFetcherUtils.createDirectoryIfNoExists = createDirectoryIfNoExists;
116
+ async function checkFileExists(fileUri) {
117
+ const fileInfo = await getInfoAsync(fileUri);
118
+ return fileInfo.exists;
119
+ }
120
+ ResourceFetcherUtils.checkFileExists = checkFileExists;
121
+ function getFilenameFromUri(uri) {
122
+ let cleanUri = uri.replace(/^https?:\/\//, '');
123
+ cleanUri = cleanUri.split('#')?.[0] ?? cleanUri;
124
+ return cleanUri.replace(/[^a-zA-Z0-9._-]/g, '_');
125
+ }
126
+ ResourceFetcherUtils.getFilenameFromUri = getFilenameFromUri;
127
+ })(ResourceFetcherUtils || (ResourceFetcherUtils = {}));
@@ -0,0 +1,6 @@
1
+ import { ToolCall } from '../types/llm';
2
+ import { Schema } from 'jsonschema';
3
+ import * as zCore from 'zod/v4/core';
4
+ export declare const parseToolCall: (message: string) => ToolCall[];
5
+ export declare const getStructuredOutputPrompt: <T extends zCore.$ZodType>(responseSchema: T | Schema) => string;
6
+ export declare const fixAndValidateStructuredOutput: <T extends zCore.$ZodType>(output: string, responseSchema: T | Schema) => zCore.output<T>;
@@ -0,0 +1,72 @@
1
+ import * as z from 'zod/v4';
2
+ import { Validator } from 'jsonschema';
3
+ import { jsonrepair } from 'jsonrepair';
4
+ import { DEFAULT_STRUCTURED_OUTPUT_PROMPT } from '../constants/llmDefaults';
5
+ import * as zCore from 'zod/v4/core';
6
+ import { Logger } from '../common/Logger';
7
+ export const parseToolCall = (message) => {
8
+ try {
9
+ const unparsedToolCalls = message.match('\\[(.|\\s)*\\]');
10
+ if (!unparsedToolCalls) {
11
+ throw Error('Regex did not match array.');
12
+ }
13
+ const parsedMessage = JSON.parse(unparsedToolCalls[0]);
14
+ const results = [];
15
+ for (const tool of parsedMessage) {
16
+ if ('name' in tool &&
17
+ typeof tool.name === 'string' &&
18
+ 'arguments' in tool &&
19
+ tool.arguments !== null &&
20
+ typeof tool.arguments === 'object') {
21
+ results.push({
22
+ toolName: tool.name,
23
+ arguments: tool.arguments,
24
+ });
25
+ }
26
+ }
27
+ return results;
28
+ }
29
+ catch (e) {
30
+ Logger.error(e);
31
+ return [];
32
+ }
33
+ };
34
+ const filterObjectKeys = (obj, keysToRemove) => {
35
+ const entries = Object.entries(obj);
36
+ const filteredEntries = entries.filter(([key, _]) => !keysToRemove.includes(key));
37
+ return Object.fromEntries(filteredEntries);
38
+ };
39
+ export const getStructuredOutputPrompt = (responseSchema) => {
40
+ const schemaObject = responseSchema instanceof zCore.$ZodType
41
+ ? filterObjectKeys(z.toJSONSchema(responseSchema), [
42
+ '$schema',
43
+ 'additionalProperties',
44
+ ])
45
+ : responseSchema;
46
+ const schemaString = JSON.stringify(schemaObject);
47
+ return DEFAULT_STRUCTURED_OUTPUT_PROMPT(schemaString);
48
+ };
49
+ const extractBetweenBrackets = (text) => {
50
+ const startIndex = text.search(/[\\{\\[]/); // First occurrence of either { or [
51
+ const openingBracket = text[startIndex];
52
+ const closingBracket = openingBracket === '{' ? '}' : ']';
53
+ if (!openingBracket)
54
+ throw Error("Couldn't find JSON in text");
55
+ return text.slice(text.indexOf(openingBracket), text.lastIndexOf(closingBracket) + 1);
56
+ };
57
+ // this is a bit hacky typing
58
+ export const fixAndValidateStructuredOutput = (output, responseSchema) => {
59
+ const extractedOutput = extractBetweenBrackets(output);
60
+ const repairedOutput = jsonrepair(extractedOutput);
61
+ const outputJSON = JSON.parse(repairedOutput);
62
+ if (responseSchema instanceof zCore.$ZodType) {
63
+ return z.parse(responseSchema, outputJSON);
64
+ }
65
+ else {
66
+ const validator = new Validator();
67
+ validator.validate(outputJSON, responseSchema, {
68
+ throwAll: true,
69
+ });
70
+ return outputJSON;
71
+ }
72
+ };
@@ -0,0 +1,21 @@
1
+ export const longCommonInfPref = (seq1, seq2, hammingDistThreshold) => {
2
+ let maxInd = 0;
3
+ let maxLength = 0;
4
+ for (let i = 0; i < seq1.length; i++) {
5
+ let j = 0;
6
+ let hammingDist = 0;
7
+ while (j < seq2.length &&
8
+ i + j < seq1.length &&
9
+ (seq1[i + j] === seq2[j] || hammingDist < hammingDistThreshold)) {
10
+ if (seq1[i + j] !== seq2[j]) {
11
+ hammingDist++;
12
+ }
13
+ j++;
14
+ }
15
+ if (j >= maxLength) {
16
+ maxLength = j;
17
+ maxInd = i;
18
+ }
19
+ }
20
+ return maxInd;
21
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-executorch",
3
- "version": "0.5.7",
3
+ "version": "0.5.8",
4
4
  "description": "An easy way to run AI models in React Native with ExecuTorch",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./lib/module/index.js",
@@ -85,6 +85,10 @@ export class LLMModule {
85
85
  this.controller.interrupt();
86
86
  }
87
87
 
88
+ getGeneratedTokenCount() {
89
+ return this.controller.getGeneratedTokenCount();
90
+ }
91
+
88
92
  delete() {
89
93
  this.controller.delete();
90
94
  }
package/src/types/llm.ts CHANGED
@@ -6,7 +6,6 @@ export interface LLMType {
6
6
  isGenerating: boolean;
7
7
  downloadProgress: number;
8
8
  error: string | null;
9
- getGeneratedTokenCount: () => number;
10
9
  configure: ({
11
10
  chatConfig,
12
11
  toolsConfig,
@@ -16,6 +15,7 @@ export interface LLMType {
16
15
  toolsConfig?: ToolsConfig;
17
16
  generationConfig?: GenerationConfig;
18
17
  }) => void;
18
+ getGeneratedTokenCount: () => number;
19
19
  generate: (messages: Message[], tools?: LLMTool[]) => Promise<void>;
20
20
  sendMessage: (message: string) => Promise<void>;
21
21
  deleteMessage: (index: number) => void;