UNPKG

react-native-executorch

Version:

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

128 lines (127 loc) 5.39 kB
/** * @internal */ import { getInfoAsync, makeDirectoryAsync, } from 'expo-file-system'; import { RNEDirectory } from '../constants/directories'; import { Asset } from 'expo-asset'; import { Logger } from '../common/Logger'; export var ResourceFetcherUtils; (function (ResourceFetcherUtils) { function getType(source) { if (typeof source === 'object') { return 0 /* SourceType.OBJECT */; } else if (typeof source === 'number') { const uri = Asset.fromModule(source).uri; if (!uri.includes('://')) { return 2 /* SourceType.RELEASE_MODE_FILE */; } return 3 /* SourceType.DEV_MODE_FILE */; } else { // typeof source == 'string' if (source.startsWith('file://')) { return 1 /* SourceType.LOCAL_FILE */; } return 4 /* 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 = await ResourceFetcherUtils.getType(source); let length = 0; if (type === 4 /* SourceType.REMOTE_FILE */ && typeof source === 'string') { try { 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; } } 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; /* * Increments the Hugging Face download counter if the URI points to a Software Mansion Hugging Face repo. * More information: https://huggingface.co/docs/hub/models-download-stats */ 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 = {}));