react-native-executorch
Version:
An easy way to run AI models in React Native with ExecuTorch
155 lines (152 loc) • 5.51 kB
JavaScript
;
import { RNEDirectory } from '../constants/directories';
import { Asset } from 'expo-asset';
import { Logger } from '../common/Logger';
/**
* @internal
*/
import { getInfoAsync, makeDirectoryAsync } from 'expo-file-system/legacy';
export let HTTP_CODE = /*#__PURE__*/function (HTTP_CODE) {
HTTP_CODE[HTTP_CODE["OK"] = 200] = "OK";
HTTP_CODE[HTTP_CODE["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
return HTTP_CODE;
}({});
export let DownloadStatus = /*#__PURE__*/function (DownloadStatus) {
DownloadStatus[DownloadStatus["ONGOING"] = 0] = "ONGOING";
DownloadStatus[DownloadStatus["PAUSED"] = 1] = "PAUSED";
return DownloadStatus;
}({});
export let SourceType = /*#__PURE__*/function (SourceType) {
SourceType[SourceType["OBJECT"] = 0] = "OBJECT";
SourceType[SourceType["LOCAL_FILE"] = 1] = "LOCAL_FILE";
SourceType[SourceType["RELEASE_MODE_FILE"] = 2] = "RELEASE_MODE_FILE";
SourceType[SourceType["DEV_MODE_FILE"] = 3] = "DEV_MODE_FILE";
SourceType[SourceType["REMOTE_FILE"] = 4] = "REMOTE_FILE";
return SourceType;
}({});
export let ResourceFetcherUtils;
(function (_ResourceFetcherUtils) {
function getType(source) {
if (typeof source === 'object') {
return SourceType.OBJECT;
} else if (typeof source === 'number') {
const uri = Asset.fromModule(source).uri;
if (uri.startsWith('http')) {
return SourceType.DEV_MODE_FILE;
}
return SourceType.RELEASE_MODE_FILE;
}
// typeof source == 'string'
if (source.startsWith('file://')) {
return SourceType.LOCAL_FILE;
}
return SourceType.REMOTE_FILE;
}
_ResourceFetcherUtils.getType = getType;
async function getFilesSizes(sources) {
const results = [];
let totalLength = 0;
let previousFilesTotalLength = 0;
for (const source of sources) {
const type = ResourceFetcherUtils.getType(source);
let length = 0;
try {
if (type === SourceType.REMOTE_FILE && typeof source === 'string') {
const response = await fetch(source, {
method: 'HEAD'
});
if (!response.ok) {
Logger.warn(`Failed to fetch HEAD for ${source}: ${response.status}`);
continue;
}
const contentLength = response.headers.get('content-length');
if (!contentLength) {
Logger.warn(`No content-length header for ${source}`);
}
length = contentLength ? parseInt(contentLength, 10) : 0;
previousFilesTotalLength = totalLength;
totalLength += length;
}
} catch (error) {
Logger.warn(`Error fetching HEAD for ${source}:`, error);
continue;
} finally {
results.push({
source,
type,
length,
previousFilesTotalLength
});
}
}
return {
results,
totalLength
};
}
_ResourceFetcherUtils.getFilesSizes = getFilesSizes;
function removeFilePrefix(uri) {
return uri.startsWith('file://') ? uri.slice(7) : uri;
}
_ResourceFetcherUtils.removeFilePrefix = removeFilePrefix;
function hashObject(jsonString) {
let hash = 0;
for (let i = 0; i < jsonString.length; i++) {
// eslint-disable-next-line no-bitwise
hash = (hash << 5) - hash + jsonString.charCodeAt(i);
// eslint-disable-next-line no-bitwise
hash |= 0;
}
// eslint-disable-next-line no-bitwise
return (hash >>> 0).toString();
}
_ResourceFetcherUtils.hashObject = hashObject;
function calculateDownloadProgress(totalLength, previousFilesTotalLength, currentFileLength, setProgress) {
return progress => {
if (progress === 1 && previousFilesTotalLength === totalLength - currentFileLength) {
setProgress(1);
return;
}
// Avoid division by zero
if (totalLength === 0) {
setProgress(0);
return;
}
const baseProgress = previousFilesTotalLength / totalLength;
const scaledProgress = progress * (currentFileLength / totalLength);
const updatedProgress = baseProgress + scaledProgress;
setProgress(updatedProgress);
};
}
_ResourceFetcherUtils.calculateDownloadProgress = calculateDownloadProgress;
async function triggerHuggingFaceDownloadCounter(uri) {
const url = new URL(uri);
if (url.host === 'huggingface.co' && url.pathname.startsWith('/software-mansion/')) {
const baseUrl = `${url.protocol}//${url.host}${url.pathname.split('resolve')[0]}`;
fetch(`${baseUrl}resolve/main/config.json`, {
method: 'HEAD'
});
}
}
_ResourceFetcherUtils.triggerHuggingFaceDownloadCounter = triggerHuggingFaceDownloadCounter;
async function createDirectoryIfNoExists() {
if (!(await checkFileExists(RNEDirectory))) {
await makeDirectoryAsync(RNEDirectory, {
intermediates: true
});
}
}
_ResourceFetcherUtils.createDirectoryIfNoExists = createDirectoryIfNoExists;
async function checkFileExists(fileUri) {
const fileInfo = await getInfoAsync(fileUri);
return fileInfo.exists;
}
_ResourceFetcherUtils.checkFileExists = checkFileExists;
function getFilenameFromUri(uri) {
let cleanUri = uri.replace(/^https?:\/\//, '');
cleanUri = cleanUri.split('#')?.[0] ?? cleanUri;
return cleanUri.replace(/[^a-zA-Z0-9._-]/g, '_');
}
_ResourceFetcherUtils.getFilenameFromUri = getFilenameFromUri;
})(ResourceFetcherUtils || (ResourceFetcherUtils = {}));
//# sourceMappingURL=ResourceFetcherUtils.js.map