idmission-web-sdk 1.0.76 → 1.0.78
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.
- package/dist/components/selfie_capture/SelfieCaptureLoadingOverlay.d.ts +1 -1
- package/dist/components/submission/SubmissionProvider.d.ts +40 -2
- package/dist/components/video_id/IdVideoCapture.d.ts +3 -1
- package/dist/contexts/SubmissionContext.d.ts +0 -34
- package/dist/sdk2.cjs.development.js +157 -108
- package/dist/sdk2.cjs.development.js.map +1 -1
- package/dist/sdk2.cjs.production.js +1 -1
- package/dist/sdk2.cjs.production.js.map +1 -1
- package/dist/sdk2.esm.js +158 -109
- package/dist/sdk2.esm.js.map +1 -1
- package/dist/sdk2.umd.development.js +157 -108
- package/dist/sdk2.umd.development.js.map +1 -1
- package/dist/sdk2.umd.production.js +1 -1
- package/dist/sdk2.umd.production.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk2.cjs.development.js","sources":["../src/version.ts","../src/lib/utils/dataUrlToBase64.ts","../src/contexts/SubmissionContext.ts","../src/components/common/Page.tsx","../src/components/common/overlay.tsx","../src/components/common/LoaderButton.tsx","../src/components/submission/GeolocationAccessDeniedOverlay.tsx","../src/components/submission/Errors.ts","../src/components/submission/SubmissionErrorOverlay.tsx","../src/components/submission/TokenMissingErrorOverlay.tsx","../src/components/submission/TokenInvalidFormatErrorOverlay.tsx","../src/components/submission/TokenInvalidSignatureErrorOverlay.tsx","../src/components/submission/TokenExpiredErrorOverlay.tsx","../src/components/submission/TokenPublicKeyErrorOverlay.tsx","../src/components/submission/SubmissionProvider.tsx","../src/lib/models/DocumentDetection.ts","../../tfjs-core/src/device_util.ts","../src/components/id_capture/DocumentCaptureGuideOverlay.tsx","../src/lib/barcode/Native.js","../src/lib/barcode/ZXing.js","../src/lib/barcode/Scan.ts","../src/lib/utils/getBlobDimensions.ts","../src/lib/utils/deviceDetection.ts","../src/lib/camera/Camera.ts","../src/components/camera/CameraProvider.tsx","../src/lib/models/Focus.ts","../../tfjs-core/src/backends/backend.ts","../../tfjs-core/src/util_base.ts","../../tfjs-core/src/environment.ts","../../tfjs-core/src/global_util.ts","../../tfjs-core/src/kernel_names.ts","../../tfjs-core/src/log.ts","../../tfjs-core/src/kernel_registry.ts","../../tfjs-core/src/platforms/is_typed_array_browser.ts","../../tfjs-core/src/util.ts","../../tfjs-core/src/profiler.ts","../../tfjs-core/src/tape.ts","../../tfjs-core/src/tensor_format.ts","../../tfjs-core/src/tensor.ts","../../tfjs-core/src/types.ts","../../tfjs-core/src/tensor_util.ts","../../tfjs-core/src/engine.ts","../../tfjs-core/src/flags.ts","../../tfjs-core/src/tensor_util_env.ts","../../tfjs-core/src/ops/operation.ts","../../tfjs-core/src/ops/tensor_ops_util.ts","../../tfjs-core/src/io/composite_array_buffer.ts","../../tfjs-core/src/io/io_utils.ts","../../tfjs-core/src/io/router_registry.ts","../../tfjs-core/src/io/indexed_db.ts","../../tfjs-core/src/io/local_storage.ts","../../tfjs-core/src/io/model_management.ts","../../tfjs-core/src/platforms/platform_browser.ts","../../tfjs-core/src/platforms/platform_node.ts","../../tfjs-core/src/ops/buffer.ts","../../tfjs-core/src/ops/cast.ts","../../tfjs-core/src/ops/clone.ts","../../tfjs-core/src/ops/print.ts","../../tfjs-core/src/base_side_effects.ts","../../tfjs-core/src/globals.ts","../../tfjs-core/src/ops/add.ts","../../tfjs-core/src/ops/floorDiv.ts","../../tfjs-core/src/ops/div.ts","../../tfjs-core/src/ops/mul.ts","../../tfjs-core/src/ops/abs.ts","../../tfjs-core/src/ops/fill.ts","../../tfjs-core/src/ops/broadcast_util.ts","../../tfjs-core/src/ops/zeros_like.ts","../../tfjs-core/src/ops/pow.ts","../../tfjs-core/src/ops/scalar.ts","../../tfjs-core/src/ops/sqrt.ts","../../tfjs-core/src/ops/square.ts","../../tfjs-core/src/gradients.ts","../../tfjs-core/src/ops/sub.ts","../../tfjs-core/src/ops/maximum.ts","../../tfjs-core/src/serialization.ts","../../tfjs-core/src/optimizers/optimizer.ts","../../tfjs-core/src/optimizers/adadelta_optimizer.ts","../../tfjs-core/src/optimizers/adagrad_optimizer.ts","../../tfjs-core/src/optimizers/adam_optimizer.ts","../../tfjs-core/src/optimizers/adamax_optimizer.ts","../../tfjs-core/src/optimizers/sgd_optimizer.ts","../../tfjs-core/src/optimizers/momentum_optimizer.ts","../../tfjs-core/src/optimizers/rmsprop_optimizer.ts","../../tfjs-core/src/optimizers/register_optimizers.ts","../../tfjs-core/src/index.ts","../../tfjs-backend-webgl/src/canvas_util.ts","../src/components/common/cdn.ts","../src/lib/utils/getFrameDimensions.ts","../src/components/common/InvisibleCanvas.tsx","../src/lib/utils/cropping.ts","../src/components/id_capture/IdCaptureModelsProvider.tsx","../src/components/common/debug.tsx","../src/components/common/ExitCaptureButton.tsx","../src/components/common/spinner.tsx","../src/components/common/SelfieProgressPreview.tsx","../src/lib/locales/en/translation.js","../src/lib/locales/es/translation.js","../src/lib/locales/index.ts","../src/components/common/GuidanceMessage.tsx","../src/components/id_capture/IdCapture.tsx","../src/components/id_capture/IdCaptureLoadingOverlay.tsx","../src/components/id_capture/FlipIdPrompt.tsx","../src/components/common/ButtonsRow.tsx","../src/components/camera/CameraVideoTag.tsx","../src/components/common/useShowSuccessScreen.ts","../src/components/fallback_flows/IdCapture.tsx","../src/components/id_capture/IdCaptureWizard.tsx","../src/components/selfie_capture/HighPerformanceSelfieGuidanceModelsProvider.tsx","../src/lib/utils/useTimeout.ts","../src/components/fallback_flows/SelfieCapture.tsx","../src/components/selfie_capture/SelfieCapture.tsx","../src/components/face_liveness/FaceLivenessCapture.tsx","../src/components/face_liveness/FaceLivenessWizard.tsx","../src/components/GuideOrientationProvider.tsx","../src/components/submission/SubmissionSuccess.tsx","../src/components/additional_document_capture/AdditionalDocumentCapture.tsx","../src/components/additional_document_capture/AdditionalDocumentCaptureWizard.tsx","../src/components/signature_capture/data.ts","../src/components/common/signature.tsx","../src/lib/camera/useVideoRecorder.ts","../src/components/video_signature_capture/VideoSignatureCapture.tsx","../src/components/video_signature_capture/VideoSignatureWizard.tsx","../src/components/video_id/IdVideoCaptureFlipIdPrompt.tsx","../src/components/video_id/IdVideoCaptureGuides.tsx","../src/components/video_id/IdVideoCapture.tsx","../src/components/CompositeWizard.tsx","../src/themes/index.tsx","../src/components/customer_verification/CustomerVerificationCapture.tsx","../src/components/customer_identification/CustomerIdentificationCapture.tsx","../src/lib/models/preloadModels.ts","../src/index.tsx"],"sourcesContent":["export const webSdkVersion = '1.0.76';\n","export async function dataUrlToBase64(url: string): Promise<string> {\n return url.replace(/^data:image\\/(png|jpeg);base64,/, '')\n}\n\nexport function dataUrlToBase64Sync(url: string): string {\n return url.replace(/^data:.*;base64,/, '')\n}\n\nexport function contentDispositionFromDataUrl(url: string): string {\n return url.match(/^(data:.*;base64),/)?.[1] ?? ''\n}\n","import { createContext } from 'react'\nimport { UploadedDocument } from '../components/additional_document_capture/AdditionalDocumentCapture'\nimport { SignatureData } from '../components/signature_capture/data'\nimport { webSdkVersion } from '../version'\nimport { getPlatform } from '../lib/utils/platform'\nimport { NetworkError, SubmissionError } from '../components/submission/Errors'\nimport { dataUrlToBase64Sync } from '../lib/utils/dataUrlToBase64'\n\nexport enum SubmissionAction {\n NONE = 'NONE',\n ENROLL = 'ENROLL',\n IDENTIFY = 'IDENTIFY',\n VALIDATE = 'VALIDATE',\n VERIFY = 'VERIFY',\n}\n\nexport enum SubmissionStatus {\n READY = 'READY',\n SUBMITTING = 'SUBMITTING',\n SUBMITTED = 'SUBMITTED',\n FAILED = 'FAILED',\n}\n\nexport type SubmissionEnvironment = 'prod' | 'demo'\n\nexport const submissionHosts = {\n prod: 'https://api.idmission.com',\n demo: 'https://apidemo.idmission.com',\n}\n\nexport type SubmissionRequest = {\n securityData: {\n userName: string\n password: string\n merchantId: number\n }\n customerData: {\n idData: {\n idImageFront?: string\n idImageBack?: string\n\n idType: 'NSP'\n idCountry: 'NSP'\n idState: ''\n }\n personalData?: PersonalData\n cardData?: CardData\n biometricData?: {\n selfie?: string\n }\n signatureData?: {\n signatureImage?: string\n }\n additionalDocuments?: UploadedDocument[]\n }\n biometricData?: {\n selfie?: string\n videoData?: string\n }\n additionalData: {\n uniqueRequestId: string\n clientTraceId?: string\n manualReviewRequired: 'Y' | 'N'\n bypassAgeValidation: 'Y' | 'N'\n deDuplicationRequired: 'Y' | 'N'\n bypassNameMatching: 'Y' | 'N'\n postDataAPIRequired: 'Y' | 'N'\n postDataOnReviewRequired: 'Y' | 'N'\n sendInputImagesInPost: 'Y' | 'N'\n sendProcessedImagesInPost: 'Y' | 'N'\n needImmediateResponse: 'Y' | 'N'\n deduplicationSynchronous: 'Y' | 'N'\n verifyDataWithHost: 'Y' | 'N'\n idBackImageRequired: 'Y' | 'N'\n stripSpecialCharacters: 'Y' | 'N'\n idImageResolutionCheck: 'Y' | 'N'\n metadata?: string\n }\n employee?: { companyId?: string }\n}\n\nexport type CaptureAttemptMetadata = {\n autoCapture: 'Y' | 'N' // always Y until we add support for manual capture\n captureTime: number // time from start of the camera start to camera stop in ms\n operationTime?: number // time from start of the selfie detection or ID detection to capture in ms\n}\n\nexport type PersonalData = {\n uniqueNumber?: string\n name?: string\n phone?: string\n phoneCountryCode?: string\n email?: string\n dob?: string // date of birth, formatted DD/MM/YYYY, e.g. 31/12/2019\n gender?: 'M' | 'F'\n addressLine1?: string\n addressLine2?: string\n city?: string\n district?: string // two-letter code indicating state if USA, e.g. CA\n postalCode?: string\n country?: string // three-letter code indicating country, e.g. USA\n}\n\nexport type CardData = {\n cardToken?: string\n cardLast4?: string\n cardExpDate?: string\n nameOnCard?: string\n}\n\nexport type SubmissionMetadata = {\n selfie: CaptureAttemptMetadata[]\n back: CaptureAttemptMetadata[]\n front: CaptureAttemptMetadata[]\n sdkVersion: string\n isRealIDCheckRequired: 'true' | 'false'\n os?: string\n osVersion?: string\n browserVersion?: string\n Resolution?: string\n GeoLocation?: string\n}\n\nexport type SubmissionResponseStatus = {\n statusCode: string\n statusMessage?: string\n errorData?: string\n}\n\nexport type SubmissionResponse = {\n status: SubmissionResponseStatus\n resultData: Record<string, unknown>\n}\n\nexport type LivenessCheckRequest = {\n securityData: {\n userName: string\n password: string\n merchantId: number\n }\n customerData: {\n biometricData: {\n selfie: string\n }\n }\n additionalData: {\n uniqueRequestId: string\n stripSpecialCharacters: 'Y' | 'N'\n estimateAge: 'Y' | 'N'\n predictGender: 'Y' | 'N'\n metadata?: string\n }\n}\nexport type LiveCheckResponse = {\n status: { statusCode: string; statusMessage: string; errorData: string }\n resultData: {\n verificationResult: string\n eyeCovering: 'true' | 'false'\n faceMask: 'true' | 'false'\n headCovering: 'true' | 'false'\n cellPhone: 'true' | 'false'\n }\n}\n\nexport type SubmissionState = {\n submit: () => Promise<SubmissionResponse | null>\n submissionStatus: SubmissionStatus\n submissionRequest: SubmissionRequest | null\n submissionResponse: SubmissionResponse | null\n submissionError: SubmissionError | NetworkError | null\n submissionEnvironment: SubmissionEnvironment\n\n idFrontImage: string | null\n idBackImage: string | null\n passportImage: string | null\n selfieImage: string | null\n signatureData: SignatureData | null\n signatureVideoUrl: string | null\n idCaptureVideoUrl: string | null\n additionalDocuments: UploadedDocument[] | null\n\n setIdFrontImage: (image: string) => void\n setIdBackImage: (image: string) => void\n setPassportImage: (image: string) => void\n setSelfieImage: (image: string) => void\n setSignatureData: (signatureData: SignatureData) => void\n setSignatureVideoUrl: (videoDataUrl: string) => void\n setIdCaptureVideoUrl: (videoDataUrl: string) => void\n setAdditionalDocuments: (uploadedDocuments: UploadedDocument[]) => void\n\n logIdFrontCaptureAttempt: (attempt: CaptureAttemptMetadata) => void\n logIdBackCaptureAttempt: (attempt: CaptureAttemptMetadata) => void\n logSelfieCaptureAttempt: (attempt: CaptureAttemptMetadata) => void\n\n livenessCheckRequest: LivenessCheckRequest | null\n checkLiveness: (imageDataUrl: string) => Promise<LiveCheckResponse>\n\n retryLocationAccess: () => void\n}\n\nexport const SubmissionContext = createContext<SubmissionState>({\n submit: async () => null,\n submissionStatus: SubmissionStatus.READY,\n submissionRequest: null,\n submissionResponse: null,\n submissionError: null,\n submissionEnvironment: 'prod',\n\n idFrontImage: null,\n idBackImage: null,\n passportImage: null,\n selfieImage: null,\n signatureData: null,\n signatureVideoUrl: null,\n idCaptureVideoUrl: null,\n additionalDocuments: null,\n\n setIdFrontImage: () => null,\n setIdBackImage: () => null,\n setPassportImage: () => null,\n setSelfieImage: () => null,\n setSignatureData: () => null,\n setSignatureVideoUrl: () => null,\n setIdCaptureVideoUrl: () => null,\n setAdditionalDocuments: () => null,\n\n logIdFrontCaptureAttempt: () => null,\n logIdBackCaptureAttempt: () => null,\n logSelfieCaptureAttempt: () => null,\n\n livenessCheckRequest: null,\n checkLiveness: async () => {\n throw new Error('checkLiveness is not implemented')\n },\n\n retryLocationAccess: () => null,\n})\n\nexport function parseJwt(token: string): Record<string, unknown> {\n const base64Url = token.split('.')[1]\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')\n const jsonPayload = decodeURIComponent(\n window\n .atob(base64)\n .split('')\n .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join('')\n )\n\n return JSON.parse(jsonPayload)\n}\n\nexport function determineSubmissionHost(\n environment: SubmissionEnvironment,\n token?: string\n): string {\n if (token) {\n switch (parseJwt(token)['iss']) {\n case 'https://auth.idmission.com/auth/realms/identity':\n return submissionHosts.prod\n case 'https://demoauth.idmission.com/auth/realms/identity':\n return submissionHosts.demo\n }\n }\n\n const host = submissionHosts[environment]\n if (!host)\n throw new Error(`unrecognized SubmissionEnvironment ${environment}`)\n return host\n}\n\nexport function determineSubmissionEndpoint(\n action: SubmissionAction,\n hasId: boolean,\n hasSelfie: boolean,\n hasToken: boolean\n): string {\n const v = hasToken ? 'v4' : 'v3'\n switch (action) {\n case SubmissionAction.ENROLL:\n return hasId\n ? `/${v}/customer/enroll`\n : `/${v}/customer/enroll-biometrics`\n\n case SubmissionAction.IDENTIFY:\n return `/${v}/customer/identify`\n\n case SubmissionAction.VALIDATE:\n return hasSelfie\n ? `/${v}/customer/validate-id-match-face`\n : `/${v}/customer/validate-id`\n\n case SubmissionAction.VERIFY:\n return `/${v}/customer/verify`\n\n default:\n throw new Error(`unrecognized SubmissionAction ${action}`)\n }\n}\n\nexport function liveCheckEndpoint(hasToken: boolean): string {\n const v = hasToken ? 'v4' : 'v3'\n return `/${v}/customer/live-check`\n}\n\nexport function apiHeaders(token?: string): HeadersInit {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n Origin: '*',\n }\n if (token) {\n headers['Authorization'] = `Bearer ${token}`\n }\n return headers\n}\n\nexport function attachMetadataToRequest(\n request: SubmissionRequest | LivenessCheckRequest,\n {\n selfieCaptureAttempts,\n idFrontCaptureAttempts,\n idBackCaptureAttempts,\n geolocationResult,\n }: {\n selfieCaptureAttempts: CaptureAttemptMetadata[]\n idFrontCaptureAttempts: CaptureAttemptMetadata[]\n idBackCaptureAttempts: CaptureAttemptMetadata[]\n geolocationResult: GeolocationPosition | null\n }\n) {\n const metadata: SubmissionMetadata = {\n selfie: selfieCaptureAttempts,\n front: idFrontCaptureAttempts,\n back: idBackCaptureAttempts,\n isRealIDCheckRequired: 'false',\n sdkVersion: `WebSDK_${webSdkVersion}`,\n Resolution: `${window.innerWidth} x ${window.innerHeight}`,\n }\n const platform = getPlatform()\n if (platform) {\n metadata.os = platform.os.family\n metadata.osVersion = platform.os.version\n metadata.browserVersion = `${platform.name} ${platform.version}`\n }\n if (geolocationResult) {\n metadata.GeoLocation = JSON.stringify(geolocationResult)\n }\n request.additionalData.metadata = JSON.stringify(metadata)\n}\n\nexport function videoDataUrlToB64(url: string): Promise<string> {\n return new Promise((resolve) => {\n const reader = new FileReader()\n reader.onloadend = () => {\n resolve(dataUrlToBase64Sync(reader.result as string))\n }\n fetch(url)\n .then((resp) => resp.blob())\n .then((blob) => reader.readAsDataURL(blob))\n })\n}\n","import React, {\n CSSProperties,\n forwardRef,\n ReactElement,\n ReactNode,\n RefCallback,\n useEffect,\n useState,\n} from 'react'\nimport styled from 'styled-components'\n\nexport const PageContainerDiv = styled.div<{\n $heightOffset?: number\n}>`\n ${(props) =>\n props.theme.isFullscreen === false\n ? ``\n : `\n position: fixed;\n top: 0;\n left: 0;\n width: var(--app-width);\n height: calc(\n var(--app-height) - ${props.$heightOffset ?? 0}px\n );\n overflow-x: hidden;\n overflow-y: auto;\n `}\n\n ${(props) =>\n props.theme.fontFamily ? `font-family: ${props.theme.fontFamily};` : ``}\n\n &.flex {\n display: flex;\n }\n\n &.padded {\n box-sizing: border-box;\n padding: 16px 24px;\n }\n`\n\nexport const PageContainer = forwardRef(\n (\n {\n children,\n className,\n heightOffset = 0,\n style,\n onClick,\n }: {\n ref?: RefCallback<HTMLDivElement>\n children: ReactNode\n className?: string\n heightOffset?: number\n style?: CSSProperties\n onClick?: () => void\n },\n ref: React.ForwardedRef<HTMLDivElement>\n ): ReactElement => {\n const [dimensionsCalculated, setDimensionsCalculated] = useState(false)\n\n useEffect(() => {\n setDimensionsCalculated(false)\n const calcAppDimensions = () => {\n const doc = document.documentElement\n doc.style.setProperty('--app-width', `${window.innerWidth}px`)\n doc.style.setProperty('--app-height', `${window.innerHeight}px`)\n }\n window.addEventListener('resize', calcAppDimensions)\n calcAppDimensions()\n setDimensionsCalculated(true)\n\n return () => {\n window.removeEventListener('resize', calcAppDimensions)\n }\n }, [])\n\n return (\n <PageContainerDiv\n ref={ref}\n style={style}\n onClick={onClick}\n className={className}\n $heightOffset={heightOffset}\n >\n {dimensionsCalculated && children}\n </PageContainerDiv>\n )\n }\n)\n\nPageContainer.displayName = 'PageContainer'\n","import styled from 'styled-components'\nimport { PageContainer } from './Page'\n\nexport const OverlayContainer = styled(PageContainer)`\n background: ${(props) =>\n props.theme.background ? `${props.theme.background}` : `white`};\n ${(props) =>\n props.theme.textColor ? `color: ${props.theme.textColor};` : ``}\n z-index: 10000;\n`\n\nexport const OverlayInner = styled.div`\n text-align: ${(props) => props.theme.textAlign ?? 'center'};\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n max-height: var(--app-height);\n height: 100%;\n ${(props) =>\n props.theme.padding\n ? `box-sizing: border-box; padding: ${props.theme.padding};`\n : ``}\n`\n\nexport const OverlayImageContainer = styled.div`\n position: relative;\n display: flex;\n flex-grow: 1;\n padding-bottom: 25px;\n max-width: var(--app-width);\n max-height: var(--app-height);\n overflow: hidden;\n\n & > img {\n margin: 0 auto;\n width: max-content;\n max-width: 100%;\n max-height: 100%;\n aspect-ratio: initial;\n object-fit: contain;\n display: block;\n }\n`\n\nexport const OverlayImageRow = styled.div`\n display: flex;\n margin: auto;\n\n & > div {\n max-height: calc(100vh - 320px);\n\n & > img {\n width: 100%;\n max-height: 100%;\n height: auto;\n object-fit: contain;\n }\n }\n`\n","import React, {\n CSSProperties,\n ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { LaddaButton } from 'ladda'\nimport styled from 'styled-components'\n\nexport type LoaderButtonVariant =\n | 'primary'\n | 'secondary'\n | 'positive'\n | 'negative'\n | 'warning'\n\nexport type LoaderButtonColors = {\n backgroundColor?: string\n textColor?: string\n loadingBackgroundColor?: string\n loadingTextColor?: string\n}\n\nexport type LoaderButtonProps = {\n children?: ReactNode\n className?: string\n disabled?: boolean\n finished?: boolean\n colors?: LoaderButtonColors\n onClick?: () => void\n style?: CSSProperties\n variant?: LoaderButtonVariant\n}\n\nexport const LoaderButton = ({\n children,\n className,\n colors = {},\n disabled,\n finished,\n onClick,\n style,\n variant = 'primary',\n}: LoaderButtonProps) => {\n const buttonRef = useRef<HTMLButtonElement | null>(null)\n const laddaRef = useRef<LaddaButton | null>(null)\n const [laddaLoaded, setLaddaLoaded] = useState(false)\n\n useEffect(() => {\n let interval: NodeJS.Timeout\n\n import('ladda').then((Ladda) => {\n if (!buttonRef.current) return\n laddaRef.current = Ladda.create(buttonRef.current)\n laddaRef.current.start()\n setLaddaLoaded(true)\n\n let currentProgress = 0\n interval = setInterval(() => {\n if (currentProgress < 0.9) currentProgress += 0.1\n laddaRef.current?.setProgress(currentProgress)\n }, 250)\n })\n\n return () => {\n laddaRef.current?.remove()\n clearInterval(interval)\n }\n }, [])\n\n useEffect(() => {\n if (laddaLoaded && finished) laddaRef.current?.stop()\n }, [finished, laddaLoaded])\n\n return (\n <StyledButton\n className={`ladda-button ${className}`}\n data-style=\"expand-right\"\n disabled={disabled}\n ref={buttonRef}\n onClick={onClick}\n $backgroundColor={colors.backgroundColor}\n $textColor={colors.textColor}\n $disabledBackgroundColor={colors.loadingBackgroundColor}\n $disabledTextColor={colors.loadingTextColor}\n $variant={variant}\n style={style}\n >\n <span className=\"ladda-label\">{children}</span>\n </StyledButton>\n )\n}\n\nconst StyledButton = styled.button<{\n $backgroundColor?: string\n $textColor?: string\n $disabledBackgroundColor?: string\n $disabledTextColor?: string\n $variant?: LoaderButtonVariant\n}>`\n ${(props) =>\n props.theme.buttons?.style === 'bootstrap' &&\n `\n border-radius: 0;\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n text-transform: none;\n -webkit-appearance: button;\n \n &:not(:disabled),\n &[type='button']:not(:disabled),\n &[type='reset']:not(:disabled),\n &[type='submit']:not(:disabled) {\n cursor: pointer;\n }\n \n &:focus:not(:focus-visible) {\n outline: 0;\n }\n \n --bs-btn-padding-x: 0.75rem;\n --bs-btn-padding-y: 0.375rem;\n --bs-btn-font-family: ;\n --bs-btn-font-size: 1rem;\n --bs-btn-font-weight: 400;\n --bs-btn-line-height: 1.5;\n --bs-btn-color: var(--bs-body-color);\n --bs-btn-bg: transparent;\n --bs-btn-border-width: var(--bs-border-width);\n --bs-btn-border-color: transparent;\n --bs-btn-border-radius: var(--bs-border-radius);\n --bs-btn-hover-border-color: transparent;\n --bs-btn-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15),\n 0 1px 1px rgba(0, 0, 0, 0.075);\n --bs-btn-disabled-opacity: 0.65;\n --bs-btn-focus-box-shadow: 0 0 0 0.25rem\n rgba(var(--bs-btn-focus-shadow-rgb), 0.5);\n display: inline-block;\n padding: var(--bs-btn-padding-y) var(--bs-btn-padding-x);\n font-family: var(--bs-btn-font-family);\n font-size: var(--bs-btn-font-size);\n font-weight: var(--bs-btn-font-weight);\n line-height: var(--bs-btn-line-height);\n color: var(--bs-btn-color);\n text-align: center;\n text-decoration: none;\n vertical-align: middle;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: var(--bs-btn-border-width) solid var(--bs-btn-border-color);\n border-radius: var(--bs-btn-border-radius);\n background-color: var(--bs-btn-bg);\n //transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,\n // border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;\n \n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n \n &:hover {\n filter: brightness(1.15);\n }\n \n &:focus-visible {\n color: var(--bs-btn-hover-color);\n background-color: var(--bs-btn-hover-bg);\n border-color: var(--bs-btn-hover-border-color);\n outline: 0;\n box-shadow: var(--bs-btn-focus-box-shadow);\n }\n \n &:disabled,\n &.disabled,\n fieldset:disabled & {\n color: var(--bs-btn-disabled-color);\n pointer-events: none;\n background-color: var(--bs-btn-disabled-bg);\n border-color: var(--bs-btn-disabled-border-color);\n opacity: var(--bs-btn-disabled-opacity);\n }\n \n --bs-btn-color: ${\n props.$textColor ??\n props.theme.buttons?.[props.$variant ?? 'primary']?.textColor ??\n '#fff'\n };\n --bs-btn-bg: ${\n props.$backgroundColor ??\n props.theme.buttons?.[props.$variant ?? 'primary']?.backgroundColor ??\n '#0d6efd'\n };\n --bs-btn-border-color: ${props.$backgroundColor ?? '#0d6efd'};\n --bs-btn-focus-shadow-rgb: 49, 132, 253;\n --bs-btn-active-color: #fff;\n --bs-btn-active-bg: #0a58ca;\n --bs-btn-active-border-color: #0a53be;\n --bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n --bs-btn-disabled-color: ${\n props.$disabledTextColor ??\n props.theme.buttons?.loading?.textColor ??\n '#fff'\n };\n --bs-btn-disabled-bg: ${\n props.$disabledBackgroundColor ??\n props.theme.buttons?.loading?.backgroundColor ??\n 'gray'\n };\n --bs-btn-disabled-border-color: ${\n props.$disabledBackgroundColor ?? '#0d6efd'\n };\n \n --bs-btn-padding-y: 14px;\n --bs-btn-padding-x: 1rem;\n --bs-btn-font-size: 18px;\n --bs-btn-border-radius: 4px;\n `}\n\n /*!\n * Ladda\n * http://lab.hakim.se/ladda\n * MIT licensed\n *\n * Copyright (C) 2018 Hakim El Hattab, http://hakim.se\n */\n @keyframes ladda-spinner-line-fade {\n 0%,\n 100% {\n opacity: 0.22;\n }\n 1% {\n opacity: 1;\n }\n }\n\n position: relative;\n\n .ladda-spinner {\n position: absolute;\n z-index: 2;\n display: inline-block;\n width: 32px;\n top: 50%;\n margin-top: 0;\n opacity: 0;\n pointer-events: none;\n }\n .ladda-label {\n position: relative;\n z-index: 3;\n }\n .ladda-progress {\n position: absolute;\n width: 0;\n height: 100%;\n left: 0;\n top: 0;\n background: rgba(0, 0, 0, 0.2);\n display: none;\n transition: 0.1s linear all !important;\n }\n &[data-loading] .ladda-progress {\n display: block;\n }\n\n transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;\n\n .ladda-spinner,\n .ladda-label {\n transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;\n }\n &[data-style='zoom-in'],\n &[data-style='zoom-in'] .ladda-spinner,\n &[data-style='zoom-in'] .ladda-label,\n &[data-style='zoom-out'],\n &[data-style='zoom-out'] .ladda-spinner,\n &[data-style='zoom-out'] .ladda-label {\n transition: 0.3s ease all !important;\n }\n &[data-style='expand-right'] .ladda-spinner {\n right: -6px;\n }\n &[data-style='expand-right'][data-size='s'] .ladda-spinner,\n &[data-style='expand-right'][data-size='xs'] .ladda-spinner {\n right: -12px;\n }\n &[data-style='expand-right'][data-loading] {\n padding-right: 56px;\n }\n &[data-style='expand-right'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='expand-right'][data-loading][data-size='s'],\n &[data-style='expand-right'][data-loading][data-size='xs'] {\n padding-right: 40px;\n }\n &[data-style='expand-left'] .ladda-spinner {\n left: 26px;\n }\n &[data-style='expand-left'][data-size='s'] .ladda-spinner,\n &[data-style='expand-left'][data-size='xs'] .ladda-spinner {\n left: 4px;\n }\n &[data-style='expand-left'][data-loading] {\n padding-left: 56px;\n }\n &[data-style='expand-left'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='expand-left'][data-loading][data-size='s'],\n &[data-style='expand-left'][data-loading][data-size='xs'] {\n padding-left: 40px;\n }\n &[data-style='expand-up'] {\n overflow: hidden;\n }\n &[data-style='expand-up'] .ladda-spinner {\n top: -32px;\n left: 50%;\n margin-left: 0;\n }\n &[data-style='expand-up'][data-loading] {\n padding-top: 54px;\n }\n &[data-style='expand-up'][data-loading] .ladda-spinner {\n opacity: 1;\n top: 26px;\n margin-top: 0;\n }\n &[data-style='expand-up'][data-loading][data-size='s'],\n &[data-style='expand-up'][data-loading][data-size='xs'] {\n padding-top: 32px;\n }\n &[data-style='expand-up'][data-loading][data-size='s'] .ladda-spinner,\n &[data-style='expand-up'][data-loading][data-size='xs'] .ladda-spinner {\n top: 4px;\n }\n &[data-style='expand-down'] {\n overflow: hidden;\n }\n &[data-style='expand-down'] .ladda-spinner {\n top: 62px;\n left: 50%;\n margin-left: 0;\n }\n &[data-style='expand-down'][data-size='s'] .ladda-spinner,\n &[data-style='expand-down'][data-size='xs'] .ladda-spinner {\n top: 40px;\n }\n &[data-style='expand-down'][data-loading] {\n padding-bottom: 54px;\n }\n &[data-style='expand-down'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='expand-down'][data-loading][data-size='s'],\n &[data-style='expand-down'][data-loading][data-size='xs'] {\n padding-bottom: 32px;\n }\n &[data-style='slide-left'] {\n overflow: hidden;\n }\n &[data-style='slide-left'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-left'] .ladda-spinner {\n left: 100%;\n margin-left: 0;\n }\n &[data-style='slide-left'][data-loading] .ladda-label {\n opacity: 0;\n left: -100%;\n }\n &[data-style='slide-left'][data-loading] .ladda-spinner {\n opacity: 1;\n left: 50%;\n }\n &[data-style='slide-right'] {\n overflow: hidden;\n }\n &[data-style='slide-right'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-right'] .ladda-spinner {\n right: 100%;\n margin-left: 0;\n left: 16px;\n }\n [dir='rtl'] &[data-style='slide-right'] .ladda-spinner {\n right: auto;\n }\n &[data-style='slide-right'][data-loading] .ladda-label {\n opacity: 0;\n left: 100%;\n }\n &[data-style='slide-right'][data-loading] .ladda-spinner {\n opacity: 1;\n left: 50%;\n }\n &[data-style='slide-up'] {\n overflow: hidden;\n }\n &[data-style='slide-up'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-up'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n margin-top: 1em;\n }\n &[data-style='slide-up'][data-loading] .ladda-label {\n opacity: 0;\n top: -1em;\n }\n &[data-style='slide-up'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-top: 0;\n }\n &[data-style='slide-down'] {\n overflow: hidden;\n }\n &[data-style='slide-down'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-down'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n margin-top: -2em;\n }\n &[data-style='slide-down'][data-loading] .ladda-label {\n opacity: 0;\n top: 1em;\n }\n &[data-style='slide-down'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-top: 0;\n }\n &[data-style='zoom-out'] {\n overflow: hidden;\n }\n &[data-style='zoom-out'] .ladda-spinner {\n left: 50%;\n margin-left: 32px;\n transform: scale(2.5);\n }\n &[data-style='zoom-out'] .ladda-label {\n position: relative;\n display: inline-block;\n }\n &[data-style='zoom-out'][data-loading] .ladda-label {\n opacity: 0;\n transform: scale(0.5);\n }\n &[data-style='zoom-out'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-left: 0;\n transform: none;\n }\n &[data-style='zoom-in'] {\n overflow: hidden;\n }\n &[data-style='zoom-in'] .ladda-spinner {\n left: 50%;\n margin-left: -16px;\n transform: scale(0.2);\n }\n &[data-style='zoom-in'] .ladda-label {\n position: relative;\n display: inline-block;\n }\n &[data-style='zoom-in'][data-loading] .ladda-label {\n opacity: 0;\n transform: scale(2.2);\n }\n &[data-style='zoom-in'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-left: 0;\n transform: none;\n }\n &[data-style='contract'] {\n overflow: hidden;\n width: 100px;\n }\n &[data-style='contract'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n }\n &[data-style='contract'][data-loading] {\n border-radius: 50%;\n width: 52px;\n }\n &[data-style='contract'][data-loading] .ladda-label {\n opacity: 0;\n }\n &[data-style='contract'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='contract-overlay'] {\n overflow: hidden;\n width: 100px;\n box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0);\n }\n &[data-style='contract-overlay'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n }\n &[data-style='contract-overlay'][data-loading] {\n border-radius: 50%;\n width: 52px;\n box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0.8);\n }\n &[data-style='contract-overlay'][data-loading] .ladda-label {\n opacity: 0;\n }\n &[data-style='contract-overlay'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n [dir='rtl'] .ladda-spinner > div {\n left: 25% !important;\n }\n`\n","import React, { ReactElement, useContext } from 'react'\nimport {\n OverlayContainer,\n OverlayImageContainer,\n OverlayInner,\n} from '../common/overlay'\nimport { useTranslation } from 'react-i18next'\nimport { SubmissionContext } from '../../contexts/SubmissionContext'\nimport { LoaderButton } from '../common/LoaderButton'\n\nexport type GeolocationAccessDeniedOverlayProps = {\n accessBlockedImageUrl?: string\n}\n\nexport const GeolocationAccessDeniedOverlay = ({\n accessBlockedImageUrl,\n}: GeolocationAccessDeniedOverlayProps): ReactElement => {\n const { t } = useTranslation()\n const { retryLocationAccess } = useContext(SubmissionContext)\n\n return (\n <OverlayContainer>\n <div style={{ display: 'flex', height: '100%' }}>\n <OverlayInner style={{ maxWidth: 500, height: 'auto', margin: 'auto' }}>\n <OverlayImageContainer style={{ flexGrow: 0 }}>\n <img src={accessBlockedImageUrl} alt={''} />\n </OverlayImageContainer>\n\n <h3>{t('Your location access is disabled')}</h3>\n <p style={{ lineHeight: 1.5, marginBottom: 50 }}>\n {t(\n 'This application requires access to your location to continue. ' +\n 'Please accept the permission once prompted by the browser. ' +\n 'If the browser does not prompt for location permissions, you must go to settings ' +\n 'and provide location access to the current browser.'\n )}\n </p>\n\n <LoaderButton\n variant=\"primary\"\n onClick={retryLocationAccess}\n style={{ width: 200, marginLeft: 'auto', marginRight: 'auto' }}\n finished\n >\n {t('Retry')}\n </LoaderButton>\n </OverlayInner>\n </div>\n </OverlayContainer>\n )\n}\n","import { SubmissionResponseStatus } from '../../contexts/SubmissionContext'\n\nexport class SubmissionError extends Error {\n constructor(public status: SubmissionResponseStatus) {\n super(status.statusMessage)\n }\n}\n\nexport class NetworkError extends Error {}\n\nexport class TokenPublicKeyError extends Error {\n constructor(public err: Error, public host: string) {\n super(err.message)\n }\n}\n","import React, { ReactElement } from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\nimport { NetworkError, SubmissionError } from './Errors'\nimport { LoaderButton } from '../common/LoaderButton'\nimport { useTranslation } from 'react-i18next'\n\nexport type SubmissionErrorOverlayProps = {\n error: SubmissionError | NetworkError\n onRetry?: () => void\n}\n\nexport const SubmissionErrorOverlay = ({\n error,\n onRetry,\n}: SubmissionErrorOverlayProps): ReactElement => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n {error instanceof NetworkError ? (\n <NetworkErrorContent error={error} onRetry={onRetry} />\n ) : (\n <SubmissionErrorContent error={error} />\n )}\n </OverlayInner>\n </OverlayContainer>\n )\n}\n\nconst SubmissionErrorContent = ({ error }: { error: SubmissionError }) => {\n const { t } = useTranslation()\n\n const headingText = t(`We're sorry, an unexpected error has occurred.`)\n\n return (\n <>\n <h3 style={{ marginBottom: 8 }}>{headingText}</h3>\n {error.status.statusCode && (\n <p style={{ marginBottom: 0 }}>\n <code>Status: {error.status.statusCode}</code>\n </p>\n )}\n <p style={{ marginBottom: 0 }}>\n Message: <code>{error.message}</code>\n </p>\n {error.status.errorData && (\n <p style={{ marginBottom: 0 }}>\n Data: <code>{error.status.errorData}</code>\n </p>\n )}\n </>\n )\n}\n\nconst NetworkErrorContent = ({\n onRetry,\n}: {\n error: NetworkError\n onRetry?: () => void\n}) => {\n const { t } = useTranslation()\n const headingText = t('Network unreachable')\n const messageText = t(\n `We're having trouble reaching our services, please check your connection and try again.`\n )\n const retryText = t('Retry')\n\n return (\n <>\n <h3 style={{ marginBottom: 8 }}>{headingText}</h3>\n <p style={{ marginBottom: 0 }}>{messageText}</p>\n\n {onRetry && (\n <div style={{ marginTop: 32 }}>\n <LoaderButton variant=\"warning\" finished onClick={onRetry}>\n {retryText}\n </LoaderButton>\n </div>\n )}\n </>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenMissingErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> is missing.\n </p>\n <p style={{ lineHeight: '1.5rem' }}>\n Please refer to the{' '}\n <a\n href=\"https://www.npmjs.com/package/idmission-web-sdk#getting-started\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n Getting Started\n </a>{' '}\n section of the documentation for information on how to use your\n credentials to generate a valid{' '}\n <a href=\"https://jwt.io\" target=\"_blank\" rel=\"noreferrer\">\n JSON Web Token\n </a>{' '}\n for your IDmission account. Every usage of the IDmission WebSDK must\n be authorized with a valid JWT from IDmission's servers.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenInvalidFormatErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> is invalid.\n </p>\n <p>\n JSON Web Tokens consist of three parts separated by dots (\n <code>.</code>), which are:\n </p>\n <div style={{ display: 'flex' }}>\n <ul style={{ display: 'inline', margin: '0 auto' }}>\n <li>Header</li>\n <li>Payload</li>\n <li>Signature</li>\n </ul>\n </div>\n <p>\n Therefore, a JWT typically looks like the following:{' '}\n <code>xxxxx.yyyyy.zzzzz</code>\n </p>\n <p style={{ lineHeight: '1.5rem' }}>\n Please refer to the{' '}\n <a\n href=\"https://www.npmjs.com/package/idmission-web-sdk#getting-started\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n Getting Started\n </a>{' '}\n section of the documentation for information on how to use your\n credentials to generate a valid{' '}\n <a href=\"https://jwt.io\" target=\"_blank\" rel=\"noreferrer\">\n JSON Web Token\n </a>{' '}\n for your IDmission account. Every usage of the IDmission WebSDK must\n be authorized with a valid JWT from IDmission's servers.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenInvalidSignatureErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> could not be validated.\n </p>\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n The signature of your token could not be validated. Check your token\n generation routine, it's possible that some malicious behavior is\n at play. This can also happen if you attempt to manually modify your\n token before passing it to the IDmission WebSDK.\n </p>\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n If you believe you have reached this page in error, please contact us\n at <a href=\"mailto:support@idmission.com\">support@idmission.com</a>.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenExpiredErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> is expired.\n </p>\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n Ensure you are generating a fresh token for each request to the\n IDmission WebSDK.\n </p>\n <p style={{ lineHeight: '1.5rem' }}>\n Please refer to the{' '}\n <a\n href=\"https://www.npmjs.com/package/idmission-web-sdk#getting-started\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n Getting Started\n </a>{' '}\n section of the documentation for information on how to use your\n credentials to generate a valid{' '}\n <a href=\"https://jwt.io\" target=\"_blank\" rel=\"noreferrer\">\n JSON Web Token\n </a>{' '}\n for your IDmission account. Every usage of the IDmission WebSDK must\n be authorized with a valid JWT from IDmission's servers.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\nimport { TokenPublicKeyError } from './Errors'\n\nexport const TokenPublicKeyErrorOverlay = ({\n error,\n}: {\n error: TokenPublicKeyError | null\n}) => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n {error?.host ? (\n <>\n Failed to reach <code>{error.host}</code>.\n </>\n ) : (\n <>\n Failed to obtain public key for <code>submissionToken</code>.\n </>\n )}\n </p>\n {error?.message && (\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n <code>{error.message}</code>\n </p>\n )}\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n Please ensure that IDmission's servers can be reached. If you\n believe you have reached this page in error, please contact us at{' '}\n <a href=\"mailto:support@idmission.com\">support@idmission.com</a>.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React, { ReactElement, useCallback, useEffect, useState } from 'react'\nimport {\n apiHeaders,\n attachMetadataToRequest,\n CaptureAttemptMetadata,\n CardData,\n determineSubmissionEndpoint,\n determineSubmissionHost,\n liveCheckEndpoint,\n LivenessCheckRequest,\n parseJwt,\n PersonalData,\n SubmissionAction,\n SubmissionContext,\n SubmissionEnvironment,\n SubmissionRequest,\n SubmissionResponse,\n SubmissionState,\n SubmissionStatus,\n videoDataUrlToB64,\n} from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { UploadedDocument } from '../additional_document_capture/AdditionalDocumentCapture'\nimport { SignatureData } from '../signature_capture/data'\nimport { GeolocationAccessDeniedOverlay } from './GeolocationAccessDeniedOverlay'\nimport { SubmissionErrorOverlay } from './SubmissionErrorOverlay'\nimport { NetworkError, SubmissionError, TokenPublicKeyError } from './Errors'\nimport { TokenMissingErrorOverlay } from './TokenMissingErrorOverlay'\nimport { TokenInvalidFormatErrorOverlay } from './TokenInvalidFormatErrorOverlay'\nimport { TokenInvalidSignatureErrorOverlay } from './TokenInvalidSignatureErrorOverlay'\nimport { TokenExpiredErrorOverlay } from './TokenExpiredErrorOverlay'\nimport { TokenPublicKeyErrorOverlay } from './TokenPublicKeyErrorOverlay'\n\nexport type TokenState =\n | 'NOT_PARSED'\n | 'PARSING'\n | 'GOOD'\n | 'EXPIRED'\n | 'INVALID_FORMAT'\n | 'INVALID_SIGNATURE'\n | 'MISSING'\n | 'PUBLIC_KEY_LOAD_FAILED'\n\nexport type SubmissionProviderProps = {\n action: SubmissionAction\n children: ReactElement\n token: string\n url?: string\n environment?: SubmissionEnvironment\n companyId?: string\n enrollmentId?: string\n personalData?: PersonalData\n cardData?: CardData\n bypassAgeValidation?: boolean\n bypassNameMatching?: boolean\n needImmediateResponse?: boolean\n manualReviewRequired?: boolean\n idBackImageRequired?: boolean\n idImageResolutionCheck?: boolean\n verifyIdWithExternalDatabases?: boolean\n deduplicationEnabled?: boolean\n deduplicationSynchronous?: boolean\n geolocationEnabled?: boolean\n geolocationRequired?: boolean\n webhooksEnabled?: boolean\n webhooksClientTraceId?: string\n webhooksStripSpecialCharacters?: boolean\n webhooksSendInputImages?: boolean\n webhooksSendProcessedImages?: boolean\n webhooksFireOnReview?: boolean\n onSubmit?: (payload: SubmissionRequest) => void\n onBeforeSubmit?: (req: SubmissionRequest) => Promise<SubmissionRequest>\n onBeforeLivenessCheck?: (\n req: LivenessCheckRequest\n ) => Promise<LivenessCheckRequest>\n onResponseReceived?: (res: SubmissionResponse, req: SubmissionRequest) => void\n onRequestFailure?: (err: Error) => void\n}\n\nexport const SubmissionProvider = ({\n action,\n children,\n url,\n environment = 'prod',\n token,\n companyId,\n enrollmentId,\n personalData,\n cardData,\n bypassAgeValidation = false,\n bypassNameMatching = true,\n needImmediateResponse = false,\n manualReviewRequired = false,\n idBackImageRequired = true,\n idImageResolutionCheck = true,\n verifyIdWithExternalDatabases = false,\n deduplicationEnabled = false,\n deduplicationSynchronous = false,\n geolocationEnabled = true,\n geolocationRequired = false,\n webhooksEnabled = false,\n webhooksClientTraceId,\n webhooksStripSpecialCharacters = true,\n webhooksSendInputImages = false,\n webhooksSendProcessedImages = false,\n webhooksFireOnReview = false,\n onSubmit,\n onBeforeSubmit,\n onBeforeLivenessCheck,\n onResponseReceived,\n onRequestFailure,\n}: SubmissionProviderProps): ReactElement => {\n const [submissionStatus, setSubmissionStatus] = useState<SubmissionStatus>(\n SubmissionStatus.READY\n )\n const [submissionRequest, setSubmissionRequest] =\n useState<SubmissionRequest | null>(null)\n const [submissionResponse, setSubmissionResponse] =\n useState<SubmissionResponse | null>(null)\n const [submissionError, setSubmissionError] = useState<\n SubmissionError | NetworkError | null\n >(null)\n const [retrySubmission, setRetrySubmission] = useState<(() => void) | null>(\n null\n )\n const [livenessCheckRequest, setLivenessCheckRequest] =\n useState<LivenessCheckRequest | null>(null)\n\n const [idFrontImage, setIdFrontImage] = useState<string | null>(null)\n const [idBackImage, setIdBackImage] = useState<string | null>(null)\n const [passportImage, setPassportImage] = useState<string | null>(null)\n const [selfieImage, setSelfieImage] = useState<string | null>(null)\n const [signatureData, setSignatureData] = useState<SignatureData | null>(null)\n const [signatureVideoUrl, setSignatureVideoUrl] = useState<string | null>(\n null\n )\n const [idCaptureVideoUrl, setIdCaptureVideoUrl] = useState<string | null>(\n null\n )\n const [additionalDocuments, setAdditionalDocuments] = useState<\n UploadedDocument[] | null\n >(null)\n\n const [geolocationResult, setGeolocationResult] =\n useState<GeolocationPosition | null>(null)\n const [geolocationAttempts, setGeolocationAttempts] = useState(0)\n const [geolocationBlocked, setGeolocationBlocked] = useState(false)\n\n const [idFrontCaptureAttempts, setIdFrontCaptureAttempts] = useState<\n CaptureAttemptMetadata[]\n >([])\n const [idBackCaptureAttempts, setIdBackCaptureAttempts] = useState<\n CaptureAttemptMetadata[]\n >([])\n const [selfieCaptureAttempts, setSelfieCaptureAttempts] = useState<\n CaptureAttemptMetadata[]\n >([])\n\n const logIdFrontCaptureAttempt = useCallback(\n (attempt: CaptureAttemptMetadata) => {\n setIdFrontCaptureAttempts((attempts) => [...attempts, attempt])\n },\n []\n )\n const logIdBackCaptureAttempt = useCallback(\n (attempt: CaptureAttemptMetadata) => {\n setIdBackCaptureAttempts((attempts) => [...attempts, attempt])\n },\n []\n )\n const logSelfieCaptureAttempt = useCallback(\n (attempt: CaptureAttemptMetadata) => {\n setSelfieCaptureAttempts((attempts) => [...attempts, attempt])\n },\n []\n )\n\n const buildSubmissionPayload = useCallback(async () => {\n let submissionRequest: SubmissionRequest = {\n securityData: { userName: '', password: '', merchantId: 0 },\n customerData: {\n idData: { idType: 'NSP', idCountry: 'NSP', idState: '' },\n },\n additionalData: {\n uniqueRequestId: new Date().getTime().toString(),\n manualReviewRequired: manualReviewRequired ? 'Y' : 'N',\n bypassAgeValidation: bypassAgeValidation ? 'Y' : 'N',\n bypassNameMatching: bypassNameMatching ? 'Y' : 'N',\n postDataAPIRequired: webhooksEnabled ? 'Y' : 'N',\n postDataOnReviewRequired: webhooksFireOnReview ? 'Y' : 'N',\n sendInputImagesInPost: webhooksSendInputImages ? 'Y' : 'N',\n sendProcessedImagesInPost: webhooksSendProcessedImages ? 'Y' : 'N',\n needImmediateResponse: needImmediateResponse ? 'Y' : 'N',\n deDuplicationRequired: deduplicationEnabled ? 'Y' : 'N',\n deduplicationSynchronous: deduplicationSynchronous ? 'Y' : 'N',\n verifyDataWithHost: verifyIdWithExternalDatabases ? 'Y' : 'N',\n idBackImageRequired: idBackImageRequired ? 'Y' : 'N',\n stripSpecialCharacters: webhooksStripSpecialCharacters ? 'Y' : 'N',\n idImageResolutionCheck: idImageResolutionCheck ? 'Y' : 'N',\n },\n }\n\n if (idFrontImage) {\n submissionRequest.customerData.idData.idImageFront = idFrontImage\n }\n if (idBackImage) {\n submissionRequest.customerData.idData.idImageBack = idBackImage\n }\n if (passportImage) {\n submissionRequest.customerData.idData.idImageFront = passportImage\n }\n if (selfieImage) {\n if (action === SubmissionAction.IDENTIFY) {\n submissionRequest.biometricData = { selfie: selfieImage }\n } else {\n submissionRequest.customerData.biometricData = { selfie: selfieImage }\n }\n }\n if (companyId) {\n submissionRequest.employee = { companyId }\n }\n if (personalData) {\n submissionRequest.customerData.personalData = personalData\n }\n if (cardData) {\n submissionRequest.customerData.cardData = cardData\n }\n if (enrollmentId) {\n submissionRequest.customerData.personalData ||= {}\n submissionRequest.customerData.personalData.uniqueNumber = enrollmentId\n }\n if (webhooksClientTraceId) {\n submissionRequest.additionalData.clientTraceId = webhooksClientTraceId\n }\n if (signatureData) {\n submissionRequest.customerData.signatureData = {\n signatureImage: JSON.stringify(signatureData),\n // signatureImage: signatureData.fileContent,\n }\n }\n if (additionalDocuments) {\n submissionRequest.customerData.additionalDocuments =\n additionalDocuments.map((d) => ({\n ...d,\n additionalDocument: JSON.stringify({\n ...(d.additionalDocument as Record<string, string>),\n uniqueId: submissionRequest.additionalData.uniqueRequestId,\n }),\n }))\n }\n if (idCaptureVideoUrl || signatureVideoUrl) {\n submissionRequest.biometricData ||= {}\n submissionRequest.biometricData.videoData = await videoDataUrlToB64(\n idCaptureVideoUrl ?? signatureVideoUrl ?? ''\n )\n }\n\n attachMetadataToRequest(submissionRequest, {\n selfieCaptureAttempts,\n idFrontCaptureAttempts,\n idBackCaptureAttempts,\n geolocationResult,\n })\n\n if (onBeforeSubmit) {\n const onBeforeSubmitResult = await onBeforeSubmit(submissionRequest)\n if (onBeforeSubmitResult) submissionRequest = onBeforeSubmitResult\n }\n\n return submissionRequest\n }, [\n action,\n additionalDocuments,\n bypassAgeValidation,\n bypassNameMatching,\n cardData,\n companyId,\n deduplicationEnabled,\n deduplicationSynchronous,\n enrollmentId,\n geolocationResult,\n idBackCaptureAttempts,\n idBackImage,\n idBackImageRequired,\n idCaptureVideoUrl,\n idFrontCaptureAttempts,\n idFrontImage,\n idImageResolutionCheck,\n manualReviewRequired,\n needImmediateResponse,\n onBeforeSubmit,\n passportImage,\n personalData,\n selfieCaptureAttempts,\n selfieImage,\n signatureData,\n signatureVideoUrl,\n verifyIdWithExternalDatabases,\n webhooksClientTraceId,\n webhooksEnabled,\n webhooksFireOnReview,\n webhooksSendInputImages,\n webhooksSendProcessedImages,\n webhooksStripSpecialCharacters,\n ])\n\n const defaultOnSubmit = useCallback(async () => {\n if (action === SubmissionAction.NONE) {\n const submissionResponse = {\n status: { statusCode: '000' },\n resultData: {},\n }\n setSubmissionStatus(SubmissionStatus.SUBMITTED)\n setSubmissionResponse(submissionResponse)\n return submissionResponse\n }\n\n setSubmissionStatus(SubmissionStatus.SUBMITTING)\n\n try {\n const payload = await buildSubmissionPayload()\n const host = url || determineSubmissionHost(environment, token)\n const endpoint = determineSubmissionEndpoint(\n action,\n !!(idFrontImage || idBackImage || passportImage),\n !!selfieImage,\n !!token\n )\n const response = await fetch(host + endpoint, {\n method: 'POST',\n headers: apiHeaders(token),\n body: JSON.stringify(payload),\n }).catch((e) => {\n throw new NetworkError(e.message)\n })\n\n if (!response || !response.ok) {\n const statusMessage = await response?.text()\n\n if (!statusMessage || statusMessage === 'Load failed')\n throw new NetworkError(statusMessage)\n\n throw new SubmissionError({\n statusCode: response?.statusText ?? '???',\n statusMessage,\n })\n }\n\n const submissionResponse = await response.json()\n if (submissionResponse.status.statusCode !== '000') {\n throw new SubmissionError(submissionResponse.status)\n }\n\n setSubmissionRequest(payload)\n setSubmissionResponse(submissionResponse)\n setSubmissionStatus(SubmissionStatus.SUBMITTED)\n onResponseReceived?.(submissionResponse, payload)\n return submissionResponse\n } catch (e) {\n const err = e as Error\n setSubmissionStatus(SubmissionStatus.FAILED)\n setSubmissionError(\n e instanceof SubmissionError || e instanceof NetworkError\n ? e\n : err.message === 'Load failed'\n ? new NetworkError()\n : new SubmissionError({ statusCode: '', statusMessage: err.message })\n )\n setRetrySubmission(() =>\n ['VERIFY', 'IDENTIFY'].includes(action) ? () => null : defaultOnSubmit\n )\n onRequestFailure?.(err)\n throw err\n }\n }, [\n action,\n buildSubmissionPayload,\n environment,\n idBackImage,\n idFrontImage,\n onRequestFailure,\n onResponseReceived,\n passportImage,\n selfieImage,\n token,\n url,\n ])\n\n const submit = useCallback(async () => {\n if (onSubmit) return onSubmit(await buildSubmissionPayload())\n return await defaultOnSubmit()\n }, [buildSubmissionPayload, defaultOnSubmit, onSubmit])\n\n const checkLiveness = useCallback(\n async (imageDataUrl: string) => {\n try {\n let request: LivenessCheckRequest = {\n securityData: { userName: '', password: '', merchantId: 0 },\n customerData: {\n biometricData: { selfie: await dataUrlToBase64(imageDataUrl) },\n },\n additionalData: {\n uniqueRequestId: new Date().getTime().toString(),\n stripSpecialCharacters: webhooksStripSpecialCharacters ? 'Y' : 'N',\n estimateAge: 'N',\n predictGender: 'N',\n },\n }\n\n attachMetadataToRequest(request, {\n selfieCaptureAttempts,\n idFrontCaptureAttempts,\n idBackCaptureAttempts,\n geolocationResult,\n })\n\n setLivenessCheckRequest(request)\n\n if (onBeforeLivenessCheck) {\n const onBeforeLivenessCheckResult = await onBeforeLivenessCheck(\n request\n )\n if (onBeforeLivenessCheckResult) request = onBeforeLivenessCheckResult\n }\n\n const host = url || determineSubmissionHost(environment, token)\n const endpoint = liveCheckEndpoint(!!token)\n const response = await fetch(host + endpoint, {\n method: 'POST',\n headers: apiHeaders(token),\n body: JSON.stringify(request),\n }).catch((e) => {\n throw new NetworkError(e.message)\n })\n\n if (!response.ok) {\n const statusMessage = await response.text()\n\n if (!statusMessage || statusMessage === 'Load failed')\n throw new NetworkError(statusMessage)\n\n throw new SubmissionError({\n statusCode: response.statusText,\n statusMessage,\n })\n }\n\n const submissionResponse = await response.json()\n if (submissionResponse.status.statusCode !== '000') {\n throw new SubmissionError(submissionResponse.status)\n }\n\n setSubmissionResponse(submissionResponse)\n return submissionResponse\n } catch (e) {\n const err = e as Error\n setSubmissionStatus(SubmissionStatus.FAILED)\n setSubmissionError(\n e instanceof SubmissionError || e instanceof NetworkError\n ? e\n : err.message === 'Load failed'\n ? new NetworkError()\n : new SubmissionError({\n statusCode: '',\n statusMessage: err.message,\n })\n )\n // the face liveness routine will call again, so don't repeat the call here.\n setRetrySubmission(() => () => null)\n onRequestFailure?.(err)\n throw err\n }\n },\n [\n environment,\n geolocationResult,\n idBackCaptureAttempts,\n idFrontCaptureAttempts,\n onBeforeLivenessCheck,\n onRequestFailure,\n selfieCaptureAttempts,\n token,\n url,\n webhooksStripSpecialCharacters,\n ]\n )\n\n const retryLocationAccess = useCallback(() => {\n setGeolocationAttempts((n) => n + 1)\n }, [])\n\n useEffect(() => {\n if (!geolocationEnabled) return\n\n console.log('making geolocation attempt', geolocationAttempts)\n navigator.geolocation.getCurrentPosition(\n (position) => {\n setGeolocationResult(position)\n setGeolocationBlocked(false)\n },\n (positionError) => {\n if (positionError.code === 1) {\n setGeolocationBlocked(true)\n } else {\n throw new Error(positionError.message)\n }\n }\n )\n }, [geolocationAttempts, geolocationEnabled, geolocationRequired])\n\n const onRetry = useCallback(() => {\n if (!retrySubmission) return\n setSubmissionError(null)\n setSubmissionStatus(SubmissionStatus.READY)\n retrySubmission()\n }, [retrySubmission])\n\n const [tokenState, setTokenState] = useState<TokenState>('NOT_PARSED')\n const [tokenError, setTokenError] = useState<TokenPublicKeyError | null>(null)\n useEffect(() => {\n ;(async () => {\n setTokenState('PARSING')\n if (!token) return setTokenState('MISSING')\n\n let parsed: Record<string, unknown>\n try {\n parsed = parseJwt(token)\n } catch (e) {\n console.error('error parsing token', e)\n return setTokenState('INVALID_FORMAT')\n }\n\n const iss = parsed.iss as string\n let publicKey: CryptoKey\n try {\n const resp = await fetch(iss).then((r) => r.json())\n publicKey = await importRsaKey(\n `-----BEGIN PUBLIC KEY-----\\n${resp.public_key}\\n-----END PUBLIC KEY-----`\n )\n } catch (e) {\n console.error('error fetching public key', e)\n setTokenError(new TokenPublicKeyError(e as Error, iss))\n return setTokenState('PUBLIC_KEY_LOAD_FAILED')\n }\n\n let valid = false\n try {\n const parts = token.split('.')\n await window.crypto.subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey, //from generateKey or importKey above\n str2ab(parts[1]), //ArrayBuffer of the signature\n str2ab(parts[2]) //ArrayBuffer of the data\n )\n valid = true\n } catch (e) {\n console.error('error validating token', e)\n }\n if (!valid) return setTokenState('INVALID_SIGNATURE')\n\n const exp = parsed.exp\n if (Date.now() >= (exp as number) * 1000) {\n return setTokenState('EXPIRED')\n }\n\n setTokenState('GOOD')\n })()\n }, [token])\n\n const value: SubmissionState = {\n submit,\n submissionStatus,\n submissionRequest,\n submissionResponse,\n submissionError,\n submissionEnvironment: environment,\n\n idFrontImage,\n idBackImage,\n passportImage,\n selfieImage,\n signatureData,\n signatureVideoUrl,\n idCaptureVideoUrl,\n additionalDocuments,\n\n setIdFrontImage,\n setIdBackImage,\n setPassportImage,\n setSelfieImage,\n setSignatureData,\n setSignatureVideoUrl,\n setIdCaptureVideoUrl,\n setAdditionalDocuments,\n\n logIdFrontCaptureAttempt,\n logIdBackCaptureAttempt,\n logSelfieCaptureAttempt,\n\n livenessCheckRequest,\n checkLiveness,\n retryLocationAccess,\n }\n\n if (tokenState === 'MISSING') {\n return <TokenMissingErrorOverlay />\n }\n\n if (tokenState === 'INVALID_FORMAT') {\n return <TokenInvalidFormatErrorOverlay />\n }\n\n if (tokenState === 'INVALID_SIGNATURE') {\n return <TokenInvalidSignatureErrorOverlay />\n }\n\n if (tokenState === 'EXPIRED') {\n return <TokenExpiredErrorOverlay />\n }\n\n if (tokenState === 'PUBLIC_KEY_LOAD_FAILED') {\n return <TokenPublicKeyErrorOverlay error={tokenError} />\n }\n\n return (\n <SubmissionContext.Provider value={value}>\n {geolocationRequired && geolocationBlocked ? (\n <GeolocationAccessDeniedOverlay />\n ) : (\n children\n )}\n\n {submissionError && (\n <SubmissionErrorOverlay error={submissionError} onRetry={onRetry} />\n )}\n </SubmissionContext.Provider>\n )\n}\n\nfunction str2ab(str: string) {\n const buf = new ArrayBuffer(str.length)\n const bufView = new Uint8Array(buf)\n for (let i = 0, strLen = str.length; i < strLen; i++) {\n bufView[i] = str.charCodeAt(i)\n }\n return buf\n}\n\nfunction importRsaKey(pem: string) {\n // fetch the part of the PEM string between header and footer\n const pemHeader = '-----BEGIN PUBLIC KEY-----'\n const pemFooter = '-----END PUBLIC KEY-----'\n const pemContents = pem.substring(\n pemHeader.length,\n pem.length - pemFooter.length - 1\n )\n // base64 decode the string to get the binary data\n const binaryDerString = window.atob(pemContents)\n // convert from a binary string to an ArrayBuffer\n const binaryDer = str2ab(binaryDerString)\n\n return window.crypto.subtle.importKey(\n 'spki',\n binaryDer,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: 'SHA-256',\n },\n true,\n ['verify']\n )\n}\n","import * as tf from '@tensorflow/tfjs'\n\nexport enum DocumentType {\n NONE = 'NONE',\n ID_CARD = 'ID_CARD',\n ID_CARD_FRONT = 'ID_CARD_FRONT',\n ID_CARD_BACK = 'ID_CARD_BACK',\n PASSPORT = 'PASSPORT',\n}\n\nexport let documentDetectionModel: tf.GraphModel | null\n\nexport async function loadDocumentDetectionModel(\n url: string\n): Promise<tf.GraphModel> {\n if (documentDetectionModel) return documentDetectionModel\n\n documentDetectionModel = await tf.loadGraphModel(url)\n await tf.ready()\n\n // warm the model by predicting on an empty image\n const zeroes = tf.zeros([448, 448, 3])\n const tfInt32 = tf.cast(zeroes, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(tfInt32.dataSync()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n tf.dispose(await documentDetectionModel.executeAsync(tf4d))\n\n tfInt32.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(zeroes)\n\n return documentDetectionModel\n}\n\nexport function unloadDocumentDetectionModel(): void {\n documentDetectionModel = null\n}\n\nexport type RawEdgeDetectionResult = tf.Tensor<tf.Rank>[]\n\nexport async function makeDocumentDetectionPredictions(\n model: tf.GraphModel,\n image: ImageBitmap | ImageData | HTMLImageElement\n): Promise<[RawEdgeDetectionResult, () => void]> {\n const tfImg = tf.browser.fromPixels(image)\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n const tfInt32 = tf.cast(tfResize, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(tfInt32.dataSync()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n const predictions = (await model.executeAsync(tf4d)) as RawEdgeDetectionResult\n const cleanup = () => {\n tfInt32.dispose()\n tfImg.dispose()\n tfResize.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(predictions)\n }\n return [predictions, cleanup]\n}\n\nexport type DocumentDetectionResults = {\n boxes: number[][]\n scores: number[]\n labels: number[]\n}\n\nexport const labelMap: { [id: number]: Label } = {\n 1: 'Document',\n 2: 'MRZ',\n 3: 'PDF417',\n 4: 'Primary face',\n 5: 'Secondary face',\n 6: 'Glare',\n 7: 'Punch Hole',\n 8: 'Passport Page',\n}\n\nexport type Label =\n | 'Document'\n | 'MRZ'\n | 'PDF417'\n | 'Primary face'\n | 'Secondary face'\n | 'Glare'\n | 'Punch Hole'\n | 'Passport Page'\n\nexport async function runDocumentDetection(\n model: tf.GraphModel,\n image: ImageBitmap | ImageData | HTMLImageElement\n): Promise<DocumentDetectionResults> {\n const [predictions, cleanup] = await makeDocumentDetectionPredictions(\n model,\n image\n )\n\n const [boxes] = (await predictions[2].array()) as number[][][]\n const [scores] = (await predictions[6].array()) as number[][]\n const [labels] = (await predictions[4].array()) as number[][]\n\n cleanup()\n\n return { boxes, scores, labels }\n}\n\nexport type DetectedObject = {\n score: number\n bbox: number[]\n label: Label\n}\n\nexport function bboxToDetectedObjectUnscaled(\n box: number[],\n score: number,\n label: number\n): DetectedObject {\n const [minY, minX, maxY, maxX] = box\n const bbox = [minX, minY, maxX - minX, maxY - minY]\n return { score, bbox, label: labelMap[label] }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nlet isMobileMockValue: boolean|undefined;\n\nexport function mockIsMobile(value: boolean|undefined) {\n isMobileMockValue = value;\n}\n\nexport function isMobile(nav?: Navigator): boolean {\n if (isMobileMockValue !== undefined) {\n return isMobileMockValue;\n }\n if (nav || _isNavigatorDefined()) {\n if (!nav) {\n nav = navigator;\n }\n if (nav.product === 'ReactNative') {\n return true;\n }\n\n const a = nav.userAgent || nav.vendor ||\n // tslint:disable-next-line:no-any\n (typeof window !== 'undefined' ? (window as any).opera : '');\n // Use `navigator.userAgentData.mobile` as fallback.\n if (!a) {\n // tslint:disable-next-line:no-any\n const navAny = nav as any;\n return navAny.userAgentData && navAny.userAgentData.mobile;\n }\n // tslint:disable-next-line:max-line-length\n return /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n","import React, { ReactElement, useContext, useEffect } from 'react'\nimport { GuideOrientationContext } from '../../contexts/GuideOrientationContext'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport { PageContainer } from '../common/Page'\nimport styled, { useTheme } from 'styled-components'\n\nexport const GuidesContainer = styled.div`\n display: flex;\n flex-flow: column nowrap;\n width: 100%;\n height: 100%;\n`\n\nexport const GuideCenterRow = styled.div`\n position: relative;\n display: flex;\n flex-flow: row nowrap;\n align-items: center;\n justify-items: center;\n box-sizing: border-box;\n max-width: 100%;\n max-height: 100%;\n`\n\nexport const GuideRegion = styled.div<{\n $minWidth?: number\n $minHeight?: number\n}>`\n display: flex;\n flex-direction: column;\n justify-content: end;\n width: 100%;\n height: 100%;\n flex-grow: 1;\n background: ${(props) =>\n props.theme?.idCapture?.guideOverlay?.backgroundColor ??\n 'rgba(0, 0, 0, 0.5)'};\n color: ${(props) =>\n props.theme?.idCapture?.guideOverlay?.textColor ?? 'white'};\n text-align: center;\n ${(props) => (props.$minWidth ? `min-width: ${props.$minWidth}px;` : ``)}\n ${(props) => (props.$minHeight ? `min-width: ${props.$minHeight}px;` : ``)}\n`\n\nexport const GuideCenterRegion = styled.div<{ $isMirrored?: boolean }>`\n ${(props) => (props.$isMirrored ? 'transform: scaleX(-1);' : '')}\n box-sizing: border-box;\n`\n\nexport const GuideCenterBorder = styled.div<{\n $borderWidth: number\n $borderColor?: string\n}>`\n position: relative;\n border: ${(props) =>\n `${props.$borderWidth ?? 4}px solid ${props.$borderColor ?? 'white'}`};\n`\n\nexport const GuideText = styled.span`\n align-content: center;\n margin-top: 12px;\n margin-bottom: 12px;\n`\n\nexport const GuideImage = styled.img<{\n $width?: number\n $height?: number\n}>`\n display: block;\n ${(props) =>\n props.$width\n ? `width: ${props.$width}px; max-width: ${props.$width}px;`\n : `max-width: none;`}\n ${(props) =>\n props.$height\n ? `height: ${props.$height}px; max-height: ${props.$height}px;`\n : `max-width: none;`}\n`\n\nexport type DocumentCaptureGuideOverlayClassNames = {\n container?: string\n inner?: string\n dimmingRegion?: string\n dimmingRegionTop?: string\n dimmingRegionLeft?: string\n dimmingRegionRight?: string\n dimmingRegionBottom?: string\n centerRow?: string\n centerRegion?: string\n centerRegionInner?: string\n image?: string\n guideText?: string\n}\n\nexport type DocumentCaptureGuideOverlayProps = {\n classNames?: DocumentCaptureGuideOverlayClassNames\n width?: number\n height?: number\n padding?: number\n borderWidth?: number\n borderColor?: string\n isMirrored?: boolean\n instruction?: string\n portraitGuidesImageUrl?: string\n landscapeGuidesImageUrl?: string\n onClick?: () => void\n}\n\nexport const DocumentCaptureGuideOverlay = ({\n classNames = {},\n width = 0,\n height = 0,\n padding = isMobile() ? 0 : 50,\n borderWidth,\n borderColor,\n isMirrored = false,\n instruction = '',\n portraitGuidesImageUrl,\n landscapeGuidesImageUrl,\n onClick,\n}: DocumentCaptureGuideOverlayProps): ReactElement => {\n const {\n orientation,\n wrapperRef,\n wrapperWidth,\n wrapperHeight,\n imageAspectRatio,\n wrapperAspectRatio,\n onImageLoaded,\n setDimensions,\n } = useContext(GuideOrientationContext)\n\n const theme = useTheme()\n if (borderWidth === undefined)\n borderWidth = theme.idCapture?.guideBox?.borderWidth ?? 4\n\n if (width == 0) width = wrapperWidth\n if (height == 0) height = wrapperHeight\n\n useEffect(() => {\n setDimensions({ width, height })\n }, [height, setDimensions, width])\n\n const paddingAndBorderPx = padding * 2 + borderWidth * 2\n const imgSrc =\n orientation === 'portrait'\n ? portraitGuidesImageUrl\n : landscapeGuidesImageUrl\n\n let imageWidth: number | undefined = undefined,\n imageHeight: number | undefined = undefined\n if (imageAspectRatio >= wrapperAspectRatio) {\n imageWidth = wrapperWidth - paddingAndBorderPx\n } else {\n imageHeight = wrapperHeight - paddingAndBorderPx\n }\n\n return (\n <StyledPageContainer\n ref={wrapperRef}\n onClick={onClick}\n className={classNames.container}\n >\n <GuidesContainer className={classNames.inner}>\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Top')}\n >\n {instruction !== '' && (\n <GuideText className={classNames.guideText}>\n {instruction}\n </GuideText>\n )}\n </GuideRegion>\n\n <GuideCenterRow className={classNames.centerRow}>\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Left')}\n />\n\n <GuideCenterRegion\n $isMirrored={isMirrored}\n className={classNames.centerRegion}\n >\n <GuideCenterBorder\n $borderWidth={borderWidth}\n $borderColor={borderColor}\n className={classNames.centerRegionInner}\n >\n <GuideImage\n src={imgSrc}\n alt=\"\"\n onLoad={onImageLoaded}\n className={classNames.image}\n $width={imageWidth}\n $height={imageHeight}\n />\n </GuideCenterBorder>\n </GuideCenterRegion>\n\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Right')}\n />\n </GuideCenterRow>\n\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Bottom')}\n >\n {instruction !== '' && (\n <GuideText style={{ opacity: 0 }}>{instruction}</GuideText>\n )}\n </GuideRegion>\n </GuidesContainer>\n </StyledPageContainer>\n )\n}\n\nconst StyledPageContainer = styled(PageContainer)`\n z-index: 1000;\n`\n\nconst regionClsx = (\n classNames: DocumentCaptureGuideOverlayClassNames,\n which: 'Top' | 'Left' | 'Right' | 'Bottom'\n): string =>\n [classNames.dimmingRegion, classNames[`dimmingRegion${which}`]]\n .filter((v) => v)\n .join(' ')\n","export async function getNativeBarcodeReaderResult(image) {\n if (!('BarcodeDetector' in window)) return []\n const barcodeDetector = new BarcodeDetector({ formats: ['pdf417'] })\n console.log('this is a real native result!')\n return await barcodeDetector.detect(image)\n}\n","export async function getZxingBarcodeReaderResult(image, rotate = false) {\n let canvas, ctx, imageWidth, imageHeight\n\n const actualImage = await new Promise((resolve) => {\n imageWidth = image.naturalWidth\n imageHeight = image.naturalHeight\n canvas = document.createElement('canvas')\n ctx = canvas.getContext('2d')\n if (!ctx) return []\n\n if (rotate) {\n console.log('rotating!!')\n canvas.width = imageHeight\n canvas.height = imageWidth\n ctx.setTransform(0, 1, -1, 0, canvas.width, 0)\n ctx.drawImage(image, 0, 0, imageWidth, imageHeight)\n const newImage = new Image()\n newImage.width = canvas.width\n newImage.height = canvas.height\n newImage.onload = () => {\n resolve(newImage)\n }\n\n canvas.toBlob((blob) => {\n if (blob) newImage.src = URL.createObjectURL(blob)\n })\n } else {\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height)\n resolve(image)\n }\n })\n\n const source = new ZXing.BitmapLuminanceSource(ctx, actualImage)\n const binarizer = new ZXing.Common.HybridBinarizer(source)\n const bitmap = new ZXing.BinaryBitmap(binarizer)\n const results = ZXing.PDF417.PDF417Reader.decode(bitmap, null, false)\n\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n canvas.remove()\n\n return results\n}\n","import { getNativeBarcodeReaderResult, PDF417DetectionResult } from './Native'\nimport { getZxingBarcodeReaderResult } from './ZXing'\n\nexport function supportsNativeBarcodeScanning(): boolean {\n return 'BarcodeDetector' in window\n}\n\nexport function scanBarcode(\n blob: Blob,\n bbox?: number[]\n): Promise<PDF417DetectionResult | null> {\n return new Promise((resolve) => {\n const image = new Image()\n image.onload = async () => {\n if (supportsNativeBarcodeScanning()) {\n const result = await getNativeBarcodeReaderResult(image)\n console.log('native result', result, `${image.width}x${image.height}`)\n if (result.length > 0) {\n resolve({ ...result[0], Source: 'native' })\n } else {\n resolve(null)\n }\n } else {\n const shouldRotate = (bbox?.[2] ?? 0) < (bbox?.[3] ?? 0)\n const result = await getZxingBarcodeReaderResult(image, shouldRotate)\n console.log('zxing result', result)\n if (result.length > 0) {\n resolve({ ...result[0], Source: 'zxing' })\n } else {\n resolve(null)\n }\n }\n }\n image.src = URL.createObjectURL(blob)\n })\n}\n","export function getBlobDimensions(blob: Blob): Promise<[number, number]> {\n return new Promise((resolve) => {\n const image = new Image()\n image.onload = () => {\n resolve([image.naturalWidth, image.naturalHeight])\n }\n image.src = URL.createObjectURL(blob)\n })\n}\n","export function iOS(): boolean {\n return (\n [\n 'iPad Simulator',\n 'iPhone Simulator',\n 'iPod Simulator',\n 'iPad',\n 'iPhone',\n 'iPod',\n ].includes(navigator.platform) ||\n // iPad on iOS 13 detection\n (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n )\n}\n\nexport function wideAngleIsBetter(): boolean {\n if (!iOS()) return false\n\n const smallerSide = smallerSideIos()\n const realWidth = window.screen.width * window.devicePixelRatio\n const realHeight = window.screen.height * window.devicePixelRatio\n\n return (\n (realWidth == 1179 && realHeight == 2556) ||\n (realWidth == 1290 &&\n realHeight == 2796 &&\n (smallerSide == 393 || smallerSide == 430))\n )\n}\n\nfunction smallerSideIos() {\n return window.screen.width < window.screen.height\n ? window.screen.width\n : window.screen.height\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport { wideAngleIsBetter } from '../utils/deviceDetection'\nimport { getPlatform } from '../utils/platform'\n\nexport type Camera = {\n stream: MediaStream\n isRearFacing: boolean\n release: () => void\n label: string\n width: number\n height: number\n}\n\nexport type CameraResolution = 'LOW' | 'MID' | 'MAX'\n\nlet choosingCamera = false\n\nexport async function selectAndOpenCamera(\n resolution: CameraResolution = 'MID'\n): Promise<Camera> {\n if (choosingCamera) {\n await new Promise((resolve) => {\n const interval = setInterval(() => {\n if (!choosingCamera) {\n clearInterval(interval)\n resolve(null)\n }\n }, 10)\n })\n }\n\n choosingCamera = true\n\n const video: MediaTrackConstraints = {\n facingMode: { ideal: 'environment' },\n focusMode: 'continuous',\n }\n if (resolution === 'LOW') {\n video.width = { ideal: 640 }\n } else if (resolution === 'MID') {\n video.width = { ideal: 1920 }\n }\n\n const stream = await navigator.mediaDevices.getUserMedia({ video })\n let mediaTrackSettings = stream.getVideoTracks()[0].getSettings()\n const camera: Camera = {\n // you only get the labels for each camera if you call getUserMedia first.\n stream,\n isRearFacing: false,\n release: () => {\n camera.stream.getTracks().forEach((track) => track.stop())\n },\n width: mediaTrackSettings.width ?? 0,\n height: mediaTrackSettings.height ?? 0,\n label: '',\n }\n\n let chosenLabel = ''\n let bestResDevice: [string, number, number] = ['', 0, 0]\n const videoDevices = (await navigator.mediaDevices.enumerateDevices()).filter(\n (deviceInfo) => deviceInfo.kind === 'videoinput'\n )\n\n await Promise.all(\n videoDevices.map(async (deviceInfo) => {\n console.log('checking out', deviceInfo.label, resolution)\n const { width: maxWidth, height: maxHeight } =\n await getVideoDeviceMaxDimensions(deviceInfo)\n console.log('device', deviceInfo.label, 'max dimensions', {\n maxWidth,\n maxHeight,\n })\n if (maxWidth > bestResDevice[1]) {\n bestResDevice = [deviceInfo.deviceId, maxWidth, maxHeight]\n }\n if (deviceInfo.label) {\n const label = deviceInfo.label.toLocaleLowerCase().split(' ').join('')\n if (\n labelMatches(label, rearLabels) &&\n !labelMatches(label, backUltraWideLabels)\n ) {\n camera.label = label\n camera.isRearFacing = true\n video.deviceId = deviceInfo.deviceId\n chosenLabel = label\n if (resolution === 'MAX') {\n console.log('going for max!', `${maxWidth}x${maxHeight}`)\n video.width = { exact: maxWidth }\n video.height = { exact: maxHeight }\n }\n }\n }\n })\n )\n\n if (resolution === 'MAX' && chosenLabel === '') {\n chosenLabel = bestResDevice[0]\n video.deviceId = bestResDevice[0]\n video.width = { ideal: bestResDevice[1] }\n video.height = { ideal: bestResDevice[2] }\n }\n console.log('chose device', chosenLabel, resolution)\n\n camera.label = chosenLabel\n\n if (video.deviceId) {\n camera.release()\n camera.stream = await navigator.mediaDevices.getUserMedia({ video })\n mediaTrackSettings = camera.stream.getVideoTracks()[0].getSettings()\n camera.width = mediaTrackSettings.width ?? 0\n camera.height = mediaTrackSettings.height ?? 0\n }\n\n console.log('SETTINGS', camera.stream.getVideoTracks()[0].getSettings())\n\n choosingCamera = false\n return camera\n}\n\n// interface HasCapabilities {\n// getCapabilities?: () => {\n// width: { max: number }\n// height: { max: number }\n// }\n// }\nexport async function getVideoDeviceMaxDimensions(\n deviceInfo: MediaDeviceInfo\n): Promise<{\n width: number\n height: number\n}> {\n const best = await bestAvailableResolution(deviceInfo)\n if (!best) return { width: 1, height: 1 }\n return { width: best.width, height: best.height }\n // try {\n // const {\n // width: { max: width },\n // height: { max: height },\n // } = (deviceInfo as HasCapabilities).getCapabilities?.() ?? {\n // width: { max: 1920 },\n // height: { max: 1080 },\n // }\n //\n // return { width, height }\n // } catch (e) {\n // console.error(e)\n // return { width: 1, height: 1 }\n // }\n}\n\ntype Resolution = {\n label: string\n width: number\n height: number\n ratio: string\n}\nexport const quickScan: Resolution[] = [\n // {\n // label: '4K(UHD)',\n // width: 3840,\n // height: 2160,\n // ratio: '16:9',\n // },\n {\n label: '1080p(FHD)',\n width: 1920,\n height: 1080,\n ratio: '16:9',\n },\n {\n label: 'UXGA',\n width: 1600,\n height: 1200,\n ratio: '4:3',\n },\n {\n label: '720p(HD)',\n width: 1280,\n height: 720,\n ratio: '16:9',\n },\n {\n label: 'SVGA',\n width: 800,\n height: 600,\n ratio: '4:3',\n },\n {\n label: 'VGA',\n width: 640,\n height: 480,\n ratio: '4:3',\n },\n {\n label: '360p(nHD)',\n width: 640,\n height: 360,\n ratio: '16:9',\n },\n {\n label: 'CIF',\n width: 352,\n height: 288,\n ratio: '4:3',\n },\n {\n label: 'QVGA',\n width: 320,\n height: 240,\n ratio: '4:3',\n },\n {\n label: 'QCIF',\n width: 176,\n height: 144,\n ratio: '4:3',\n },\n {\n label: 'QQVGA',\n width: 160,\n height: 120,\n ratio: '4:3',\n },\n]\n\nasync function bestAvailableResolution(\n deviceInfo: MediaDeviceInfo\n): Promise<Resolution | null> {\n for (let i = 0; i !== quickScan.length; ++i) {\n if (await isResolutionAvailable(quickScan[i], deviceInfo)) {\n return quickScan[i]\n }\n }\n\n return null\n}\n\nfunction isResolutionAvailable(\n candidate: Resolution,\n deviceInfo: MediaDeviceInfo\n): Promise<boolean> {\n return new Promise((resolve) => {\n // const devices = []\n // const deviceInfos = await navigator.mediaDevices.enumerateDevices()\n //\n // for (let i = 0; i !== deviceInfos.length; ++i) {\n // const deviceInfo = deviceInfos[i]\n // if (deviceInfo.kind === 'videoinput') {\n // devices.push(deviceInfo)\n // }\n // }\n\n const video = document.createElement('video')\n const windowWithStream = window as unknown as { stream: MediaStream }\n const existingStream = windowWithStream.stream\n if (existingStream) {\n existingStream.getTracks().forEach((track) => {\n track.stop()\n })\n }\n\n const constraints = {\n audio: false,\n video: {\n deviceId: deviceInfo.deviceId,\n // ? { exact: deviceInfo.deviceId }\n // : undefined,\n width: { exact: candidate.width }, //new syntax\n height: { exact: candidate.height }, //new syntax\n },\n }\n\n setTimeout(\n () => {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(gotStream)\n .catch((error) => {\n console.log('getUserMedia error!', error, candidate)\n resolve(false)\n })\n },\n windowWithStream.stream ? 200 : 0\n ) //official examples had this at 200\n\n function gotStream(mediaStream: MediaStream) {\n //change the video dimensions\n console.log(\n 'Display size for ' +\n candidate.label +\n ': ' +\n candidate.width +\n 'x' +\n candidate.height\n )\n video.width = candidate.width\n video.height = candidate.height\n\n windowWithStream.stream = mediaStream // make globally available\n video.srcObject = mediaStream\n\n resolve(true)\n }\n })\n}\n\nexport type FacingMode = 'user' | 'environment' | 'left' | 'right'\n\nexport async function listAvailableCameras(\n facingMode?: FacingMode,\n requestMicAccess: boolean = false\n): Promise<MediaDeviceInfo[]> {\n // The first thing we need to do is call getUserMedia() so that the subsequent call to enumerateDevices() works.\n let cameraEnumerationStream: MediaStream | null =\n await navigator.mediaDevices.getUserMedia({\n video: { facingMode: { exact: facingMode } },\n audio: requestMicAccess,\n })\n\n // This lists all available cameras attached to the user's device.\n const videoDevices = (await navigator.mediaDevices.enumerateDevices()).filter(\n ({ kind }) => kind === 'videoinput'\n )\n\n // Release the access to the user's camera that we obtained for enumeration purposes.\n cameraEnumerationStream.getVideoTracks().forEach((track) => {\n track.enabled = false\n track.stop()\n })\n\n cameraEnumerationStream = null\n\n return videoDevices\n}\n\nconst frontLabels = [\n 'front',\n 'avant',\n 'anteriore',\n 'cameraaanvoorzijde',\n 'kamerapåframsidan',\n 'forsidekamera',\n 'kamerapåforsiden',\n 'aparatprzedni',\n 'etukamera',\n 'kameradepan',\n 'ÖnKamera',\n 'cameramặttrước',\n 'camerăfață',\n 'prednákamera',\n 'prednjakamera',\n 'előlapikamera',\n 'přednífotoaparát',\n 'μπροστινήκάμερα',\n 'переднякамера',\n 'передняякамера',\n 'преднакамера',\n 'алдыңғыкамера',\n 'מצלמה קדמית',\n 'الكاميرا الأمامية',\n 'फ़्रंटकैमरा',\n '前置相机',\n '前置鏡頭',\n '前面カメラ',\n '전면카메라',\n 'กล้องด้านหน้า',\n].map((s) => s.toLocaleLowerCase().split(' ').join(''))\nconst rearLabels = [\n 'back',\n 'rear',\n 'posterior',\n 'trasera',\n 'traseira',\n 'arrière',\n 'rückkamera',\n 'fotocamera(posteriore)',\n 'cameraaanachterzijde',\n 'kamerapåbaksidan',\n 'kamerapåbaksiden',\n 'bagsidekamera',\n 'aparattylny',\n 'takakamera',\n 'arkakamera',\n 'kamerabelakang',\n 'cameramặtsau',\n 'camerăspate',\n 'stražnjakamera',\n 'zadnákamera',\n 'hátoldalikamera',\n 'zadnífotoaparát',\n 'πίσωκάμερα',\n 'заднякамера',\n 'Задняякамера',\n 'заднакамера',\n 'артқыкамера',\n 'מצלמה אחורית',\n 'الكاميرا الخلفية',\n 'बैककैमरा',\n '后置相机',\n '後置鏡頭',\n '背面カメラ',\n '후면카메라',\n 'กล้องด้านหลัง',\n].map((s) => s.toLocaleLowerCase().split(' ').join(''))\nconst backUltraWideLabels = [\n 'backultrawidecamera',\n 'ultraampliaposterior',\n 'ultra-angulartraseira',\n 'ultragrandeangulartraseira',\n 'ultragrandangle',\n 'ultragranangular',\n 'ultra-weitwinkelkamera',\n 'ultra-grandangolo',\n 'ultrabredecameraaanachterzijde',\n 'ultravidvinkelkamerapåbaksidan',\n 'ultravidvinkelkameraetpåbagsiden',\n 'ultravidvinkelkamerabak',\n 'ultragenişkameraarkayüzü',\n 'ultralaajakulmainentakakamera',\n 'tylnyaparatultraszerokokątny',\n 'cameracựcrộngmặtsau',\n 'camerăcuobiectivultra‑superangularspate',\n 'ultraszéleslátószögűkamera',\n 'kameraultralebarbelakang',\n 'stražnjaultraširokakamera',\n 'zadníultraširokoúhlýfotoaparát',\n 'ultraširokouhlá',\n 'πίσωυπερευρείακάμερα',\n 'заднянадширококутнакамера',\n 'Задняясверхширокоугольнаякамера',\n 'Задна свръх широкоъгълна камера',\n 'артқыультракеңбұрыштыкамера',\n 'מצלמה אולטרה רחבה אחורית',\n 'كاميرا خلفية عريضة جدًا',\n 'बैकअल्ट्रावाइडकैमरा',\n '后置超广角相机',\n '後置超廣角鏡頭相機',\n '背面超広角カメラ',\n '후면울트라와이드카메라',\n 'กล้องด้านหลังอัลตร้าไวด์',\n].map((s) => s.toLocaleLowerCase().split(' ').join(''))\n\nconst labelMatches = (\n labelOrDevice: string | MediaDeviceInfo,\n labelSetOrLabel: string | string[]\n) => {\n const label =\n labelOrDevice instanceof MediaDeviceInfo\n ? getDeviceLabel(labelOrDevice)\n : labelOrDevice\n\n const labelSet =\n typeof labelSetOrLabel === 'string' ? [labelSetOrLabel] : labelSetOrLabel\n\n return labelSet.some((l) => label.includes(l))\n}\n\nconst getDeviceLabel = (deviceInfo: MediaDeviceInfo) =>\n deviceInfo.label.toLocaleLowerCase().split(' ').join('')\n\nlet currentCamera: Camera | undefined\n\nexport function obtainCameraAccess(\n stream: MediaStream,\n deviceLabel: string,\n video?: HTMLVideoElement | null\n): Camera {\n releaseCameraAccess()\n\n console.log('obtaining camera access...')\n let { width, height } = stream.getVideoTracks()[0].getSettings()\n const label = deviceLabel.toLocaleLowerCase().split(' ').join('')\n const isRearFacing = labelMatches(label, [\n ...rearLabels,\n ...backUltraWideLabels,\n 'iphone',\n ])\n const release = () => {\n stream.getTracks().forEach((track) => {\n track.enabled = false\n track.stop()\n })\n if (video) {\n video.pause()\n video.srcObject = null\n video.src = ''\n }\n }\n\n width ||= 0\n height ||= 0\n\n currentCamera = {\n label: deviceLabel,\n stream,\n width,\n height,\n isRearFacing,\n release,\n }\n if (video) video.srcObject = stream\n\n return currentCamera\n}\n\nexport function releaseCameraAccess() {\n if (!currentCamera) return\n console.log('releasing camera access...')\n currentCamera.release()\n currentCamera = undefined\n}\n\nexport const useHighestResCaptureDevice = (\n {\n preferFrontFacingCamera = false,\n preferContinuityCamera = true,\n requestMicrophoneAccess = false,\n }: {\n preferFrontFacingCamera: boolean\n preferContinuityCamera: boolean\n requestMicrophoneAccess: boolean\n } = {\n preferFrontFacingCamera: false,\n preferContinuityCamera: true,\n requestMicrophoneAccess: false,\n }\n) => {\n const videoRef = useRef<HTMLVideoElement | null>(null)\n const cameraRef = useRef<Camera | null>(null)\n const [cameraReady, setCameraReady] = useState(false)\n const [videoDevice, setVideoDevice] = useState<MediaDeviceInfo | null>(null)\n const [videoLoaded, setVideoLoaded] = useState(false)\n const [iphoneContinuityCameraAvailable, setIphoneContinuityCameraAvailable] =\n useState(false)\n const [iphoneContinuityCameraAllowed, setIphoneContinuityCameraAllowed] =\n useState(preferContinuityCamera)\n const [iphoneContinuityCameraDenied, setIphoneContinuityCameraDenied] =\n useState(false)\n const [cameraAccessDenied, setCameraAccessDenied] = useState(false)\n\n useEffect(() => {\n console.log(\n 'iphone continuity camera allowed changed',\n iphoneContinuityCameraAllowed\n )\n releaseCameraAccess()\n cameraRef.current = null\n setVideoLoaded(false)\n }, [iphoneContinuityCameraAllowed])\n\n const retryCameraAccess = useCallback(() => {\n setCameraAccessDenied(false)\n }, [])\n\n useEffect(() => {\n if (cameraAccessDenied) return\n\n setCameraReady(false)\n listAvailableCameras()\n .then((availableCameras) => {\n let selectedCamera: MediaDeviceInfo | undefined\n\n const platform = getPlatform()\n if (\n !iphoneContinuityCameraDenied &&\n (!platform || platform.os.family === 'OS X')\n ) {\n const iphoneContinuityCamera = availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, 'iphone')\n )\n setIphoneContinuityCameraAvailable(!!iphoneContinuityCamera)\n if (iphoneContinuityCamera && iphoneContinuityCameraAllowed) {\n selectedCamera = iphoneContinuityCamera\n }\n } else if (platform?.os.family === 'Android') {\n availableCameras.reverse()\n }\n\n if (preferFrontFacingCamera) {\n selectedCamera = availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, frontLabels)\n )\n }\n\n if (wideAngleIsBetter()) {\n selectedCamera ||= availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, backUltraWideLabels)\n )\n } else {\n selectedCamera ||= availableCameras.find(\n (deviceInfo) =>\n labelMatches(deviceInfo, rearLabels) &&\n !labelMatches(deviceInfo, backUltraWideLabels)\n )\n }\n\n selectedCamera ||= availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, rearLabels)\n )\n\n // on iOS, the front facing camera always is at the first position in the list, so we skip it if all else fails.\n if (\n !preferFrontFacingCamera &&\n platform?.os.family === 'iOS' &&\n availableCameras.length > 0\n ) {\n selectedCamera ||= availableCameras[1]\n }\n\n selectedCamera ||= availableCameras[0]\n\n setVideoDevice(selectedCamera)\n })\n .catch((e) => {\n if ((e as { name: string }).name === 'NotAllowedError') {\n console.error('camera access has been blocked by the user', e)\n setCameraAccessDenied(true)\n } else {\n console.error('camera access encountered some other error', e)\n throw e\n }\n })\n }, [\n cameraAccessDenied,\n iphoneContinuityCameraAllowed,\n iphoneContinuityCameraDenied,\n preferFrontFacingCamera,\n ])\n\n useEffect(() => {\n if (!videoDevice) return\n\n const cleanup = () => {\n releaseCameraAccess()\n cameraRef.current = null\n setVideoLoaded(false)\n }\n\n if (!navigator.mediaDevices?.getUserMedia) return cleanup\n ;(async () => {\n let stream: MediaStream | null = null\n try {\n stream = await navigator.mediaDevices.getUserMedia({\n audio: requestMicrophoneAccess,\n video: {\n deviceId: { exact: videoDevice.deviceId },\n width: { ideal: 1920 },\n aspectRatio: 1.777777778,\n },\n })\n } catch (e) {\n if ((e as { name: string }).name === 'NotAllowedError') {\n if (iphoneContinuityCameraAllowed) {\n setIphoneContinuityCameraAvailable(false)\n setIphoneContinuityCameraDenied(true)\n } else {\n setCameraAccessDenied(true)\n }\n return\n }\n }\n\n if (!stream) {\n try {\n stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: true,\n })\n\n console.log('opened stream with no width and height constraints')\n } catch (e) {\n console.log('cannot open stream at all')\n }\n }\n\n if (!stream) {\n throw new Error('failed to open camera')\n }\n\n const handleStreamEnded = () => {\n if (iphoneContinuityCameraAvailable && iphoneContinuityCameraAllowed) {\n console.log('someone unplugged the continuity camera')\n releaseCameraAccess()\n cameraRef.current = null\n setIphoneContinuityCameraAvailable(false)\n setIphoneContinuityCameraDenied(true)\n setVideoDevice(null)\n } else {\n console.log('someone unplugged the webcam')\n releaseCameraAccess()\n cameraRef.current = null\n setVideoLoaded(false)\n setCameraAccessDenied(true)\n }\n }\n\n videoRef.current?.addEventListener('ended', handleStreamEnded)\n stream.getVideoTracks().forEach((track) => {\n track.onended = handleStreamEnded\n })\n\n cameraRef.current = obtainCameraAccess(\n stream,\n videoDevice.label,\n videoRef.current\n )\n })()\n\n return cleanup\n }, [\n iphoneContinuityCameraAllowed,\n iphoneContinuityCameraAvailable,\n requestMicrophoneAccess,\n videoDevice,\n ])\n\n useEffect(() => {\n setCameraReady(false)\n\n if (videoDevice && videoLoaded) {\n setCameraReady(true)\n }\n }, [videoLoaded, videoDevice])\n\n const takePhoto = useCallback(async (): Promise<Blob | null> => {\n const canvas = document.createElement('canvas')\n const ctx = canvas.getContext('2d')\n if (!ctx || !cameraRef.current || !videoRef.current) return null\n\n canvas.width = videoRef.current?.videoWidth\n canvas.height = videoRef.current?.videoHeight\n ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height)\n const photoURL = canvas.toDataURL('image/jpeg', 0.98)\n const data = await fetch(photoURL)\n return await data.blob()\n }, [])\n\n return {\n videoRef,\n videoDevice,\n videoLoaded,\n setVideoLoaded,\n cameraRef,\n cameraReady,\n cameraAccessDenied,\n retryCameraAccess,\n releaseCameraAccess,\n iphoneContinuityCameraAvailable,\n iphoneContinuityCameraAllowed,\n setIphoneContinuityCameraAllowed,\n takePhoto,\n }\n}\n\nexport const useDualResCaptureDevice = () => {\n const {\n videoRef: maxVideoRef,\n videoDevice,\n videoLoaded: maxVideoLoaded,\n setVideoLoaded: setMaxVideoLoaded,\n cameraRef: maxCameraRef,\n cameraReady: maxCameraReady,\n takePhoto: takeFullResPhoto,\n } = useHighestResCaptureDevice()\n\n const minVideoRef = useRef<HTMLVideoElement | null>(null)\n const [minCamera, setMinCamera] = useState<Camera | null>(null)\n const [minVideoLoaded, setMinVideoLoaded] = useState(false)\n\n useEffect(() => {\n if (!videoDevice || !maxCameraRef.current) return\n\n let cam: Camera\n const cleanup = () => {\n cam?.release()\n setMinCamera(null)\n setMinVideoLoaded(false)\n }\n\n if (!minVideoRef.current) return cleanup\n if (!navigator.mediaDevices?.getUserMedia) return cleanup\n ;(async () => {\n if (!maxCameraRef.current) return\n\n let idealWidth = 448\n let idealHeight = 448\n\n if (maxCameraRef.current.width < maxCameraRef.current.height) {\n idealHeight =\n 448 * (maxCameraRef.current.height / maxCameraRef.current.width)\n } else {\n idealWidth =\n 448 * (maxCameraRef.current.width / maxCameraRef.current.height)\n }\n\n console.log('min dimensions', idealWidth, idealHeight)\n\n const constraints = {\n audio: false,\n video: {\n deviceId: { exact: videoDevice.deviceId },\n width: { ideal: idealWidth },\n height: { ideal: idealHeight },\n },\n }\n\n const stream = await navigator.mediaDevices.getUserMedia(constraints)\n cam = obtainCameraAccess(stream, videoDevice.label, minVideoRef.current)\n setMinCamera(cam)\n })()\n\n return cleanup\n }, [maxCameraRef, videoDevice])\n\n return {\n minVideoRef,\n maxVideoRef,\n minCamera,\n maxCamera: maxCameraRef.current,\n maxCameraReady,\n minVideoLoaded,\n maxVideoLoaded,\n setMinVideoLoaded,\n setMaxVideoLoaded,\n takeFullResPhoto,\n }\n}\n","import React, {\n createContext,\n MutableRefObject,\n ReactElement,\n useEffect,\n} from 'react'\nimport { Camera, useHighestResCaptureDevice } from '../../lib/camera/Camera'\n\nexport type CameraState = {\n videoRef: MutableRefObject<HTMLVideoElement | null>\n videoLoaded: boolean\n setVideoLoaded: (value: boolean) => void\n cameraRef: MutableRefObject<Camera | null>\n cameraReady: boolean\n cameraAccessDenied: boolean\n retryCameraAccess: () => void\n releaseCameraAccess: () => void\n iphoneContinuityCameraAvailable: boolean\n iphoneContinuityCameraAllowed: boolean\n setIphoneContinuityCameraAllowed: (value: boolean) => void\n takePhoto: () => Promise<Blob | null>\n}\n\nexport const CameraStateContext = createContext<CameraState>({\n videoRef: { current: null },\n videoLoaded: false,\n cameraRef: { current: null },\n cameraReady: false,\n cameraAccessDenied: false,\n retryCameraAccess: () => null,\n releaseCameraAccess: () => null,\n iphoneContinuityCameraAvailable: false,\n iphoneContinuityCameraAllowed: true,\n setIphoneContinuityCameraAllowed: () => null,\n takePhoto: () => Promise.resolve(null),\n setVideoLoaded: () => null,\n})\n\nexport type CameraProviderProps = {\n children: ReactElement\n preferFrontFacingCamera?: boolean\n preferContinuityCamera?: boolean\n requestMicrophoneAccess?: boolean\n}\n\nexport const CameraProvider = ({\n children,\n preferFrontFacingCamera = false,\n preferContinuityCamera = true,\n requestMicrophoneAccess = false,\n}: CameraProviderProps): ReactElement => {\n const {\n videoRef,\n videoLoaded,\n setVideoLoaded,\n cameraRef,\n cameraReady,\n cameraAccessDenied,\n retryCameraAccess,\n releaseCameraAccess,\n iphoneContinuityCameraAvailable,\n iphoneContinuityCameraAllowed,\n setIphoneContinuityCameraAllowed,\n takePhoto,\n } = useHighestResCaptureDevice({\n preferFrontFacingCamera,\n preferContinuityCamera,\n requestMicrophoneAccess,\n })\n\n useEffect(() => {\n return () => {\n releaseCameraAccess()\n }\n }, [releaseCameraAccess])\n\n const value = {\n videoRef,\n videoLoaded,\n setVideoLoaded,\n cameraRef,\n cameraReady,\n cameraAccessDenied,\n releaseCameraAccess,\n retryCameraAccess,\n iphoneContinuityCameraAvailable,\n iphoneContinuityCameraAllowed,\n setIphoneContinuityCameraAllowed,\n takePhoto,\n }\n\n return (\n <CameraStateContext.Provider value={value}>\n {children}\n </CameraStateContext.Provider>\n )\n}\n","import * as tf from '@tensorflow/tfjs'\n\nexport let focusModel: tf.LayersModel | null\n\nexport async function loadFocusModel(url: string): Promise<tf.LayersModel> {\n if (focusModel) return focusModel\n\n focusModel = await tf.loadLayersModel(url)\n await tf.ready()\n\n // warm the model by predicting on an empty image...\n const zeroes = tf.zeros([448, 448, 3])\n const tfInt32 = tf.cast(zeroes, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(await tfInt32.data()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n const warmupResult = (await focusModel.predict(tf4d)) as tf.Tensor<tf.Rank>\n await warmupResult.data()\n tf.dispose(warmupResult)\n\n tfInt32.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(zeroes)\n\n return focusModel\n}\n\nexport function unloadFocusModel(): void {\n focusModel = null\n}\n\n// The model outputs a binary classification: [blurry, focused]\n// the outputs are just the inverse of one another e.g. b=1-f or f=1-b\ntype BlurScore = number\ntype FocusScore = number\nexport type FocusPrediction = [BlurScore, FocusScore]\n\nexport async function makeFocusPrediction(\n model: tf.LayersModel,\n imageData: ImageBitmap | ImageData\n): Promise<[FocusPrediction, () => void]> {\n const tfImg = tf.browser.fromPixels(imageData)\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n const tfInt32 = tf.cast(tfResize, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(await tfInt32.data()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n const predictions = (await model.predict(tf4d)) as tf.Tensor<tf.Rank>\n const [focusPrediction] = (await predictions.array()) as FocusPrediction[]\n const cleanup = () => {\n tfInt32.dispose()\n tfImg.dispose()\n tfResize.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(predictions)\n }\n\n return [focusPrediction, cleanup]\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Backend, DataToGPUOptions, GPUData, Tensor} from '../tensor';\nimport {DataId} from '../tensor_info';\nimport {BackendValues, DataType, WebGLData, WebGPUData} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n kernelMs: number|{error: string};\n getExtraProfileInfo?(): string; // a field for additional timing information\n // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n read(dataId: DataId): Promise<BackendValues>;\n readSync(dataId: DataId): BackendValues;\n disposeData(dataId: DataId, force?: boolean): boolean;\n write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void;\n memory(): {unreliable: boolean;}; // Backend-specific information.\n /** Returns number of data ids currently in the storage. */\n numDataIds(): number;\n refCount(dataId: DataId): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage<T> {\n private data = new WeakMap<DataId, T>();\n private dataIdsCount = 0;\n\n constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n get(dataId: DataId) {\n if (!this.data.has(dataId)) {\n this.dataMover.moveData(this.backend, dataId);\n }\n return this.data.get(dataId);\n }\n\n set(dataId: DataId, value: T): void {\n this.dataIdsCount++;\n this.data.set(dataId, value);\n }\n\n has(dataId: DataId): boolean {\n return this.data.has(dataId);\n }\n\n delete(dataId: DataId): boolean {\n this.dataIdsCount--;\n return this.data.delete(dataId);\n }\n\n numDataIds(): number {\n return this.dataIdsCount;\n }\n}\n\nexport interface DataMover {\n /**\n * To be called by backends whenever they see a dataId that they don't own.\n * Upon calling this method, the mover will fetch the tensor from another\n * backend and register it with the current active backend.\n */\n moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n // check if backend timer is available\n timerAvailable(): boolean;\n time(f: () => void): Promise<BackendTimingInfo>;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n refCount(dataId: DataId): number {\n return notYetImplemented('refCount');\n }\n incRef(dataId: DataId): void {\n return notYetImplemented('incRef');\n }\n timerAvailable(): boolean {\n return true;\n }\n time(f: () => void): Promise<BackendTimingInfo> {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise<BackendValues> {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n readToGPU(dataId: object, options?: DataToGPUOptions): GPUData {\n return notYetImplemented('readToGPU');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object, force?: boolean): boolean {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n return notYetImplemented('move');\n }\n\n createTensorFromGPUData(\n values: WebGLData|WebGPUData, shape: number[], dtype: DataType): Tensor {\n return notYetImplemented('createTensorFromGPUData');\n }\n\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, TensorLike, TypedArray, WebGLData, WebGPUData} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n swap(array, counter, index);\n }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n * as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n // tslint:disable-next-line:no-any\n array: any[]|Uint32Array|Int32Array|Float32Array,\n // tslint:disable-next-line:no-any\n array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n if (array.length !== array2.length) {\n throw new Error(\n `Array sizes must match to be shuffled together ` +\n `First array length was ${array.length}` +\n `Second array length was ${array2.length}`);\n }\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element of each array with it\n swap(array, counter, index);\n swap(array2, counter, index);\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap<T>(\n object: {[index: number]: T}, left: number, right: number) {\n const temp = object[left];\n object[left] = object[right];\n object[right] = temp;\n}\n\nexport function sum(arr: number[]): number {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n const r = Math.random();\n return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n const diff = Number(a[i]) - Number(b[i]);\n result += diff * diff;\n }\n return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n * error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n if (!expr) {\n throw new Error(typeof msg === 'string' ? msg : msg());\n }\n}\n\nexport function assertShapesMatch(\n shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n assert(\n arraysEqual(shapeA, shapeB),\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n assert(\n a != null,\n () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n if (shape.length === 0) {\n // Scalar.\n return 1;\n }\n let size = shape[0];\n for (let i = 1; i < shape.length; i++) {\n size *= shape[i];\n }\n return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n return shape.length === 0;\n}\n\nexport function arraysEqualWithNull(n1: number[], n2: number[]) {\n if (n1 === n2) {\n return true;\n }\n\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n if (n1 === n2) {\n return true;\n }\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function isInt(a: number): boolean {\n return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n // tslint:disable-next-line:no-any\n if ((Math as any).tanh != null) {\n // tslint:disable-next-line:no-any\n return (Math as any).tanh(x);\n }\n if (x === Infinity) {\n return 1;\n } else if (x === -Infinity) {\n return -1;\n } else {\n const e2x = Math.exp(2 * x);\n return (e2x - 1) / (e2x + 1);\n }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n const width = Math.ceil(Math.sqrt(size));\n return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indices to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indices to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number,\n scheduleFn?: (functionRef: Function, delay: number) =>\n void): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let tryCount = 0;\n\n const tryFn = () => {\n if (checkFn()) {\n resolve();\n return;\n }\n\n tryCount++;\n\n const nextBackoff = delayFn(tryCount);\n\n if (maxCounter != null && tryCount >= maxCounter) {\n reject();\n return;\n }\n\n if (scheduleFn != null) {\n scheduleFn(tryFn, nextBackoff);\n } else {\n // google3 does not allow assigning another variable to setTimeout.\n // Don't refactor this so scheduleFn has a default value of setTimeout.\n setTimeout(tryFn, nextBackoff);\n }\n };\n\n tryFn();\n });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n shape: number[], size: number): number[] {\n let shapeProd = 1;\n let implicitIdx = -1;\n\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] >= 0) {\n shapeProd *= shape[i];\n } else if (shape[i] === -1) {\n if (implicitIdx !== -1) {\n throw Error(\n `Shapes can only have 1 implicit size. ` +\n `Found -1 at dim ${implicitIdx} and dim ${i}`);\n }\n implicitIdx = i;\n } else if (shape[i] < 0) {\n throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n }\n }\n\n if (implicitIdx === -1) {\n if (size > 0 && size !== shapeProd) {\n throw Error(`Size(${size}) must match the product of shape ${shape}`);\n }\n return shape;\n }\n\n if (shapeProd === 0) {\n throw Error(\n `Cannot infer the missing size in [${shape}] when ` +\n `there are 0 elements`);\n }\n if (size % shapeProd !== 0) {\n throw Error(\n `The implicit shape can't be a fractional number. ` +\n `Got ${size} / ${shapeProd}`);\n }\n\n const newShape = shape.slice();\n newShape[implicitIdx] = size / shapeProd;\n return newShape;\n}\n\nexport function parseAxisParam(\n axis: number|number[], shape: number[]): number[] {\n const rank = shape.length;\n\n // Normalize input\n axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n // Check for valid range\n assert(\n axis.every(ax => ax >= -rank && ax < rank),\n () =>\n `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n `got axis ${axis}`);\n\n // Check for only integers\n assert(\n axis.every(ax => isInt(ax)),\n () => `All values in axis param must be integers but ` +\n `got axis ${axis}`);\n\n // Handle negative axis.\n return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n {newShape: number[], keptDims: number[]} {\n const newShape: number[] = [];\n const keptDims: number[] = [];\n const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n const axes = (axis == null || isEmptyArray) ?\n null :\n parseAxisParam(axis, shape).sort();\n let j = 0;\n for (let i = 0; i < shape.length; ++i) {\n if (axes != null) {\n if (axes[j] === i && shape[i] !== 1) {\n throw new Error(\n `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n }\n if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n if (axes[j] <= i) {\n j++;\n }\n }\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n }\n return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType<D extends NumericDataType>(\n dtype: D, size: number): DataTypeMap[D] {\n return getArrayFromDType<D>(dtype, size);\n}\n\nexport function getArrayFromDType<D extends DataType>(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else if (dtype === 'string') {\n values = new Array<string>(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors<D extends DataType>(\n vals: DataTypeMap[D]|number[], dtype: D): void {\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n }\n }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n if (newType === 'complex64') {\n return false;\n }\n if (newType === 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'bool' && oldType === 'bool') {\n return false;\n }\n return true;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS\n * is not possible since it depends on the encoding of the html page that\n * serves the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike|WebGLData|WebGPUData): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (\n values instanceof Int32Array || values instanceof Uint8Array ||\n values instanceof Uint8ClampedArray) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\nfunction createNestedArray(\n offset: number, shape: number[], a: TypedArray, isComplex = false) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0] * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n shape: number[], a: TypedArray, isComplex = false) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}${\n isComplex ? ' for a complex tensor' : ''}.`);\n }\n\n return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function convertBackendValuesAndArrayBuffer(\n data: BackendValues|ArrayBuffer, dtype: DataType) {\n // If is type Uint8Array[], return it directly.\n if (Array.isArray(data)) {\n return data;\n }\n if (dtype === 'float32') {\n return data instanceof Float32Array ? data : new Float32Array(data);\n } else if (dtype === 'int32') {\n return data instanceof Int32Array ? data : new Int32Array(data);\n } else if (dtype === 'bool' || dtype === 'string') {\n return Uint8Array.from(new Int32Array(data));\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\nexport function makeOnesTypedArray<D extends DataType>(\n size: number, dtype: D): DataTypeMap[D] {\n const array = makeZerosTypedArray(size, dtype);\n for (let i = 0; i < array.length; i++) {\n array[i] = 1;\n }\n return array;\n}\n\nexport function makeZerosTypedArray<D extends DataType>(\n size: number, dtype: D): DataTypeMap[D] {\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(size) as DataTypeMap[D];\n } else if (dtype === 'int32') {\n return new Int32Array(size) as DataTypeMap[D];\n } else if (dtype === 'bool') {\n return new Uint8Array(size) as DataTypeMap[D];\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray<D extends DataType>(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a\n * tensor/multidimentional array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise<unknown> {\n // We chose to not use 'obj instanceOf Promise' for two reasons:\n // 1. It only reliably works for es6 Promise, not other Promise\n // implementations.\n // 2. It doesn't work with framework that uses zone.js. zone.js monkey\n // patch the async calls, so it is possible the obj (patched) is\n // comparing to a pre-patched Promise.\n return object && object.then && typeof object.then === 'function';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean|string;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise<FlagValue>);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // Jasmine spies on this in 'environment_test.ts'\n getQueryParams = getQueryParams;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platformName}.`);\n }\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because\n // the environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n }\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise<FlagValue> {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (isPromise(flagValue)) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue;\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n getString(flagName: string): string {\n return this.get(flagName) as string;\n }\n\n getFlags(): Flags {\n return this.flags;\n }\n // For backwards compatibility.\n get features(): Flags {\n return this.flags;\n }\n\n set(flagName: string, value: FlagValue): void {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot set flag ${flagName} as it has not been registered.`);\n }\n this.flags[flagName] = value;\n if (this.flagRegistry[flagName].setHook != null) {\n this.flagRegistry[flagName].setHook(value);\n }\n }\n\n private evaluateFlag(flagName: string): FlagValue|Promise<FlagValue> {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = this.getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n const lowerCaseValue = value.toLowerCase();\n if (lowerCaseValue === 'true' || lowerCaseValue === 'false') {\n return lowerCaseValue === 'true';\n } else if (`${+ lowerCaseValue}` === lowerCaseValue) {\n return +lowerCaseValue;\n } else {\n return value;\n }\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map<string, any>};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map<string, any>} {\n if (globalNameSpace == null) {\n // tslint:disable-next-line:no-any\n let ns: any;\n if (typeof (window) !== 'undefined') {\n ns = window;\n } else if (typeof (global) !== 'undefined') {\n ns = global;\n } else if (typeof (process) !== 'undefined') {\n ns = process;\n } else if (typeof (self) !== 'undefined') {\n ns = self;\n } else {\n throw new Error('Could not find a global object');\n }\n globalNameSpace = ns;\n }\n return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map<string, any> {\n const ns = getGlobalNamespace();\n if (ns._tfGlobals == null) {\n ns._tfGlobals = new Map();\n }\n return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n * the first time it is fetched.\n */\nexport function getGlobal<T>(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {TensorInfo} from './tensor_info';\nimport {DataType, DrawOptions, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMinAttrs {\n axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolGrad = 'AvgPoolGrad';\nexport type AvgPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPoolGradAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n dataFormat: 'NDHWC'|'NCDHW';\n}\n\nexport const AvgPool3DGrad = 'AvgPool3DGrad';\nexport type AvgPool3DGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPool3DGradAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface BincountAttrs {\n size: number;\n}\n\nexport const BitwiseAnd = 'BitwiseAnd';\nexport type BitwiseAndInputs = BinaryInputs;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick<NamedTensorInfoMap, 's0'|'s1'>;\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n clipValueMin: number;\n clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick<NamedTensorInfoMap, 'real'|'imag'>;\n\nexport const ComplexAbs = 'ComplexAbs';\nexport type ComplexAbsInputs = UnaryInputs;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface Conv2DBackpropFilterAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n filterShape: [number, number, number, number];\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv2DBackpropInputAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv3DAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterV2Inputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\n\nexport interface Conv3DBackpropFilterV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n filterShape: [number, number, number, number, number];\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputV2Inputs =\n Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv3DBackpropInputV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumprod = 'Cumprod';\nexport type CumprodInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumprodAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick<NamedTensorInfoMap, 'image'|'boxes'|'boxInd'>;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface DenseBincountAttrs {\n size: number;\n binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface DepthwiseConv2dNativeAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n 'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface DepthwiseConv2dNativeBackpropFilterAttrs {\n strides: [number, number]|number;\n dilations: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n filterShape: [number, number, number, number];\n}\n\nexport const DepthwiseConv2dNativeBackpropInput =\n 'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface DepthwiseConv2dNativeBackpropInputAttrs {\n strides: [number, number]|number;\n dilations: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Dilation2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Draw = 'Draw';\nexport type DrawInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface DrawAttrs {\n canvas: HTMLCanvasElement;\n options?: DrawOptions;\n}\n\nexport const RealDiv = 'RealDiv';\nexport type RealDivInputs = BinaryInputs;\n\nexport const Einsum = 'Einsum';\nexport type EinsumInputs = TensorInfo[];\nexport interface EinsumAttrs {\n equation: string;\n}\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick<NamedTensorInfoMap, 'dy'|'y'>;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const ExpandDims = 'ExpandDims';\nexport type ExpandDimsInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface ExpandDimsAttrs {\n dim: number;\n}\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n shape: number[];\n value: number|string;\n dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick<NamedTensorInfoMap, 'image'>;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n Pick<NamedTensorInfoMap, 'x'|'scale'|'offset'|'mean'|'variance'>;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick<NamedTensorInfoMap, 'x'|'indices'>;\nexport interface GatherV2Attrs {\n axis: number;\n batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick<NamedTensorInfoMap, 'params'|'indices'>;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const LeakyRelu = 'LeakyRelu';\nexport type LeakyReluInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LeakyReluAttrs {\n alpha: number;\n}\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n start: number;\n stop: number;\n num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogicalXor = 'LogicalXor';\nexport type LogicalXorInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LowerBound = 'LowerBound';\nexport type LowerBoundInputs =\n Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LRNAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const LRNGrad = 'LRNGrad';\nexport type LRNGradInputs = Pick<NamedTensorInfoMap, 'x'|'y'|'dy'>;\nexport interface LRNGradAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const MatrixBandPart = 'MatrixBandPart';\nexport type MatrixBandPartInputs =\n Pick<NamedTensorInfoMap, 'input'|'numLower'|'numUpper'>;\nexport interface MatrixBandPartAttrs {}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxAttrs {\n reductionIndices: number|number[];\n keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolGrad = 'MaxPoolGrad';\nexport type MaxPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPoolGradAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NDHWC'|'NCDHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DGrad = 'MaxPool3DGrad';\nexport type MaxPool3DGradInputs =\n Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPool3DGradAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolWithArgmaxAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MinAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const MirrorPad = 'MirrorPad';\nexport type MirrorPadInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MirrorPadAttrs {\n paddings: Array<[number, number]>;\n mode: 'reflect'|'symmetric';\n}\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multinomial = 'Multinomial';\nexport type MultinomialInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface MultinomialAttrs {\n numSamples: number;\n seed: number;\n normalized: boolean;\n}\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Neg = 'Neg';\nexport type NegInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV4Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV5Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick<NamedTensorInfoMap, 'indices'>;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n dtype: DataType;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick<NamedTensorInfoMap, 'x'|'alpha'>;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const RaggedGather = 'RaggedGather';\nexport type RaggedGatherInputs = {\n paramsNestedSplits: TensorInfo[]\n}&Pick<NamedTensorInfoMap, 'paramsDenseValues'|'indices'>;\nexport interface RaggedGatherAttrs {\n outputRaggedRank: number;\n}\n\nexport const RaggedRange = 'RaggedRange';\nexport type RaggedRangeInputs =\n Pick<NamedTensorInfoMap, 'starts'|'limits'|'deltas'>;\n\nexport const RaggedTensorToTensor = 'RaggedTensorToTensor';\nexport type RaggedTensorToTensorInputs =\n Pick<NamedTensorInfoMap, 'shape'|'values'|'defaultValue'>&\n {rowPartitionTensors: TensorInfo[]};\nexport interface RaggedTensorToTensorAttrs {\n rowPartitionTypes: string[];\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReverseAttrs {\n dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick<NamedTensorInfoMap, 'indices'|'updates'>;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const TensorScatterUpdate = 'TensorScatterUpdate';\nexport type TensorScatterUpdateInputs =\n Pick<NamedTensorInfoMap, 'tensor'|'indices'|'updates'>;\nexport interface TensorScatterUpdateAttrs {}\n\nexport const SearchSorted = 'SearchSorted';\nexport type SearchSortedInputs =\n Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\nexport interface SearchSortedAttrs {\n side: 'left'|'right';\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick<NamedTensorInfoMap, 'condition'|'t'|'e'>;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SliceAttrs {\n begin: number|number[];\n size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n Pick<NamedTensorInfoMap, 'indices'|'values'|'denseShape'|'defaultValue'>;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n Pick<NamedTensorInfoMap, 'inputIndices'|'inputShape'|'newShape'>;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick<NamedTensorInfoMap, 'sparseIndices'|'sparseValues'|'defaultValue'>;\nexport interface SparseToDenseAttrs {\n outputShape: number[];\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const StaticRegexReplace = 'StaticRegexReplace';\nexport type StaticRegexReplaceInputs = UnaryInputs;\nexport interface StaticRegexReplaceAttrs {\n pattern: string;\n rewrite: string;\n replaceGlobal: boolean;\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface StridedSliceAttrs {\n begin: number[];\n end: number[];\n strides: number[];\n beginMask: number;\n endMask: number;\n ellipsisMask: number;\n newAxisMask: number;\n shrinkAxisMask: number;\n}\n\nexport const StringNGrams = 'StringNGrams';\nexport type StringNGramsInputs = Pick<NamedTensorInfoMap, 'data'|'dataSplits'>;\nexport interface StringNGramsAttrs {\n separator: string;\n nGramWidths: number[];\n leftPad: string;\n rightPad: string;\n padWidth: number;\n preserveShortSequences: boolean;\n}\n\nexport const StringSplit = 'StringSplit';\nexport type StringSplitInputs = Pick<NamedTensorInfoMap, 'input'|'delimiter'>;\nexport interface StringSplitAttrs {\n skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface StringToHashBucketFastAttrs {\n numBuckets: number;\n}\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick<NamedTensorInfoMap, 'image'|'transforms'>;\nexport interface TransformAttrs {\n interpolation: 'nearest'|'bilinear';\n fillMode: 'constant'|'reflect'|'wrap'|'nearest';\n fillValue: number;\n outputShape?: [number, number];\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick<NamedTensorInfoMap, 'value'>;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick<NamedTensorInfoMap, 'x'|'segmentIds'>;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const UpperBound = 'UpperBound';\nexport type UpperBoundInputs =\n Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap;\n}\nexport interface FromPixelsAttrs {\n numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(...msg);\n }\n}\n\nexport function log(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.log(...msg);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {TensorInfo} from './tensor_info';\nimport {RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map<`${string}_${string}`,\n KernelConfig>());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map<string, GradConfig>());\n\ntype AttributeValue =\n number | number[] | boolean | boolean[] | string | string[] | NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue | RecursiveArray<AttributeValue>;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n inputs: NamedTensorInfoMap,\n backend: {},\n attrs?: NamedAttrMap,\n}) => TensorInfo | TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n (dy: Tensor | Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n kernelName: string;\n backendName: string;\n kernelFunc: KernelFunc;\n setupFunc?: KernelSetupFunc;\n disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n kernelName: string;\n inputsToSave?: string[];\n // When saveAllInputs is true, all inputs will be saved. Only use this flag\n // if inputs is an array of Tensors.\n saveAllInputs?: boolean;\n outputsToSave?: boolean[];\n gradFunc: GradFunc;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo|undefined;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n log.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n log.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string,\n backendName: string): `${string}_${string}` {\n return `${backendName}_${kernelName}`;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport function isTypedArrayBrowser(a: unknown): a is Uint8Array\n | Float32Array | Int32Array | Uint8ClampedArray {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {isTypedArrayBrowser} from './platforms/is_typed_array_browser';\nimport {BackendValues, DataType, RecursiveArray, TensorLike, TypedArray} from './types';\nimport * as base from './util_base';\nexport * from './util_base';\nexport * from './hash_util';\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n value: DataType, dtype: DataType): BackendValues {\n if (dtype === 'string') {\n return encodeString(value);\n }\n\n return toTypedArray([value], dtype);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n return (a instanceof Float32Array && dtype === 'float32') ||\n (a instanceof Int32Array && dtype === 'int32') ||\n (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n if (dtype === 'string') {\n throw new Error('Cannot convert a string[] to a TypedArray');\n }\n if (Array.isArray(a)) {\n a = flatten(a);\n }\n\n if (env().getBool('DEBUG')) {\n base.checkConversionForErrors(a as number[], dtype);\n }\n if (noConversionNeeded(a, dtype)) {\n return a as TypedArray;\n }\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(a as number[]);\n } else if (dtype === 'int32') {\n return new Int32Array(a as number[]);\n } else if (dtype === 'bool') {\n const bool = new Uint8Array((a as number[]).length);\n for (let i = 0; i < bool.length; ++i) {\n if (Math.round((a as number[])[i]) !== 0) {\n bool[i] = 1;\n }\n }\n return bool;\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n return env().platform.now();\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n path: string, requestInits?: RequestInit): Promise<Response> {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array|\n Uint8ClampedArray {\n // TODO(mattsoulanille): Remove this fallback in 5.0.0\n if (env().platform.isTypedArray != null) {\n return env().platform.isTypedArray(a);\n } else {\n return isTypedArrayBrowser(a);\n }\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten<number>().\n/**\n * Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n * @param arr The nested array to flatten.\n * @param result The destination array which holds the elements.\n * @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n * to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten<T extends number|boolean|string|Promise<number>|TypedArray>(\n arr: T|RecursiveArray<T>, result: T[] = [], skipTypedArray = false): T[] {\n if (result == null) {\n result = [];\n }\n if (typeof arr === 'boolean' || typeof arr === 'number' ||\n typeof arr === 'string' || base.isPromise(arr) || arr == null ||\n isTypedArray(arr) && skipTypedArray) {\n result.push(arr as T);\n } else if (Array.isArray(arr) || isTypedArray(arr)) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n let maxIndex = -1;\n for (const key of Object.keys(arr)) {\n // 0 or positive integer.\n if (/^([1-9]+[0-9]*|0)$/.test(key)) {\n maxIndex = Math.max(maxIndex, Number(key));\n }\n }\n for (let i = 0; i <= maxIndex; i++) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n flatten((arr as RecursiveArray<T>)[i], result, skipTypedArray);\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer, BackendTimingInfo} from './backends/backend';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n kernelName: string,\n outputs: Tensor[],\n inputs: NamedTensorMap,\n timeMs: Promise<number|{error: string}>,\n extraInfo: Promise<string>\n};\n\nexport class Profiler {\n constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n if (logger == null) {\n this.logger = new Logger();\n }\n }\n\n profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n KernelProfile {\n let outputs: Tensor[];\n const holdResultWrapperFn = () => {\n outputs = f();\n };\n let timer: Promise<BackendTimingInfo>;\n const start = util.now();\n if (this.backendTimer.timerAvailable()) {\n timer = this.backendTimer.time(holdResultWrapperFn);\n } else {\n holdResultWrapperFn();\n for (const output of outputs) {\n output.dataSync();\n }\n timer = Promise.resolve({kernelMs: util.now() - start});\n }\n if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {\n for (let i = 0; i < outputs.length; i++) {\n const output = outputs[i];\n // Dangling promise here because we don't want to propagate up\n // asynchronicity.\n output.data().then(tensorVals => {\n checkComputationForErrors(tensorVals, output.dtype, kernelName);\n });\n }\n }\n\n const kernelProfile = {\n kernelName,\n outputs,\n inputs,\n timeMs: timer.then(timing => timing.kernelMs),\n extraInfo: timer.then(\n timing => timing.getExtraProfileInfo != null ?\n timing.getExtraProfileInfo() :\n '')\n };\n return kernelProfile;\n }\n\n logKernelProfile(kernelProfile: KernelProfile): void {\n const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n outputs.forEach(result => {\n Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n this.logger.logKernelProfile(\n kernelName, result, valueContainer[0], valueContainer[1], inputs,\n valueContainer[2]);\n });\n });\n }\n}\n\nexport function checkComputationForErrors<D extends DataType>(\n vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n if (dtype !== 'float32') {\n // Only floating point computations will generate NaN values\n return false;\n }\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n // Throwing custom exception so behavior is testable.\n console.warn(`Found ${num} in the result of '${kernelName}'`);\n return true;\n }\n }\n return false;\n}\n\nexport class Logger {\n logKernelProfile(\n name: string, result: Tensor, vals: TypedArray,\n timeMs: number|{error: string}, inputs: NamedTensorMap,\n extraInfo?: string) {\n const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n timeMs['error'];\n const paddedName = util.rightPad(name, 25);\n const rank = result.rank;\n const size = result.size;\n const shape = util.rightPad(result.shape.toString(), 14);\n let inputShapesDescription = '';\n\n for (const name in inputs) {\n const input = inputs[name];\n if (input != null) {\n // The input might be a non-tensor (e.g HTMLImageElement), in which case\n // we claim the output shape as input shape.\n const inputShape = input.shape || result.shape;\n const inputRank = inputShape.length;\n inputShapesDescription +=\n `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n }\n }\n\n console.log(\n `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n inputShapesDescription}\\t%c${extraInfo}`,\n 'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n 'color: green', 'color: steelblue');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n id: number;\n kernelName: string;\n outputs: Tensor[];\n inputs: NamedTensorMap;\n // Optional params, defined only for ops with gradient impl.\n gradient?: (dys: Tensor[]) => NamedGradientMap;\n saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n // Forward pass to compute all the nodes and Tensors that are transitively a\n // function of x.\n const tensorsFromX: {[tensorId: number]: boolean} = {};\n const nodesFromX: {[nodeId: number]: boolean} = {};\n for (let i = 0; i < xs.length; i++) {\n tensorsFromX[xs[i].id] = true;\n }\n\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n for (const inputName in nodeInputs) {\n const input = nodeInputs[inputName];\n\n let anyInputFromX = false;\n for (let j = 0; j < xs.length; j++) {\n if (tensorsFromX[input.id]) {\n node.outputs.forEach(output => tensorsFromX[output.id] = true);\n anyInputFromX = true;\n nodesFromX[node.id] = true;\n break;\n }\n }\n\n if (anyInputFromX) {\n break;\n }\n }\n }\n\n // Backward pass to find all of the nodes and Tensors that lead to y.\n const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n tensorsLeadToY[y.id] = true;\n const nodesToY: {[nodeId: number]: boolean} = {};\n\n for (let i = tape.length - 1; i >= 0; i--) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n\n // If any of the outputs lead to y, mark all of the inputs as leading to y.\n for (let j = 0; j < node.outputs.length; j++) {\n if (tensorsLeadToY[node.outputs[j].id]) {\n for (const inputName in nodeInputs) {\n tensorsLeadToY[nodeInputs[inputName].id] = true;\n nodesToY[node.id] = true;\n }\n break;\n }\n }\n }\n\n // Return the paths that come from x and lead to y.\n const filteredTape: TapeNode[] = [];\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n\n if (nodesFromX[node.id] && nodesToY[node.id]) {\n // Prune the inputs from the node that aren't a function of x.\n const prunedInputs: {[inputName: string]: Tensor} = {};\n for (const inputName in node.inputs) {\n const nodeInput = node.inputs[inputName];\n if (tensorsFromX[nodeInput.id]) {\n prunedInputs[inputName] = nodeInput;\n }\n }\n\n // Copy the node and overwrite inputsAndArgs to the pruned version.\n const prunedNode = Object.assign({}, node);\n prunedNode.inputs = prunedInputs;\n prunedNode.outputs = node.outputs;\n\n filteredTape.push(prunedNode);\n }\n }\n\n return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n add: (a: Tensor, b: Tensor) => Tensor) {\n // Walk the tape backward and keep a map of Tensor to its gradient.\n for (let i = filteredTape.length - 1; i >= 0; i--) {\n const node = filteredTape[i];\n\n const dys: Tensor[] = [];\n node.outputs.forEach(o => {\n const gradTensor = tensorAccumulatedGradientMap[o.id];\n if (gradTensor != null) {\n dys.push(gradTensor);\n } else {\n // This particular output is not in the back-propagation subgraph, so it\n // does not affect the final output, thus we put null for its dy.\n dys.push(null);\n }\n });\n\n if (node.gradient == null) {\n throw new Error(\n `Cannot compute gradient: gradient function not found ` +\n `for ${node.kernelName}.`);\n }\n\n // Backprop dy through this node and accumulate gradients over the inputs.\n const inputGradients = node.gradient(dys);\n\n for (const inputName in node.inputs) {\n if (!(inputName in inputGradients)) {\n throw new Error(\n `Cannot backprop through input ${inputName}. ` +\n `Available gradients found: ${Object.keys(inputGradients)}.`);\n }\n\n // Call the gradient function.\n const dx = tidy(() => inputGradients[inputName]());\n if (dx.dtype !== 'float32') {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n }\n const x = node.inputs[inputName];\n if (!util.arraysEqual(dx.shape, x.shape)) {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `'${inputName}' has shape '${dx.shape}', which does not match ` +\n `the shape of the input '${x.shape}'`);\n }\n\n if (tensorAccumulatedGradientMap[x.id] == null) {\n tensorAccumulatedGradientMap[x.id] = dx;\n } else {\n const curGradient = tensorAccumulatedGradientMap[x.id];\n tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n curGradient.dispose();\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n verbose: boolean) {\n const strides = computeStrides(shape);\n const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n const rank = shape.length;\n const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n const lines = ['Tensor'];\n if (verbose) {\n lines.push(` dtype: ${dtype}`);\n lines.push(` rank: ${rank}`);\n lines.push(` shape: [${shape}]`);\n lines.push(` values:`);\n }\n lines.push(valsLines.map(l => ' ' + l).join('\\n'));\n return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[]): number[] {\n const n = sizeFromShape(shape);\n const numCols = strides[strides.length - 1];\n const padPerCol = new Array(numCols).fill(0);\n const rank = shape.length;\n const valuesOrTuples =\n dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n if (rank > 1) {\n for (let row = 0; row < n / numCols; row++) {\n const offset = row * numCols;\n for (let j = 0; j < numCols; j++) {\n padPerCol[j] = Math.max(\n padPerCol[j],\n valToString(valuesOrTuples[offset + j], 0, dtype).length);\n }\n }\n }\n return padPerCol;\n}\n\nfunction valToString(\n val: number|string|[number, number], pad: number, dtype: DataType) {\n let valStr: string;\n if (Array.isArray(val)) {\n valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n } else if (isString(val)) {\n valStr = `'${val}'`;\n } else if (dtype === 'bool') {\n valStr = boolNumToString(val);\n } else {\n valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n }\n\n return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[], padPerCol: number[], isLast = true): string[] {\n const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n const size = shape[0];\n const rank = shape.length;\n if (rank === 0) {\n if (dtype === 'complex64') {\n const complexTuple = createComplexTuples(vals);\n return [valToString(complexTuple[0], 0, dtype)];\n }\n if (dtype === 'bool') {\n return [boolNumToString(vals[0] as number)];\n }\n return [vals[0].toString()];\n }\n\n if (rank === 1) {\n if (size > FORMAT_LIMIT_NUM_VALS) {\n const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n let firstVals = Array.from<number|string|[number, number]>(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from<number|string|[number, number]>(vals.slice(\n (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n size * storagePerElement));\n if (dtype === 'complex64') {\n firstVals = createComplexTuples(firstVals);\n lastVals = createComplexTuples(lastVals);\n }\n return [\n '[' +\n firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ', ..., ' +\n lastVals\n .map(\n (x, i) => valToString(\n x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n .join(', ') +\n ']'\n ];\n }\n const displayVals: Array<number|string|[number, number]> =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from<number|string>(vals);\n\n return [\n '[' +\n displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ']'\n ];\n }\n\n // The array is rank 2 or more.\n const subshape = shape.slice(1);\n const substrides = strides.slice(1);\n const stride = strides[0] * storagePerElement;\n const lines: string[] = [];\n if (size > FORMAT_LIMIT_NUM_VALS) {\n for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n false /* isLast */));\n }\n lines.push('...');\n for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n } else {\n for (let i = 0; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n }\n const sep = rank === 2 ? ',' : '';\n lines[0] = '[' + (size > 0 ? lines[0] + sep : '');\n for (let i = 1; i < lines.length - 1; i++) {\n lines[i] = ' ' + lines[i] + sep;\n }\n let newLineSep = ',\\n';\n for (let i = 2; i < rank; i++) {\n newLineSep += '\\n';\n }\n lines[lines.length - 1] =\n ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n TypedArray): Array<[number, number]> {\n const complexTuples: Array<[number, number]> = [];\n for (let i = 0; i < vals.length; i += 2) {\n complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n }\n return complexTuples;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265\n/// <reference types=\"@webgpu/types/dist\" />\n\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\nimport {DataId, TensorInfo} from './tensor_info';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData<D extends DataType> {\n dataId?: DataId;\n values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer<R extends Rank, D extends DataType = 'float32'> {\n size: number;\n shape: ShapeMap[R];\n strides: number[];\n values: DataTypeMap[D];\n\n constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n this.shape = shape.slice() as ShapeMap[R];\n this.size = util.sizeFromShape(shape);\n\n if (values != null) {\n const n = values.length;\n util.assert(\n n === this.size,\n () => `Length of values '${n}' does not match the size ` +\n `inferred by the shape '${this.size}'.`);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `complex64 dtype TensorBuffers are not supported. Please create ` +\n `a TensorBuffer for the real and imaginary parts separately and ` +\n `call tf.complex(real, imag).`);\n }\n this.values = values || util.getArrayFromDType(dtype, this.size);\n this.strides = computeStrides(shape);\n }\n\n /**\n * Sets a value in the buffer at a given location.\n *\n * @param value The value to set.\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n set(value: SingleValueMap[D], ...locs: number[]): void {\n if (locs.length === 0) {\n locs = [0];\n }\n util.assert(\n locs.length === this.rank,\n () => `The number of provided coordinates (${locs.length}) must ` +\n `match the rank (${this.rank})`);\n\n const index = this.locToIndex(locs);\n this.values[index] = value as number;\n }\n\n /**\n * Returns the value in the buffer at the provided location.\n *\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n get(...locs: number[]): SingleValueMap[D] {\n if (locs.length === 0) {\n locs = [0];\n }\n let i = 0;\n for (const loc of locs) {\n if (loc < 0 || loc >= this.shape[i]) {\n const msg = `Requested out of range element at ${locs}. ` +\n ` Buffer shape=${this.shape}`;\n throw new Error(msg);\n }\n i++;\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return this.values[index] as SingleValueMap[D];\n }\n\n locToIndex(locs: number[]): number {\n if (this.rank === 0) {\n return 0;\n } else if (this.rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return index;\n }\n\n indexToLoc(index: number): number[] {\n if (this.rank === 0) {\n return [];\n } else if (this.rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(this.shape.length);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / this.strides[i]);\n index -= locs[i] * this.strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n }\n\n get rank() {\n return this.shape.length;\n }\n\n /**\n * Creates an immutable `tf.Tensor` object from the buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n toTensor(): Tensor<R> {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor<R>;\n }\n}\n\nexport interface DataToGPUWebGLOption {\n customTexShape?: [number, number];\n}\n\nexport type DataToGPUOptions = DataToGPUWebGLOption;\n\nexport interface GPUData {\n tensorRef: Tensor;\n texture?: WebGLTexture;\n buffer?: GPUBuffer;\n texShape?: [number, number];\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise<BackendValues>;\n readSync(dataId: DataId): BackendValues;\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast<T extends Tensor>(x: T, dtype: DataType): T;\n buffer<R extends Rank, D extends DataType>(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer<R, D>;\n print<T extends Tensor>(x: T, verbose: boolean): void;\n clone<T extends Tensor>(x: T): T;\n // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n deprecationWarningFn = fn;\n}\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * For performance reasons, functions that create tensors do not necessarily\n * perform a copy of the data passed to them (e.g. if the data is passed as a\n * `Float32Array`), and changes to the data will change the tensor. This is not\n * a feature and is not supported. To avoid this behavior, use the tensor before\n * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor<R extends Rank = Rank> implements TensorInfo {\n /** Unique id of this tensor. */\n readonly id: number;\n /**\n * Id of the bucket holding the data for this tensor. Multiple arrays can\n * point to the same bucket (e.g. when calling array.reshape()).\n */\n dataId: DataId;\n /** The shape of the tensor. */\n readonly shape: ShapeMap[R];\n /** Number of elements in the tensor. */\n readonly size: number;\n /** The data type for the array. */\n readonly dtype: DataType;\n /** The rank type for the array (see `Rank` enum). */\n readonly rankType: R;\n\n /** Whether this tensor has been globally kept. */\n kept = false;\n /** The id of the scope this tensor is being tracked in. */\n scopeId: number;\n\n /**\n * Number of elements to skip in each dimension when indexing. See\n * https://docs.scipy.org/doc/numpy/reference/generated/\\\n * numpy.ndarray.strides.html\n */\n readonly strides: number[];\n\n constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n this.shape = shape.slice() as ShapeMap[R];\n this.dtype = dtype || 'float32';\n this.size = util.sizeFromShape(shape);\n this.strides = computeStrides(shape);\n this.dataId = dataId;\n this.id = id;\n this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n }\n\n get rank(): number {\n return this.shape.length;\n }\n\n /**\n * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async buffer<D extends DataType = 'float32'>(): Promise<TensorBuffer<R, D>> {\n const vals = await this.data<D>();\n return opHandler.buffer(this.shape, this.dtype as D, vals);\n }\n\n /**\n * Returns a `tf.TensorBuffer` that holds the underlying data.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n bufferSync<D extends DataType = 'float32'>(): TensorBuffer<R, D> {\n return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * asynchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async array(): Promise<ArrayMap[R]> {\n const vals = await this.data();\n return toNestedArray(this.shape, vals, this.dtype === 'complex64') as\n ArrayMap[R];\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * synchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n arraySync(): ArrayMap[R] {\n return toNestedArray(\n this.shape, this.dataSync(), this.dtype === 'complex64') as\n ArrayMap[R];\n }\n\n /**\n * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n * promise of `TypedArray` that resolves when the computation has finished.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]> {\n this.throwIfDisposed();\n const data = trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n const bytes = await data as Uint8Array[];\n try {\n return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as Promise<DataTypeMap[D]>;\n }\n\n /**\n * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`\n * and `data()`, this method prevents data from being downloaded to CPU.\n *\n * For WebGL backend, the data will be stored on a densely packed texture.\n * This means that the texture will use the RGBA channels to store value.\n *\n * For WebGPU backend, the data will be stored on a buffer. There is no\n * parameter, so can not use a user-defined size to create the buffer.\n *\n * @param options:\n * For WebGL,\n * - customTexShape: Optional. If set, will use the user defined\n * texture shape to create the texture.\n *\n * @returns For WebGL backend, a GPUData contains the new texture and\n * its information.\n * {\n * tensorRef: The tensor that is associated with this texture,\n * texture: WebGLTexture,\n * texShape: [number, number] // [height, width]\n * }\n *\n * For WebGPU backend, a GPUData contains the new buffer.\n * {\n * tensorRef: The tensor that is associated with this buffer,\n * buffer: GPUBuffer,\n * }\n *\n * Remember to dispose the GPUData after it is used by\n * `res.tensorRef.dispose()`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataToGPU(options?: DataToGPUOptions): GPUData {\n this.throwIfDisposed();\n return trackerFn().readToGPU(this.dataId, options);\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D] {\n this.throwIfDisposed();\n const data = trackerFn().readSync(this.dataId);\n if (this.dtype === 'string') {\n try {\n return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as DataTypeMap[D];\n }\n\n /** Returns the underlying bytes of the tensor's data. */\n async bytes(): Promise<Uint8Array[]|Uint8Array> {\n this.throwIfDisposed();\n const data = await trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n return data as Uint8Array[];\n } else {\n return new Uint8Array((data as TypedArray).buffer);\n }\n }\n\n /**\n * Disposes `tf.Tensor` from memory.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n trackerFn().disposeTensor(this);\n this.isDisposedInternal = true;\n }\n\n protected isDisposedInternal = false;\n get isDisposed(): boolean {\n return this.isDisposedInternal;\n }\n\n throwIfDisposed() {\n if (this.isDisposed) {\n throw new Error(`Tensor is disposed.`);\n }\n }\n\n /**\n * Prints the `tf.Tensor`. See `tf.print` for details.\n *\n * @param verbose Whether to print verbose information about the tensor,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n print(verbose = false): void {\n return opHandler.print(this, verbose);\n }\n\n /**\n * Returns a copy of the tensor. See `tf.clone` for details.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n clone<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return opHandler.clone(this);\n }\n\n /**\n * Returns a human-readable description of the tensor. Useful for logging.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n toString(verbose = false): string {\n const vals = this.dataSync();\n return tensorToString(vals, this.shape, this.dtype, verbose);\n }\n\n cast<T extends this>(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable<R> {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable<R>;\n }\n}\n\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport function getGlobalTensorClass() {\n // Use getGlobal so that we can augment the Tensor class across package\n // boundaries becase the node resolution alg may result in different modules\n // being returned for this file depending on the path they are loaded from.\n return getGlobal('Tensor', () => {\n return Tensor;\n });\n}\n\n// Global side effect. Cache global reference to Tensor class\ngetGlobalTensorClass();\n\nexport interface NumericTensor<R extends Rank = Rank> extends Tensor<R> {\n dtype: NumericDataType;\n dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D];\n data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]>;\n dataToGPU(options?: DataToGPUOptions): GPUData;\n}\n\nexport interface StringTensor<R extends Rank = Rank> extends Tensor<R> {\n dtype: 'string';\n dataSync<D extends DataType = 'string'>(): DataTypeMap[D];\n data<D extends DataType = 'string'>(): Promise<DataTypeMap[D]>;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor<Rank.R0>;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor<Rank.R1>;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor<Rank.R2>;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor<Rank.R3>;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor<Rank.R4>;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor<Rank.R5>;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor<Rank.R6>;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable<R extends Rank = Rank> extends Tensor<R> {\n name: string;\n\n constructor(\n initialValue: Tensor<R>, public trainable: boolean, name: string,\n tensorId: number) {\n super(\n initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n this.name = name;\n }\n\n /**\n * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n * the same shape and dtype as the old `tf.Tensor`.\n *\n * @param newValue New tensor to be assigned to this variable.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n assign(newValue: Tensor<R>): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n override dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n R0: number[];\n R1: [number];\n R2: [number, number];\n R3: [number, number, number];\n R4: [number, number, number, number];\n R5: [number, number, number, number, number];\n R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n R0: number;\n R1: number[];\n R2: number[][];\n R3: number[][][];\n R4: number[][][][];\n R5: number[][][][][];\n R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n float32: Float32Array;\n int32: Int32Array;\n bool: Uint8Array;\n complex64: Float32Array;\n string: string[];\n}\n\nexport interface SingleValueMap {\n bool: boolean;\n int32: number;\n float32: number;\n complex64: number;\n string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\n\nexport type DataTypeFor<T extends number|string|boolean> =\n T extends number|boolean ? NumericDataType : T extends string ? 'string' :\n never;\n\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n R0 = 'R0',\n R1 = 'R1',\n R2 = 'R2',\n R3 = 'R3',\n R4 = 'R4',\n R5 = 'R5',\n R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray<T> =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray<T extends any> {\n [index: number]: T|RecursiveArray<T>;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'int32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'bool',\n 'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n 'float32' = 'float32',\n 'int32' = 'float32',\n 'bool' = 'float32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n 'float32' = 'complex64',\n 'int32' = 'complex64',\n 'bool' = 'complex64',\n 'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n 'float32': UpcastFloat32AndMap,\n 'int32': UpcastInt32AndMap,\n 'bool': UpcastBoolAndMap,\n 'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n if (typeA === 'string' || typeB === 'string') {\n if (typeA === 'string' && typeB === 'string') {\n return 'string';\n }\n throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n }\n return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n TypedArray|number|boolean|string|RecursiveArray<number|number[]|TypedArray>|\n RecursiveArray<boolean>|RecursiveArray<string>|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\n/**\n * Type for representing all permutations and combinations of 'RGBA' channels.\n */\nexport type WebGLChannels = 'A'|'B'|'G'|'R'|'AB'|'AG'|'AR'|'BA'|'BG'|'BR'|'GA'|\n 'GB'|'GR'|'RA'|'RB'|'RG'|'ABG'|'ABR'|'AGB'|'AGR'|'ARB'|'ARG'|'BAG'|'BAR'|\n 'BGA'|'BGR'|'BRA'|'BRG'|'GAB'|'GAR'|'GBA'|'GBR'|'GRA'|'GRB'|'RAB'|'RAG'|\n 'RBA'|'RBG'|'RGA'|'RGB'|'ABGR'|'ABRG'|'AGBR'|'AGRB'|'ARBG'|'ARGB'|'BAGR'|\n 'BARG'|'BGAR'|'BGRA'|'BRAG'|'BRGA'|'GABR'|'GARB'|'GBAR'|'GBRA'|'GRAB'|\n 'GRBA'|'RABG'|'RAGB'|'RBAG'|'RBGA'|'RGAB'|'RGBA';\n\n/** Type for representing a texture data to create a tensor. */\nexport interface WebGLData {\n texture: WebGLTexture;\n height: number;\n width: number;\n channels: WebGLChannels;\n}\n\n/**\n * Type for representing a buffer data to create a tensor. Buffer usage should\n * at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC. When\n * zeroCopy is false or undefined (default), this GPUBuffer will be copied to\n * the tensor's resource buffer. When zeroCopy is true, tensor will use this\n * GPUBuffer as tensor's resource buffer, user should not destroy this GPUBuffer\n * until all access is done. If not specified at creating a tensor, tensor type\n * is float32.\n */\nexport interface WebGPUData {\n buffer: GPUBuffer;\n zeroCopy?: boolean;\n}\n\nexport function isWebGLData(values: unknown): values is WebGLData {\n return values != null && typeof values === 'object' && 'texture' in values &&\n values.texture instanceof WebGLTexture;\n}\nexport function isWebGPUData(values: unknown): values is WebGPUData {\n return typeof GPUBuffer !== 'undefined' && values != null &&\n typeof values === 'object' && 'buffer' in values &&\n values.buffer instanceof GPUBuffer;\n}\n\nexport interface ImageOptions {\n /**\n * Optional. A number in range [0-1]. If the image is a 2D tensor or a 3D\n * tensor with 1 or 3 channels, the alpha channels would set as its value;\n * otherwise, it would not make effects.\n */\n alpha?: number;\n}\n\nexport interface ContextOptions {\n /**\n * Optional. If the canvas has created a context, it would not make effects.\n * If it is not set, it would be variable based on the current backend.\n */\n contextType?: string;\n /**\n * Optional. A WebGLContextAttributes configuration. If the canvas has created\n * a context, it would not make effects.\n */\n contextAttributes?: WebGLContextAttributes;\n}\n\nexport interface DrawOptions {\n /**\n * Optional. An object of options to customize the values of image tensor.\n */\n imageOptions?: ImageOptions;\n /**\n * Optional. An object to configure the context of the canvas to draw to.\n */\n contextOptions?: ContextOptions;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch<T extends Tensor>(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport { getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap } from './kernel_registry';\nimport { TensorInfo } from './tensor_info';\nimport * as log from './log';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataToGPUOptions, GPUData, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {DataId} from './tensor_info';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc<T> = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n * value: Tensor,\n * gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc<T extends Tensor> =\n (...inputs: Array<Tensor|GradSaveFunc>) => {\n value: T;\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n };\n\nexport type MemoryInfo = {\n numTensors: number; numDataBuffers: number; numBytes: number;\n unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n name: string; bytesAdded: number; totalBytesSnapshot: number;\n tensorsAdded: number;\n totalTensorsSnapshot: number;\n inputShapes: number[][];\n outputShapes: number[][];\n kernelTimeMs: number | {error: string} | Promise<number|{error: string}>;\n extraInfo: string | Promise<string>;\n};\n\nexport type ProfileInfo = {\n newBytes: number; newTensors: number; peakBytes: number;\n kernels: KernelInfo[];\n result: TensorContainer;\n kernelNames: string[];\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn<T extends TensorContainer> = () => T;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\ninterface RegisteredKernelInvocation<I extends NamedTensorMap> {\n kernelName: string;\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation<T extends Tensor|Tensor[],\n I extends NamedTensorMap> {\n forwardFunc: ForwardFunc<T>;\n backwardsFunc: (dy: T, saved: Tensor[]) => {\n [P in keyof I]: () => I[P]\n };\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation<T extends Tensor|Tensor[],\n I extends NamedTensorMap>(\n kernelInvocation: RegisteredKernelInvocation<I>|\n CustomGradKernelInvocation<T, I>):\n kernelInvocation is RegisteredKernelInvocation<I> {\n return (kernelInvocation as RegisteredKernelInvocation<I>).kernelName != null;\n}\n\nclass EngineState {\n // Public since optimizers will use it.\n registeredVariables: NamedVariableMap = {};\n\n nextTapeNodeId = 0;\n numBytes = 0;\n numTensors = 0;\n numStringTensors = 0;\n numDataBuffers = 0;\n\n activeTape: TapeNode[];\n // Number of nested tf.grad() statements when computing higher-order\n // gradients. E.g. `1` for first-order gradients and `2` for second-order\n // gradients. Used to track if the tape should be removed after a backprop.\n gradientDepth = 0;\n // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n // off the tape.\n kernelDepth = 0;\n\n // Keep Tensors that parallel the tapes.\n activeScope: ScopeState;\n scopeStack: ScopeState[] = [];\n /**\n * Keeps track of the number of data moves during a kernel execution. We\n * maintain a stack since kernels can call other kernels, recursively.\n */\n numDataMovesStack: number[] = [];\n nextScopeId = 0;\n\n tensorInfo = new WeakMap<DataId, {\n backend: KernelBackend,\n bytes: number,\n dtype: DataType,\n shape: number[]\n }>();\n\n profiling = false;\n activeProfile: ProfileInfo = {\n newBytes: 0,\n newTensors: 0,\n peakBytes: 0,\n kernels: [],\n result: null,\n get kernelNames():\n string[] {\n return Array.from(new Set(this.kernels.map(k => k.name)));\n }\n };\n\n dispose() {\n for (const variableName in this.registeredVariables) {\n this.registeredVariables[variableName].dispose();\n }\n }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n state: EngineState;\n backendName: string;\n registry: {[id: string]: KernelBackend} = {};\n registryFactory: {\n [id: string]: {\n factory: () => KernelBackend | Promise<KernelBackend>,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise<boolean>;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise<void> {\n if (this.pendingBackendInit != null) {\n return this.pendingBackendInit.then(() => {});\n }\n if (this.backendInstance != null) {\n return;\n }\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const success = await this.initializeBackend(backendName).success;\n if (success) {\n await this.setBackend(backendName);\n return;\n }\n }\n\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n get backend(): KernelBackend {\n if (this.pendingBackendInit != null) {\n throw new Error(\n `Backend '${this.backendName}' has not yet been initialized. Make ` +\n `sure to await tf.ready() or await tf.setBackend() before calling ` +\n `other methods`);\n }\n if (this.backendInstance == null) {\n const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n if (asyncInit) {\n throw new Error(\n `The highest priority backend '${name}' has not yet been ` +\n `initialized. Make sure to await tf.ready() or ` +\n `await tf.setBackend() before calling other methods`);\n }\n this.setBackend(name);\n }\n return this.backendInstance;\n }\n\n backendNames(): string[] {\n return Object.keys(this.registryFactory);\n }\n\n findBackend(backendName: string): KernelBackend {\n if (!(backendName in this.registry)) {\n // If the backend hasn't been initialized but we have a registry entry for\n // it, initialize it and return it.\n if (backendName in this.registryFactory) {\n const {asyncInit} = this.initializeBackend(backendName);\n if (asyncInit) {\n // Backend is not ready yet.\n return null;\n }\n } else {\n return null;\n }\n }\n return this.registry[backendName];\n }\n\n findBackendFactory(backendName: string):\n () => KernelBackend | Promise<KernelBackend> {\n if (!(backendName in this.registryFactory)) {\n return null;\n }\n return this.registryFactory[backendName].factory;\n }\n\n registerBackend(\n backendName: string,\n factory: () => KernelBackend | Promise<KernelBackend>,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n log.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise<boolean> {\n if (this.registryFactory[backendName] == null) {\n throw new Error(`Backend name '${backendName}' not found in registry`);\n }\n this.backendName = backendName;\n if (this.registry[backendName] == null) {\n this.backendInstance = null;\n const {success, asyncInit} = this.initializeBackend(backendName);\n const result = asyncInit ? await success : success;\n if (!result) {\n return false;\n }\n }\n this.backendInstance = this.registry[backendName];\n this.setupRegisteredKernels();\n // Reset the profiler.\n this.profiler = new Profiler(this.backendInstance);\n\n return true;\n }\n\n private setupRegisteredKernels(): void {\n const kernels = getKernelsForBackend(this.backendName);\n kernels.forEach(kernel => {\n if (kernel.setupFunc != null) {\n kernel.setupFunc(this.backendInstance);\n }\n });\n }\n\n private disposeRegisteredKernels(backendName: string): void {\n const kernels = getKernelsForBackend(backendName);\n kernels.forEach(kernel => {\n if (kernel.disposeFunc != null) {\n kernel.disposeFunc(this.registry[backendName]);\n }\n });\n }\n\n /**\n * Initializes a backend by looking up the backend name in the factory\n * registry and calling the factory method. Returns a boolean representing\n * whether the initialization of the backend suceeded. Throws an error if\n * there is no backend in the factory registry.\n */\n private initializeBackend(backendName: string):\n {success: boolean|Promise<boolean>, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend) &&\n typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n const refCount = srcBackend.refCount(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId, true);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype, refCount);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy<T extends TensorContainer>(nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>):\n T {\n let name: string = null;\n if (fn == null) {\n // Called with only 1 argument.\n if (typeof nameOrFn !== 'function') {\n throw new Error('Please provide a function to tidy()');\n }\n fn = nameOrFn;\n } else {\n // Called with 2 arguments.\n if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n throw new Error(\n 'When calling with two arguments, the first argument ' +\n 'to tidy() must be a string');\n }\n if (typeof fn !== 'function') {\n throw new Error(\n 'When calling with two arguments, the 2nd argument ' +\n 'to tidy() must be a function');\n }\n name = nameOrFn as string;\n // TODO(nsthorat,smilkov): Do operation logging and performance\n // profiling.\n }\n let result: T;\n return this.scopedRun(\n () => this.startScope(name), () => this.endScope(result), () => {\n result = fn();\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n return result;\n });\n }\n\n private scopedRun<T>(start: () => void, end: () => void, f: () => T): T {\n start();\n try {\n const res = f();\n end();\n return res;\n } catch (ex) {\n end();\n throw ex;\n }\n }\n\n private static nextTensorId = 0;\n private nextTensorId(): number {\n return Engine.nextTensorId++;\n }\n\n private static nextVariableId = 0;\n private nextVariableId(): number {\n return Engine.nextVariableId++;\n }\n\n /**\n * This method is called instead of the public-facing tensor.clone() when\n * saving a tensor for backwards pass. It makes sure to add the clone\n * operation to the tape regardless of being called inside a kernel\n * execution.\n */\n private clone(x: Tensor): Tensor {\n const y: Tensor = ENGINE.runKernel(Identity,\n {x} as unknown as NamedTensorMap);\n const inputs = {x};\n const grad = (dy: Tensor) => ({\n x: () => {\n const dtype = 'float32';\n const gradInputs = {x: dy};\n const attrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, gradInputs as unknown as NamedTensorMap,\n // tslint:disable-next-line: no-unnecessary-type-assertion\n attrs as unknown as NamedAttrMap) as Tensor;\n }\n });\n const saved: Tensor[] = [];\n this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n return y;\n }\n\n /**\n * Execute a kernel with the given name and return the output tensor.\n *\n * @param kernelName The name of the kernel to execute.\n * @param inputs A map of input names to tensors.\n * @param attrs A map of attribute names to their values. An attribute is a\n * primitive (non-tensor) input to the kernel.\n * @param inputsToSave A list of tensors, inputs to save for the backprop\n * computation.\n * @param outputsToSave A list of booleans, specifying which output to save\n * for the backprop computation. These are booleans since the output\n * tensors are not visible to the user.\n */\n runKernel<T extends Tensor|Tensor[]>(\n kernelName: string, inputs: NamedTensorMap, attrs?: NamedAttrMap): T {\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const hasKernel = getKernel(kernelName, this.backendName) != null;\n if (!hasKernel) {\n throw new Error(`Kernel '${kernelName}' not registered for backend '${\n this.backendName}'`);\n }\n return this.runKernelFunc({kernelName, inputs, attrs});\n }\n\n private shouldCheckForMemLeaks(): boolean {\n return this.ENV.getBool('IS_TEST');\n }\n\n private checkKernelForMemLeak(\n kernelName: string, numDataIdsBefore: number,\n outInfos: TensorInfo[]): void {\n const numDataIdsAfter = this.backend.numDataIds();\n\n // Count the number of data ids associated with the result of the kernel.\n let numOutputDataIds = 0;\n outInfos.forEach(info => {\n // Complex numbers allocate 3 data ids, one for 'real', one for\n // 'imaginary', and one for the container that holds the former two.\n numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n });\n\n // Account for the number of moves during kernel execution. A \"data move\"\n // can happen in the middle of a kernel execution, placing a new (key,value)\n // pair in the data storage. Since data moves have net zero effect (we\n // always remove the data from the old backend), we have to cancel them out\n // when detecting memory leaks.\n const numMoves =\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n const dataIdsLeaked =\n numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n if (dataIdsLeaked > 0) {\n throw new Error(\n `Backend '${this.backendName}' has an internal memory leak ` +\n `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n }\n }\n\n /**\n * Internal helper method to execute a kernel Func\n *\n * Use `runKernel` to execute kernels from outside of engine.\n */\n private runKernelFunc<T extends Tensor|Tensor[], I extends NamedTensorMap>(\n kernelParams: RegisteredKernelInvocation<I>|\n CustomGradKernelInvocation<T, I>): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n\n let out: TensorInfo|TensorInfo[];\n\n const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n kernelParams.kernelName :\n this.state.activeScope != null ? this.state.activeScope.name : '';\n\n // Create the kernelFunc from either a registered kernel OR passed in\n // forward/backward functions (used by custom grad). In this context a\n // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n if (isRegisteredKernelInvocation(kernelParams)) {\n const {kernelName, inputs, attrs} = kernelParams;\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const kernel = getKernel(kernelName, this.backendName);\n util.assert(\n kernel != null,\n () => `Cannot find registered kernel '${kernelName}' for backend '${\n this.backendName}'`);\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n\n const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n // todo (yassogba) remove this option (Tensor) when node backend\n // methods have been modularized and they all return tensorInfo.\n // TensorInfos do not have a rank attribute.\n if ((outInfo as Tensor).rank != null) {\n return outInfo as Tensor;\n }\n return this.makeTensorFromTensorInfo(outInfo);\n });\n\n // Save any required inputs and outputs.\n\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since there would be no backprop for these tensors\n // (which would otherwise dispose them).\n if (isTapeOn) {\n const tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const {forwardFunc} = kernelParams;\n // Running a customGrad op.\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n // Scope name is used to print a more helpful error message if needed.\n this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n //\n // Run the kernelFunc. Optionally profiling it.\n //\n const {inputs, attrs} = kernelParams;\n const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n null :\n kernelParams.backwardsFunc;\n\n let kernelProfile: KernelProfile;\n this.scopedRun(\n // Stop recording to a tape when running a kernel.\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelOrScopeName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelOrScopeName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // We return an empty list rather than throw an error because the kernel we\n // are looking up may not actually be relevant to backproping through the\n // overall function\n //\n // See 'does not error if irrelevant (pruned) ops are missing grads' test\n // in gradients_test.ts for an example.\n return [];\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n * @deprecated\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const tensorInfo: TensorInfo = {dataId, shape, dtype};\n return this.makeTensorFromTensorInfo(tensorInfo, backend);\n }\n\n /**\n * Internal method used by backends. Makes a new tensor that is a wrapper\n * around an existing data id in TensorInfo. It doesn't create a new data id,\n * only increments the ref count used in memory tracking.\n */\n makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend):\n Tensor {\n const {dataId, shape, dtype} = tensorInfo;\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n trackTensor(a: Tensor, backend: KernelBackend): void {\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.numBytes += bytes;\n\n if (!this.state.tensorInfo.has(a.dataId)) {\n this.state.numDataBuffers++;\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes\n });\n }\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n // Track the tensor by dataId and increase the refCount for the dataId in the\n // backend.\n // TODO(pyu10055): This is currently used by makeVariable method, to increase\n // refCount on the backend for the dataId. It can potentially be replaced with\n // Identity op indead of calling backend directly.\n incRef(a: Tensor, backend: KernelBackend): void {\n this.trackTensor(a, backend);\n this.backend.incRef(a.dataId);\n }\n\n removeDataId(dataId: DataId, backend: KernelBackend) {\n if (this.state.tensorInfo.has(dataId) &&\n this.state.tensorInfo.get(dataId).backend === backend) {\n this.state.tensorInfo.delete(dataId);\n this.state.numDataBuffers--;\n }\n }\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n this.state.numBytes -= info.bytes;\n }\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n const bytes = a.size * util.bytesPerElement(a.dtype);\n this.state.numBytes -= bytes;\n }\n\n // Remove the reference to dataId if backend dispose the data successfully\n if (info.backend.disposeData(a.dataId)) {\n this.removeDataId(a.dataId, info.backend);\n }\n\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise<TensorContainer>)):\n Promise<ProfileInfo> {\n this.state.profiling = true;\n\n const startBytes = this.state.numBytes;\n const startNumTensors = this.state.numTensors;\n\n this.state.activeProfile.kernels = [];\n this.state.activeProfile.result = await query();\n\n this.state.profiling = false;\n\n this.state.activeProfile.peakBytes = Math.max(\n ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n this.state.activeProfile.newTensors =\n this.state.numTensors - startNumTensors;\n for (const kernel of this.state.activeProfile.kernels) {\n kernel.kernelTimeMs = await kernel.kernelTimeMs;\n kernel.extraInfo = await kernel.extraInfo;\n }\n return this.state.activeProfile;\n }\n\n isTapeOn(): boolean {\n return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n }\n\n private addTapeNode(\n kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n const tapeNode: TapeNode =\n {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n gradientsFunc = gradConfig.gradFunc;\n }\n if (gradientsFunc != null) {\n tapeNode.gradient = (dys: Tensor[]) => {\n // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n // the backprop graph to the user as null instead of zeros\n dys = dys.map((dy, i) => {\n if (dy == null) {\n const output = outputs[i];\n const vals = util.makeZerosTypedArray(output.size, output.dtype);\n return this.makeTensor(vals, output.shape, output.dtype);\n }\n return dy;\n });\n // Grad functions of ops with single outputs expect a dy, while ops\n // with multiple outputs expect dys (array of dy).\n return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n };\n }\n this.state.activeTape.push(tapeNode);\n }\n\n keep<T extends Tensor>(result: T): T {\n result.kept = true;\n return result;\n }\n\n private startTape() {\n if (this.state.gradientDepth === 0) {\n this.state.activeTape = [];\n }\n this.state.gradientDepth++;\n }\n\n private endTape() {\n this.state.gradientDepth--;\n }\n\n /**\n * Start a scope. Use this with endScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n startScope(name?: string) {\n const scopeInfo: ScopeState = {\n track: [],\n name: 'unnamed scope',\n id: this.state.nextScopeId++\n };\n if (name) {\n scopeInfo.name = name;\n }\n this.state.scopeStack.push(scopeInfo);\n this.state.activeScope = scopeInfo;\n }\n\n /**\n * End a scope. Use this with startScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n endScope(result?: TensorContainer) {\n const tensorsToTrackInParent = getTensorsInContainer(result);\n const tensorsToTrackInParentSet =\n new Set(tensorsToTrackInParent.map(t => t.id));\n\n // Dispose the arrays tracked in this scope.\n for (let i = 0; i < this.state.activeScope.track.length; i++) {\n const tensor = this.state.activeScope.track[i];\n if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n tensor.dispose();\n }\n }\n\n const oldScope = this.state.scopeStack.pop();\n this.state.activeScope = this.state.scopeStack.length === 0 ?\n null :\n this.state.scopeStack[this.state.scopeStack.length - 1];\n\n // Track the current result in the parent scope.\n tensorsToTrackInParent.forEach(tensor => {\n // Only track the tensor if was allocated in the inner scope and is not\n // globally kept.\n if (!tensor.kept && tensor.scopeId === oldScope.id) {\n this.track(tensor);\n }\n });\n }\n\n /**\n * Returns gradients of `f` with respect to each of the `xs`. The gradients\n * returned are of the same length as `xs`, but some might be null if `f`\n * was not a function of that `x`. It also takes optional dy to multiply the\n * gradient, which defaults to `1`.\n */\n gradients<T extends Tensor>(\n f: () => T, xs: Tensor[], dy?: T,\n allowNoGradients = false): {value: T, grads: Tensor[]} {\n util.assert(\n xs.length > 0, () => 'gradients() received an empty list of xs.');\n if (dy != null && dy.dtype !== 'float32') {\n throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n }\n\n const y = this.scopedRun(\n () => this.startTape(), () => this.endTape(),\n () => this.tidy('forward', f));\n\n util.assert(\n y instanceof Tensor,\n () => 'The result y returned by f() must be a tensor.');\n // Filter out the nodes that don't connect x => y.\n const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n throw new Error(\n 'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n 'that the f you passed encloses all operations that lead from x ' +\n 'to y.');\n }\n\n return this.tidy('backward', () => {\n const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n // Backprop gradients through the filtered nodes.\n backpropagateGradients(\n accumulatedGradientMap, filteredTape,\n // Pass the tidy function to avoid circular dep with `tape.ts`.\n f => this.tidy(f as ScopeFn<Tensor>),\n // Pass an add function to avoide a circular dep with `tape.ts`.\n add);\n const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n if (this.state.gradientDepth === 0) {\n // This means that we are not computing higher-order gradients\n // and can clean up the tape.\n this.state.activeTape.forEach(node => {\n for (const tensor of node.saved) {\n tensor.dispose();\n }\n });\n this.state.activeTape = null;\n }\n return {value: y, grads};\n });\n }\n\n customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n (...args: Array<Tensor|GradSaveFunc>) => T {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in customGrad(f) must be a function.');\n return (...inputs: Tensor[]): T => {\n util.assert(\n inputs.every(t => t instanceof Tensor),\n () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n 'tensors');\n\n let res: {\n value: T,\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n };\n const inputMap: NamedTensorMap = {};\n inputs.forEach((input, i) => {\n inputMap[i] = input;\n });\n\n const forwardFunc: ForwardFunc<T> = (_, save) => {\n res = f(...[...inputs, save]);\n util.assert(\n res.value instanceof Tensor,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.value` is a tensor');\n util.assert(\n util.isFunction(res.gradFunc),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function.');\n return res.value;\n };\n\n const backwardsFunc = (dy: T, saved: Tensor[]) => {\n const gradRes = res.gradFunc(dy, saved);\n const grads: Tensor[] = Array.isArray(gradRes) ? gradRes : [gradRes];\n util.assert(\n grads.length === inputs.length,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'the same number of tensors as inputs passed to f(...).');\n util.assert(\n grads.every(t => t instanceof Tensor),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'a list of only tensors.');\n const gradMap: {[key: string]: () => Tensor} = {};\n grads.forEach((grad, i) => {\n gradMap[i] = () => grad;\n });\n return gradMap;\n };\n\n return this.runKernelFunc({\n forwardFunc,\n backwardsFunc,\n inputs: inputMap,\n });\n };\n }\n\n readSync(dataId: DataId): BackendValues {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readSync(dataId);\n }\n read(dataId: DataId): Promise<BackendValues> {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readToGPU(dataId, options);\n }\n\n async time(query: () => void): Promise<TimingInfo> {\n const start = now();\n const timingInfo = await this.backend.time(query) as TimingInfo;\n timingInfo.wallMs = now() - start;\n return timingInfo;\n }\n\n /**\n * Tracks a Tensor in the current scope to be automatically cleaned up\n * when the current scope ends, and returns the value.\n *\n * @param result The Tensor to track in the current scope.\n */\n private track<T extends Tensor>(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as unknown as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/** Whether this browser is Safari. */\nENV.registerFlag(\n 'IS_SAFARI',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Safari/.test(navigator.userAgent) &&\n /Apple/.test(navigator.vendor));\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n\n/** Whether to check computation result for errors. */\nENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => ENV.getBool('DEBUG'));\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);\n\n/** Whether to enable canvas2d willReadFrequently for GPU backends */\nENV.registerFlag('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU', () => false);\n\n/** Whether to use setTimeoutCustom */\nENV.registerFlag('USE_SETTIMEOUTCUSTOM', () => false);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {DataType, isWebGLData, isWebGPUData, TensorLike, WebGLData, WebGPUData} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\nimport {bytesPerElement} from './util_base';\n\nexport function inferShape(\n val: TensorLike|WebGLData|WebGPUData, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\n }\n\n if (isWebGLData(val)) {\n const usedChannels = val.channels || 'RGBA';\n return [val.height, val.width * usedChannels.length];\n } else if (isWebGPUData(val)) {\n return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];\n }\n if (!Array.isArray(val)) {\n return []; // Scalar.\n }\n const shape: number[] = [];\n\n while (Array.isArray(firstElem) ||\n isTypedArray(firstElem) && dtype !== 'string') {\n shape.push(firstElem.length);\n firstElem = firstElem[0];\n }\n if (Array.isArray(val) &&\n env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n deepAssertShapeConsistency(val, shape, []);\n }\n\n return shape;\n}\n\nfunction deepAssertShapeConsistency(\n val: TensorLike, shape: number[], indices: number[]) {\n indices = indices || [];\n if (!(Array.isArray(val)) && !isTypedArray(val)) {\n assert(\n shape.length === 0,\n () => `Element arr[${indices.join('][')}] is a primitive, ` +\n `but should be an array/TypedArray of ${shape[0]} elements`);\n return;\n }\n assert(\n shape.length > 0,\n () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n `but is an array of ${val.length} elements`);\n assert(\n val.length === shape[0],\n () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n `elements, but has ${val.length} elements`);\n const subShape = shape.slice(1);\n for (let i = 0; i < val.length; ++i) {\n deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n }\n}\n\nfunction assertDtype(\n expectedDtype: DataType|'numeric'|'string_or_numeric',\n actualDType: DataType, argName: string, functionName: string) {\n if (expectedDtype === 'string_or_numeric') {\n return;\n }\n if (expectedDtype == null) {\n throw new Error(`Expected dtype cannot be null.`);\n }\n if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n expectedDtype === 'numeric' && actualDType === 'string') {\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must ` +\n `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n }\n}\n\nexport function convertToTensor<T extends Tensor>(\n x: T|TensorLike, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T {\n if (x instanceof Tensor) {\n assertDtype(parseAsDtype, x.dtype, argName, functionName);\n return x;\n }\n let inferredDtype = inferDtype(x);\n // If the user expects a bool/int/float, use that info to update the\n // inferredDtype when it is not a string.\n if (inferredDtype !== 'string' &&\n ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n inferredDtype = parseAsDtype as DataType;\n }\n assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n if ((x == null) ||\n (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n typeof x !== 'boolean' && typeof x !== 'string')) {\n const type = x == null ? 'null' : (x as {}).constructor.name;\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must be a ` +\n `Tensor or TensorLike, but got '${type}'`);\n }\n const inferredShape = inferShape(x, inferredDtype);\n if (!isTypedArray(x) && !Array.isArray(x)) {\n x = [x] as number[];\n }\n const skipTypedArray = true;\n const values = inferredDtype !== 'string' ?\n toTypedArray(x, inferredDtype as DataType) :\n flatten(x as string[], [], skipTypedArray) as string[];\n return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray<T extends Tensor>(\n arg: Array<T|TensorLike>, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T[] {\n if (!Array.isArray(arg)) {\n throw new Error(\n `Argument ${argName} passed to ${functionName} must be a ` +\n '`Tensor[]` or `TensorLike[]`');\n }\n const tensors = arg as T[];\n return tensors.map(\n (t, i) =>\n convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op<T extends Function>(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (isPromise(result)) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {isWebGLData, isWebGPUData, TensorLike, TypedArray, WebGLData, WebGPUData} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike|WebGLData|WebGPUData, shape: number[],\n inferredShape: number[], dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n } else if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n\n if (isWebGPUData(values) || isWebGLData(values)) {\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new Error(\n `Creating tensor from GPU data only supports ` +\n `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n }\n return ENGINE.backend.createTensorFromGPUData(\n values, shape || inferredShape, dtype);\n }\n\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n // Verify that the shape matches the inferred shape.\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n","/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {TypedArray} from '../types';\nimport * as util from '../util';\n\ntype BufferShard = {\n start: number,\n end: number,\n buffer: ArrayBuffer,\n};\n\n/**\n * Wraps a list of ArrayBuffers into a `slice()`-able object without allocating\n * a large ArrayBuffer.\n *\n * Allocating large ArrayBuffers (~2GB) can be unstable on Chrome. TFJS loads\n * its weights as a list of (usually) 4MB ArrayBuffers and then slices the\n * weight tensors out of them. For small models, it's safe to concatenate all\n * the weight buffers into a single ArrayBuffer and then slice the weight\n * tensors out of it, but for large models, a different approach is needed.\n */\n\nexport class CompositeArrayBuffer {\n private shards: BufferShard[] = [];\n private previousShardIndex = 0;\n private bufferUniformSize?: number;\n public readonly byteLength: number;\n\n /**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n * ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n */\n static join(buffers?: ArrayBuffer[] | ArrayBuffer) {\n return new CompositeArrayBuffer(buffers).slice();\n }\n\n constructor(buffers?: ArrayBuffer | ArrayBuffer[] | TypedArray |\n TypedArray[]) {\n if (buffers == null) {\n return;\n }\n // Normalize the `buffers` input to be `ArrayBuffer[]`.\n if (!(buffers instanceof Array)) {\n buffers = [buffers];\n }\n buffers = buffers.map((bufferOrTypedArray) => {\n if (util.isTypedArray(bufferOrTypedArray)) {\n return bufferOrTypedArray.buffer;\n }\n return bufferOrTypedArray;\n });\n\n // Skip setting up shards if there are no buffers.\n if (buffers.length === 0) {\n return;\n }\n\n this.bufferUniformSize = buffers[0].byteLength;\n let start = 0;\n\n for (let i = 0; i < buffers.length; i++) {\n const buffer = buffers[i];\n // Check that all buffers except the last one have the same length.\n if (i !== buffers.length - 1 &&\n buffer.byteLength !== this.bufferUniformSize) {\n // Unset the buffer uniform size, since the buffer sizes are not\n // uniform.\n this.bufferUniformSize = undefined;\n }\n\n // Create the shards, including their start and end points.\n const end = start + buffer.byteLength;\n this.shards.push({ buffer, start, end });\n start = end;\n }\n\n // Set the byteLenghth\n if (this.shards.length === 0) {\n this.byteLength = 0;\n }\n this.byteLength = this.shards[this.shards.length - 1].end;\n }\n\n slice(start = 0, end = this.byteLength): ArrayBuffer {\n // If there are no shards, then the CompositeArrayBuffer was initialized\n // with no data.\n if (this.shards.length === 0) {\n return new ArrayBuffer(0);\n }\n\n // NaN is treated as zero for slicing. This matches ArrayBuffer's behavior.\n start = isNaN(Number(start)) ? 0 : start;\n end = isNaN(Number(end)) ? 0 : end;\n\n // Fix the bounds to within the array.\n start = Math.max(0, start);\n end = Math.min(this.byteLength, end);\n if (end <= start) {\n return new ArrayBuffer(0);\n }\n\n const startShardIndex = this.findShardForByte(start);\n if (startShardIndex === -1) {\n // This should not happen since the start and end indices are always\n // within 0 and the composite array's length.\n throw new Error(`Could not find start shard for byte ${start}`);\n }\n\n const size = end - start;\n const outputBuffer = new ArrayBuffer(size);\n const outputArray = new Uint8Array(outputBuffer);\n let sliced = 0;\n for (let i = startShardIndex; i < this.shards.length; i++) {\n const shard = this.shards[i];\n\n const globalStart = start + sliced;\n const localStart = globalStart - shard.start;\n const outputStart = sliced;\n\n const globalEnd = Math.min(end, shard.end);\n const localEnd = globalEnd - shard.start;\n\n const outputSlice = new Uint8Array(shard.buffer, localStart,\n localEnd - localStart);\n outputArray.set(outputSlice, outputStart);\n sliced += outputSlice.length;\n\n if (end < shard.end) {\n break;\n }\n }\n return outputBuffer;\n }\n\n /**\n * Get the index of the shard that contains the byte at `byteIndex`.\n */\n private findShardForByte(byteIndex: number): number {\n if (this.shards.length === 0 || byteIndex < 0 ||\n byteIndex >= this.byteLength) {\n return -1;\n }\n\n // If the buffers have a uniform size, compute the shard directly.\n if (this.bufferUniformSize != null) {\n this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);\n return this.previousShardIndex;\n }\n\n // If the buffers don't have a uniform size, we need to search for the\n // shard. That means we need a function to check where the byteIndex lies\n // relative to a given shard.\n function check(shard: BufferShard) {\n if (byteIndex < shard.start) {\n return -1;\n }\n if (byteIndex >= shard.end) {\n return 1;\n }\n return 0;\n }\n\n // For efficiency, try the previous shard first.\n if (check(this.shards[this.previousShardIndex]) === 0) {\n return this.previousShardIndex;\n }\n\n // Otherwise, use a generic search function.\n // This should almost never end up being used in practice since the weight\n // entries should always be in order.\n const index = search(this.shards, check);\n if (index === -1) {\n return -1;\n }\n\n this.previousShardIndex = index;\n return this.previousShardIndex;\n }\n}\n\n/**\n * Search for an element of a sorted array.\n *\n * @param sortedArray The sorted array to search\n * @param compare A function to compare the current value against the searched\n * value. Return 0 on a match, negative if the searched value is less than\n * the value passed to the function, and positive if the searched value is\n * greater than the value passed to the function.\n * @returns The index of the element, or -1 if it's not in the array.\n */\nexport function search<T>(sortedArray: T[], compare: (t: T) => number): number {\n // Binary search\n let min = 0;\n let max = sortedArray.length;\n\n while (min <= max) {\n const middle = Math.floor((max - min) / 2) + min;\n const side = compare(sortedArray[middle]);\n\n if (side === 0) {\n return middle;\n } else if (side < 0) {\n max = middle;\n } else {\n min = middle + 1;\n }\n }\n return -1;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightData, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array<Promise<TypedArray>> = [];\n\n const names: string[] = Array.isArray(tensors) ?\n tensors.map(tensor => tensor.name) :\n Object.keys(tensors);\n\n for (let i = 0; i < names.length; ++i) {\n const name = names[i];\n const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n t.dtype !== 'string' && t.dtype !== 'complex64') {\n throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n }\n const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n if (t.dtype === 'string') {\n const utf8bytes = new Promise<TypedArray>(async resolve => {\n const vals = await t.bytes() as Uint8Array[];\n const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n NUM_BYTES_STRING_LENGTH * vals.length;\n const bytes = new Uint8Array(totalNumBytes);\n let offset = 0;\n for (let i = 0; i < vals.length; i++) {\n const val = vals[i];\n const bytesOfLength =\n new Uint8Array(new Uint32Array([val.length]).buffer);\n bytes.set(bytesOfLength, offset);\n offset += NUM_BYTES_STRING_LENGTH;\n bytes.set(val, offset);\n offset += val.length;\n }\n resolve(bytes);\n });\n dataPromises.push(utf8bytes);\n } else {\n dataPromises.push(t.data());\n }\n if (group != null) {\n spec.group = group;\n }\n specs.push(spec);\n }\n\n const tensorValues = await Promise.all(dataPromises);\n return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param weightData A flat ArrayBuffer or an array of ArrayBuffers carrying the\n * binary values of the tensors concatenated in the order specified in\n * `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n * whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n * to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n weightData: WeightData,\n specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const compositeBuffer = new CompositeArrayBuffer(weightData);\n const out: NamedTensorMap = {};\n let float16Decode: (buffer: Uint16Array) => Float32Array | undefined;\n let offset = 0;\n for (const spec of specs) {\n const name = spec.name;\n const dtype = spec.dtype;\n const shape = spec.shape;\n const size = sizeFromShape(shape);\n let values: TypedArray|string[]|Uint8Array[];\n\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n if (!('min' in quantization && 'scale' in quantization)) {\n throw new Error(\n `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n `doesn't have corresponding metadata min and scale.`);\n }\n } else if (quantization.dtype === 'float16') {\n if (dtype !== 'float32') {\n throw new Error(\n `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n `which only supports weights of type float32 not ${dtype}.`);\n }\n } else {\n throw new Error(\n `Weight ${spec.name} has unknown ` +\n `quantization dtype ${quantization.dtype}. ` +\n `Supported quantization dtypes are: ` +\n `'uint8', 'uint16', and 'float16'.`);\n }\n const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n const byteBuffer =\n compositeBuffer.slice(offset, offset + size * quantizationSizeFactor);\n const quantizedArray = (quantization.dtype === 'uint8') ?\n new Uint8Array(byteBuffer) :\n new Uint16Array(byteBuffer);\n if (dtype === 'float32') {\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n values = new Float32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = v * quantization.scale + quantization.min;\n }\n } else if (quantization.dtype === 'float16') {\n if (float16Decode === undefined) {\n float16Decode = getFloat16Decoder();\n }\n values = float16Decode(quantizedArray as Uint16Array);\n } else {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type float32.`);\n }\n } else if (dtype === 'int32') {\n if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type int32.`);\n }\n values = new Int32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = Math.round(v * quantization.scale + quantization.min);\n }\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * quantizationSizeFactor;\n } else if (dtype === 'string') {\n const size = sizeFromShape(spec.shape);\n values = [];\n for (let i = 0; i < size; i++) {\n const byteLength = new Uint32Array(\n compositeBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(\n compositeBuffer.slice(offset, offset + byteLength));\n (values as Uint8Array[]).push(bytes);\n offset += byteLength;\n }\n } else {\n const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n const byteBuffer = compositeBuffer.slice(offset,\n offset + size * dtypeFactor);\n\n if (dtype === 'float32') {\n values = new Float32Array(byteBuffer);\n } else if (dtype === 'int32') {\n values = new Int32Array(byteBuffer);\n } else if (dtype === 'bool') {\n values = new Uint8Array(byteBuffer);\n } else if (dtype === 'complex64') {\n values = new Float32Array(byteBuffer);\n const real = new Float32Array(values.length / 2);\n const image = new Float32Array(values.length / 2);\n for (let i = 0; i < real.length; i++) {\n real[i] = values[i * 2];\n image[i] = values[i * 2 + 1];\n }\n const realTensor = tensor(real, shape, 'float32');\n const imageTensor = tensor(image, shape, 'float32');\n out[name] = complex(realTensor, imageTensor);\n realTensor.dispose();\n imageTensor.dispose();\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n if (dtype !== 'complex64') {\n out[name] = tensor(values, shape, dtype);\n }\n }\n return out;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n // TODO(adarob, cais): Support quantization.\n if (xs === null) {\n throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n }\n\n let totalByteLength = 0;\n\n // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n // can have a different byte length from that of the `TypedArray` itself,\n // for example, when the `TypedArray` is created from an offset in an\n // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n // the `TypedArray` in byte length. If an element of `xs` does not show\n // this property, a new `TypedArray` that satisfy this property will be\n // constructed and pushed into `normalizedXs`.\n const normalizedXs: TypedArray[] = [];\n xs.forEach((x: TypedArray) => {\n totalByteLength += x.byteLength;\n // tslint:disable:no-any\n normalizedXs.push(\n x.byteLength === x.buffer.byteLength ? x :\n new (x.constructor as any)(x));\n if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n x as any instanceof Uint8Array)) {\n throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n }\n // tslint:enable:no-any\n });\n\n const y = new Uint8Array(totalByteLength);\n let offset = 0;\n normalizedXs.forEach((x: TypedArray) => {\n y.set(new Uint8Array(x.buffer), offset);\n offset += x.byteLength;\n });\n\n return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n if (useNodeBuffer) {\n return Buffer.byteLength(str, 'utf8');\n }\n return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n if (useNodeBuffer) {\n return Buffer.from(buffer).toString('base64');\n }\n const buf = new Uint8Array(buffer);\n let s = '';\n for (let i = 0, l = buf.length; i < l; i++) {\n s += String.fromCharCode(buf[i]);\n }\n return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n if (useNodeBuffer) {\n const buf = Buffer.from(str, 'base64');\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const s = atob(str);\n const buffer = new Uint8Array(s.length);\n for (let i = 0; i < s.length; ++i) {\n buffer.set([s.charCodeAt(i)], i);\n }\n return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n * ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n *\n * @deprecated Use tf.io.CompositeArrayBuffer.join() instead.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]\n | ArrayBuffer): ArrayBuffer {\n return CompositeArrayBuffer.join(buffers);\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n const SEPARATOR = '/';\n path = path.trim();\n while (path.endsWith(SEPARATOR)) {\n path = path.slice(0, path.length - 1);\n }\n const items = path.split(SEPARATOR);\n return items[items.length - 1];\n}\n\n/**\n * Create `ModelJSON` from `ModelArtifacts`.\n *\n * @param artifacts Model artifacts, describing the model and its weights.\n * @param manifest Weight manifest, describing where the weights of the\n * `ModelArtifacts` are stored, and some metadata about them.\n * @returns Object representing the `model.json` file describing the model\n * artifacts and weights\n */\nexport function getModelJSONForModelArtifacts(\n artifacts: ModelArtifacts, manifest: WeightsManifestConfig): ModelJSON {\n const result: ModelJSON = {\n modelTopology: artifacts.modelTopology,\n format: artifacts.format,\n generatedBy: artifacts.generatedBy,\n convertedBy: artifacts.convertedBy,\n weightsManifest: manifest\n };\n if (artifacts.signature != null) {\n result.signature = artifacts.signature;\n }\n if (artifacts.userDefinedMetadata != null) {\n result.userDefinedMetadata = artifacts.userDefinedMetadata;\n }\n if (artifacts.modelInitializer != null) {\n result.modelInitializer = artifacts.modelInitializer;\n }\n if (artifacts.initializerSignature != null) {\n result.initializerSignature = artifacts.initializerSignature;\n }\n if (artifacts.trainingConfig != null) {\n result.trainingConfig = artifacts.trainingConfig;\n }\n return result;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file and weights.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param weightSpecs The list of WeightsManifestEntry for the model. Must be\n * passed if the modelJSON has a weightsManifest.\n * @param weightData An ArrayBuffer or array of ArrayBuffers of weight data for\n * the model corresponding to the weights in weightSpecs. Must be passed if\n * the modelJSON has a weightsManifest.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport function getModelArtifactsForJSONSync(\n modelJSON: ModelJSON, weightSpecs?: WeightsManifestEntry[],\n weightData?: WeightData): ModelArtifacts {\n\n const modelArtifacts: ModelArtifacts = {\n modelTopology: modelJSON.modelTopology,\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy\n };\n\n if (modelJSON.trainingConfig != null) {\n modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n }\n if (modelJSON.weightsManifest != null) {\n if (!weightSpecs) {\n throw new Error('modelJSON has weightsManifest but weightSpecs is null');\n }\n if (!weightData) {\n throw new Error('modelJSON has weightsManifest but weightData is null');\n }\n modelArtifacts.weightSpecs = weightSpecs;\n modelArtifacts.weightData = weightData;\n }\n if (modelJSON.signature != null) {\n modelArtifacts.signature = modelJSON.signature;\n }\n if (modelJSON.userDefinedMetadata != null) {\n modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n }\n if (modelJSON.modelInitializer != null) {\n modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n }\n if (modelJSON.initializerSignature != null) {\n modelArtifacts.initializerSignature = modelJSON.initializerSignature;\n }\n\n return modelArtifacts;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n * reads weights from the listed path(s), and returns a Promise of the\n * weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n modelJSON: ModelJSON,\n loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n /* weightSpecs */ WeightsManifestEntry[], WeightData,\n ]>): Promise<ModelArtifacts> {\n let weightSpecs: WeightsManifestEntry[] | undefined;\n let weightData: WeightData | undefined;\n\n if (modelJSON.weightsManifest != null) {\n [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);\n }\n\n return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n new CompositeArrayBuffer(modelArtifacts.weightData).byteLength,\n };\n}\n\n/**\n * Concatenate the weights stored in a WeightsManifestConfig into a list of\n * WeightsManifestEntry\n *\n * @param weightsManifest The WeightsManifestConfig to extract weights from.\n * @returns A list of WeightsManifestEntry of the weights in the weightsManifest\n */\nexport function getWeightSpecs(weightsManifest: WeightsManifestConfig):\n WeightsManifestEntry[] {\n const weightSpecs: WeightsManifestEntry[] = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n return weightSpecs;\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise<void> {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise<void>((resolve, reject) => {\n const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n deleteRequest.onsuccess = () => resolve();\n deleteRequest.onerror = error => reject(error);\n });\n}\n\nfunction getIndexedDBFactory(): IDBFactory {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Add more info about what IOHandler subtypes are available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'Failed to obtain IndexedDB factory because the current environment' +\n 'is not a web browser.');\n }\n // tslint:disable-next-line:no-any\n const theWindow: any = typeof window === 'undefined' ? self : window;\n const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n theWindow.shimIndexedDB;\n if (factory == null) {\n throw new Error(\n 'The current browser does not appear to support IndexedDB.');\n }\n return factory;\n}\n\nfunction setUpDatabase(openRequest: IDBRequest) {\n const db = openRequest.result as IDBDatabase;\n db.createObjectStore(MODEL_STORE_NAME, {keyPath: 'modelPath'});\n db.createObjectStore(INFO_STORE_NAME, {keyPath: 'modelPath'});\n}\n\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB implements IOHandler {\n protected readonly indexedDB: IDBFactory;\n protected readonly modelPath: string;\n\n static readonly URL_SCHEME = 'indexeddb://';\n\n constructor(modelPath: string) {\n this.indexedDB = getIndexedDBFactory();\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For IndexedDB, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n // TODO(cais): Support saving GraphDef models.\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n return this.databaseAction(this.modelPath, modelArtifacts) as\n Promise<SaveResult>;\n }\n\n async load(): Promise<ModelArtifacts> {\n return this.databaseAction(this.modelPath) as Promise<ModelArtifacts>;\n }\n\n /**\n * Perform database action to put model artifacts into or read model artifacts\n * from IndexedDB object store.\n *\n * Whether the action is put or get depends on whether `modelArtifacts` is\n * specified. If it is specified, the action will be put; otherwise the action\n * will be get.\n *\n * @param modelPath A unique string path for the model.\n * @param modelArtifacts If specified, it will be the model artifacts to be\n * stored in IndexedDB.\n * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n * of `ModelArtifacts`, if the action is get.\n */\n private databaseAction(modelPath: string, modelArtifacts?: ModelArtifacts):\n Promise<ModelArtifacts|SaveResult> {\n return new Promise<ModelArtifacts|SaveResult>((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n } else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n } else {\n // Put model into object store.\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n let putInfoRequest: IDBRequest<IDBValidKey>;\n try {\n putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n } catch (error) {\n return reject(error);\n }\n let modelTx: IDBTransaction;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n let putModelRequest: IDBRequest<IDBValidKey>;\n try {\n putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n } catch (error) {\n // Sometimes, the serialized value is too large to store.\n return reject(error);\n }\n putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),\n * which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath: string): IOHandler {\n return new BrowserIndexedDB(modelPath);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n key;\n}\n\nexport class BrowserIndexedDBManager implements ModelStoreManager {\n private indexedDB: IDBFactory;\n\n constructor() {\n this.indexedDB = getIndexedDBFactory();\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n return new Promise<{[path: string]: ModelArtifactsInfo}>(\n (resolve, reject) => {\n const openRequest =\n this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n const store = tx.objectStore(INFO_STORE_NAME);\n // tslint:disable:max-line-length\n // Need to cast `store` as `any` here because TypeScript's DOM\n // library does not have the `getAll()` method even though the\n // method is supported in the latest version of most mainstream\n // browsers:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n // tslint:enable:max-line-length\n // tslint:disable-next-line:no-any\n const getAllInfoRequest = (store as any).getAll() as IDBRequest;\n getAllInfoRequest.onsuccess = () => {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n for (const item of getAllInfoRequest.result) {\n out[item.modelPath] = item.modelArtifactsInfo;\n }\n resolve(out);\n };\n getAllInfoRequest.onerror = error => {\n db.close();\n return reject(getAllInfoRequest.error);\n };\n tx.oncomplete = () => db.close();\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n\n async removeModel(path: string): Promise<ModelArtifactsInfo> {\n path = maybeStripScheme(path);\n return new Promise<ModelArtifactsInfo>((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n const getInfoRequest = infoStore.get(path);\n let modelTx: IDBTransaction;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n } else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () =>\n resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error =>\n reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error(\n 'purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths: string[] = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\n\ntype LocalStorageKeys = {\n /** Key of the localStorage entry storing `ModelArtifactsInfo`. */\n info: string,\n /**\n * Key of the localStorage entry storing the 'modelTopology' key of\n * `model.json`\n */\n topology: string,\n /**\n * Key of the localStorage entry storing the `weightsManifest.weights` entries\n * of `model.json`\n */\n weightSpecs: string,\n /** Key of the localStorage entry storing the weight data in Base64 */\n weightData: string,\n /**\n * Key of the localStorage entry storing the remaining fields of `model.json`\n * @see {@link ModelMetadata}\n */\n modelMetadata: string,\n};\n\ntype ModelMetadata = Omit<ModelJSON, 'modelTopology'|'weightsManifest'>;\n\nfunction getModelKeys(path: string): LocalStorageKeys {\n return {\n info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n modelMetadata:\n [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n };\n}\n\nfunction removeItems(keys: LocalStorageKeys): void {\n for (const key of Object.values(keys)) {\n window.localStorage.removeItem(key);\n }\n}\n\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key: string) {\n const items = key.split(PATH_SEPARATOR);\n if (items.length < 3) {\n throw new Error(`Invalid key format: ${key}`);\n }\n return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n key;\n}\n\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage implements IOHandler {\n protected readonly LS: Storage;\n protected readonly modelPath: string;\n protected readonly keys: LocalStorageKeys;\n\n static readonly URL_SCHEME = 'localstorage://';\n\n constructor(modelPath: string) {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n // TODO(cais): Add more info about what IOHandler subtypes are\n // available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'The current environment does not support local storage.');\n }\n this.LS = window.localStorage;\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For local storage, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n this.keys = getModelKeys(this.modelPath);\n }\n\n /**\n * Save model artifacts to browser local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @param modelArtifacts The model artifacts to be stored.\n * @returns An instance of SaveResult.\n */\n async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n\n // TODO(mattsoulanille): Support saving models over 2GB that exceed\n // Chrome's ArrayBuffer size limit.\n const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(\n this.keys.weightData,\n arrayBufferToBase64String(weightBuffer));\n\n // Note that JSON.stringify doesn't write out keys that have undefined\n // values, so for some keys, we set undefined instead of a null-ish\n // value.\n const metadata: Required<ModelMetadata> = {\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n signature: modelArtifacts.signature != null ?\n modelArtifacts.signature :\n undefined,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ?\n modelArtifacts.userDefinedMetadata :\n undefined,\n modelInitializer: modelArtifacts.modelInitializer != null ?\n modelArtifacts.modelInitializer :\n undefined,\n initializerSignature: modelArtifacts.initializerSignature != null ?\n modelArtifacts.initializerSignature :\n undefined,\n trainingConfig: modelArtifacts.trainingConfig != null ?\n modelArtifacts.trainingConfig :\n undefined\n };\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));\n\n return {modelArtifactsInfo};\n } catch (err) {\n // If saving failed, clean up all items saved so far.\n removeItems(this.keys);\n\n throw new Error(\n `Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load(): Promise<ModelArtifacts> {\n const info =\n JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n if (info == null) {\n throw new Error(\n `In local storage, there is no model with name '${this.modelPath}'`);\n }\n\n if (info.modelTopologyType !== 'JSON') {\n throw new Error(\n 'BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n\n const out: ModelArtifacts = {};\n\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(\n `In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(\n `In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString) as ModelMetadata;\n out.format = metadata.format;\n out.generatedBy = metadata.generatedBy;\n out.convertedBy = metadata.convertedBy;\n if (metadata.signature != null) {\n out.signature = metadata.signature;\n }\n if (metadata.userDefinedMetadata != null) {\n out.userDefinedMetadata = metadata.userDefinedMetadata;\n }\n if (metadata.modelInitializer != null) {\n out.modelInitializer = metadata.modelInitializer;\n }\n if (metadata.initializerSignature != null) {\n out.initializerSignature = metadata.initializerSignature;\n }\n if (metadata.trainingConfig != null) {\n out.trainingConfig = metadata.trainingConfig;\n }\n }\n\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(\n `In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n return out;\n }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(\n url.slice(BrowserLocalStorage.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n private readonly LS: Storage;\n\n constructor() {\n assert(\n env().getBool('IS_BROWSER'),\n () => 'Current environment is not a web browser');\n assert(\n typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined',\n () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n }\n }\n return out;\n }\n\n async removeModel(path: string): Promise<ModelArtifactsInfo> {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n removeItems(keys);\n return info;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = ModelStoreManagerRegistry.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(ModelStoreManagerRegistry.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise<ModelArtifactsInfo> {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a registered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise<ModelArtifactsInfo> {\n const schemeAndPath = parseURL(url);\n const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n return manager.removeModel(schemeAndPath.path);\n}\n\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function copyModel(\n sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {\n const deleteSource = false;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function moveModel(\n sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\nimport {isTypedArrayBrowser} from './is_typed_array_browser';\n\nexport class PlatformBrowser implements Platform {\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n private textEncoder: TextEncoder;\n\n // For setTimeoutCustom\n private readonly messageName = 'setTimeoutCustom';\n private functionRefs: Function[] = [];\n private handledMessageCount = 0;\n private hasEventListener = false;\n\n fetch(path: string, init?: RequestInit): Promise<Response> {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n\n // If the setTimeout nesting level is greater than 5 and timeout is less\n // than 4ms, timeout will be clamped to 4ms, which hurts the perf.\n // Interleaving window.postMessage and setTimeout will trick the browser and\n // avoid the clamp.\n setTimeoutCustom(functionRef: Function, delay: number): void {\n if (typeof window === 'undefined' ||\n !env().getBool('USE_SETTIMEOUTCUSTOM')) {\n setTimeout(functionRef, delay);\n return;\n }\n\n this.functionRefs.push(functionRef);\n setTimeout(() => {\n window.postMessage(\n {name: this.messageName, index: this.functionRefs.length - 1}, '*');\n }, delay);\n\n if (!this.hasEventListener) {\n this.hasEventListener = true;\n window.addEventListener('message', (event: MessageEvent) => {\n if (event.source === window && event.data.name === this.messageName) {\n event.stopPropagation();\n const functionRef = this.functionRefs[event.data.index];\n functionRef();\n this.handledMessageCount++;\n if (this.handledMessageCount === this.functionRefs.length) {\n this.functionRefs = [];\n this.handledMessageCount = 0;\n }\n }\n }, true);\n }\n }\n\n isTypedArray(a: unknown): a is Uint8Array | Float32Array | Int32Array\n | Uint8ClampedArray {\n return isTypedArrayBrowser(a);\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise<Response>;\nlet systemFetch: FetchFn;\n// These getters and setters are for testing so we don't export a mutable\n// variable.\nexport function resetSystemFetch() {\n systemFetch = null;\n}\nexport function setSystemFetch(fetchFn: FetchFn) {\n systemFetch = fetchFn;\n}\nexport function getSystemFetch(): FetchFn {\n return systemFetch;\n}\n\nexport class PlatformNode implements Platform {\n private textEncoder: TextEncoder;\n // tslint:disable-next-line:no-any\n util: any;\n\n constructor() {\n // tslint:disable-next-line:no-require-imports\n this.util = require('util');\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n this.textEncoder = new this.util.TextEncoder();\n }\n\n fetch(path: string, requestInits?: RequestInit): Promise<Response> {\n if (env().global.fetch != null) {\n return env().global.fetch(path, requestInits);\n }\n\n if (systemFetch == null) {\n systemFetch = getNodeFetch.importFetch();\n }\n return systemFetch(path, requestInits);\n }\n\n now(): number {\n const time = process.hrtime();\n return time[0] * 1000 + time[1] / 1000000;\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Node built-in encoder only supports utf-8, but got ${encoding}`);\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n if (bytes.length === 0) {\n return '';\n }\n return new this.util.TextDecoder(encoding).decode(bytes);\n }\n isTypedArray(a: unknown): a is Float32Array | Int32Array | Uint8Array\n | Uint8ClampedArray {\n return this.util.types.isFloat32Array(a)\n || this.util.types.isInt32Array(a)\n || this.util.types.isUint8Array(a)\n || this.util.types.isUint8ClampedArray(a);\n }\n}\n\nif (env().get('IS_NODE') && !env().get('IS_BROWSER')) {\n env().setPlatform('node', new PlatformNode());\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer<R extends Rank, D extends DataType = 'float32'>(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer<R, D> {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer<R, D>(shape, dtype, values);\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_<T extends Tensor>(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const cast = /* @__PURE__ */ op({cast_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernel(Identity, inputs as unknown as NamedTensorMap);\n}\n\nexport const clone = /* @__PURE__ */ op({clone_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print<T extends Tensor>(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n env().set('DEPRECATION_WARNINGS_ENABLED', false);\n console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n console.warn(\n msg + ' You can disable deprecation warnings with ' +\n 'tf.disableDeprecationWarnings().');\n }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n * (undisposed) at this time, which is ≤ the number of tensors\n * (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n * data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n * `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n * `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n * this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n * const x = tf.tensor1d([1, 2, 3]);\n * let x2 = x.square();\n * x2.dispose();\n * x2 = x.square();\n * x2.dispose();\n * return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise<TensorContainer>)):\n Promise<ProfileInfo> {\n return ENGINE.profile(f);\n}\n\n/**\n * Executes the provided function `fn` and after it is executed, cleans up all\n * intermediate tensors allocated by `fn` except those returned by `fn`.\n * `fn` must not return a Promise (async functions not allowed). The returned\n * result can be a complex object.\n *\n * Using this method helps avoid memory leaks. In general, wrap calls to\n * operations in `tf.tidy` for automatic memory cleanup.\n *\n * NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to\n * dispose variables, please use `tf.disposeVariables` or call dispose()\n * directly on variables.\n *\n * ```js\n * // y = 2 ^ 2 + 1\n * const y = tf.tidy(() => {\n * // a, b, and one will be cleaned up when the tidy ends.\n * const one = tf.scalar(1);\n * const a = tf.scalar(2);\n * const b = a.square();\n *\n * console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n * // The value returned inside the tidy function will return\n * // through the tidy, in this case to the variable y.\n * return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * y.print();\n * ```\n *\n * @param nameOrFn The name of the closure, or the function to execute.\n * If a name is provided, the 2nd argument should be the function.\n * If debug mode is on, the timing and the memory usage of the function\n * will be tracked and displayed on the console using the provided name.\n * @param fn The function to execute.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function tidy<T extends TensorContainer>(\n nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>): T {\n return ENGINE.tidy(nameOrFn, fn);\n}\n\n/**\n * Disposes any `tf.Tensor`s found within the provided object.\n *\n * @param container an object that may be a `tf.Tensor` or may directly\n * contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If\n * the object is not a `tf.Tensor` or does not contain `Tensors`, nothing\n * happens. In general it is safe to pass any object here, except that\n * `Promise`s are not supported.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function dispose(container: TensorContainer) {\n const tensors = getTensorsInContainer(container);\n tensors.forEach(tensor => tensor.dispose());\n}\n\n/**\n * Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed\n * automatically.\n *\n * ```js\n * let b;\n * const y = tf.tidy(() => {\n * const one = tf.scalar(1);\n * const a = tf.scalar(2);\n *\n * // b will not be cleaned up by the tidy. a and one will be cleaned up\n * // when the tidy ends.\n * b = tf.keep(a.square());\n *\n * console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n * // The value returned inside the tidy function will return\n * // through the tidy, in this case to the variable y.\n * return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * console.log('y:');\n * y.print();\n * console.log('b:');\n * b.print();\n * ```\n *\n * @param result The tensor to keep from being disposed.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function keep<T extends Tensor>(result: T): T {\n return ENGINE.keep(result);\n}\n\n/**\n * Executes `f()` and returns a promise that resolves with timing\n * information.\n *\n * The result is an object with the following properties:\n *\n * - `wallMs`: Wall execution time.\n * - `kernelMs`: Kernel execution time, ignoring data transfer. If using the\n * WebGL backend and the query timer extension is not available, this will\n * return an error object.\n * - On `WebGL` The following additional properties exist:\n * - `uploadWaitMs`: CPU blocking time on texture uploads.\n * - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).\n *\n * ```js\n * const x = tf.randomNormal([20, 20]);\n * const time = await tf.time(() => x.matMul(x));\n *\n * console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);\n * ```\n *\n * @param f The function to execute and time.\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nexport function time(f: () => void): Promise<TimingInfo> {\n return ENGINE.time(f);\n}\n\n/**\n * Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and\n * executing operations on those tensors. Returns a promise that resolves\n * to a boolean if the backend initialization was successful.\n *\n * Note this disposes the current backend, if any, as well as any tensors\n * associated with it. A new backend is initialized, even if it is of the\n * same type as the previous one.\n *\n * @param backendName The name of the backend. Currently supports\n * `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js\n * (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).\n *\n * @doc {heading: 'Backends'}\n */\nexport function setBackend(backendName: string): Promise<boolean> {\n return ENGINE.setBackend(backendName);\n}\n\n/**\n * Returns a promise that resolves when the currently selected backend (or the\n * highest priority one) has initialized. Await this promise when you are using\n * a backend that has async initialization.\n *\n * @doc {heading: 'Backends'}\n */\nexport function ready(): Promise<void> {\n return ENGINE.ready();\n}\n\n/**\n * Returns the current backend name (cpu, webgl, etc). The backend is\n * responsible for creating tensors and executing operations on those tensors.\n *\n * @doc {heading: 'Backends'}\n */\nexport function getBackend(): string {\n return ENGINE.backendName;\n}\n\n/**\n * Removes a backend and the registered factory.\n *\n * @doc {heading: 'Backends'}\n */\nexport function removeBackend(name: string): void {\n ENGINE.removeBackend(name);\n}\n\n/**\n * Finds the backend registered under the provided name. Returns null if the\n * name is not in the registry, or the registration hasn't finished yet.\n */\nexport function findBackend(name: string): KernelBackend {\n return ENGINE.findBackend(name);\n}\n\n/**\n * Finds the backend factory registered under the provided name. Returns a\n * function that produces a new backend when called. Returns null if the name\n * is not in the registry.\n */\nexport function findBackendFactory(name: string): () =>\n KernelBackend | Promise<KernelBackend> {\n return ENGINE.findBackendFactory(name);\n}\n\n/**\n * Registers a global backend. The registration should happen when importing\n * a module file (e.g. when importing `backend_webgl.ts`), and is used for\n * modular builds (e.g. custom tfjs bundle with only webgl support).\n *\n * @param factory The backend factory function. When called, it should\n * return a backend instance, or a promise of an instance.\n * @param priority The priority of the backend (higher = more important).\n * In case multiple backends are registered, the priority is used to find\n * the best backend. Defaults to 1.\n * @return False if there is already a registered backend under this name, true\n * if not.\n *\n * @doc {heading: 'Backends'}\n */\nexport function registerBackend(\n name: string, factory: () => KernelBackend | Promise<KernelBackend>,\n priority = 1): boolean {\n return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n env().setPlatform(platformName, platform);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Add, AddInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print(); // or tf.add(a, b)\n * ```\n *\n * ```js\n * // Broadcast add a with b.\n * const a = tf.scalar(5);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print(); // or tf.add(a, b)\n * ```\n * @param a The first `tf.Tensor` to add.\n * @param b The second `tf.Tensor` to add. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction add_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'add');\n let $b = convertToTensor(b, 'b', 'add');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: AddInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n\nexport const add = /* @__PURE__ */ op({add_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FloorDiv, FloorDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n * The result is rounded with floor function.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.floorDiv(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.floorDiv(b).print(); // or tf.floorDiv(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction floorDiv_<T extends Tensor>(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'floorDiv');\n let $b = convertToTensor(b, 'b', 'floorDiv');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: FloorDivInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(FloorDiv, inputs as unknown as NamedTensorMap);\n}\n\nexport const floorDiv = /* @__PURE__ */ op({floorDiv_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RealDiv, RealDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {floorDiv} from './floorDiv';\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction div_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'div');\n let $b = convertToTensor(b, 'b', 'div');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'int32' && $b.dtype === 'int32') {\n return floorDiv($a, $b);\n }\n\n const inputs: RealDivInputs = {a: $a, b: $b};\n const attrs = {};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(RealDiv,\n inputs as unknown as NamedTensorMap, attrs) as T;\n}\n\nexport const div = /* @__PURE__ */ op({div_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multiply, MultiplyInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.\n *\n * We also expose `tf.mulStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([2, 3, 4, 5]);\n *\n * a.mul(b).print(); // or tf.mul(a, b)\n * ```\n *\n * ```js\n * // Broadcast mul a with b.\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.scalar(5);\n *\n * a.mul(b).print(); // or tf.mul(a, b)\n * ```\n * @param a The first tensor to multiply.\n * @param b The second tensor to multiply. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mul_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'mul');\n let $b = convertToTensor(b, 'b', 'mul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: MultiplyInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Multiply, inputs as unknown as NamedTensorMap);\n}\nexport const mul = /* @__PURE__ */ op({mul_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Abs, AbsInputs, ComplexAbs, ComplexAbsInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes absolute value element-wise: `abs(x)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.abs().print(); // or tf.abs(x)\n * ```\n * @param x The input `tf.Tensor`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction abs_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'abs');\n\n if ($x.dtype === 'complex64') {\n const inputs: ComplexAbsInputs = {x: $x};\n return ENGINE.runKernel(ComplexAbs, inputs as unknown as NamedTensorMap);\n } else {\n const inputs: AbsInputs = {x: $x};\n return ENGINE.runKernel(Abs, inputs as unknown as NamedTensorMap);\n }\n}\n\nexport const abs = /* @__PURE__ */ op({abs_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Fill, FillAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {inferDtype} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\n/**\n * Creates a `tf.Tensor` filled with a scalar value.\n *\n * ```js\n * tf.fill([2, 2], 4).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param value The scalar value to fill the tensor with.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n * 'float32' if the given param value is a number, otherwise 'string'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction fill<R extends Rank>(\n shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor<R> {\n assertNonNegativeIntegerDimensions(shape);\n\n dtype = dtype || inferDtype(value);\n const attrs: FillAttrs = {shape, value, dtype};\n\n return ENGINE.runKernel(Fill, {}, attrs as unknown as NamedAttrMap);\n}\n\nexport {fill};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(\n inShape: number[], outShape: number[]): number[] {\n const inRank = inShape.length;\n const dims: number[] = [];\n for (let i = 0; i < inRank; i++) {\n const dim = inRank - 1 - i;\n const a = inShape[dim] || 1;\n const b = outShape[outShape.length - 1 - i] || 1;\n if (b > 1 && a === 1) {\n dims.unshift(dim);\n }\n }\n return dims;\n}\n\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(\n inShape: number[], outShape: number[]): number[] {\n const result: number[] = [];\n for (let i = 0; i < outShape.length; i++) {\n const inDim = inShape[inShape.length - i - 1];\n const outAxis = outShape.length - i - 1;\n const outDim = outShape[outAxis];\n if (inDim == null || (inDim === 1 && outDim > 1)) {\n result.unshift(outAxis);\n }\n }\n return result;\n}\n\nexport function assertAndGetBroadcastShape(\n shapeA: number[], shapeB: number[]): number[] {\n const l = Math.max(shapeA.length, shapeB.length);\n const result = new Array(l);\n\n for (let i = 0; i < l; i++) {\n let a = shapeA[shapeA.length - i - 1];\n if (a == null) {\n a = 1;\n }\n let b = shapeB[shapeB.length - i - 1];\n if (b == null) {\n b = 1;\n }\n if (a === 1) {\n result[l - i - 1] = b;\n } else if (b === 1) {\n result[l - i - 1] = a;\n } else if (a !== b) {\n const errMsg = `Operands could not be broadcast together with shapes ` +\n `${shapeA} and ${shapeB}.`;\n throw Error(errMsg);\n } else {\n result[l - i - 1] = a;\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ZerosLike, ZerosLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.zerosLike(x).print();\n * ```\n *\n * @param x The tensor of required shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction zerosLike_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'zerosLike');\n const inputs: ZerosLikeInputs = {x: $x};\n return ENGINE.runKernel(ZerosLike, inputs as unknown as NamedTensorMap);\n}\nexport const zerosLike = /* @__PURE__ */ op({zerosLike_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Pow, PowInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the power of one `tf.Tensor` to another. Supports broadcasting.\n *\n * Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for\n * corresponding elements in x and y. The result's dtype will be the upcasted\n * type of the `base` and `exp` dtypes.\n *\n * ```js\n * const a = tf.tensor([[2, 3], [4, 5]])\n * const b = tf.tensor([[1, 2], [3, 0]]).toInt();\n *\n * a.pow(b).print(); // or tf.pow(a, b)\n * ```\n *\n * ```js\n * const a = tf.tensor([[1, 2], [3, 4]])\n * const b = tf.tensor(2).toInt();\n *\n * a.pow(b).print(); // or tf.pow(a, b)\n * ```\n * We also expose `powStrict` which has the same signature as this op and\n * asserts that `base` and `exp` are the same shape (does not broadcast).\n *\n * @param base The base `tf.Tensor` to pow element-wise.\n * @param exp The exponent `tf.Tensor` to pow element-wise.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction pow_<T extends Tensor>(\n base: Tensor|TensorLike, exp: Tensor|TensorLike): T {\n let $base = convertToTensor(base, 'base', 'pow');\n let $exp = convertToTensor(exp, 'exp', 'pow');\n [$base, $exp] = makeTypesMatch($base, $exp);\n\n const inputs: PowInputs = {a: $base, b: $exp};\n\n return ENGINE.runKernel(Pow, inputs as unknown as NamedTensorMap);\n}\n\nexport const pow = /* @__PURE__ */ op({pow_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar} from '../tensor';\nimport {DataType} from '../types';\nimport {isTypedArray} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.scalar` as it makes the code more readable.\n *\n * ```js\n * tf.scalar(3.14).print();\n * ```\n *\n * @param value The value of the scalar.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function scalar(\n value: number|boolean|string|Uint8Array, dtype?: DataType): Scalar {\n if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&\n dtype !== 'complex64') {\n throw new Error(\n 'Error creating a new Scalar: value must be a primitive ' +\n '(number|boolean|string)');\n }\n if (dtype === 'string' && isTypedArray(value) &&\n !(value instanceof Uint8Array)) {\n throw new Error(\n 'When making a scalar from encoded string, ' +\n 'the value must be `Uint8Array`.');\n }\n const shape: number[] = [];\n const inferredShape: number[] = [];\n return makeTensor(value, shape, inferredShape, dtype) as Scalar;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sqrt, SqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.sqrt().print(); // or tf.sqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sqrt_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sqrt', 'float32');\n\n const inputs: SqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Sqrt, inputs as unknown as NamedTensorMap);\n}\nexport const sqrt = /* @__PURE__ */ op({sqrt_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Computes square of `x` element-wise: `x ^ 2`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);\n *\n * x.square().print(); // or tf.square(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction square_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'square');\n const attrs = {};\n return ENGINE.runKernel('Square', {x: $x}, attrs);\n}\n\nexport const square = /* @__PURE__ */ op({square_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CustomGradientFunc, ENGINE} from './engine';\nimport {Scalar, Tensor, Variable} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {convertToTensor, convertToTensorArray} from './tensor_util_env';\nimport {TensorLike} from './types';\nimport * as util from './util';\n\n/**\n * Provided `f(x)`, returns another function `g(x, dy?)`, which gives the\n * gradient of `f(x)` with respect to `x`.\n *\n * If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to\n * `x` is computed instead. `f(x)` must take a single tensor `x` and return a\n * single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.grad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * g(x).print();\n * ```\n *\n * ```js\n * // f(x) = x ^ 3\n * const f = x => x.pow(tf.scalar(3, 'int32'));\n * // f'(x) = 3x ^ 2\n * const g = tf.grad(f);\n * // f''(x) = 6x\n * const gg = tf.grad(g);\n *\n * const x = tf.tensor1d([2, 3]);\n * gg(x).print();\n * ```\n *\n * @param f The function f(x), to compute gradient for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grad(f: (x: Tensor) => Tensor): (\n x: TensorLike|Tensor, dy?: TensorLike|Tensor) => Tensor {\n util.assert(\n util.isFunction(f), () => 'The f passed in grad(f) must be a function');\n return (x: TensorLike|Tensor, dy?: TensorLike|Tensor): Tensor => {\n // x can be of any dtype, thus null as the last argument.\n const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');\n const $dy: Tensor =\n (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;\n return ENGINE.tidy(() => {\n const {value, grads} = ENGINE.gradients(() => f($x), [$x], $dy);\n if ($dy != null) {\n util.assertShapesMatch(\n value.shape, $dy.shape,\n 'The shape of dy passed in grad(f)(x, dy) must match the shape ' +\n 'returned by f(x)');\n }\n checkGrads(grads);\n return grads[0];\n });\n };\n}\n\n/**\n * Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,\n * which gives an array of gradients of `f()` with respect to each input\n * [`x1`,`x2`,...].\n *\n * If `dy` is passed when calling `g()`, the gradient of\n * `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.\n * The provided `f` must take one or more tensors and return a single tensor\n * `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df / da = b, df / db = a\n * const g = tf.grads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const [da, db] = g([a, b]);\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @param f The function `f(x1, x2,...)` to compute gradients for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grads(f: (...args: Tensor[]) => Tensor): (\n args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike) => Tensor[] {\n util.assert(\n util.isFunction(f), () => 'The f passed in grads(f) must be a function');\n return (args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike): Tensor[] => {\n util.assert(\n Array.isArray(args),\n () => 'The args passed in grads(f)(args) must be an array ' +\n 'of `Tensor`s or `TensorLike`s');\n // args can be of any dtype, thus null as the last argument.\n const $args =\n convertToTensorArray(args, 'args', 'tf.grads', 'string_or_numeric');\n const $dy: Tensor =\n (dy != null) ? convertToTensor(dy, 'dy', 'tf.grads') : null;\n return ENGINE.tidy(() => {\n const {value, grads} = ENGINE.gradients(() => f(...$args), $args, $dy);\n if ($dy != null) {\n util.assertShapesMatch(\n value.shape, $dy.shape,\n 'The shape of dy passed in grads(f)([x1,...], dy) must ' +\n 'match the shape returned by f([x1,...])');\n }\n checkGrads(grads);\n return grads;\n });\n };\n}\n\n/**\n * Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grad: The gradient of `f(x)` w.r.t. `x` (result of `tf.grad`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.valueAndGrad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * const {value, grad} = g(x);\n *\n * console.log('value');\n * value.print();\n * console.log('grad');\n * grad.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrad<I extends Tensor, O extends Tensor>(f: (x: I) => O): (\n x: I, dy?: O) => {\n value: O;\n grad: I;\n} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in valueAndGrad(f) must be a function');\n return (x: I, dy?: O) => {\n util.assert(\n x instanceof Tensor,\n () => 'The x passed in valueAndGrad(f)(x) must be a tensor');\n util.assert(\n dy == null || dy instanceof Tensor,\n () => 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');\n const {grads, value} = ENGINE.gradients(() => f(x), [x], dy);\n checkGrads(grads);\n return {grad: grads[0] as I, value};\n };\n}\n\n/**\n * Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grads: The gradients of `f()` w.r.t. each input (result of `tf.grads`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df/da = b, df/db = a\n * const g = tf.valueAndGrads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const {value, grads} = g([a, b]);\n *\n * const [da, db] = grads;\n *\n * console.log('value');\n * value.print();\n *\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrads<O extends Tensor>(f: (...args: Tensor[]) => O): (\n args: Tensor[], dy?: O) => {\n grads: Tensor[];\n value: O;\n} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in valueAndGrads(f) must be a function');\n return (args: Tensor[], dy?: O) => {\n util.assert(\n Array.isArray(args) && args.every(arg => arg instanceof Tensor),\n () => 'The args passed in valueAndGrads(f)(args) must be array of ' +\n 'tensors');\n util.assert(\n dy == null || dy instanceof Tensor,\n () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');\n const res = ENGINE.gradients(() => f(...args), args, dy);\n if (dy != null) {\n util.assertShapesMatch(\n res.value.shape, dy.shape,\n 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +\n 'match the shape returned by f([x1,...])');\n }\n checkGrads(res.grads);\n return res;\n };\n}\n\n/**\n * Computes and returns the gradient of f(x) with respect to the list of\n * trainable variables provided by `varList`. If no list is provided, it\n * defaults to all trainable variables.\n *\n * ```js\n * const a = tf.variable(tf.tensor1d([3, 4]));\n * const b = tf.variable(tf.tensor1d([5, 6]));\n * const x = tf.tensor1d([1, 2]);\n *\n * // f(a, b) = a * x ^ 2 + b * x\n * const f = () => a.mul(x.square()).add(b.mul(x)).sum();\n * // df/da = x ^ 2, df/db = x\n * const {value, grads} = tf.variableGrads(f);\n *\n * Object.keys(grads).forEach(varName => grads[varName].print());\n * ```\n *\n * @param f The function to execute. f() should return a scalar.\n * @param varList The list of variables to compute the gradients with respect\n * to. Defaults to all trainable variables.\n * @returns An object with the following keys and values:\n * - `value`: The value of the function `f`.\n * - `grads`: A map from the names of the variables to the gradients.\n * If the `varList` argument is provided explicitly and contains a subset of\n * non-trainable variables, this map in the return value will contain keys\n * that map the names of the non-trainable variables to `null`.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction variableGrads(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in variableGrads(f) must be a function');\n util.assert(\n varList == null ||\n Array.isArray(varList) && varList.every(v => v instanceof Variable),\n () =>\n 'The varList passed in variableGrads(f, varList) must be an array ' +\n 'of variables');\n\n const specifiedVarList = varList != null;\n if (!specifiedVarList) {\n // Get all of the trainable variables.\n varList = [];\n for (const varName in ENGINE.registeredVariables) {\n varList.push(ENGINE.registeredVariables[varName]);\n }\n }\n\n const specifiedNonTrainable: Variable[] =\n specifiedVarList ? varList.filter(variable => !variable.trainable) : null;\n\n // Prune non-trainable variables.\n const originalVarCount = varList.length;\n varList = varList.filter(variable => variable.trainable);\n util.assert(\n varList.length > 0,\n () => `variableGrads() expects at least one of the input variables to ` +\n `be trainable, but none of the ${originalVarCount} variables is ` +\n `trainable.`);\n\n const allowNoGradients = true;\n const {value, grads} = ENGINE.gradients(f, varList, null, allowNoGradients);\n\n util.assert(\n grads.some(g => g != null),\n () => 'Cannot find a connection between any variable and the result of ' +\n 'the loss function y=f(x). Please make sure the operations that ' +\n 'use variables are inside the function f passed to minimize().');\n util.assert(\n value.rank === 0,\n () => `The f passed in variableGrads(f) must return a scalar, but it ` +\n `returned a rank-${value.rank} tensor`);\n\n const namedGrads: NamedTensorMap = {};\n varList.forEach((v, i) => {\n if (grads[i] != null) {\n namedGrads[v.name] = grads[i];\n }\n });\n if (specifiedNonTrainable != null) {\n // If varList is explicitly provided and contains non-trainable values,\n // add them to the returned gradients with `null` values.\n specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);\n }\n return {value, grads: namedGrads};\n}\n\n/**\n * Overrides the gradient computation of a function `f`.\n *\n * Takes a function\n * `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`\n * and returns another function `g(...inputs)` which takes the same inputs as\n * `f`. When called, `g` returns `f().value`. In backward mode, custom gradients\n * with respect to each input of `f` are computed using `f().gradFunc`.\n *\n * The `save` function passed to `f` should be used for saving tensors needed\n * in the gradient. And the `saved` passed to the `gradFunc` is a\n * `NamedTensorMap`, which contains those saved tensors.\n *\n * ```js\n * const customOp = tf.customGrad((x, save) => {\n * // Save x to make sure it's available later for the gradient.\n * save([x]);\n * // Override gradient of our custom x ^ 2 op to be dy * abs(x);\n * return {\n * value: x.square(),\n * // Note `saved.x` which points to the `x` we saved earlier.\n * gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]\n * };\n * });\n *\n * const x = tf.tensor1d([-1, -2, 3]);\n * const dx = tf.grad(x => customOp(x));\n *\n * console.log(`f(x):`);\n * customOp(x).print();\n * console.log(`f'(x):`);\n * dx(x).print();\n * ```\n *\n * @param f The function to evaluate in forward mode, which should return\n * `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`\n * returns the custom gradients of `f` with respect to its inputs.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n (...args: Tensor[]) => T {\n return ENGINE.customGrad(f);\n}\n\nfunction checkGrads(grads: Tensor[]) {\n const numNullGradients = grads.filter(g => g == null).length;\n if (numNullGradients > 0) {\n throw new Error(\n `Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.`);\n }\n}\n\nexport {\n customGrad,\n variableGrads,\n valueAndGrad,\n valueAndGrads,\n grad,\n grads,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Sub, SubInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.sub(b).print(); // or tf.sub(a, b)\n * ```\n *\n * ```js\n * // Broadcast subtract a with b.\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.scalar(5);\n *\n * a.sub(b).print(); // or tf.sub(a, b)\n * ```\n * @param a The first `tf.Tensor` to subtract from.\n * @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction sub_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'sub');\n let $b = convertToTensor(b, 'b', 'sub');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: SubInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Sub, inputs as unknown as NamedTensorMap);\n}\n\nexport const sub = /* @__PURE__ */ op({sub_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Maximum, MaximumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the max of a and b (`a > b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `tf.maximumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.maximum(b).print(); // or tf.maximum(a, b)\n * ```\n *\n * ```js\n * // Broadcast maximum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.maximum(b).print(); // or tf.maximum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction maximum_<T extends Tensor>(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'maximum');\n let $b = convertToTensor(b, 'b', 'maximum');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'bool') {\n $a = cast($a, 'int32');\n $b = cast($b, 'int32');\n }\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: MaximumInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Maximum, inputs as unknown as NamedTensorMap);\n}\n\nexport const maximum = /* @__PURE__ */ op({maximum_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from './util';\n\n/**\n * Types to support JSON-esque data structures internally.\n *\n * Internally ConfigDict's use camelCase keys and values where the\n * values are class names to be instantiated. On the python side, these\n * will be snake_case. Internally we allow Enums into the values for better\n * type safety, but these need to be converted to raw primitives (usually\n * strings) for round-tripping with python.\n *\n * toConfig returns the TS-friendly representation. model.toJSON() returns\n * the pythonic version as that's the portable format. If you need to\n * python-ify a non-model level toConfig output, you'll need to use a\n * convertTsToPythonic from serialization_utils in -Layers.\n *\n */\nexport declare type ConfigDictValue =\n boolean | number | string | null | ConfigDictArray | ConfigDict;\nexport declare interface ConfigDict {\n [key: string]: ConfigDictValue;\n}\nexport declare interface ConfigDictArray extends Array<ConfigDictValue> {}\n\n/**\n * Type to represent the class-type of Serializable objects.\n *\n * Ie the class prototype with access to the constructor and any\n * static members/methods. Instance methods are not listed here.\n *\n * Source for this idea: https://stackoverflow.com/a/43607255\n */\nexport declare type SerializableConstructor<T extends Serializable> = {\n // tslint:disable-next-line:no-any\n new (...args: any[]): T; className: string; fromConfig: FromConfigMethod<T>;\n};\nexport declare type FromConfigMethod<T extends Serializable> =\n (cls: SerializableConstructor<T>, config: ConfigDict) => T;\n\n/**\n * Serializable defines the serialization contract.\n *\n * TFJS requires serializable classes to return their className when asked\n * to avoid issues with minification.\n */\nexport abstract class Serializable {\n /**\n * Return the class name for this class to use in serialization contexts.\n *\n * Generally speaking this will be the same thing that constructor.name\n * would have returned. However, the class name needs to be robust\n * against minification for serialization/deserialization to work properly.\n *\n * There's also places such as initializers.VarianceScaling, where\n * implementation details between different languages led to different\n * class hierarchies and a non-leaf node is used for serialization purposes.\n */\n getClassName(): string {\n return (this.constructor as SerializableConstructor<Serializable>)\n .className;\n }\n\n /**\n * Return all the non-weight state needed to serialize this object.\n */\n abstract getConfig(): ConfigDict;\n\n /**\n * Creates an instance of T from a ConfigDict.\n *\n * This works for most descendants of serializable. A few need to\n * provide special handling.\n * @param cls A Constructor for the class to instantiate.\n * @param config The Configuration for the object.\n */\n /** @nocollapse */\n static fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config);\n }\n}\n\n/**\n * Maps string keys to class constructors.\n *\n * Used during (de)serialization from the cross-language JSON format, which\n * requires the class name in the serialization format matches the class\n * names as used in Python, should it exist.\n */\nexport class SerializationMap {\n private static instance: SerializationMap;\n classNameMap: {\n [className: string]:\n [SerializableConstructor<Serializable>, FromConfigMethod<Serializable>]\n };\n\n private constructor() {\n this.classNameMap = {};\n }\n\n /**\n * Returns the singleton instance of the map.\n */\n static getMap(): SerializationMap {\n if (SerializationMap.instance == null) {\n SerializationMap.instance = new SerializationMap();\n }\n return SerializationMap.instance;\n }\n\n /**\n * Registers the class as serializable.\n */\n static register<T extends Serializable>(cls: SerializableConstructor<T>) {\n SerializationMap.getMap().classNameMap[cls.className] =\n [cls, cls.fromConfig];\n }\n}\n\n/**\n * Register a class with the serialization map of TensorFlow.js.\n *\n * This is often used for registering custom Layers, so they can be\n * serialized and deserialized.\n *\n * Example:\n *\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n * static className = 'MyCustomLayer';\n *\n * constructor(config) {\n * super(config);\n * }\n * }\n * tf.serialization.registerClass(MyCustomLayer);\n * ```\n *\n * @param cls The class to be registered. It must have a public static member\n * called `className` defined and the value must be a non-empty string.\n *\n * @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true}\n */\nexport function registerClass<T extends Serializable>(\n cls: SerializableConstructor<T>) {\n assert(\n cls.className != null,\n () => `Class being registered does not have the static className ` +\n `property defined.`);\n assert(\n typeof cls.className === 'string',\n () => `className is required to be a string, but got type ` +\n typeof cls.className);\n assert(\n cls.className.length > 0,\n () => `Class being registered has an empty-string as its className, ` +\n `which is disallowed.`);\n\n SerializationMap.register(cls);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {dispose} from '../globals';\nimport {variableGrads} from '../gradients';\nimport {scalar} from '../ops/ops';\nimport {Serializable} from '../serialization';\nimport {Scalar, Variable} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\n/**\n * A variable that belongs to an optimizer.\n *\n * The `originalName` field is required for keeping track of the canonical\n * name of the variable, which is usually the name of the model weight that\n * the variable is related to plus a suffix, e.g., 'dense1/kernel/momentum'.\n * The name of the `Variable` object itself cannot be used directly due to\n * possible deduplication: Every `Variable` must have a unique name but more\n * than one optimizer objects of the same type may be created for the same model\n * or the same `Variable`.\n */\nexport interface OptimizerVariable {\n originalName: string;\n variable: Variable;\n}\n\n/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */\nexport abstract class Optimizer extends Serializable {\n protected iterations_: number;\n\n /**\n * Executes `f()` and minimizes the scalar output of `f()` by computing\n * gradients of y with respect to the list of trainable variables provided by\n * `varList`. If no list is provided, it defaults to all trainable variables.\n *\n * @param f The function to execute and whose output to minimize.\n * @param returnCost Whether to return the scalar cost value produced by\n * executing `f()`.\n * @param varList An optional list of variables to update. If specified, only\n * the trainable variables in varList will be updated by minimize. Defaults to\n * all trainable variables.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n minimize(f: () => Scalar, returnCost = false, varList?: Variable[]): Scalar\n |null {\n const {value, grads} = this.computeGradients(f, varList);\n\n if (varList != null) {\n const gradArray: NamedTensor[] =\n varList.map(v => ({name: v.name, tensor: grads[v.name]}));\n this.applyGradients(gradArray);\n } else {\n this.applyGradients(grads);\n }\n\n // Dispose gradients.\n dispose(grads);\n\n if (returnCost) {\n return value;\n } else {\n value.dispose();\n return null;\n }\n }\n\n /**\n * The number of iterations that this optimizer instance has been invoked for.\n */\n get iterations(): number {\n if (this.iterations_ == null) {\n this.iterations_ = 0;\n }\n return this.iterations_;\n }\n\n protected incrementIterations() {\n this.iterations_ = this.iterations + 1;\n }\n\n /**\n * Executes f() and computes the gradient of the scalar output of f() with\n * respect to the list of trainable variables provided by `varList`. If no\n * list is provided, it defaults to all trainable variables.\n *\n * @param f The function to execute and whose output to use for computing\n * gradients with respect to variables.\n * @param varList An optional list of variables to compute gradients with\n * respect to. If specified, only the trainable variables in varList will have\n * gradients computed with respect to. Defaults to all trainable variables.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n computeGradients(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n return variableGrads(f, varList);\n }\n\n /**\n * Updates variables by using the computed gradients.\n *\n * @param variableGradients A mapping of variable name to its gradient value.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n abstract applyGradients(variableGradients: NamedTensorMap|\n NamedTensor[]): void;\n\n /**\n * Dispose the variables (if any) owned by this optimizer instance.\n */\n dispose(): void {\n if (this.iterations_ != null) {\n dispose(this.iterations_);\n }\n }\n\n async saveIterations(): Promise<NamedTensor> {\n if (this.iterations_ == null) {\n this.iterations_ = 0;\n }\n return {\n name: 'iter', // Named for Python compatibility.\n // TODO(cais): Use 'int64' type when available.\n tensor: scalar(this.iterations_, 'int32')\n };\n }\n\n async getWeights(): Promise<NamedTensor[]> {\n throw new Error('getWeights() is not implemented for this optimizer yet.');\n }\n\n async setWeights(weightValues: NamedTensor[]): Promise<void> {\n throw new Error(\n `setWeights() is not implemented for this optimizer class ` +\n `${this.getClassName()}`);\n }\n\n /**\n * Extract the first element of the weight values and set it\n * as the iterations counter variable of this instance of optimizer.\n *\n * @param weightValues\n * @returns Weight values with the first element consumed and excluded.\n */\n protected async extractIterations(weightValues: NamedTensor[]):\n Promise<NamedTensor[]> {\n this.iterations_ = (await weightValues[0].tensor.data())[0];\n return weightValues.slice(1);\n }\n}\n\nObject.defineProperty(Optimizer, Symbol.hasInstance, {\n value: (instance: Optimizer) => {\n return instance.minimize != null && instance.computeGradients != null &&\n instance.applyGradients != null;\n }\n});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/ops';\nimport {square} from '../ops/square';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdadeltaOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adadelta';\n }\n private accumulatedGrads: OptimizerVariable[] = [];\n private accumulatedUpdates: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected rho: number,\n protected epsilon: number = null) {\n super();\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedGrads[i] == null) {\n this.accumulatedGrads[i] = {\n originalName: `${name}/accum_grad`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedUpdates[i] == null) {\n this.accumulatedUpdates[i] = {\n originalName: `${name}/accum_var`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedGrad = this.accumulatedGrads[i].variable;\n const accumulatedUpdate = this.accumulatedUpdates[i].variable;\n\n tidy(() => {\n const newAccumulatedGrad =\n add(mul(accumulatedGrad, this.rho),\n mul(square(gradient), 1 - this.rho));\n\n const updates =\n mul(div(sqrt(add(accumulatedUpdate, this.epsilon)),\n sqrt(add(accumulatedGrad, this.epsilon))),\n gradient);\n\n const newAccumulatedUpdate =\n add(mul(accumulatedUpdate, this.rho),\n mul(square(updates), 1 - this.rho));\n\n accumulatedGrad.assign(newAccumulatedGrad);\n accumulatedUpdate.assign(newAccumulatedUpdate);\n\n const newValue = add(mul(updates, -this.learningRate), value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedUpdates != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n dispose(this.accumulatedUpdates.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedGrads, ...this.accumulatedUpdates];\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const variableCount = weightValues.length / 2;\n const trainable = false;\n this.accumulatedGrads =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedUpdates =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'rho': this.rho,\n 'epsilon': this.epsilon\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate'], config['rho'], config['epsilon']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {fill} from '../ops/fill';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdagradOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adagrad';\n }\n\n private accumulatedGrads: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, private initialAccumulatorValue = 0.1) {\n super();\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n if (this.accumulatedGrads[i] == null) {\n const trainable = false;\n this.accumulatedGrads[i] = {\n originalName: `${name}/accumulator`,\n variable: tidy(\n () => fill(value.shape, this.initialAccumulatorValue)\n .variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedGrad = this.accumulatedGrads[i].variable;\n\n tidy(() => {\n const newAccumulatedGrad = add(accumulatedGrad, square(gradient));\n accumulatedGrad.assign(newAccumulatedGrad);\n\n const newValue = add(\n mul(div(gradient,\n sqrt(add(newAccumulatedGrad, ENGINE.backend.epsilon()))),\n -this.learningRate),\n value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedGrads != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n return [await this.saveIterations()].concat(this.accumulatedGrads.map(\n v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const trainable = false;\n this.accumulatedGrads = weightValues.map(\n v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'initialAccumulatorValue': this.initialAccumulatorValue,\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate'], config['initialAccumulatorValue']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {pow} from '../ops/pow';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adam';\n }\n private accBeta1: Variable;\n private accBeta2: Variable;\n\n private accumulatedFirstMoment: OptimizerVariable[] = [];\n private accumulatedSecondMoment: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected beta1: number,\n protected beta2: number, protected epsilon: number = null) {\n super();\n tidy(() => {\n // accB* will be updated by batch.\n this.accBeta1 = scalar(beta1).variable();\n this.accBeta2 = scalar(beta2).variable();\n });\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const varNames = Array.isArray(variableGradients) ?\n variableGradients.map(v => v.name) :\n Object.keys(variableGradients);\n tidy(() => {\n const oneMinusAccBeta1 = sub(1, this.accBeta1);\n const oneMinusAccBeta2 = sub(1, this.accBeta2);\n\n varNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedFirstMoment[i] == null) {\n this.accumulatedFirstMoment[i] = {\n originalName: `${name}/m`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedSecondMoment[i] == null) {\n this.accumulatedSecondMoment[i] = {\n originalName: `${name}/v`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const firstMoment = this.accumulatedFirstMoment[i].variable;\n const secondMoment = this.accumulatedSecondMoment[i].variable;\n\n const newFirstMoment =\n add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n const newSecondMoment =\n add(mul(secondMoment, this.beta2),\n mul(square(gradient), 1 - this.beta2));\n\n const biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);\n const biasCorrectedSecondMoment =\n div(newSecondMoment, oneMinusAccBeta2);\n\n firstMoment.assign(newFirstMoment);\n secondMoment.assign(newSecondMoment);\n\n const newValue =\n add(mul(div(biasCorrectedFirstMoment,\n add(sqrt(biasCorrectedSecondMoment), this.epsilon)),\n -this.learningRate),\n value);\n value.assign(newValue);\n });\n\n this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n this.accBeta2.assign(mul(this.accBeta2, this.beta2));\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.accBeta1.dispose();\n this.accBeta2.dispose();\n\n if (this.accumulatedFirstMoment != null) {\n dispose(this.accumulatedFirstMoment.map(v => v.variable));\n }\n if (this.accumulatedSecondMoment != null) {\n dispose(this.accumulatedSecondMoment.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n tidy(() => {\n this.accBeta1.assign(pow(this.beta1, this.iterations_ + 1));\n this.accBeta2.assign(pow(this.beta2, this.iterations_ + 1));\n });\n\n const variableCount = weightValues.length / 2;\n const trainable = false;\n this.accumulatedFirstMoment =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedSecondMoment =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'beta1': this.beta1,\n 'beta2': this.beta2,\n 'epsilon': this.epsilon,\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['beta1'], config['beta2'],\n config['epsilon']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {abs} from '../ops/abs';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {maximum} from '../ops/maximum';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamaxOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adamax';\n }\n private accBeta1: Variable;\n private iteration: Variable;\n\n private accumulatedFirstMoment: OptimizerVariable[] = [];\n private accumulatedWeightedInfNorm: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected beta1: number,\n protected beta2: number, protected epsilon: number = null,\n protected decay = 0.0) {\n super();\n\n tidy(() => {\n this.iteration = scalar(0).variable();\n this.accBeta1 = scalar(beta1).variable();\n });\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n tidy(() => {\n const oneMinusAccBeta1 = sub(1, this.accBeta1);\n const lr =\n div(-this.learningRate, add(mul(this.iteration, this.decay), 1));\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedFirstMoment[i] == null) {\n this.accumulatedFirstMoment[i] = {\n originalName: `${name}/m`,\n variable: zerosLike(value).variable(trainable)\n };\n }\n if (this.accumulatedWeightedInfNorm[i] == null) {\n this.accumulatedWeightedInfNorm[i] = {\n originalName: `${name}/v`,\n variable: zerosLike(value).variable(trainable)\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const firstMoment = this.accumulatedFirstMoment[i].variable;\n const weightedInfNorm = this.accumulatedWeightedInfNorm[i].variable;\n\n const newFirstMoment =\n add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n\n const ut0 = mul(weightedInfNorm, this.beta2);\n const ut1 = abs(gradient);\n\n const newWeightedInfNorm = maximum(ut0, ut1);\n\n firstMoment.assign(newFirstMoment);\n weightedInfNorm.assign(newWeightedInfNorm);\n\n const newValue =\n add(mul(div(lr, oneMinusAccBeta1),\n div(newFirstMoment, add(newWeightedInfNorm, this.epsilon))),\n value);\n\n value.assign(newValue);\n });\n\n this.iteration.assign(add(this.iteration, 1));\n this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.accBeta1.dispose();\n this.iteration.dispose();\n\n if (this.accumulatedFirstMoment != null) {\n dispose(this.accumulatedFirstMoment.map(v => v.variable));\n }\n if (this.accumulatedWeightedInfNorm != null) {\n dispose(this.accumulatedWeightedInfNorm.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n throw new Error('getWeights() is not implemented for Adamax yet.');\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n throw new Error('setWeights() is not implemented for Adamax yet.');\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'beta1': this.beta1,\n 'beta2': this.beta2,\n 'epsilon': this.epsilon,\n 'decay': this.decay\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['beta1'], config['beta2'],\n config['epsilon'], config['decay']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {keep, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer} from './optimizer';\n\n/** @doclink Optimizer */\nexport class SGDOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'SGD';\n }\n protected c: Scalar;\n\n constructor(protected learningRate: number) {\n super();\n this.setLearningRate(learningRate);\n }\n\n applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n const varNames = Array.isArray(variableGradients) ?\n variableGradients.map(v => v.name) :\n Object.keys(variableGradients);\n varNames.forEach((name, i) => {\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n const value = ENGINE.registeredVariables[name];\n tidy(() => {\n const newValue = add(mul(this.c, gradient), value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n /**\n * Sets the learning rate of the optimizer.\n */\n setLearningRate(learningRate: number) {\n this.learningRate = learningRate;\n if (this.c != null) {\n this.c.dispose();\n }\n this.c = keep(scalar(-learningRate));\n }\n\n override dispose() {\n this.c.dispose();\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n return [await this.saveIterations()];\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n if (weightValues.length !== 0) {\n throw new Error('SGD optimizer does not have settable weights.');\n }\n }\n\n getConfig(): ConfigDict {\n return {'learningRate': this.learningRate};\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {OptimizerVariable} from './optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\n\n/** @doclink Optimizer */\nexport class MomentumOptimizer extends SGDOptimizer {\n /** @nocollapse */\n // Name matters for Python compatibility.\n static override get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Momentum';\n }\n private m: Scalar;\n private accumulations: OptimizerVariable[] = [];\n\n constructor(\n protected override learningRate: number, private momentum: number,\n private useNesterov = false) {\n super(learningRate);\n this.m = scalar(this.momentum);\n }\n\n override applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n if (this.accumulations[i] == null) {\n const trainable = false;\n this.accumulations[i] = {\n originalName: `${name}/momentum`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const accumulation = this.accumulations[i].variable;\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n tidy(() => {\n let newValue: Tensor;\n const newAccumulation = add(mul(this.m, accumulation), gradient);\n if (this.useNesterov) {\n newValue = add(\n mul(this.c, add(gradient, mul(newAccumulation, this.m))), value);\n } else {\n newValue = add(mul(this.c, newAccumulation), value);\n }\n accumulation.assign(newAccumulation);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.m.dispose();\n if (this.accumulations != null) {\n dispose(this.accumulations.map(v => v.variable));\n }\n }\n\n /**\n * Sets the momentum of the optimizer.\n *\n * @param momentum\n */\n setMomentum(momentum: number) {\n this.momentum = momentum;\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n return [await this.saveIterations()].concat(this.accumulations.map(\n v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const trainable = false;\n this.accumulations = weightValues.map(\n v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n }\n\n override getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'momentum': this.momentum,\n 'useNesterov': this.useNesterov\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['momentum'], config['useNesterov']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class RMSPropOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'RMSProp';\n }\n private centered: boolean;\n\n private accumulatedMeanSquares: OptimizerVariable[] = [];\n private accumulatedMoments: OptimizerVariable[] = [];\n private accumulatedMeanGrads: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected decay = 0.9,\n protected momentum = 0.0, protected epsilon: number = null,\n centered = false) {\n super();\n\n this.centered = centered;\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n if (learningRate == null) {\n throw new Error(`learningRate for RMSPropOptimizer must be defined.`);\n }\n }\n\n applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedMeanSquares[i] == null) {\n this.accumulatedMeanSquares[i] = {\n originalName: `${name}/rms`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedMoments[i] == null) {\n this.accumulatedMoments[i] = {\n originalName: `${name}/momentum`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedMeanGrads[i] == null && this.centered) {\n this.accumulatedMeanGrads[i] = {\n originalName: `${name}/mg`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedMeanSquare = this.accumulatedMeanSquares[i].variable;\n const accumulatedMoments = this.accumulatedMoments[i].variable;\n tidy(() => {\n const newAccumulatedMeanSquare =\n add(mul(accumulatedMeanSquare, this.decay),\n mul(square(gradient), 1 - this.decay));\n\n if (this.centered) {\n const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;\n // Centered gradient\n const newAccumulatedMeanGrad =\n add(mul(accumulatedMeanGrad, this.decay),\n mul(gradient, 1 - this.decay));\n\n const gradContribution =\n div(mul(gradient, this.learningRate),\n sqrt(\n sub(newAccumulatedMeanSquare,\n add(square(newAccumulatedMeanGrad), this.epsilon))));\n const newAccumulatedMoments =\n add(mul(accumulatedMoments, this.momentum), gradContribution);\n\n accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n accumulatedMeanGrad.assign(newAccumulatedMeanGrad);\n accumulatedMoments.assign(newAccumulatedMoments);\n\n const newValue = sub(value, newAccumulatedMoments);\n value.assign(newValue);\n } else {\n // Plain gradient\n const newAccumulatedMeanSquare =\n add(mul(accumulatedMeanSquare, this.decay),\n mul(square(gradient), 1 - this.decay));\n\n const newAccumulatedMoments =\n add(mul(accumulatedMoments, this.momentum),\n div(mul(gradient, this.learningRate),\n sqrt(add(newAccumulatedMeanSquare, this.epsilon))));\n\n accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n accumulatedMoments.assign(newAccumulatedMoments);\n\n const newValue = sub(value, newAccumulatedMoments);\n value.assign(newValue);\n }\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedMeanSquares != null) {\n dispose(this.accumulatedMeanSquares.map(v => v.variable));\n }\n if (this.accumulatedMeanGrads != null && this.centered) {\n dispose(this.accumulatedMeanGrads.map(v => v.variable));\n }\n if (this.accumulatedMoments != null) {\n dispose(this.accumulatedMoments.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedMeanSquares, ...this.accumulatedMoments];\n if (this.centered) {\n variables.push(...this.accumulatedMeanGrads);\n }\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const variableCount =\n this.centered ? weightValues.length / 3 : weightValues.length / 2;\n const trainable = false;\n this.accumulatedMeanSquares =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedMoments =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n if (this.centered) {\n this.accumulatedMeanGrads =\n weightValues.slice(variableCount * 2, variableCount * 3)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'decay': this.decay,\n 'momentum': this.momentum,\n 'epsilon': this.epsilon,\n 'centered': this.centered\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['decay'], config['momentum'],\n config['epsilon'], config['centered']);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AdadeltaOptimizer} from './adadelta_optimizer';\nimport {AdagradOptimizer} from './adagrad_optimizer';\nimport {AdamOptimizer} from './adam_optimizer';\nimport {AdamaxOptimizer} from './adamax_optimizer';\nimport {MomentumOptimizer} from './momentum_optimizer';\nimport {RMSPropOptimizer} from './rmsprop_optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\nimport {registerClass} from '../serialization';\n\nconst OPTIMIZERS = [\n AdadeltaOptimizer,\n AdagradOptimizer,\n AdamOptimizer,\n AdamaxOptimizer,\n MomentumOptimizer,\n RMSPropOptimizer,\n SGDOptimizer,\n];\n\nexport function registerOptimizers() {\n for (const optimizer of OPTIMIZERS) {\n registerClass(optimizer);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code.\nimport './base_side_effects';\n\n// TODO(mattSoulanille): Move this to base_side_effects.ts\n// It is here for now because custom bundles need to avoid calling it, and they\n// only replace the index.js file, not the base_side_effects file.\nimport {registerOptimizers} from './optimizers/register_optimizers';\nregisterOptimizers();\n\n// All exports from this package should be in base.\nexport * from './base';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nconst contexts: {[key: string]: WebGLRenderingContext} = {};\n\nconst WEBGL_ATTRIBUTES: WebGLContextAttributes = {\n alpha: false,\n antialias: false,\n premultipliedAlpha: false,\n preserveDrawingBuffer: false,\n depth: false,\n stencil: false,\n failIfMajorPerformanceCaveat: true\n};\n\nexport function clearWebGLContext(webGLVersion: number) {\n delete contexts[webGLVersion];\n}\n\nexport function setWebGLContext(\n webGLVersion: number, gl: WebGLRenderingContext) {\n contexts[webGLVersion] = gl;\n}\n\nexport function getWebGLContext(\n webGLVersion: number,\n customCanvas?: HTMLCanvasElement|OffscreenCanvas): WebGLRenderingContext {\n if (!(webGLVersion in contexts) || customCanvas != null) {\n const newCtx = getWebGLRenderingContext(webGLVersion, customCanvas);\n if (newCtx !== null) {\n contexts[webGLVersion] = newCtx;\n } else {\n console.log('Could not get context for WebGL version', webGLVersion);\n return null;\n }\n }\n const gl = contexts[webGLVersion];\n if (gl == null || gl.isContextLost()) {\n delete contexts[webGLVersion];\n return getWebGLContext(webGLVersion);\n }\n\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.STENCIL_TEST);\n gl.disable(gl.BLEND);\n gl.disable(gl.DITHER);\n gl.disable(gl.POLYGON_OFFSET_FILL);\n gl.disable(gl.SAMPLE_COVERAGE);\n gl.enable(gl.SCISSOR_TEST);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n\n return contexts[webGLVersion];\n}\n\nfunction createCanvas(webGLVersion: number) {\n // Use canvas element for Safari, since its offscreen canvas does not support\n // fencing.\n if (!env().getBool('IS_SAFARI') && typeof OffscreenCanvas !== 'undefined' &&\n webGLVersion === 2) {\n return new OffscreenCanvas(300, 150);\n } else if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n } else {\n throw new Error('Cannot create a canvas in this context');\n }\n}\n\nfunction getWebGLRenderingContext(\n webGLVersion: number,\n customCanvas?: HTMLCanvasElement|OffscreenCanvas): WebGLRenderingContext {\n if (webGLVersion !== 1 && webGLVersion !== 2) {\n throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');\n }\n const canvas =\n customCanvas == null ? createCanvas(webGLVersion) : customCanvas;\n\n canvas.addEventListener('webglcontextlost', (ev: Event) => {\n ev.preventDefault();\n delete contexts[webGLVersion];\n }, false);\n\n if (env().getBool('SOFTWARE_WEBGL_ENABLED')) {\n WEBGL_ATTRIBUTES.failIfMajorPerformanceCaveat = false;\n }\n\n if (webGLVersion === 1) {\n return (\n canvas.getContext('webgl', WEBGL_ATTRIBUTES) ||\n (canvas as HTMLCanvasElement)\n .getContext('experimental-webgl', WEBGL_ATTRIBUTES));\n }\n return canvas.getContext('webgl2', WEBGL_ATTRIBUTES) as WebGLRenderingContext;\n}\n","export const DEFAULT_CDN_URL = 'https://websdk-cdn-dev.idmission.com/assets'\n","export type Frame =\n | ImageBitmap\n | HTMLVideoElement\n | HTMLImageElement\n | HTMLCanvasElement\n\nexport function getFrameDimensions(frame: Frame): [number, number] {\n let frameWidth = frame.width,\n frameHeight = frame.height\n\n if (frame instanceof HTMLVideoElement) {\n frameWidth = frame.videoWidth\n frameHeight = frame.videoHeight\n }\n\n return [frameWidth, frameHeight]\n}\n","import styled from 'styled-components'\nimport { Frame, getFrameDimensions } from '../../lib/utils/getFrameDimensions'\n\nexport const InvisibleCanvas = styled.canvas`\n display: none;\n`\n\nexport function drawToCanvas(\n canvas: HTMLCanvasElement | null,\n frame: Frame,\n width?: number,\n height?: number,\n): void {\n if (!canvas) return\n const ctx = canvas.getContext('2d')\n if (!ctx) return\n if (!width || !height) {\n const [frameWidth, frameHeight] = getFrameDimensions(frame)\n width ||= frameWidth\n height ||= frameHeight\n }\n canvas.width = width\n canvas.height = height\n ctx.drawImage(frame, 0, 0, width, height)\n}\n\nexport function clearCanvas(canvas: HTMLCanvasElement | null) {\n if (!canvas) return\n const ctx = canvas.getContext('2d')\n if (!ctx) return\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n}\n","import { Face } from '@tensorflow-models/face-detection'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport { Frame, getFrameDimensions } from './getFrameDimensions'\nimport { clearCanvas } from '../../components/common/InvisibleCanvas'\n\nexport function cropToShoulders(\n rawCanvas: HTMLCanvasElement | null,\n cropCanvas: HTMLCanvasElement | null,\n frame: ImageData,\n face: Face,\n): string {\n if (!rawCanvas || !cropCanvas) return ''\n\n const rawCtx = rawCanvas.getContext('2d')\n const cropCtx = cropCanvas.getContext('2d')\n if (!rawCtx || !cropCtx) throw new Error('could not get 2d context')\n\n rawCanvas.width = frame.width\n rawCanvas.height = frame.height\n rawCtx.putImageData(frame, 0, 0)\n\n const { xMin, width } = face.box\n const frameHeight = frame.height\n const xPadding = frameHeight * 0.6 - width\n const xPos = Math.max(0, xMin - xPadding / 2)\n if (isMobile()) {\n cropCanvas.width = frame.width\n cropCanvas.height = frame.height\n cropCtx.drawImage(rawCanvas, 0, 0, cropCanvas.width, cropCanvas.height)\n } else {\n cropCanvas.width = width + xPadding\n cropCanvas.height = frame.height\n cropCtx.drawImage(\n rawCanvas,\n xPos,\n 0,\n cropCanvas.width,\n cropCanvas.height,\n 0,\n 0,\n cropCanvas.width,\n cropCanvas.height,\n )\n }\n\n const dataURL = cropCanvas.toDataURL('image/jpeg', 0.92)\n\n clearCanvas(rawCanvas)\n clearCanvas(cropCanvas)\n\n return dataURL\n}\n\nexport function cropToBoundingBox(\n frame: Frame,\n bbox: number[],\n): HTMLCanvasElement {\n const canvas = document.createElement('canvas')\n const ctx = canvas.getContext('2d')\n if (!ctx) throw new Error('could not get 2d context')\n\n const [frameWidth, frameHeight] = getFrameDimensions(frame)\n const [xMin, yMin, width, height] = bbox\n canvas.width = width * frameWidth\n canvas.height = height * frameHeight\n ctx.drawImage(\n frame,\n xMin * frameWidth,\n yMin * frameHeight,\n width * frameWidth,\n height * frameHeight,\n 0,\n 0,\n width * frameWidth,\n height * frameHeight,\n )\n return canvas\n}\n","import React, {\n createContext,\n MutableRefObject,\n ReactElement,\n ReactNode,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport * as tf from '@tensorflow/tfjs'\nimport { setWebGLContext } from '@tensorflow/tfjs'\nimport {\n bboxToDetectedObjectUnscaled,\n DetectedObject,\n documentDetectionModel,\n DocumentType,\n loadDocumentDetectionModel,\n RawEdgeDetectionResult,\n unloadDocumentDetectionModel,\n} from '../../lib/models/DocumentDetection'\nimport {\n focusModel,\n FocusPrediction,\n loadFocusModel,\n unloadFocusModel,\n} from '../../lib/models/Focus'\nimport {\n clearWebGLContext,\n getWebGLContext,\n} from '@tensorflow/tfjs-backend-webgl/dist/canvas_util'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { Frame, getFrameDimensions } from '../../lib/utils/getFrameDimensions'\nimport { cropToBoundingBox } from '../../lib/utils/cropping'\nimport {\n clearCanvas,\n drawToCanvas,\n InvisibleCanvas,\n} from '../common/InvisibleCanvas'\n\nexport type IdCapturePrediction = {\n detectedObjects: DetectedObject[]\n detectionTime: number\n detectionScore: number\n detectionThresholdMet: boolean\n detectedDocumentType: DocumentType\n\n passportDetectionScore: number\n passportDetectionThresholdMet: boolean\n\n mrzDetectionScore: number\n mrzDetectionThresholdMet: boolean\n\n pdf417DetectionScore: number\n pdf417DetectionThresholdMet: boolean\n\n bestDocumentOrPassport: DetectedObject | undefined\n bestMrz: DetectedObject | undefined\n bestPdf417: DetectedObject | undefined\n\n focusScore: number\n focusThresholdMet: boolean\n focusPredictionTime: number\n\n frameWidth: number\n frameHeight: number\n\n allZero: boolean\n}\n\nexport type IdCaptureThresholds = {\n document?: number\n passport?: number\n mrz?: number\n pdf417?: number\n focus?: number\n}\n\nconst PRERESIZE = false\n// export const PREDICTION_POSITIONS = { boxes: 1, scores: 4, labels: 2 } // for docdetectuint8\nexport const PREDICTION_POSITIONS = { boxes: 0, scores: 7, labels: 4 } // for documentdetectionquantized\n// export const PREDICTION_POSITIONS = { boxes: 2, scores: 6, labels: 4 } // for documentdetection\n// export const PREDICTION_POSITIONS = { boxes: 5, scores: 4, labels: 1 } // for edgeDetection\n\nexport type IdCaptureModelsState = {\n ready: boolean\n working: MutableRefObject<boolean>\n error: Error | null\n\n thresholds: IdCaptureThresholds\n setThresholds: (value: IdCaptureThresholds) => void\n\n makePrediction: (frame: Frame) => void\n onPredictionMade: (handler: (prediction: IdCapturePrediction) => void) => void\n\n detectionTime: number\n focusPredictionTime: number\n\n getBestFrame: () => Promise<Blob | null>\n resetBestFrame: () => void\n}\n\nexport const IdCaptureModelsContext = createContext<IdCaptureModelsState>({\n ready: false,\n working: { current: false },\n error: null,\n\n thresholds: {},\n setThresholds: () => null,\n\n makePrediction: () => null,\n onPredictionMade: () => null,\n\n detectionTime: 0,\n focusPredictionTime: 0,\n\n getBestFrame: () => Promise.resolve(null),\n resetBestFrame: () => null,\n})\n\nexport type IdCaptureModelsProviderProps = {\n children: ReactNode\n documentDetectionModelUrl?: string | undefined\n focusModelUrl?: string | undefined\n logPredictions?: boolean\n}\n\nconst defaultDocumentDetectionModelUrl = `${DEFAULT_CDN_URL}/models/documentdetection448/model.json`\nconst defaultFocusModelUrl = `${DEFAULT_CDN_URL}/models/focus/model.json`\n\nexport const IdCaptureModelsProvider = ({\n children,\n documentDetectionModelUrl,\n focusModelUrl,\n logPredictions = false,\n}: IdCaptureModelsProviderProps): ReactElement => {\n const [ready, setReady] = useState(false)\n const [documentDetectionThreshold, setDocumentDetectionThreshold] =\n useState(0)\n const [passportDetectionThreshold, setPassportDetectionThreshold] =\n useState(0)\n const [mrzDetectionThreshold, setMrzDetectionThreshold] = useState(0)\n const [pdf417DetectionThreshold, setPdf417DetectionThreshold] = useState(0)\n const [focusThreshold, setFocusThreshold] = useState(0)\n const working = useRef(false)\n const onPredictionHandler =\n useRef<(prediction: IdCapturePrediction) => void>()\n const lastPredictionCanvas = useRef<HTMLCanvasElement | null>(null)\n const [detectionTime, setDetectionTime] = useState<number>(0)\n const [focusPredictionTime, setFocusPredictionTime] = useState<number>(0)\n const [loadingError, setLoadingError] = useState<Error | null>(null)\n\n useEffect(() => {\n setReady(false)\n\n const ddmUrl = documentDetectionModelUrl || defaultDocumentDetectionModelUrl\n const fmUrl = focusModelUrl || defaultFocusModelUrl\n\n async function loadModels() {\n tf.ENV.set('WEBGL_DELETE_TEXTURE_THRESHOLD', 50 * 1024 * 1024)\n await tf.setBackend('webgl')\n await tf.ready()\n await Promise.all([\n loadDocumentDetectionModel(ddmUrl),\n loadFocusModel(fmUrl),\n ])\n }\n\n async function reloadModels() {\n setReady(false)\n unloadDocumentDetectionModel()\n unloadFocusModel()\n clearWebGLContext(2)\n const ctx = document.createElement('canvas').getContext('webgl2')\n if (ctx && ddmUrl && fmUrl) {\n setWebGLContext(2, ctx)\n disposeTfBackend()\n await loadModels()\n setReady(true)\n }\n }\n\n loadModels()\n .then(() => {\n setReady(true)\n })\n .catch((e) => {\n setLoadingError(e as Error)\n })\n\n const webGLCanvas = getWebGLContext(2).canvas\n webGLCanvas.addEventListener('webglcontextlost', reloadModels)\n\n return () => {\n webGLCanvas.removeEventListener?.('webglcontextlost', reloadModels)\n }\n }, [documentDetectionModelUrl, focusModelUrl])\n\n const thresholds = useMemo<IdCaptureThresholds>(\n () => ({\n document: documentDetectionThreshold,\n passport: passportDetectionThreshold,\n mrz: mrzDetectionThreshold,\n pdf417: pdf417DetectionThreshold,\n focus: focusThreshold,\n }),\n [\n documentDetectionThreshold,\n focusThreshold,\n mrzDetectionThreshold,\n passportDetectionThreshold,\n pdf417DetectionThreshold,\n ],\n )\n\n const setThresholds = useCallback((thresholds: IdCaptureThresholds) => {\n if (thresholds.document) setDocumentDetectionThreshold(thresholds.document)\n if (thresholds.passport) setPassportDetectionThreshold(thresholds.passport)\n if (thresholds.mrz) setMrzDetectionThreshold(thresholds.mrz)\n if (thresholds.pdf417) setPdf417DetectionThreshold(thresholds.pdf417)\n if (thresholds.focus) setFocusThreshold(thresholds.focus)\n }, [])\n\n const [timesAllZero, setTimesAllZero] = useState(0)\n const bestPredictionCanvas = useRef<HTMLCanvasElement | null>(null)\n const bestFocusScore = useRef<number>(0)\n const makePrediction = useCallback(\n (frame: Frame) => {\n working.current = true\n ;(async () => {\n if (\n !documentDetectionModel ||\n !focusModel ||\n !lastPredictionCanvas.current\n )\n return\n\n const prediction = await makePredictions(\n frame,\n lastPredictionCanvas.current,\n thresholds,\n logPredictions,\n )\n\n setDetectionTime(prediction.detectionTime)\n setFocusPredictionTime(prediction.focusPredictionTime)\n\n if (bestFocusScore.current <= prediction.focusScore) {\n bestFocusScore.current = prediction.focusScore\n drawToCanvas(bestPredictionCanvas.current, frame)\n }\n\n if (prediction.allZero) setTimesAllZero((n) => n + 1)\n\n onPredictionHandler.current?.(prediction)\n\n working.current = false\n })()\n },\n [logPredictions, thresholds],\n )\n\n useEffect(() => {\n if (timesAllZero >= 2) {\n setLoadingError(new Error('model is returning all zeroes'))\n }\n }, [timesAllZero])\n\n const onPredictionMade = useCallback(\n (handler: (prediction: IdCapturePrediction) => void) => {\n onPredictionHandler.current = handler\n },\n [],\n )\n\n const getBestFrame = useCallback(async () => {\n if (!bestPredictionCanvas.current) return null\n const photoURL = bestPredictionCanvas.current.toDataURL('image/jpeg', 0.98)\n const data = await fetch(photoURL)\n return await data.blob()\n }, [])\n\n const resetBestFrame = useCallback(() => {\n bestFocusScore.current = 0\n clearCanvas(bestPredictionCanvas.current)\n }, [])\n\n const value = useMemo<IdCaptureModelsState>(\n () => ({\n ready,\n working,\n thresholds,\n setThresholds,\n makePrediction,\n onPredictionMade,\n detectionTime,\n focusPredictionTime,\n getBestFrame,\n resetBestFrame,\n error: loadingError,\n }),\n [\n detectionTime,\n focusPredictionTime,\n getBestFrame,\n loadingError,\n makePrediction,\n onPredictionMade,\n ready,\n resetBestFrame,\n setThresholds,\n thresholds,\n ],\n )\n\n return (\n <IdCaptureModelsContext.Provider value={value}>\n {children}\n <InvisibleCanvas ref={lastPredictionCanvas} />\n <InvisibleCanvas ref={bestPredictionCanvas} />\n </IdCaptureModelsContext.Provider>\n )\n}\n\nasync function makePredictions(\n frame: Frame,\n lastPredictionCanvas: HTMLCanvasElement,\n thresholds: IdCaptureThresholds,\n logPredictions: boolean = false,\n): Promise<IdCapturePrediction> {\n const [frameWidth, frameHeight] = getFrameDimensions(frame)\n\n if (PRERESIZE) {\n if (logPredictions) console.time('pre-resize')\n const preResizeCanvas = document.createElement('canvas')\n const [w, h] =\n frameWidth > frameHeight\n ? [frameWidth * (448 / frameHeight), 448]\n : [448, frameHeight * (448 / frameWidth)]\n drawToCanvas(preResizeCanvas, frame, w, h)\n frame = preResizeCanvas\n if (logPredictions) console.timeEnd('pre-resize')\n }\n\n drawToCanvas(lastPredictionCanvas, frame)\n\n const { boxes, scores, labels, time } =\n await makeDocumentDetectionPredictions(frame, logPredictions)\n\n const allZero =\n boxes.length > 0 && !boxes.some((box) => box.some((n) => n > 0))\n\n const detectedObjects = applyNonMaxSuppression(\n boxes.map((box, i) =>\n bboxToDetectedObjectUnscaled(box, scores[i], labels[i]),\n ),\n )\n\n const bestDocument = detectedObjects.find((obj) => obj.label === 'Document')\n const bestPassportPage = detectedObjects.find(\n (obj) => obj.label === 'Passport Page',\n )\n const bestDocumentScore = bestDocument?.score ?? 0\n const passportDetectionScore = bestPassportPage?.score ?? 0\n const passportDetectionThresholdMet =\n passportDetectionScore >= (thresholds.passport ?? 0)\n const bestDocumentOrPassport =\n bestDocumentScore > passportDetectionScore ? bestDocument : bestPassportPage\n const detectionScore = passportDetectionThresholdMet\n ? passportDetectionScore\n : bestDocumentScore\n const detectionThresholdMet = detectionScore >= (thresholds.document ?? 0)\n\n let detectedDocumentType = DocumentType.NONE\n if (passportDetectionThresholdMet) {\n detectedDocumentType = DocumentType.PASSPORT\n } else if (detectionThresholdMet) {\n detectedDocumentType = DocumentType.ID_CARD\n }\n\n const bestMrz = detectedObjects.find((obj) => obj.label === 'MRZ')\n const mrzDetectionScore = bestMrz?.score ?? 0\n const mrzDetectionThresholdMet = mrzDetectionScore >= (thresholds.mrz ?? 0)\n\n const bestPdf417 = detectedObjects.find((obj) => obj.label === 'PDF417')\n const pdf417DetectionScore = bestPdf417?.score ?? 0\n const pdf417DetectionThresholdMet =\n pdf417DetectionScore >= (thresholds.pdf417 ?? 0)\n\n let focusPrediction: FocusPrediction | null = null,\n focusPredictionTime = 0,\n focusScore = 0,\n focusThresholdMet = false\n if (detectionThresholdMet) {\n ;[focusPrediction, focusPredictionTime] = await makeFocusPrediction(\n frame,\n bestDocumentOrPassport?.bbox,\n logPredictions,\n )\n focusScore = focusPrediction?.[1] ?? 0\n focusThresholdMet = focusScore >= (thresholds.focus ?? 0)\n }\n\n return {\n detectedObjects,\n detectionScore,\n detectionTime: time,\n detectionThresholdMet,\n detectedDocumentType,\n passportDetectionScore,\n passportDetectionThresholdMet,\n mrzDetectionScore,\n mrzDetectionThresholdMet,\n pdf417DetectionScore,\n pdf417DetectionThresholdMet,\n bestDocumentOrPassport,\n bestMrz,\n bestPdf417,\n focusScore,\n focusThresholdMet,\n focusPredictionTime,\n frameWidth,\n frameHeight,\n allZero,\n }\n}\n\ntype RawDocumentDetectionPrediction = {\n boxes: number[][]\n scores: number[]\n labels: number[]\n time: number\n}\n\nasync function makeDocumentDetectionPredictions(\n image: Frame,\n logPredictions: boolean = false,\n): Promise<RawDocumentDetectionPrediction> {\n if (!documentDetectionModel) {\n throw new Error('document detection model is not loaded')\n }\n\n const startedAt = new Date()\n\n try {\n const tfImg = tf.browser.fromPixels(image)\n if (logPredictions) console.time('resize')\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n if (logPredictions) console.timeEnd('resize')\n tfImg.dispose()\n if (logPredictions) console.time('convert to int32')\n const tfInt32 = tf.cast(tfResize, 'int32')\n tfResize.dispose()\n const tf4d_ = tf.tensor4d(\n Array.from(await tfInt32.data()),\n [1, 448, 448, 3],\n )\n tfInt32.dispose()\n const tf4d = tf.cast(tf4d_, 'int32')\n if (logPredictions) console.timeEnd('convert to int32')\n tf4d_.dispose()\n if (logPredictions) console.time('predictions')\n const result = await documentDetectionModel.executeAsync(tf4d)\n if (logPredictions) console.timeEnd('predictions')\n tf4d.dispose()\n\n const predictions = result as unknown as RawEdgeDetectionResult\n if (logPredictions) {\n console.log(\n 'predictions made!',\n predictions.map((r) => r.arraySync()),\n )\n }\n\n const [boxes] = (await predictions[\n PREDICTION_POSITIONS.boxes\n ].array()) as number[][][]\n const [scores] = (await predictions[\n PREDICTION_POSITIONS.scores\n ].array()) as number[][]\n let [labels] = (await predictions[\n PREDICTION_POSITIONS.labels\n ].array()) as number[][]\n\n labels = labels.map((l) => Math.round(l))\n\n tf.dispose(result)\n\n const time = new Date().getTime() - startedAt.getTime()\n return { boxes, scores, labels, time }\n } catch (e) {\n console.error('caught error in makeDocumentDetectionPredictions', e)\n return { boxes: [], scores: [], labels: [], time: 0 }\n }\n}\n\nasync function makeFocusPrediction(\n imageData: Frame,\n bbox?: number[],\n logPredictions: boolean = false,\n): Promise<[FocusPrediction, number]> {\n if (!focusModel) {\n throw new Error('focus model is not loaded')\n }\n\n const startedAt = new Date()\n\n try {\n let tfImg: tf.Tensor3D\n if (bbox) {\n tfImg = tf.browser.fromPixels(cropToBoundingBox(imageData, bbox))\n } else {\n tfImg = tf.browser.fromPixels(imageData)\n }\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n tfImg.dispose()\n const tfInt32 = tf.cast(tfResize, 'int32')\n tfResize.dispose()\n const tf4d_ = tf.tensor4d(\n Array.from(await tfInt32.data()),\n [1, 448, 448, 3],\n )\n tfInt32.dispose()\n const tf4d = tf.cast(tf4d_, 'int32')\n tf4d_.dispose()\n if (logPredictions) console.time('focus prediction')\n const predictions = (await focusModel.predict(tf4d)) as tf.Tensor<tf.Rank>\n tf4d.dispose()\n const [focusPrediction] = (await predictions.array()) as FocusPrediction[]\n if (logPredictions) console.timeEnd('focus prediction')\n tf.dispose(predictions)\n\n const predictionTime = new Date().getTime() - startedAt.getTime()\n\n return [focusPrediction, predictionTime]\n } catch (e) {\n return [[0, 0], 0]\n }\n}\n\nfunction applyNonMaxSuppression(\n detectedObjects: DetectedObject[],\n): DetectedObject[] {\n const maxes: { [label: string]: [number, number] } = {}\n detectedObjects.forEach((obj, i) => {\n if (obj) {\n if (!maxes[obj.label]) maxes[obj.label] = [0, -1]\n if (obj.score > maxes[obj.label][0]) maxes[obj.label] = [obj.score, i]\n }\n })\n return Object.keys(maxes)\n .map((label) => detectedObjects[maxes[label][1]])\n .filter((obj) => !!obj)\n}\n\nfunction disposeTfBackend(): void {\n try {\n tf.backend().dispose()\n } catch (e) {\n console.error('failed to dispose backend', e)\n }\n}\n","import styled from 'styled-components'\nimport React, { ReactElement, useMemo } from 'react'\nimport { DetectedObject } from '../../lib/models/DocumentDetection'\nimport {\n Face,\n FaceKeypoint,\n} from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\n\nexport const DebugStatsPane = styled.span`\n font-size: 16px;\n font-family: monospace;\n position: absolute;\n left: 20px;\n bottom: 20px;\n color: limegreen;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1001;\n`\n\nexport const ObjectDetectionDebugOverlay = styled.div<{ $flipX?: boolean }>`\n position: absolute;\n z-index: 1001;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n overflow: hidden;\n ${({ $flipX }) => ($flipX ? 'transform: scaleX(-1);' : '')}\n`\n\nexport const ObjectDetectionDebugBox = styled.div<{\n $color?: string\n $flipX?: boolean\n}>`\n font: 10px monospace;\n position: absolute;\n border: 3px solid ${({ $color }) => $color ?? 'green'};\n color: ${({ $color }) => $color ?? 'green'};\n ${({ $flipX }) => ($flipX ? 'transform: scaleX(-1);' : '')}\n`\n\nexport const FaceDetectionKeypointMarker = styled.div<{\n $color?: string\n $flipX?: boolean\n}>`\n position: absolute;\n width: 4px;\n height: 4px;\n border: 2px solid ${({ $color }) => $color ?? 'red'};\n font: 10px monospace;\n color: ${({ $color }) => $color ?? 'red'};\n border-radius: 50%;\n ${({ $flipX }) => ($flipX ? 'transform: scaleX(-1);' : '')}\n`\n\nexport type DebugScalingDetails = {\n horizontal: boolean\n pageWidth: number\n pageHeight: number\n videoWidth: number\n videoHeight: number\n scaledWidth: number\n scaledHeight: number\n xOffset: number\n yOffset: number\n}\n\nexport function useDebugScalingDetails({\n enabled = true,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n}: {\n enabled?: boolean\n pageWidth: number\n pageHeight: number\n videoWidth: number\n videoHeight: number\n}): DebugScalingDetails {\n return useMemo(() => {\n let horizontal = false,\n scaledWidth = 0,\n scaledHeight = 0,\n xOffset = 0,\n yOffset = 0\n\n if (enabled) {\n horizontal = pageWidth / pageHeight < videoWidth / videoHeight\n if (horizontal) {\n scaledWidth = videoWidth * (pageHeight / videoHeight)\n xOffset = (scaledWidth - pageWidth) / 2\n } else {\n scaledHeight = videoHeight * (pageWidth / videoWidth)\n yOffset = (scaledHeight - pageHeight) / 2\n }\n }\n\n return {\n horizontal,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n }\n }, [enabled, pageHeight, pageWidth, videoHeight, videoWidth])\n}\n\nexport type DetectedObjectDebugBoxProps = {\n obj: DetectedObject\n scaling: DebugScalingDetails\n flipX?: boolean\n color?: string\n}\n\nexport function IdCaptureDetectedObjectDebugBox({\n obj,\n flipX,\n color = 'green',\n scaling: {\n horizontal,\n pageWidth,\n pageHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n },\n}: DetectedObjectDebugBoxProps): ReactElement {\n let [top, left, width, height] = [\n obj.bbox[1],\n obj.bbox[0],\n obj.bbox[2],\n obj.bbox[3],\n ]\n\n if (horizontal) {\n top *= pageHeight\n left *= scaledWidth - xOffset\n width *= scaledWidth\n height *= pageHeight\n } else {\n top *= scaledHeight - yOffset\n left *= pageWidth\n width *= pageWidth\n height *= scaledHeight\n }\n\n return (\n <ObjectDetectionDebugBox\n $flipX={flipX}\n $color={color}\n style={{ top, left, width, height }}\n >\n {obj.label} ({obj.score.toFixed(3)})\n </ObjectDetectionDebugBox>\n )\n}\n\nexport type SelfieCaptureFaceDebugBoxProps = {\n face: Face\n scaling: DebugScalingDetails\n flipX?: boolean\n color?: string\n}\n\nexport function SelfieCaptureFaceDebugBox({\n face,\n flipX,\n color = 'green',\n scaling,\n}: SelfieCaptureFaceDebugBoxProps): ReactElement {\n const {\n horizontal,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n } = scaling\n\n let top\n let left\n let width\n let height\n\n if (horizontal) {\n top = (face.box.yMin / videoHeight) * pageHeight\n left = (face.box.xMin / videoWidth) * scaledWidth - xOffset\n width = (face.box.width / videoWidth) * scaledWidth\n height = (face.box.height / videoHeight) * pageHeight\n } else {\n top = (face.box.yMin / videoHeight) * scaledHeight - yOffset\n left = (face.box.xMin / videoWidth) * pageWidth\n width = (face.box.width / videoWidth) * pageWidth\n height = (face.box.height / videoHeight) * scaledHeight\n }\n\n return (\n <>\n <ObjectDetectionDebugBox\n $flipX={flipX}\n $color={color}\n style={{ top, left, width, height }}\n />\n\n {face.keypoints.map((point, ii) => (\n <SelfieCaptureFaceKeypoint\n key={ii}\n point={point}\n scaling={scaling}\n flipX={flipX}\n />\n ))}\n </>\n )\n}\n\ntype SelfieCaptureFaceKeypointProps = {\n point: FaceKeypoint\n scaling: DebugScalingDetails\n flipX?: boolean\n color?: string\n}\n\nexport function SelfieCaptureFaceKeypoint({\n point,\n flipX,\n color = 'red',\n scaling: {\n horizontal,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n },\n}: SelfieCaptureFaceKeypointProps): ReactElement {\n let left, top\n if (horizontal) {\n left = (point.x / videoWidth) * scaledWidth - xOffset\n top = (point.y / videoHeight) * pageHeight\n } else {\n left = (point.x / videoWidth) * pageWidth\n top = (point.y / videoHeight) * scaledHeight - yOffset\n }\n\n top -= 2\n left -= 2\n\n return (\n <FaceDetectionKeypointMarker\n $flipX={flipX}\n $color={color}\n style={{ top, left }}\n />\n )\n}\n","import React from 'react'\nimport styled from 'styled-components'\n\nexport const ExitCaptureStyledButton = styled.button`\n position: absolute;\n top: 12px;\n right: 12px;\n font-size: 20px;\n width: 32px;\n height: 32px;\n font-family: monospace;\n z-index: 1002;\n border: none;\n border-radius: 4px;\n background: #ccc;\n cursor: pointer;\n padding: 8px;\n box-sizing: border-box;\n display: flex;\n\n &:hover {\n background: #ddd;\n }\n\n & > svg {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n`\n\nexport const ExitCaptureButton = ({\n onClick,\n className,\n}: {\n onClick?: () => void\n className?: string\n}) => {\n return (\n <ExitCaptureStyledButton onClick={onClick} className={className}>\n <svg\n version=\"1.1\"\n xmlns=\"http://www.w3.org/2000/svg\"\n x=\"0px\"\n y=\"0px\"\n viewBox=\"19.3 19.3 25.499999999999996 25.499999999999996\"\n enableBackground=\"new 0 0 64 64\"\n width={16}\n height={16}\n >\n <g id=\"close-outline-bot_x5F_s1g1_x5F_s2g2_x5F_s3g1_x5F_s4g1\">\n <line\n fill=\"none\"\n stroke=\"#000000\"\n strokeWidth=\"1\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeMiterlimit=\"10\"\n x1=\"19.75\"\n y1=\"44.25\"\n x2=\"44.25\"\n y2=\"19.75\"\n />\n </g>\n <g id=\"close-outline-top_x5F_s1g1_x5F_s2g2_x5F_s3g1_x5F_s4g1\">\n <line\n fill=\"none\"\n stroke=\"#000000\"\n strokeWidth=\"1\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeMiterlimit=\"10\"\n x1=\"44.25\"\n y1=\"44.25\"\n x2=\"19.75\"\n y2=\"19.75\"\n />\n </g>\n </svg>\n </ExitCaptureStyledButton>\n )\n}\n","import styled from 'styled-components'\n\nexport const Spinner = styled.div<{\n $size?: number\n $thickness?: number\n $color?: string\n}>`\n display: inline-block;\n width: ${({ $size }) => $size ?? 80}px;\n height: ${({ $size }) => $size ?? 80}px;\n margin: auto;\n\n &:after {\n content: ' ';\n display: block;\n width: ${({ $size }) => ($size ?? 80) - 16}px;\n height: ${({ $size }) => ($size ?? 80) - 16}px;\n margin: 8px;\n border-radius: 50%;\n border: ${({ $thickness }) => $thickness ?? 6}px solid\n ${({ $color }) => $color ?? '#888'};\n border-color: ${({ $color }) => $color ?? '#888'} transparent\n ${({ $color }) => $color ?? '#888'} transparent;\n animation: lds-dual-ring 1.2s linear infinite;\n box-sizing: content-box;\n }\n\n @keyframes lds-dual-ring {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n`\n","import { Spinner } from './spinner'\nimport styled from 'styled-components'\nimport React from 'react'\n\nexport type IdCaptureImagePreviewClassNames = {\n container?: string\n text?: string\n imageContainer?: string\n image?: string\n}\n\nexport type IdCaptureImagePreviewProps = {\n classNames?: IdCaptureImagePreviewClassNames\n text?: string\n imageUrl: string\n}\n\nexport const IdCaptureImagePreview = ({\n classNames = {},\n text,\n imageUrl,\n}: IdCaptureImagePreviewProps) => {\n return (\n <ImagePreviewWrapper className={classNames.container}>\n {text && (\n <ImagePreviewText className={classNames.text}>{text}</ImagePreviewText>\n )}\n\n <ImagePreviewImageWrapper className={classNames.imageContainer}>\n <img src={imageUrl} alt=\"\" className={classNames.image} />\n </ImagePreviewImageWrapper>\n </ImagePreviewWrapper>\n )\n}\n\nexport type SelfieProgressPreviewClassNames = {\n container?: string\n text?: string\n spinner?: string\n imageContainer?: string\n image?: string\n}\n\nexport type SelfieProgressPreviewProps = {\n classNames?: SelfieProgressPreviewClassNames\n text: string\n imageUrl: string\n}\n\nexport const SelfieProgressPreview = ({\n classNames = {},\n text,\n imageUrl,\n}: SelfieProgressPreviewProps) => {\n return (\n <ImagePreviewWrapper className={classNames.container}>\n <ImagePreviewText className={classNames.text}>\n <StyledSpinner\n className={classNames.spinner}\n $size={24}\n $color=\"white\"\n $thickness={3}\n />\n {text}\n </ImagePreviewText>\n\n <ImagePreviewImageWrapper className={classNames.imageContainer}>\n <img src={imageUrl} alt=\"\" className={classNames.image} />\n </ImagePreviewImageWrapper>\n </ImagePreviewWrapper>\n )\n}\n\nconst StyledSpinner = styled(Spinner)`\n position: relative;\n top: 4px;\n left: -3px;\n margin: 0 3px 0 -12px;\n`\n\nconst ImagePreviewWrapper = styled.div`\n position: absolute;\n display: flex;\n flex-direction: column;\n height: 33%;\n bottom: 12px;\n right: 12px;\n`\n\nconst ImagePreviewText = styled.div`\n display: block;\n position: absolute;\n top: -32px;\n font: 14px -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,\n Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';\n color: white;\n text-align: center;\n margin: 0 auto;\n width: 100%;\n`\n\nconst ImagePreviewImageWrapper = styled.div`\n position: relative;\n height: calc(100% - 8px);\n padding: 4px;\n border-radius: 4px;\n background: white;\n\n & > img {\n border-radius: 4px;\n width: auto;\n max-height: 100%;\n }\n`\n","export default {}\n","export default {\n 'Use your device camera to capture your ID':\n 'Para capturar la identificación hay que utilizar la cámara del dispositivo.',\n\n 'Use your iPhone as a webcam': 'Usar el iPhone como cámara web',\n 'Models warming up...': 'Cargando modelos...',\n 'Camera initializing...': 'Inicializando la cámara...',\n 'Camera access blocked': 'Acceso bloqueado a la cámara',\n 'Location access blocked': 'Acceso bloqueado a la localización',\n Continue: 'Continuar',\n 'Processing...': 'Procesando...',\n\n 'Your camera permission is disabled':\n 'El permiso de la cámara está desactivado',\n 'This application requires access to your camera to continue. Please accept the permission once prompted by the browser. If the browser does not prompt for camera permissions, you must go to settings and provide camera access to the current browser.':\n 'Esta aplicación requiere el acceso a la cámara para continuar. Hay que aceptar el permiso una vez que se muestre la ventana en el explorador. Si no aparece la ventana para otorgar permisos, entonces hay que dirigirse a Configuración y otorgar el permiso a la cámara en el explorador actual.',\n 'Your location permission is disabled':\n 'El permiso de la localización está desactivado',\n 'This application requires access to your location to continue. Please accept the permission once prompted by the browser. If the browser does not prompt for location permissions, you must go to settings and provide location access to the current browser.':\n 'Esta aplicación requiere el acceso a la localización para continuar. Hay que aceptar el permiso una vez que se muestre la ventana en el explorador. Si no aparece la ventana para otorgar permisos, entonces hay que dirigirse a Configuración y otorgar el permiso a la localización en el explorador actual.',\n Retry: 'Reintentar',\n\n 'Scan the front of ID': 'Escanear el frente de la ID',\n 'Scan the back of ID': 'Escanear el reverso de la ID',\n 'Scan the ID page of passport': 'Escanear la página de datos del pasaporte',\n\n 'ID Card Front': 'Frente de la ID',\n 'ID Card Back': 'Reverso de la ID',\n Passport: 'Pasaporte',\n\n 'Document not detected': 'No se ha detectado el documento',\n 'Document is not centered': 'Documento no centrado',\n 'Document out of focus – try improving the lighting':\n 'Documento no enfocado - hay que tratar de mejorar la iluminación',\n 'Document detected, hold still...':\n 'Se ha detectado el documento, no moverse por favor...',\n\n 'Capturing...': 'Capturando...',\n 'Capture failed!': 'Falló la captura',\n\n 'Please flip your ID card...': 'Por favor voltea la identificación...',\n 'ID card front captured.': 'Se ha capturado el frente de la identificación.',\n\n 'ID Capture Successful': 'Captura Exitosa de ID',\n 'Verify the entire ID was captured clearly with no glare.':\n 'Hay que verificar que toda la ID se vea completa y sin reflejos.',\n\n Submit: 'Enviar',\n 'Submitting...': 'Enviando...',\n\n 'Use your device camera to capture your face':\n 'Hay que utilizar la cámara del dispositivo para capturar el rostro',\n\n 'Remove Sunglasses & Hat': 'Hay que quitarse lentes y/o la gorra',\n 'Avoid Excessive Backlighting': 'Hay que evitar demasiada luz en el fondo',\n\n 'Hold still for a few seconds...':\n 'Hay que permanecer quieto por unos segundos...',\n 'Look straight into the camera...':\n 'Hay que mirar directamente a la cámara...',\n 'Move back...': 'Hay que hacerse hacia atrás..',\n 'Move forward...': 'Hay que hacerse hacia adelante...',\n 'Move to the center...': 'Hay que moverse hacia el centro...',\n 'Please remove your eye coverings (sunglasses, eye patch, etc.)...':\n 'Hay que quitarse lo que cubre los ojos (lentes, parche, etc.)...',\n 'Please remove your head coverings (hat, scarf, etc.)...':\n 'Hay que quitarse lo que cubre la cabeza (gorra, mascada, etc.)...',\n 'Please remove your mask...': 'Hay que quitarse el cubrebocas...',\n 'Live face not detected, please try again':\n 'Rostro vivo no detectado. Por favor hay que intentar de nuevo.',\n Exit: 'Salir',\n 'Face liveness has been verified!':\n 'Se ha verificado la Prueba de Vida en rostro!',\n Done: 'Terminar',\n\n 'Customer has been identified!': '¡Se ha identificado al cliente!',\n 'Customer not found': 'Cliente no encontrado',\n\n 'Additional document capture': 'Captura de otro documento',\n Next: 'Siguiente',\n\n 'Please sign the box below':\n 'Por favor, hay que firmar en el recuadro de abajo',\n Accept: 'Aceptar',\n Clear: 'Borrar',\n\n 'Video signature has been successfully captured!':\n 'La video firma ha sido exitosa.',\n\n 'Network unreachable': 'No hay conexión a internet.',\n \"We're having trouble reaching our services, please check your connection and try again.\": `Estamos teniendo problemas para alcanzar nuestros servicios, por favor verificar la conexión a internet e intentar de nuevo.`,\n \"We're sorry, an unexpected error has occurred.\": `Lo sentimos, se ha producido un error inesperado.`,\n}\n","import { useEffect, useMemo } from 'react'\nimport { initReactI18next, useTranslation } from 'react-i18next'\nimport enTranslation from './en/translation'\nimport esTranslation from './es/translation'\nimport LanguageDetector from 'i18next-browser-languagedetector'\nimport i18n from 'i18next'\n\nexport const ALL_LANGUAGES = ['auto', 'en', 'es'] as const\nexport type LangOptions = typeof ALL_LANGUAGES\nexport type LangOption = LangOptions[number]\n\nexport const resources = {\n en: { translation: enTranslation },\n es: { translation: esTranslation },\n}\n\nexport function initializeI18n() {\n i18n\n .use(LanguageDetector)\n .use(initReactI18next)\n .init({\n resources,\n detection: { caches: [] },\n fallbackLng: 'en',\n debug: false,\n interpolation: { escapeValue: false },\n })\n}\n\nexport const useLanguage = (lang: LangOption): void => {\n const { i18n } = useTranslation()\n useEffect(() => {\n if (lang !== 'auto') {\n i18n.changeLanguage(lang)\n } else {\n i18n.changeLanguage() // call without argument to use detection\n }\n }, [i18n, lang])\n}\n\nexport type CustomerSuppliedTranslations = { [lang: string]: string }\nexport type CustomerSuppliedVerbiage =\n | string\n | CustomerSuppliedTranslations\n | undefined\nexport type RecursiveVerbiageObject =\n | CustomerSuppliedVerbiage\n | { [key: string]: RecursiveVerbiageObject }\n\nfunction evaluateVerbiage(\n t: (key: string) => string,\n currentLanguage: string,\n verbiage: CustomerSuppliedVerbiage,\n fallback: string\n): string {\n if (typeof verbiage === 'string') return verbiage\n\n if (typeof verbiage === 'object') {\n const translations = verbiage as CustomerSuppliedTranslations\n if (translations[currentLanguage]) return translations[currentLanguage]\n\n const nonLocaleLang = currentLanguage.split('-')[0]\n if (translations[nonLocaleLang]) return translations[nonLocaleLang]\n }\n\n return t(fallback)\n}\n\nexport function useVerbiage(\n verbiage: CustomerSuppliedVerbiage,\n fallback: string\n): string {\n const { t, i18n } = useTranslation()\n\n return useMemo(\n () => evaluateVerbiage(t, i18n.language, verbiage, fallback),\n [fallback, i18n.language, t, verbiage]\n )\n}\n\nexport function useTranslations<\n T extends { [key: string]: RecursiveVerbiageObject }\n>(\n verbiage: T | undefined,\n fallbacks: { [K in keyof T]: string }\n): { [K in keyof T]: string } {\n const { t, i18n } = useTranslation()\n\n return useMemo(\n () => ({\n ...verbiage,\n ...Object.keys(fallbacks).reduce(\n (result, key) => ({\n ...result,\n [key as keyof T]: evaluateVerbiage(\n t,\n i18n.language,\n verbiage?.[key] as CustomerSuppliedVerbiage,\n fallbacks[key]\n ),\n }),\n {} as { [K in keyof T]: string }\n ),\n }),\n [fallbacks, i18n.language, t, verbiage]\n )\n}\n","import styled from 'styled-components'\n\nexport type GuidanceMessageVariant = 'default' | 'positive' | 'negative'\n\nexport const GuidanceMessageContainer = styled.div<{ $top?: string }>`\n position: absolute;\n top: calc(${({ $top }) => $top ?? '10vh'});\n font-weight: bold;\n width: 100%;\n display: flex;\n`\n\nexport const GuidanceMessage = styled.div<{\n $background?: string\n $textColor?: string\n $variant?: GuidanceMessageVariant\n}>`\n margin-left: auto;\n margin-right: auto;\n background: ${(props) =>\n props.$background ??\n props.theme?.guidanceMessages?.[props.$variant ?? 'default']\n ?.backgroundColor ??\n '#ccc'};\n color: ${(props) =>\n props.$textColor ??\n props.theme?.guidanceMessages?.[props.$variant ?? 'default']?.textColor ??\n 'black'};\n padding: 10px 12px 8px;\n border-radius: 8px;\n z-index: 10001;\n`\n","import React, {\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport useResizeObserver from 'use-resize-observer'\nimport {\n DocumentCaptureGuideOverlay,\n DocumentCaptureGuideOverlayClassNames,\n} from './DocumentCaptureGuideOverlay'\nimport {\n DetectedObject,\n DocumentType,\n} from '../../lib/models/DocumentDetection'\nimport { PDF417DetectionResult } from '../../lib/barcode/Native'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport {\n scanBarcode,\n supportsNativeBarcodeScanning,\n} from '../../lib/barcode/Scan'\nimport { getBlobDimensions } from '../../lib/utils/getBlobDimensions'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { CaptureAttemptMetadata } from '../../contexts/SubmissionContext'\nimport { PageContainer } from '../common/Page'\nimport {\n IdCaptureModelsContext,\n IdCapturePrediction,\n} from './IdCaptureModelsProvider'\nimport {\n DebugStatsPane,\n IdCaptureDetectedObjectDebugBox,\n ObjectDetectionDebugOverlay,\n useDebugScalingDetails,\n} from '../common/debug'\nimport { ExitCaptureButton } from '../common/ExitCaptureButton'\nimport {\n IdCaptureImagePreview,\n IdCaptureImagePreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport {\n GuidanceMessage,\n GuidanceMessageContainer,\n} from '../common/GuidanceMessage'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { useTheme } from 'styled-components'\n\ntype State = {\n videoWidth: number\n videoHeight: number\n captureStartedAt: Date | null\n\n detectedObjects: DetectedObject[]\n bestDocument: DetectedObject | undefined\n bestMrz: DetectedObject | undefined\n bestPdf417: DetectedObject | undefined\n\n documentType: DocumentType\n requiredDocumentType?: DocumentType\n documentInBounds: boolean\n documentDetectionScore: number\n documentDetectionThresholdMet: boolean\n\n mrzDetectionScore: number\n mrzDetectionThresholdMet: boolean\n\n passportPageDetectionScore: number\n passportPageDetectionThresholdMet: boolean\n\n focusScore: number\n focusThresholdMet: boolean\n\n pdf417DetectionScore: number\n pdf417DetectionThresholdMet: boolean\n\n barcodeScanningEnabled: boolean\n barcodeResult: PDF417DetectionResult | null\n waitingForBarcodeScan: boolean\n shouldScanBarcode: boolean\n autoCaptureBarcodeRequired: boolean | 'mobile'\n barcodeScanFailedAttempts: number\n maxBarcodeScanAttempts: number\n\n isGoodFrame: boolean\n goodFramesCount: number\n goodFramesThreshold: number\n goodFramesThresholdMet: boolean\n\n lastFrameCapturedAt: Date | null\n frameCaptureRate: number\n\n capturing: boolean\n captured: boolean\n captureFailed: boolean\n}\n\nconst initialState: State = {\n videoWidth: 0,\n videoHeight: 0,\n captureStartedAt: null,\n\n detectedObjects: [],\n bestDocument: undefined,\n bestMrz: undefined,\n bestPdf417: undefined,\n\n documentType: DocumentType.NONE,\n documentInBounds: false,\n\n documentDetectionScore: 0,\n documentDetectionThresholdMet: false,\n passportPageDetectionScore: 0,\n passportPageDetectionThresholdMet: false,\n mrzDetectionScore: 0,\n mrzDetectionThresholdMet: false,\n pdf417DetectionScore: 0,\n pdf417DetectionThresholdMet: false,\n focusScore: 0,\n focusThresholdMet: false,\n\n barcodeScanningEnabled: false,\n barcodeResult: null,\n waitingForBarcodeScan: false,\n shouldScanBarcode: false,\n autoCaptureBarcodeRequired: 'mobile',\n barcodeScanFailedAttempts: 0,\n maxBarcodeScanAttempts: 10,\n\n isGoodFrame: false,\n goodFramesCount: 0,\n goodFramesThreshold: 3,\n goodFramesThresholdMet: false,\n\n lastFrameCapturedAt: null,\n frameCaptureRate: 0,\n\n capturing: false,\n captured: false,\n captureFailed: false,\n}\n\ntype Action =\n | {\n type: 'configure'\n payload: {\n requiredDocumentType?: DocumentType\n goodFramesThreshold: number\n autoCaptureBarcodeRequired: boolean | 'mobile'\n barcodeScanningEnabled: boolean\n maxBarcodeScanAttempts: number\n }\n }\n | {\n type: 'objectsDetected'\n payload: { prediction: IdCapturePrediction }\n }\n | {\n type: 'barcodeScanned'\n payload: { result: PDF417DetectionResult }\n }\n | { type: 'barcodeScanFailed' }\n | { type: 'capturing' }\n | { type: 'captured' }\n | { type: 'captureFailed' }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'configure':\n return {\n ...state,\n ...action.payload,\n goodFramesCount: 0,\n captureStartedAt: new Date(),\n capturing: false,\n captured: false,\n captureFailed: false,\n }\n\n case 'objectsDetected':\n const {\n prediction: {\n detectedObjects,\n detectionScore,\n detectionThresholdMet,\n detectedDocumentType,\n passportDetectionScore,\n passportDetectionThresholdMet,\n mrzDetectionScore,\n mrzDetectionThresholdMet,\n pdf417DetectionScore,\n pdf417DetectionThresholdMet,\n bestDocumentOrPassport,\n bestMrz,\n bestPdf417,\n focusScore,\n focusThresholdMet,\n frameWidth,\n frameHeight,\n },\n } = action.payload\n\n const frameCapturedAt = new Date()\n let frameCaptureRate = 0\n let goodFramesThreshold = state.goodFramesThreshold\n if (state.lastFrameCapturedAt) {\n frameCaptureRate =\n 1000.0 /\n (frameCapturedAt.getTime() - state.lastFrameCapturedAt.getTime())\n\n if (frameCaptureRate > 0) {\n goodFramesThreshold = Math.ceil(3 * frameCaptureRate)\n }\n }\n\n let documentInBounds = false\n if (bestDocumentOrPassport) {\n const boundaryPx = 20\n let [boundaryX, boundaryY, boundaryWidth, boundaryHeight] =\n bestDocumentOrPassport.bbox\n boundaryX *= frameWidth\n boundaryWidth *= frameWidth\n boundaryY *= frameHeight\n boundaryHeight *= frameHeight\n\n documentInBounds =\n boundaryY > boundaryPx && // Is it valid top edge of ID detected?\n boundaryY + boundaryHeight + boundaryPx < frameHeight && // Is it valid bottom edge less than max video height\n (boundaryX > boundaryPx ||\n (boundaryX < boundaryPx &&\n boundaryX + boundaryWidth > frameWidth * 0.8)) && // If either the left side visible or if not, right edge of ID should be more than 80% of width.\n boundaryX + boundaryWidth + boundaryPx < frameWidth // Valid right edge if it's less than video width.\n }\n\n const barcodeScanRequired =\n state.autoCaptureBarcodeRequired === true ||\n (state.autoCaptureBarcodeRequired === 'mobile' && isMobile())\n const shouldScanBarcode =\n state.barcodeScanningEnabled &&\n pdf417DetectionThresholdMet &&\n barcodeScanRequired\n const waitingForBarcodeScan = shouldScanBarcode && !state.barcodeResult\n\n const isGoodFrame =\n detectionThresholdMet && documentInBounds && focusThresholdMet\n\n let goodFramesCount = state.goodFramesCount\n if (isGoodFrame) {\n goodFramesCount += 1\n }\n\n return {\n ...state,\n\n videoWidth: frameWidth,\n videoHeight: frameHeight,\n\n detectedObjects,\n bestDocument: bestDocumentOrPassport,\n bestMrz,\n bestPdf417,\n\n documentType: detectedDocumentType,\n documentInBounds,\n documentDetectionScore: detectionScore,\n documentDetectionThresholdMet: detectionThresholdMet,\n\n mrzDetectionScore,\n mrzDetectionThresholdMet,\n\n pdf417DetectionScore,\n pdf417DetectionThresholdMet,\n\n passportPageDetectionScore: passportDetectionScore,\n passportPageDetectionThresholdMet: passportDetectionThresholdMet,\n\n focusScore,\n focusThresholdMet,\n\n shouldScanBarcode,\n waitingForBarcodeScan,\n\n isGoodFrame,\n goodFramesCount,\n goodFramesThreshold,\n goodFramesThresholdMet: goodFramesCount >= goodFramesThreshold,\n\n lastFrameCapturedAt: frameCapturedAt,\n frameCaptureRate,\n }\n\n case 'barcodeScanned':\n return {\n ...state,\n barcodeResult: action.payload.result,\n waitingForBarcodeScan: false,\n autoCaptureBarcodeRequired: false,\n }\n\n case 'barcodeScanFailed': {\n const newState = {\n ...state,\n barcodeScanFailedAttempts: state.barcodeScanFailedAttempts + 1,\n }\n\n if (\n newState.barcodeScanFailedAttempts >= newState.maxBarcodeScanAttempts\n ) {\n newState.autoCaptureBarcodeRequired = false\n newState.shouldScanBarcode = false\n newState.waitingForBarcodeScan = false\n }\n\n return newState\n }\n\n case 'capturing':\n return {\n ...state,\n capturing: true,\n captured: false,\n captureFailed: false,\n }\n\n case 'captured':\n return {\n ...state,\n capturing: false,\n captured: true,\n captureFailed: false,\n }\n\n case 'captureFailed':\n return {\n ...state,\n capturing: false,\n captured: false,\n captureFailed: true,\n }\n\n default:\n return state\n }\n}\n\nexport type IdCaptureAssets = {\n portraitGuidesImageUrl?: string\n landscapeGuidesImageUrl?: string\n}\n\nexport type IdCaptureClassNames = {\n container?: string\n guides?: DocumentCaptureGuideOverlayClassNames\n guidanceMessageContainer?: string\n guidanceMessage?: string\n imagePreview?: IdCaptureImagePreviewClassNames\n exitCaptureBtn?: string\n}\n\nexport type IdCaptureColors = {\n guideBoxUnsatisfiedColor?: string\n guideBoxSatisfiedColor?: string\n guidanceMessagesSatisfiedBackgroundColor?: string\n guidanceMessagesUnsatisfiedBackgroundColor?: string\n guidanceMessagesSatisfiedTextColor?: string\n guidanceMessagesUnsatisfiedTextColor?: string\n}\n\nexport type IdCaptureVerbiage = {\n instructionText?: CustomerSuppliedVerbiage\n processingIdCardText?: CustomerSuppliedVerbiage\n capturingText?: CustomerSuppliedVerbiage\n captureFailedText?: CustomerSuppliedVerbiage\n guidanceSatisfiedText?: CustomerSuppliedVerbiage\n guidanceTooBlurryText?: CustomerSuppliedVerbiage\n guidanceNotCenteredText?: CustomerSuppliedVerbiage\n guidanceNotDetectedText?: CustomerSuppliedVerbiage\n}\n\nexport type IdCaptureProps = {\n requiredDocumentType?: DocumentType\n autoCaptureEnabled?: boolean\n autoCaptureScoreThreshold?: number\n autoCaptureGoodFramesRequired?: number\n autoCaptureBarcodeRequired?: boolean | 'mobile'\n mrzDetectionScoreThreshold?: number\n passportPageDetectionThreshold?: number\n pdf417DetectionThreshold?: number\n\n barcodeScanningEnabled?: boolean\n maxBarcodeScanAttempts?: number\n\n focusScoreThreshold?: number\n\n guidanceMessage?: string\n guidanceSatisfied?: boolean\n\n onPrediction?: (prediction: IdCapturePrediction) => void\n onBarcodeScanned?: (result: PDF417DetectionResult) => void\n onCapture?: (\n frame: string,\n width: number,\n height: number,\n metadata: CaptureAttemptMetadata\n ) => void\n onExit?: () => void\n\n processingScreen?: React.ReactElement\n processingDelay?: number\n\n assets?: IdCaptureAssets\n classNames?: IdCaptureClassNames\n colors?: IdCaptureColors\n verbiage?: IdCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const IdCapture = ({\n requiredDocumentType,\n autoCaptureEnabled = true,\n autoCaptureScoreThreshold = 0.8,\n autoCaptureGoodFramesRequired = 3,\n autoCaptureBarcodeRequired = 'mobile',\n mrzDetectionScoreThreshold = 0.25,\n passportPageDetectionThreshold = 0.6,\n pdf417DetectionThreshold = 0.15,\n focusScoreThreshold = 0.3,\n barcodeScanningEnabled = true,\n maxBarcodeScanAttempts = 10,\n guidanceMessage,\n guidanceSatisfied,\n onPrediction,\n onBarcodeScanned,\n onCapture,\n onExit,\n processingScreen,\n processingDelay = 0,\n assets = {},\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: IdCaptureProps): React.ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const [state, dispatch] = useReducer(reducer, initialState)\n const [imageURL, setImageURL] = useState<string>('')\n const [processingFrame, setProcessingFrame] = useState(false)\n const { cameraRef, cameraReady, takePhoto, videoRef, videoLoaded } =\n useContext(CameraStateContext)\n const captureStartedAt = useRef<Date>()\n const {\n ready: modelsReady,\n working: modelsWorking,\n setThresholds,\n makePrediction,\n onPredictionMade,\n detectionTime,\n focusPredictionTime,\n getBestFrame,\n resetBestFrame,\n } = useContext(IdCaptureModelsContext)\n\n useEffect(() => {\n captureStartedAt.current = new Date()\n }, [])\n\n useEffect(() => {\n dispatch({\n type: 'configure',\n payload: {\n requiredDocumentType,\n goodFramesThreshold: autoCaptureGoodFramesRequired,\n autoCaptureBarcodeRequired,\n barcodeScanningEnabled,\n maxBarcodeScanAttempts,\n },\n })\n\n resetBestFrame()\n setThresholds({\n document: autoCaptureScoreThreshold,\n passport: passportPageDetectionThreshold,\n mrz: mrzDetectionScoreThreshold,\n pdf417: pdf417DetectionThreshold,\n focus: focusScoreThreshold,\n })\n }, [\n requiredDocumentType,\n autoCaptureScoreThreshold,\n focusScoreThreshold,\n mrzDetectionScoreThreshold,\n autoCaptureGoodFramesRequired,\n autoCaptureBarcodeRequired,\n barcodeScanningEnabled,\n maxBarcodeScanAttempts,\n passportPageDetectionThreshold,\n pdf417DetectionThreshold,\n resetBestFrame,\n setThresholds,\n ])\n\n const animationFrame = useRef(0)\n const shouldCaptureFrames = useRef(false)\n\n useEffect(() => {\n shouldCaptureFrames.current =\n videoLoaded &&\n cameraReady &&\n modelsReady &&\n !state.capturing &&\n !state.captured\n }, [cameraReady, state.captured, state.capturing, modelsReady, videoLoaded])\n\n const [lastFrame, setLastFrame] = useState<Blob | null>(null)\n\n useEffect(() => {\n if (!modelsReady || !cameraReady || !videoLoaded) return\n\n animationFrame.current = requestAnimationFrame(async function runFrame() {\n if (shouldCaptureFrames.current && !modelsWorking.current) {\n try {\n if (state.shouldScanBarcode) {\n const frame = await takePhoto()\n if (!frame) {\n animationFrame.current = requestAnimationFrame(runFrame)\n return\n }\n setLastFrame(frame)\n }\n\n if (videoRef.current) makePrediction(videoRef.current)\n } catch (e) {\n console.error('error capturing frame', e)\n }\n }\n\n animationFrame.current = requestAnimationFrame(runFrame)\n })\n\n return () => {\n cancelAnimationFrame(animationFrame.current)\n }\n }, [\n cameraReady,\n makePrediction,\n modelsReady,\n modelsWorking,\n state.shouldScanBarcode,\n takePhoto,\n videoLoaded,\n videoRef,\n ])\n\n useEffect(() => {\n onPredictionMade((prediction) => {\n dispatch({ type: 'objectsDetected', payload: { prediction } })\n onPrediction?.(prediction)\n })\n }, [onPrediction, onPredictionMade])\n\n useEffect(() => {\n ;(async () => {\n if (state.shouldScanBarcode && lastFrame) {\n const result = await scanBarcode(lastFrame, state.bestPdf417?.bbox)\n if (result) {\n dispatch({ type: 'barcodeScanned', payload: { result } })\n onBarcodeScanned?.(result)\n } else {\n dispatch({ type: 'barcodeScanFailed' })\n }\n }\n })()\n }, [\n onBarcodeScanned,\n state.shouldScanBarcode,\n state.bestPdf417?.bbox,\n takePhoto,\n lastFrame,\n ])\n\n const shouldCapture =\n autoCaptureEnabled &&\n state.goodFramesThresholdMet &&\n !state.capturing &&\n !state.captured &&\n !state.waitingForBarcodeScan &&\n timeSince(state.captureStartedAt) >= 3000\n\n useEffect(() => {\n ;(async () => {\n if (!shouldCapture) return\n\n dispatch({ type: 'capturing' })\n\n const photo = await getBestFrame()\n if (!photo) {\n console.log('uh oh, i did not get a photo')\n dispatch({ type: 'captureFailed' })\n return\n }\n setProcessingFrame(true)\n\n const [width, height] = await getBlobDimensions(photo)\n // const canvas = new OffscreenCanvas(width, height)\n const canvas = document.createElement('canvas')\n canvas.width = width\n canvas.height = height\n\n const bitmap = await createImageBitmap(photo)\n\n // resize image to 2k max if barcode is read\n const isGreaterThan2k =\n (width > 1920 && height > 1080) || (width > 1080 && height > 1920)\n if (isGreaterThan2k && !!state.barcodeResult) {\n if (width > height) {\n canvas.width = 1920\n canvas.height = height * (1920 / width)\n } else {\n canvas.height = 1920\n canvas.width = width * (1920 / height)\n }\n const ctx2d = canvas.getContext('2d')\n if (!ctx2d) return\n ctx2d.drawImage(bitmap, 0, 0, canvas.width, canvas.height)\n } else {\n const bmpCtx = canvas.getContext('bitmaprenderer')\n if (!bmpCtx) return\n bmpCtx.transferFromImageBitmap(bitmap)\n }\n\n const imageURL = canvas.toDataURL('image/jpeg', 0.92)\n setImageURL(imageURL)\n\n setTimeout(() => {\n const captureTime =\n new Date().getTime() -\n (captureStartedAt.current ?? new Date()).getTime()\n const metadata: CaptureAttemptMetadata = {\n autoCapture: 'Y',\n captureTime,\n }\n onCapture?.(imageURL, width, height, metadata)\n dispatch({ type: 'captured' })\n setProcessingFrame(false)\n }, processingDelay)\n })()\n }, [\n getBestFrame,\n onCapture,\n processingDelay,\n shouldCapture,\n state.barcodeResult,\n ])\n\n assets.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Portrait-2.svg`\n assets.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n\n const theme = useTheme()\n colors.guideBoxUnsatisfiedColor ||=\n theme.idCapture?.guideBox?.unsatisfiedColor ?? 'white'\n colors.guideBoxSatisfiedColor ||=\n theme.idCapture?.guideBox?.satisfiedColor ?? 'green'\n\n const verbiage = useTranslations(rawVerbiage, {\n instructionText: 'Scan the front of ID',\n processingIdCardText: 'ID card front captured.',\n capturingText: 'Capturing...',\n captureFailedText: 'Capture failed!',\n guidanceSatisfiedText: 'Document detected, hold still...',\n guidanceTooBlurryText: 'Document out of focus – try improving the lighting',\n guidanceNotCenteredText: 'Document is not centered',\n guidanceNotDetectedText: 'Document not detected',\n })\n\n const debugScalingDetails = useDebugScalingDetails({\n enabled: debugMode,\n pageWidth: width,\n pageHeight: height,\n videoWidth: state.videoWidth,\n videoHeight: state.videoHeight,\n })\n\n let satisfied = state.isGoodFrame\n if (typeof guidanceSatisfied === 'boolean') satisfied = guidanceSatisfied\n\n guidanceMessage ||= satisfied\n ? verbiage.guidanceSatisfiedText\n : !state.documentDetectionThresholdMet\n ? verbiage.guidanceNotDetectedText\n : !state.documentInBounds\n ? verbiage.guidanceNotCenteredText\n : !state.focusThresholdMet\n ? verbiage.guidanceTooBlurryText\n : ''\n\n if (processingFrame) {\n return (\n <>\n {processingScreen}\n {imageURL && (\n <IdCaptureImagePreview\n classNames={classNames.imagePreview}\n text={verbiage.processingIdCardText}\n imageUrl={imageURL}\n />\n )}\n </>\n )\n }\n\n if (imageURL !== '') {\n return (\n <img\n src={imageURL}\n alt=\"\"\n style={{ maxWidth: '100%', maxHeight: '100%' }}\n />\n )\n }\n\n return (\n <PageContainer ref={ref} className={`flex ${classNames.container ?? ''}`}>\n <DocumentCaptureGuideOverlay\n classNames={classNames.guides}\n width={width}\n height={height}\n instruction={\n state.captureFailed\n ? verbiage.captureFailedText\n : state.capturing\n ? verbiage?.capturingText\n : verbiage.instructionText\n }\n portraitGuidesImageUrl={assets.portraitGuidesImageUrl}\n landscapeGuidesImageUrl={assets.landscapeGuidesImageUrl}\n isMirrored={!cameraRef.current?.isRearFacing}\n borderColor={\n state.isGoodFrame\n ? colors.guideBoxSatisfiedColor\n : colors.guideBoxUnsatisfiedColor\n }\n />\n\n {guidanceMessage !== '' && (\n <GuidanceMessageContainer\n $top=\"82.5vh\"\n className={classNames.guidanceMessageContainer}\n >\n <GuidanceMessage\n $variant={satisfied ? 'positive' : 'default'}\n className={classNames.guidanceMessage}\n >\n {guidanceMessage}\n </GuidanceMessage>\n </GuidanceMessageContainer>\n )}\n\n {debugMode && state.detectedObjects.length > 0 && (\n <ObjectDetectionDebugOverlay $flipX={!cameraRef.current?.isRearFacing}>\n {state.detectedObjects.map((obj, i) => (\n <IdCaptureDetectedObjectDebugBox\n key={i}\n obj={obj}\n scaling={debugScalingDetails}\n flipX={!cameraRef.current?.isRearFacing}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n )}\n\n {debugMode && (\n <DebugStatsPane>\n {cameraRef.current ? (\n <>\n ✅ Camera: {cameraRef.current.label} ({cameraRef.current.width}x\n {cameraRef.current.height})\n </>\n ) : (\n '❌ Camera not ready'\n )}\n <br />\n {state.frameCaptureRate > 0.75 ? '✅' : '👎'} Frame Rate:{' '}\n {Math.round((state.frameCaptureRate + Number.EPSILON) * 1000) / 1000}{' '}\n fps ({detectionTime}ms doc detect, {focusPredictionTime}ms focus)\n <br />\n {modelsReady ? (\n <>\n {state.documentDetectionThresholdMet ? '✅' : '❌'} Document\n Score: {state.documentDetectionScore} ({state.documentType})\n <br />\n {state.documentInBounds ? '✅' : '❌'} Document In Bounds\n <br />\n {state.focusThresholdMet ? '✅' : '❌'} Focus Score:{' '}\n {state.focusScore}\n <br />\n {state.goodFramesThresholdMet ? '✅' : '❌'} Good Frame Count:{' '}\n {state.goodFramesCount}/{state.goodFramesThreshold}\n {barcodeScanningEnabled && state.autoCaptureBarcodeRequired ? (\n <>\n <br />\n {state.barcodeResult ? '✅' : '❌'} Barcode Scanned (\n {supportsNativeBarcodeScanning() ? 'Native' : 'ZXing'},{' '}\n {state.barcodeScanFailedAttempts}/\n {state.maxBarcodeScanAttempts} failed attempts)\n </>\n ) : null}\n </>\n ) : (\n <>❌ Models not ready</>\n )}\n </DebugStatsPane>\n )}\n\n <ExitCaptureButton\n onClick={onExit}\n className={classNames.exitCaptureBtn}\n />\n </PageContainer>\n )\n}\n\nconst timeSince = (t: Date | null): number => {\n if (!t) return 0\n return Math.abs(new Date().getTime() - t.getTime())\n}\n","import React, { ReactElement, useContext, useEffect, useState } from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n OverlayContainer,\n OverlayImageContainer,\n OverlayInner,\n} from '../common/overlay'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport {\n CameraAccessDeniedOverlay,\n CameraAccessDeniedOverlayAssets,\n CameraAccessDeniedOverlayClassNames,\n CameraAccessDeniedOverlayColors,\n CameraAccessDeniedOverlayVerbiage,\n} from '../camera/CameraAccessDeniedOverlay'\nimport { IdCaptureModelsContext } from './IdCaptureModelsProvider'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport styled from 'styled-components'\n\nconst ContinuityCameraCheckboxContainer = styled.div`\n height: 48px;\n margin-top: -48px;\n margin-bottom: 8px;\n padding-top: 26px;\n`\n\nconst ContinuityCameraCheckbox = styled.input`\n margin-right: 8px;\n`\n\nexport type IdCaptureLoadingOverlayAssets = {\n instructionImageUrl?: string\n cameraAccessDenied?: CameraAccessDeniedOverlayAssets\n}\n\nexport type IdCaptureLoadingOverlayClassNames = {\n container?: string\n inner?: string\n heading?: string\n imageContainer?: string\n image?: string\n continuityCameraCheckboxContainer?: string\n continuityCameraCheckboxLabel?: string\n continuityCameraCheckbox?: string\n continueBtn?: string\n cameraAccessDenied?: CameraAccessDeniedOverlayClassNames\n}\n\nexport type IdCaptureLoadingOverlayColors = {\n continueBtn?: LoaderButtonColors\n cameraAccessDenied?: CameraAccessDeniedOverlayColors\n}\n\nexport type IdCaptureLoadingOverlayVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n useContinuityCameraText?: CustomerSuppliedVerbiage\n modelsWarmingUpText?: CustomerSuppliedVerbiage\n cameraInitializingText?: CustomerSuppliedVerbiage\n continueText?: CustomerSuppliedVerbiage\n cameraAccessDenied?: CameraAccessDeniedOverlayVerbiage\n}\n\nexport type IdCaptureLoadingOverlayProps = {\n onDismissed?: () => void\n\n assets?: IdCaptureLoadingOverlayAssets\n classNames?: IdCaptureLoadingOverlayClassNames\n colors?: IdCaptureLoadingOverlayColors\n verbiage?: IdCaptureLoadingOverlayVerbiage\n}\n\nexport const IdCaptureLoadingOverlay = ({\n onDismissed,\n assets = {},\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n}: IdCaptureLoadingOverlayProps): ReactElement => {\n const { ready: modelsReady } = useContext(IdCaptureModelsContext)\n const {\n cameraReady,\n cameraAccessDenied,\n iphoneContinuityCameraAvailable,\n setIphoneContinuityCameraAllowed,\n } = useContext(CameraStateContext)\n const [dismissed, setDismissed] = useState(false)\n\n assets.instructionImageUrl ||= `${DEFAULT_CDN_URL}/WebSDK-Instruction-DL-Capture-3-Portrait.png`\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: 'Use your device camera to capture your ID',\n useContinuityCameraText: 'Use your iPhone as a webcam',\n modelsWarmingUpText: 'Models warming up...',\n cameraInitializingText: 'Camera initializing...',\n continueText: 'Continue',\n })\n\n useEffect(() => {\n if (modelsReady && cameraReady) return () => null\n\n const t = setTimeout(() => {\n setDismissed(false)\n }, 500)\n\n return () => {\n clearTimeout(t)\n }\n }, [cameraReady, modelsReady])\n\n if (dismissed) return <></>\n if (cameraAccessDenied) {\n return (\n <CameraAccessDeniedOverlay\n assets={assets.cameraAccessDenied}\n classNames={classNames.cameraAccessDenied}\n colors={colors.cameraAccessDenied}\n verbiage={rawVerbiage.cameraAccessDenied}\n />\n )\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <OverlayInner className={classNames.inner}>\n <h3 className={classNames.heading}>{verbiage.headingText}</h3>\n\n <OverlayImageContainer\n className={classNames.imageContainer}\n style={{ pointerEvents: 'none' }}\n >\n <img\n alt={verbiage.headingText}\n src={assets.instructionImageUrl}\n className={classNames.image}\n />\n </OverlayImageContainer>\n\n <ContinuityCameraCheckboxContainer\n className={classNames.continuityCameraCheckboxContainer}\n >\n {iphoneContinuityCameraAvailable && (\n <>\n <ContinuityCameraCheckbox\n className={classNames.continuityCameraCheckbox}\n id=\"use-continuity-camera\"\n type=\"checkbox\"\n defaultChecked={true}\n onChange={(e) => {\n setIphoneContinuityCameraAllowed(e.target.checked)\n }}\n />\n <label\n htmlFor=\"use-continuity-camera\"\n className={classNames.continuityCameraCheckboxLabel}\n >\n {verbiage.useContinuityCameraText}\n </label>\n </>\n )}\n </ContinuityCameraCheckboxContainer>\n\n <LoaderButton\n className={classNames.continueBtn}\n variant=\"positive\"\n disabled={!cameraReady || !modelsReady}\n finished={modelsReady && cameraReady}\n colors={colors.continueBtn}\n onClick={() => {\n setDismissed(true)\n onDismissed?.()\n }}\n >\n {cameraReady && modelsReady\n ? verbiage.continueText\n : modelsReady\n ? verbiage.cameraInitializingText\n : verbiage.modelsWarmingUpText}\n </LoaderButton>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React, { ReactElement, useContext, useEffect, useState } from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport useResizeObserver from 'use-resize-observer'\nimport { GuideOrientationContext } from '../../contexts/GuideOrientationContext'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport { PageContainer } from '../common/Page'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\nimport {\n GuideCenterBorder,\n GuideCenterRow,\n GuideImage,\n GuideRegion,\n GuidesContainer,\n GuideText,\n} from './DocumentCaptureGuideOverlay'\nimport styled from 'styled-components'\n\nconst FlippingImage = styled(GuideImage)<{\n $transitionTime?: number\n $transforms?: string\n}>`\n backface-visibility: hidden;\n transform-style: preserve-3d;\n position: relative;\n top: 0;\n left: 0;\n transition: transform ${(props) => props.$transitionTime}s;\n transform: ${(props) => props.$transforms};\n`\n\nconst FlippingImageBack = styled(FlippingImage)`\n position: absolute;\n`\n\nexport type FlipIdPromptAssets = {\n frontPortraitGuidesImageUrl?: string\n frontLandscapeGuidesImageUrl?: string\n backPortraitGuidesImageUrl?: string\n backLandscapeGuidesImageUrl?: string\n}\n\nexport type FlipIdPromptClassNames = {\n container?: string\n inner?: string\n dimmingRegion?: string\n dimmingRegionTop?: string\n dimmingRegionLeft?: string\n dimmingRegionRight?: string\n dimmingRegionBottom?: string\n centerRow?: string\n centerRegion?: string\n image?: string\n guideText?: string\n}\n\nexport type FlipIdPromptVerbiage = {\n instructionText?: CustomerSuppliedVerbiage\n}\n\nexport type FlipIdPromptProps = {\n assets?: FlipIdPromptAssets\n classNames?: FlipIdPromptClassNames\n verbiage?: FlipIdPromptVerbiage\n}\n\nexport const FlipIdPrompt = ({\n assets = {},\n classNames = {},\n verbiage = {},\n}: FlipIdPromptProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const { cameraRef } = useContext(CameraStateContext)\n\n assets.frontPortraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Portrait-2.svg`\n assets.frontLandscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.backPortraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Portrait-2.svg`\n assets.backLandscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n\n const instruction = useVerbiage(\n verbiage.instructionText,\n 'Please flip your ID card...'\n )\n\n const padding = isMobile() ? 0 : 50\n const borderWidth = 4\n const borderColor = 'white'\n const isMirrored = !cameraRef.current?.isRearFacing\n\n const {\n orientation,\n wrapperRef,\n wrapperWidth,\n wrapperHeight,\n imageAspectRatio,\n wrapperAspectRatio,\n onImageLoaded,\n setDimensions,\n } = useContext(GuideOrientationContext)\n\n useEffect(() => {\n setDimensions({ width, height })\n }, [height, setDimensions, width])\n\n const paddingAndBorderPx = padding * 2 + borderWidth * 2\n\n let imageWidth: number | undefined = undefined,\n imageHeight: number | undefined = undefined\n if (imageAspectRatio >= wrapperAspectRatio) {\n imageWidth = wrapperWidth - paddingAndBorderPx\n } else {\n imageHeight = wrapperHeight - paddingAndBorderPx\n }\n\n const [transitionTime, setTransitionTime] = useState(1)\n const [rotationAngle, setRotationAngle] = useState(0)\n const frontTransforms = [`rotateY(${rotationAngle}deg)`]\n if (isMirrored) frontTransforms.push('scaleX(-1)')\n const backTransforms = [`rotateY(${180 - rotationAngle}deg)`]\n if (isMirrored) backTransforms.push('scaleX(-1)')\n\n useEffect(() => {\n const doFlip = () => {\n setTransitionTime(1)\n setRotationAngle(180)\n\n setTimeout(() => {\n setTransitionTime(0)\n setRotationAngle(0)\n }, 1500)\n }\n\n setTimeout(doFlip, 250)\n const interval = setInterval(doFlip, 2500)\n\n return () => {\n clearInterval(interval)\n }\n }, [])\n\n return (\n <PageContainer ref={ref} className={`flex ${classNames.container ?? ''}`}>\n <GuidesContainer ref={wrapperRef} className={classNames.inner}>\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Top')}\n >\n {instruction !== '' && (\n <GuideText className={classNames.guideText}>\n {instruction}\n </GuideText>\n )}\n </GuideRegion>\n\n <GuideCenterRow className={classNames.centerRow}>\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Left')}\n />\n\n <GuideCenterBorder\n $borderWidth={borderWidth}\n $borderColor={borderColor}\n className={classNames.centerRegion}\n >\n <FlippingImage\n src={\n orientation === 'portrait'\n ? assets.frontPortraitGuidesImageUrl\n : assets.frontLandscapeGuidesImageUrl\n }\n alt=\"\"\n className={classNames.image}\n $width={imageWidth}\n $height={imageHeight}\n $transitionTime={transitionTime}\n $transforms={frontTransforms.join(' ')}\n onLoad={onImageLoaded}\n />\n\n <FlippingImageBack\n src={\n orientation === 'portrait'\n ? assets.backPortraitGuidesImageUrl\n : assets.backLandscapeGuidesImageUrl\n }\n alt=\"\"\n className={classNames.image}\n $width={imageWidth}\n $height={imageHeight}\n $transitionTime={transitionTime}\n $transforms={backTransforms.join(' ')}\n />\n </GuideCenterBorder>\n\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Right')}\n />\n </GuideCenterRow>\n\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Bottom')}\n >\n {instruction !== '' && (\n <GuideText style={{ opacity: 0 }}>{instruction}</GuideText>\n )}\n </GuideRegion>\n </GuidesContainer>\n </PageContainer>\n )\n}\n\nconst regionClsx = (\n classNames: FlipIdPromptClassNames,\n which: 'Top' | 'Left' | 'Right' | 'Bottom'\n): string =>\n [classNames.dimmingRegion, classNames[`dimmingRegion${which}`]]\n .filter((v) => v)\n .join(' ')\n","import styled from 'styled-components'\n\nexport const ButtonsRow = styled.div`\n display: flex;\n gap: 0 15px;\n justify-content: center;\n`\n","import React, { ReactElement, useCallback, useContext, useEffect } from 'react'\nimport styled from 'styled-components'\nimport { CameraStateContext } from './CameraProvider'\n\nexport const CameraVideoTag = ({\n className,\n}: {\n className?: string\n}): ReactElement => {\n const { videoRef, setVideoLoaded, cameraRef } = useContext(CameraStateContext)\n\n useEffect(() => {\n setVideoLoaded(false)\n }, [setVideoLoaded])\n\n useEffect(() => {\n if (videoRef.current && cameraRef.current?.stream) {\n videoRef.current.srcObject = cameraRef.current.stream\n }\n }, [cameraRef, videoRef])\n\n const onLoadedData = useCallback(() => {\n setVideoLoaded(true)\n }, [setVideoLoaded])\n\n return (\n <FullscreenVideoTag\n className={className}\n autoPlay\n playsInline\n muted\n ref={videoRef}\n onLoadedData={onLoadedData}\n $isRearFacing={cameraRef.current?.isRearFacing}\n />\n )\n}\n\nexport const FullscreenVideoTag = styled.video<{ $isRearFacing?: boolean }>`\n transform: ${(props) => (props.$isRearFacing ? '' : 'scaleX(-1)')};\n min-width: 100%;\n min-height: 100%;\n width: auto;\n height: auto;\n object-fit: cover;\n`\n","import { useEffect, useState } from 'react'\n\nexport function useShowSuccessScreen(\n skipSuccessScreen: boolean | (() => Promise<boolean>),\n successScreenReady: boolean,\n onDoneCallback?: () => void,\n): boolean {\n const [skipSuccessScreenResolvedFalse, setSkipSuccessScreenResolvedFalse] =\n useState(false)\n\n useEffect(() => {\n if (successScreenReady && skipSuccessScreen) {\n if (typeof skipSuccessScreen === 'function') {\n ;(async () => {\n if (await skipSuccessScreen()) {\n onDoneCallback?.()\n } else {\n setSkipSuccessScreenResolvedFalse(true)\n }\n })()\n } else {\n onDoneCallback?.()\n }\n }\n }, [successScreenReady, onDoneCallback, skipSuccessScreen])\n\n return !skipSuccessScreen || skipSuccessScreenResolvedFalse\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport {\n OverlayContainer,\n OverlayImageRow,\n OverlayInner,\n} from '../common/overlay'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport styled from 'styled-components'\nimport { ButtonsRow } from '../common/ButtonsRow'\n\nexport type IdCaptureFallbackClassNames = {\n container?: string\n inner?: string\n heading?: string\n description?: string\n imageContainer?: string\n imageCol?: string\n image?: string\n instruction?: string\n buttonsRow?: string\n captureBtn?: string\n captureMoreBtn?: string\n doneBtn?: string\n}\n\nexport type IdCaptureFallbackColors = {\n captureBtn?: LoaderButtonColors\n captureMoreBtn?: LoaderButtonColors\n doneBtn?: LoaderButtonColors\n}\n\nexport type IdCaptureFallbackVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n descriptionText?: CustomerSuppliedVerbiage\n firstInstructionText?: CustomerSuppliedVerbiage\n secondInstructionText?: CustomerSuppliedVerbiage\n captureBtnText?: CustomerSuppliedVerbiage\n captureMoreBtnText?: CustomerSuppliedVerbiage\n doneBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type IdCaptureFallbackProps = {\n onCapture?: (imageData: string) => void\n onFinished?: (images: string[]) => void\n classNames?: IdCaptureFallbackClassNames\n colors?: IdCaptureFallbackColors\n verbiage?: IdCaptureFallbackVerbiage\n}\n\nexport const IdCaptureFallback = ({\n onCapture,\n onFinished,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n}: IdCaptureFallbackProps): ReactElement => {\n const fileInput = useRef<HTMLInputElement | null>(null)\n const [images, setImages] = useState<string[]>([])\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: `We're having some trouble.`,\n descriptionText:\n 'On-device capture guidance failed, please capture photos of your ID card or passport manually.',\n firstInstructionText:\n 'Please capture the front of your ID card, or the ID page of your passport.',\n secondInstructionText:\n 'Please capture the back of your ID card, or click Done if submitting a passport.',\n captureBtnText: 'Capture',\n captureMoreBtnText: 'Capture back of ID Card',\n doneBtnText: 'Done',\n })\n\n function onFileSelected(e: React.ChangeEvent<HTMLInputElement>) {\n const file = e.target.files?.[0]\n if (!file) return\n\n const reader = new FileReader()\n reader.addEventListener('load', (e) => {\n const imageData = e.target?.result as string\n setImages((images) => [...images, imageData])\n onCapture?.(imageData)\n })\n reader.readAsDataURL(file)\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <StyledOverlayInner className={classNames.inner}>\n <Heading className={classNames.heading}>{verbiage.headingText}</Heading>\n <Description className={classNames.description}>\n {verbiage.descriptionText}\n </Description>\n\n {images.length > 0 && (\n <OverlayImageRow className={classNames.imageContainer}>\n {images.map((image, i) => (\n <ImageCol key={i} className={classNames.imageCol}>\n <img src={image} alt=\"\" className={classNames.image} />\n </ImageCol>\n ))}\n </OverlayImageRow>\n )}\n\n {images.length < 2 && (\n <Instruction className={classNames.instruction}>\n {images.length === 0\n ? verbiage.firstInstructionText\n : verbiage.secondInstructionText}\n </Instruction>\n )}\n\n <input\n ref={fileInput}\n type=\"file\"\n accept=\"image/*\"\n onChange={onFileSelected}\n hidden\n />\n\n <StyledButtonsRow className={classNames.buttonsRow}>\n {images.length < 2 && (\n <LoaderButton\n variant={images.length > 0 ? 'secondary' : 'positive'}\n className={\n images.length > 0\n ? classNames.captureMoreBtn\n : classNames.captureBtn\n }\n colors={\n images.length > 0 ? colors.captureMoreBtn : colors.captureBtn\n }\n finished\n onClick={() => {\n fileInput.current?.click()\n }}\n >\n {images.length > 0\n ? verbiage.captureMoreBtnText\n : verbiage.captureBtnText}\n </LoaderButton>\n )}\n\n {images.length > 0 && (\n <LoaderButton\n variant=\"positive\"\n className={classNames.doneBtn}\n colors={colors.doneBtn}\n finished\n onClick={() => {\n onFinished?.(images)\n }}\n >\n {verbiage.doneBtnText}\n </LoaderButton>\n )}\n </StyledButtonsRow>\n </StyledOverlayInner>\n </OverlayContainer>\n )\n}\n\nconst StyledOverlayInner = styled(OverlayInner)`\n justify-content: center;\n`\n\nconst Heading = styled.h3`\n margin-bottom: 8px;\n`\n\nconst Description = styled.p`\n margin-bottom: 8px;\n`\n\nconst Instruction = styled.p`\n font-weight: bold;\n`\n\nconst ImageCol = styled.div`\n display: flex;\n justify-content: center;\n flex-grow: 1;\n flex-basis: 0;\n`\n\nconst StyledButtonsRow = styled(ButtonsRow)`\n margin-top: 32px;\n`\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport { DocumentType } from '../../lib/models/DocumentDetection'\nimport {\n IdCapture,\n IdCaptureAssets,\n IdCaptureClassNames,\n IdCaptureColors,\n IdCaptureVerbiage,\n} from './IdCapture'\nimport { PDF417DetectionResult } from '../../lib/barcode/Native'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n IdCaptureLoadingOverlay,\n IdCaptureLoadingOverlayAssets,\n IdCaptureLoadingOverlayClassNames,\n IdCaptureLoadingOverlayColors,\n IdCaptureLoadingOverlayVerbiage,\n} from './IdCaptureLoadingOverlay'\nimport {\n FlipIdPrompt,\n FlipIdPromptAssets,\n FlipIdPromptClassNames,\n FlipIdPromptVerbiage,\n} from './FlipIdPrompt'\nimport { dataUrlToBase64Sync } from '../../lib/utils/dataUrlToBase64'\nimport {\n CaptureAttemptMetadata,\n SubmissionContext,\n SubmissionStatus,\n} from '../../contexts/SubmissionContext'\nimport {\n CapturedDocument,\n CapturedDocuments,\n} from '../additional_document_capture/CapturedDocuments'\nimport {\n IdCaptureSuccess,\n IdCaptureSuccessClassNames,\n IdCaptureSuccessColors,\n IdCaptureSuccessVerbiage,\n} from './IdCaptureSuccess'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport { PageContainer } from '../common/Page'\nimport {\n IdCaptureModelsContext,\n IdCapturePrediction,\n} from './IdCaptureModelsProvider'\nimport { useShowSuccessScreen } from '../common/useShowSuccessScreen'\nimport { useTranslations } from '../../lib/locales'\nimport {\n IdCaptureFallback,\n IdCaptureFallbackClassNames,\n IdCaptureFallbackColors,\n IdCaptureFallbackVerbiage,\n} from '../fallback_flows/IdCapture'\n\nenum CaptureState {\n CAPTURING = 'CAPTURING',\n COMPLETE = 'COMPLETE',\n}\n\ntype State = {\n captureState: CaptureState\n capturedDocuments: CapturedDocuments\n requestedDocumentType: DocumentType\n currentDocumentType: DocumentType\n differentDocumentTypeDetections: number\n barcodeResult: PDF417DetectionResult | null\n}\n\nconst initialState: State = {\n captureState: CaptureState.CAPTURING,\n capturedDocuments: {},\n requestedDocumentType: DocumentType.ID_CARD_FRONT,\n currentDocumentType: DocumentType.NONE,\n differentDocumentTypeDetections: 0,\n barcodeResult: null,\n}\n\ntype Action =\n | { type: 'predictionMade'; payload: { prediction: IdCapturePrediction } }\n | { type: 'barcodeScanned'; payload: { result: PDF417DetectionResult } }\n | { type: 'imageCaptured'; payload: CapturedDocument }\n | { type: 'imageCapturedManually'; payload: { imageData: string } }\n | { type: 'reset' }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'predictionMade': {\n const { prediction } = action.payload\n const newState = {\n ...state,\n currentDocumentType: prediction.detectedDocumentType,\n }\n\n if (newState.currentDocumentType === state.requestedDocumentType) {\n newState.differentDocumentTypeDetections = 0\n }\n\n if (\n prediction.detectedDocumentType === 'PASSPORT' &&\n state.requestedDocumentType !== 'PASSPORT'\n ) {\n newState.requestedDocumentType = DocumentType.PASSPORT\n }\n\n if (\n state.requestedDocumentType === 'PASSPORT' &&\n prediction.passportDetectionScore < 0.3\n ) {\n newState.requestedDocumentType = DocumentType.ID_CARD_FRONT\n }\n\n return newState\n }\n\n case 'barcodeScanned':\n return { ...state, barcodeResult: action.payload.result }\n\n case 'imageCaptured': {\n const newState = {\n ...state,\n capturedDocuments: {\n ...state.capturedDocuments,\n [state.requestedDocumentType]: action.payload,\n },\n }\n\n if (\n state.requestedDocumentType === 'ID_CARD_FRONT' &&\n !state.capturedDocuments['ID_CARD_BACK']\n ) {\n newState.requestedDocumentType = DocumentType.ID_CARD_BACK\n } else if (\n state.requestedDocumentType === 'ID_CARD_BACK' &&\n !state.capturedDocuments['ID_CARD_FRONT']\n ) {\n newState.requestedDocumentType = DocumentType.ID_CARD_FRONT\n } else {\n newState.captureState = CaptureState.COMPLETE\n }\n\n return newState\n }\n\n case 'imageCapturedManually': {\n const newState = { ...state }\n const capturedDocument = { ...action.payload, width: 0, height: 0 }\n\n if (Object.keys(state.capturedDocuments).length === 0) {\n newState.capturedDocuments[DocumentType.PASSPORT] = capturedDocument\n } else {\n newState.capturedDocuments = {}\n newState.capturedDocuments[DocumentType.ID_CARD_FRONT] =\n state.capturedDocuments[DocumentType.PASSPORT]\n newState.capturedDocuments[DocumentType.ID_CARD_BACK] = capturedDocument\n }\n\n return newState\n }\n\n case 'reset':\n return { ...initialState }\n }\n}\n\nexport type IdCaptureWizardAssets = {\n documentDetectionModelUrl?: string\n focusModelUrl?: string\n loadingOverlay?: IdCaptureLoadingOverlayAssets\n idCardFront?: IdCaptureAssets\n idCardBack?: IdCaptureAssets\n passport?: IdCaptureAssets\n flipIdPrompt?: FlipIdPromptAssets\n}\n\nexport type IdCaptureWizardClassNames = {\n container?: string\n cameraFeed?: string\n loadingOverlay?: IdCaptureLoadingOverlayClassNames\n capture?: IdCaptureClassNames\n flipIdPrompt?: FlipIdPromptClassNames\n success?: IdCaptureSuccessClassNames\n fallback?: IdCaptureFallbackClassNames\n}\n\nexport type IdCaptureWizardColors = IdCaptureColors & {\n loadingOverlay?: IdCaptureLoadingOverlayColors\n success?: IdCaptureSuccessColors\n fallback?: IdCaptureFallbackColors\n}\n\nexport type IdCaptureWizardVerbiage = {\n loadingOverlay?: IdCaptureLoadingOverlayVerbiage\n idCardFront?: IdCaptureVerbiage\n idCardBack?: IdCaptureVerbiage\n passport?: IdCaptureVerbiage\n flipIdPrompt?: FlipIdPromptVerbiage\n success?: IdCaptureSuccessVerbiage\n fallback?: IdCaptureFallbackVerbiage\n}\n\nexport type IdCaptureSubmission = {\n idFrontImage: string | null\n idBackImage: string | null\n passportImage: string | null\n}\n\nexport type IdCaptureWizardProps = {\n onSuccess?: (submission: IdCaptureSubmission) => void\n onExitCapture?: () => void\n\n autoCaptureEnabled?: boolean\n autoCaptureGoodFramesRequired?: number\n autoCaptureBarcodeRequired?: 'mobile' | boolean\n barcodeScanningEnabled?: boolean\n idCardAutoCaptureScoreThreshold?: number\n passportAutoCaptureScoreThreshold?: number\n mrzDetectionScoreThreshold?: number\n idCardFocusScoreThreshold?: number\n passportFocusScoreThreshold?: number\n skipSuccessScreen?: boolean | (() => Promise<boolean>)\n releaseCameraAccessOnExit?: boolean\n\n assets?: IdCaptureWizardAssets\n classNames?: IdCaptureWizardClassNames\n colors?: IdCaptureWizardColors\n verbiage?: IdCaptureWizardVerbiage\n debugMode?: boolean\n}\n\nexport const IdCaptureWizard = ({\n onSuccess,\n onExitCapture,\n\n autoCaptureEnabled = true,\n autoCaptureGoodFramesRequired = 3,\n autoCaptureBarcodeRequired = 'mobile',\n barcodeScanningEnabled = false,\n idCardAutoCaptureScoreThreshold = 0.8,\n passportAutoCaptureScoreThreshold = 0.75,\n mrzDetectionScoreThreshold = 0.25,\n idCardFocusScoreThreshold = 0.3,\n passportFocusScoreThreshold = 0.3,\n skipSuccessScreen = false,\n releaseCameraAccessOnExit = true,\n\n assets = {},\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: IdCaptureWizardProps): ReactElement => {\n const [state, dispatch] = useReducer(reducer, initialState)\n const { releaseCameraAccess } = useContext(CameraStateContext)\n const [overlayDismissed, setOverlayDismissed] = useState(false)\n const {\n submissionStatus,\n setIdFrontImage,\n setIdBackImage,\n setPassportImage,\n logIdFrontCaptureAttempt,\n logIdBackCaptureAttempt,\n } = useContext(SubmissionContext)\n const { error: modelsError } = useContext(IdCaptureModelsContext)\n const operationStartedAt = useRef<Date>()\n\n useEffect(() => {\n operationStartedAt.current = new Date()\n }, [state.capturedDocuments.length])\n\n const logCaptureMetadata = useCallback(\n (metadata: CaptureAttemptMetadata) => {\n metadata.operationTime =\n new Date().getTime() -\n (operationStartedAt.current ?? new Date()).getTime()\n\n state.requestedDocumentType === 'ID_CARD_BACK'\n ? logIdBackCaptureAttempt(metadata)\n : logIdFrontCaptureAttempt(metadata)\n },\n [\n logIdBackCaptureAttempt,\n logIdFrontCaptureAttempt,\n state.requestedDocumentType,\n ]\n )\n\n const onPrediction = useCallback((prediction: IdCapturePrediction) => {\n dispatch({ type: 'predictionMade', payload: { prediction } })\n }, [])\n\n const onBarcodeScanned = useCallback((result: PDF417DetectionResult) => {\n dispatch({ type: 'barcodeScanned', payload: { result } })\n }, [])\n\n const onCapture = useCallback(\n (\n imageData: string,\n width: number,\n height: number,\n metadata: CaptureAttemptMetadata\n ) => {\n logCaptureMetadata(metadata)\n dispatch({ type: 'imageCaptured', payload: { imageData, width, height } })\n },\n [logCaptureMetadata]\n )\n\n const onSubmitClick = useCallback(() => {\n const idFrontDocument = state.capturedDocuments['ID_CARD_FRONT']\n const idBackDocument = state.capturedDocuments['ID_CARD_BACK']\n const passportDocument = state.capturedDocuments['PASSPORT']\n\n const idFrontImage =\n idFrontDocument && dataUrlToBase64Sync(idFrontDocument.imageData)\n const idBackImage =\n idBackDocument && dataUrlToBase64Sync(idBackDocument.imageData)\n const passportImage =\n passportDocument && dataUrlToBase64Sync(passportDocument.imageData)\n\n setIdFrontImage(idFrontImage)\n setIdBackImage(idBackImage)\n setPassportImage(passportImage)\n\n releaseCameraAccessOnExit && releaseCameraAccess()\n setTimeout(() => {\n onSuccess?.({ idFrontImage, idBackImage, passportImage })\n }, 0)\n }, [\n onSuccess,\n releaseCameraAccess,\n releaseCameraAccessOnExit,\n setIdBackImage,\n setIdFrontImage,\n setPassportImage,\n state.capturedDocuments,\n ])\n\n const showSuccessScreen = useShowSuccessScreen(\n skipSuccessScreen,\n state.captureState === CaptureState.COMPLETE,\n onSubmitClick\n )\n\n const onRetryClick = useCallback(() => {\n dispatch({ type: 'reset' })\n }, [])\n\n const [attempt, setAttempt] = useState(0)\n const onExit = useCallback(() => {\n setOverlayDismissed(false)\n setAttempt((n) => n + 1)\n dispatch({ type: 'reset' })\n onExitCapture?.()\n }, [onExitCapture])\n\n useEffect(() => {\n if (submissionStatus !== SubmissionStatus.READY) {\n releaseCameraAccessOnExit && releaseCameraAccess()\n }\n }, [releaseCameraAccess, releaseCameraAccessOnExit, submissionStatus])\n\n assets.idCardFront ||= {}\n assets.idCardFront.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Portrait-2.svg`\n assets.idCardFront.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.idCardBack ||= {}\n assets.idCardBack.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Portrait-2.svg`\n assets.idCardBack.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n assets.passport ||= {}\n assets.passport.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-Passport-Front-SVG-Portrait-2.svg`\n assets.passport.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-Passport-Front-SVG-Landscape-2.svg`\n assets.flipIdPrompt ||= {}\n assets.flipIdPrompt.frontPortraitGuidesImageUrl ||=\n assets.idCardFront.portraitGuidesImageUrl\n assets.flipIdPrompt.frontLandscapeGuidesImageUrl ||=\n assets.idCardFront.landscapeGuidesImageUrl\n assets.flipIdPrompt.backPortraitGuidesImageUrl ||=\n assets.idCardBack.portraitGuidesImageUrl\n assets.flipIdPrompt.backLandscapeGuidesImageUrl ||=\n assets.idCardBack.landscapeGuidesImageUrl\n\n const idCardFrontVerbiage = useTranslations(verbiage.idCardFront, {\n instructionText: 'Scan the front of ID',\n processingIdCardText: 'ID card front captured.',\n })\n const idCardBackVerbiage = useTranslations(verbiage.idCardBack, {\n instructionText: 'Scan the back of ID',\n })\n const passportVerbiage = useTranslations(verbiage.idCardBack, {\n instructionText: 'Scan the ID page of passport',\n })\n\n if (modelsError) {\n return (\n <IdCaptureFallback\n onFinished={onSubmitClick}\n onCapture={(imageData) => {\n dispatch({ type: 'imageCapturedManually', payload: { imageData } })\n }}\n classNames={classNames.fallback}\n colors={colors.fallback}\n verbiage={verbiage.fallback}\n />\n )\n }\n\n return (\n <PageContainer className={`flex ${classNames?.container ?? ''}`}>\n {state.captureState !== CaptureState.COMPLETE && (\n <CameraVideoTag className={classNames?.cameraFeed} />\n )}\n\n {overlayDismissed &&\n (() => {\n const docCount = Object.keys(state.capturedDocuments).length\n switch (state.requestedDocumentType) {\n case DocumentType.ID_CARD_FRONT:\n return (\n <IdCapture\n key={`capture${docCount}`}\n requiredDocumentType={state.requestedDocumentType}\n autoCaptureEnabled={autoCaptureEnabled}\n autoCaptureScoreThreshold={idCardAutoCaptureScoreThreshold}\n autoCaptureGoodFramesRequired={autoCaptureGoodFramesRequired}\n autoCaptureBarcodeRequired={autoCaptureBarcodeRequired}\n barcodeScanningEnabled={false}\n mrzDetectionScoreThreshold={mrzDetectionScoreThreshold}\n focusScoreThreshold={idCardFocusScoreThreshold}\n onPrediction={onPrediction}\n onCapture={onCapture}\n onExit={onExit}\n processingDelay={3500}\n assets={assets.idCardFront}\n classNames={classNames?.capture}\n colors={colors}\n verbiage={idCardFrontVerbiage}\n debugMode={debugMode}\n processingScreen={\n <FlipIdPrompt\n assets={assets.flipIdPrompt}\n classNames={classNames.flipIdPrompt}\n verbiage={verbiage.flipIdPrompt}\n />\n }\n />\n )\n\n case DocumentType.ID_CARD_BACK:\n return (\n <IdCapture\n key={`capture${docCount}`}\n requiredDocumentType={state.requestedDocumentType}\n autoCaptureEnabled={autoCaptureEnabled}\n autoCaptureScoreThreshold={idCardAutoCaptureScoreThreshold}\n autoCaptureGoodFramesRequired={autoCaptureGoodFramesRequired}\n autoCaptureBarcodeRequired={autoCaptureBarcodeRequired}\n barcodeScanningEnabled={barcodeScanningEnabled}\n mrzDetectionScoreThreshold={mrzDetectionScoreThreshold}\n focusScoreThreshold={idCardFocusScoreThreshold}\n onPrediction={onPrediction}\n onBarcodeScanned={onBarcodeScanned}\n onCapture={onCapture}\n onExit={onExit}\n assets={assets.idCardBack}\n classNames={classNames?.capture}\n colors={colors}\n verbiage={idCardBackVerbiage}\n debugMode={debugMode}\n />\n )\n\n case DocumentType.PASSPORT:\n return (\n <IdCapture\n key={`capture${docCount}`}\n requiredDocumentType={state.requestedDocumentType}\n autoCaptureEnabled={autoCaptureEnabled}\n autoCaptureScoreThreshold={passportAutoCaptureScoreThreshold}\n mrzDetectionScoreThreshold={mrzDetectionScoreThreshold}\n autoCaptureGoodFramesRequired={autoCaptureGoodFramesRequired}\n autoCaptureBarcodeRequired={autoCaptureBarcodeRequired}\n barcodeScanningEnabled={false}\n focusScoreThreshold={passportFocusScoreThreshold}\n onPrediction={onPrediction}\n onBarcodeScanned={onBarcodeScanned}\n onCapture={onCapture}\n onExit={onExit}\n assets={assets.passport}\n classNames={classNames?.capture}\n colors={colors}\n verbiage={passportVerbiage}\n debugMode={debugMode}\n />\n )\n\n default:\n return null\n }\n })()}\n\n {!overlayDismissed && (\n <IdCaptureLoadingOverlay\n key={attempt}\n assets={assets.loadingOverlay}\n classNames={classNames.loadingOverlay}\n colors={colors.loadingOverlay}\n verbiage={verbiage.loadingOverlay}\n onDismissed={() => {\n setOverlayDismissed(true)\n }}\n />\n )}\n\n {state.captureState === CaptureState.COMPLETE && showSuccessScreen && (\n <IdCaptureSuccess\n capturedDocuments={state.capturedDocuments}\n barcodeResult={state.barcodeResult}\n classNames={classNames.success}\n onSubmitClick={onSubmitClick}\n onRetryClick={onRetryClick}\n colors={colors.success}\n verbiage={verbiage.success}\n />\n )}\n </PageContainer>\n )\n}\n","import * as React from 'react'\nimport {\n createContext,\n MutableRefObject,\n ReactElement,\n ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n FaceDetector,\n FilesetResolver,\n FaceDetectorResult,\n} from '@mediapipe/tasks-vision'\n\nconst NUM_KEYPOINTS = 6\nconst GREEN = '#32EEDB'\nconst RED = '#FF2C35'\n// const FACE_DETECTOR_VERSION = mpFaceDetection.VERSION ?? '0.4.1646425229'\n// const FACE_DETECTOR_VERSION = '0.4.1646425229'\n\nexport type FaceKeypoint = { x: number; y: number; name: string }\nexport type Face = {\n keypoints: FaceKeypoint[]\n box: {\n xMin: number\n xMax: number\n yMin: number\n yMax: number\n width: number\n height: number\n }\n}\n\nfunction drawPath(\n ctx: CanvasRenderingContext2D,\n points: number[][],\n closePath: boolean,\n) {\n const region = new Path2D()\n region.moveTo(points[0][0], points[0][1])\n for (let i = 1; i < points.length; i++) {\n const point = points[i]\n region.lineTo(point[0], point[1])\n }\n\n if (closePath) {\n region.closePath()\n }\n ctx.stroke(region)\n}\n\n/**\n * Draw the keypoints on the video.\n * @param ctx 2D rendering context.\n * @param faces A list of faces to render.\n * @param boundingBox Whether or not to display the bounding box.\n * @param showKeypoints Whether or not to display the keypoints.\n */\nfunction drawResults(\n ctx: CanvasRenderingContext2D,\n faces: Face[],\n boundingBox: boolean,\n showKeypoints: boolean,\n) {\n faces.forEach((face) => {\n const keypoints = face.keypoints.map((keypoint) => [keypoint.x, keypoint.y])\n\n if (boundingBox) {\n ctx.strokeStyle = RED\n ctx.lineWidth = 1\n\n const box = face.box\n drawPath(\n ctx,\n [\n [box.xMin, box.yMin],\n [box.xMax, box.yMin],\n [box.xMax, box.yMax],\n [box.xMin, box.yMax],\n ],\n true,\n )\n }\n\n if (showKeypoints) {\n ctx.fillStyle = GREEN\n\n for (let i = 0; i < NUM_KEYPOINTS; i++) {\n const x = keypoints[i][0]\n const y = keypoints[i][1]\n\n ctx.beginPath()\n ctx.arc(x, y, 3 /* radius */, 0, 2 * Math.PI)\n ctx.fill()\n }\n }\n })\n}\n\nlet detector: FaceDetector\n\nexport async function loadHighPerformanceFaceDetector(): Promise<FaceDetector> {\n if (detector) return detector\n\n const vision = await FilesetResolver.forVisionTasks(\n 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.7/wasm',\n )\n\n detector = await FaceDetector.createFromOptions(vision, {\n baseOptions: {\n modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite`,\n delegate: 'GPU',\n },\n runningMode: 'VIDEO',\n })\n\n return detector\n}\n\ntype PredictionHandler = (prediction: Face[]) => void\ntype HighPerformanceSelfieGuidanceModelsState = {\n start: () => void\n stop: () => void\n onPredictionMade: (handler: PredictionHandler) => void\n canvasRef: MutableRefObject<HTMLCanvasElement | null>\n ready: boolean\n error: Error | null\n}\n\nexport const HighPerformanceSelfieGuidanceModelsContext =\n createContext<HighPerformanceSelfieGuidanceModelsState>({\n start: () => null,\n stop: () => null,\n onPredictionMade: () => null,\n canvasRef: { current: null },\n ready: false,\n error: null,\n })\n\nexport const HighPerformanceSelfieGuidanceModelsProvider = ({\n autoStart = true,\n children,\n throttleMs,\n}: {\n autoStart?: boolean\n children: ReactNode\n throttleMs?: number\n}): ReactElement => {\n const { videoRef, videoLoaded, cameraReady } = useContext(CameraStateContext)\n const canvasRef = useRef<HTMLCanvasElement>(null)\n const onPredictionHandler = useRef<PredictionHandler>()\n const [ready, setReady] = useState(false)\n const [running, setRunning] = useState(false)\n const detectorRef = useRef<FaceDetector | null>(null)\n const rafId = useRef(0)\n const loopId = useRef(0)\n const [error, setError] = useState<Error | null>(null)\n\n useEffect(() => {\n ;(async () => {\n setReady(false)\n try {\n detectorRef.current = await loadHighPerformanceFaceDetector()\n } catch (e) {\n setError(e as Error)\n }\n setReady(true)\n })()\n }, [])\n\n useEffect(() => {\n if (!videoLoaded || !cameraReady || !running || !ready) return\n let timer: NodeJS.Timeout\n loopId.current += 1\n const currentLoopId = loopId.current\n\n ;(async () => {\n if (!videoRef.current || !detectorRef.current) return\n\n const ctx = canvasRef.current?.getContext('2d')\n if (canvasRef.current) {\n canvasRef.current.width = videoRef.current?.videoWidth\n canvasRef.current.height = videoRef.current?.videoHeight\n ctx?.translate(videoRef.current.videoWidth, 0)\n ctx?.scale(-1, 1)\n }\n\n await (async function renderPrediction() {\n if (\n !detectorRef.current ||\n !videoRef.current ||\n currentLoopId !== loopId.current\n )\n return\n\n if (videoRef.current.readyState < 2) {\n await new Promise((resolve) => {\n if (videoRef.current)\n videoRef.current.onloadeddata = () => {\n resolve([])\n }\n })\n }\n\n const vw = videoRef.current.videoWidth\n const vh = videoRef.current.videoHeight\n ctx?.drawImage(videoRef.current, 0, 0, vw, vh)\n\n let prediction: FaceDetectorResult | null\n // Detectors can throw errors, for example when using custom URLs that\n // contain a model that doesn't provide the expected output.\n try {\n prediction = await detectorRef.current.detectForVideo(\n videoRef.current,\n performance.now(),\n )\n if (prediction) {\n const faces = prediction.detections.map<Face>((d) => ({\n keypoints: d.keypoints.map((k) => ({\n ...k,\n x: k.x * vw,\n y: k.y * vh,\n name: k.label ?? '',\n })),\n box: {\n xMin: d.boundingBox?.originX ?? 0,\n xMax:\n (d.boundingBox?.originX ?? 0) + (d.boundingBox?.width ?? 0),\n yMin: d.boundingBox?.originY ?? 0,\n yMax:\n (d.boundingBox?.originY ?? 0) + (d.boundingBox?.height ?? 0),\n width: d.boundingBox?.width ?? 0,\n height: d.boundingBox?.height ?? 0,\n },\n }))\n onPredictionHandler.current?.(faces)\n ctx && drawResults(ctx, faces, true, true)\n }\n } catch (error) {\n console.error('caught face detection error', error)\n // detector.dispose()\n }\n\n if (throttleMs) {\n timer = setTimeout(() => {\n rafId.current = requestAnimationFrame(renderPrediction)\n }, throttleMs)\n } else {\n rafId.current = requestAnimationFrame(renderPrediction)\n }\n })()\n })()\n\n return () => {\n rafId.current && cancelAnimationFrame(rafId.current)\n timer && clearTimeout(timer)\n }\n }, [cameraReady, ready, running, throttleMs, videoLoaded, videoRef])\n\n const start = useCallback(() => {\n setRunning(true)\n }, [])\n\n const stop = useCallback(() => {\n setRunning(false)\n }, [])\n\n useEffect(() => {\n if (autoStart) start()\n return () => {\n stop()\n }\n }, [autoStart, start, stop])\n\n const onPredictionMade = useCallback((handler: PredictionHandler) => {\n onPredictionHandler.current = handler\n }, [])\n\n const value = useMemo<HighPerformanceSelfieGuidanceModelsState>(\n () => ({ start, stop, ready, canvasRef, onPredictionMade, error }),\n [error, onPredictionMade, ready, start, stop],\n )\n\n return (\n <HighPerformanceSelfieGuidanceModelsContext.Provider value={value}>\n {children}\n </HighPerformanceSelfieGuidanceModelsContext.Provider>\n )\n}\n","import { useEffect, useState } from 'react'\n\nexport const useTimeout = (\n durationMs?: number,\n onTimeout?: () => void,\n timeoutAverted?: boolean,\n shouldWaitLonger?: boolean,\n shouldStart: boolean = true,\n) => {\n const [timedOut, setTimedOut] = useState(false)\n const [timeoutStartedAt, setTimeoutStartedAt] = useState<Date | null>()\n\n useEffect(() => {\n if (!durationMs || !shouldStart) return\n\n setTimeoutStartedAt(new Date())\n const timer = setTimeout(() => {\n setTimedOut(true)\n }, durationMs)\n\n return () => {\n if (timer) clearTimeout(timer)\n }\n }, [durationMs, shouldStart])\n\n useEffect(() => {\n if (!timedOut || timeoutAverted) return\n if (!shouldWaitLonger) {\n onTimeout?.()\n return\n }\n\n const t = setTimeout(() => {\n onTimeout?.()\n }, 120000)\n\n return () => {\n clearTimeout(t)\n }\n }, [onTimeout, shouldWaitLonger, timedOut, timeoutAverted])\n\n return { timedOut, timeoutStartedAt }\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport {\n OverlayContainer,\n OverlayImageContainer,\n OverlayInner,\n} from '../common/overlay'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport styled from 'styled-components'\nimport { ButtonsRow } from '../common/ButtonsRow'\n\nexport type SelfieCaptureFallbackClassNames = {\n container?: string\n inner?: string\n heading?: string\n description?: string\n imageContainer?: string\n image?: string\n buttonsRow?: string\n captureBtn?: string\n doneBtn?: string\n}\n\nexport type SelfieCaptureFallbackColors = {\n captureBtn?: LoaderButtonColors\n doneBtn?: LoaderButtonColors\n}\n\nexport type SelfieCaptureFallbackVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n descriptionText?: CustomerSuppliedVerbiage\n captureBtnText?: CustomerSuppliedVerbiage\n doneBtnText?: CustomerSuppliedVerbiage\n doneBtnLoadingText?: CustomerSuppliedVerbiage\n}\n\nexport type SelfieCaptureFallbackProps = {\n onFinished?: (imageData: string) => void\n onCapture?: (imageData: string) => void\n classNames?: SelfieCaptureFallbackClassNames\n colors?: SelfieCaptureFallbackColors\n verbiage?: SelfieCaptureFallbackVerbiage\n}\n\nexport const SelfieCaptureFallback = ({\n onFinished,\n onCapture,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n}: SelfieCaptureFallbackProps): ReactElement => {\n const [image, setImage] = useState<string | null>(null)\n const fileInput = useRef<HTMLInputElement | null>(null)\n const [loading, setLoading] = useState(false)\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: `We're having some trouble.`,\n descriptionText:\n 'On-device capture guidance failed, please capture a selfie manually.',\n captureBtnText: 'Capture',\n doneBtnText: 'Done',\n doneBtnLoadingText: 'Verifying...',\n })\n\n function onFileSelected(e: React.ChangeEvent<HTMLInputElement>) {\n const file = e.target.files?.[0]\n if (!file) return\n\n const reader = new FileReader()\n reader.addEventListener('load', (e) => {\n const imageData = e.target?.result as string\n setImage(imageData)\n onCapture?.(imageData)\n })\n reader.readAsDataURL(file)\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <StyledOverlayInner className={classNames.inner}>\n <Heading className={classNames.heading}>{verbiage.headingText}</Heading>\n\n <Description className={classNames.description}>\n {verbiage.descriptionText}\n </Description>\n\n {image && (\n <ImageContainer className={classNames.imageContainer}>\n <img src={image} alt=\"\" className={classNames.image} />\n </ImageContainer>\n )}\n\n <input\n ref={fileInput}\n type=\"file\"\n accept=\"image/*\"\n onChange={onFileSelected}\n hidden\n />\n\n <StyledButtonsRow className={classNames.buttonsRow}>\n {!image && (\n <LoaderButton\n variant=\"positive\"\n className={classNames.captureBtn}\n colors={colors.captureBtn}\n finished\n onClick={() => {\n fileInput.current?.click()\n }}\n >\n {verbiage.captureBtnText}\n </LoaderButton>\n )}\n\n {image && (\n <LoaderButton\n variant=\"positive\"\n key={loading ? 'loading-btn' : 'ready-btn'}\n className={classNames.doneBtn}\n colors={colors.doneBtn}\n finished={!loading}\n onClick={() => {\n setLoading(true)\n onFinished?.(image)\n }}\n >\n {loading ? verbiage.doneBtnLoadingText : verbiage.doneBtnText}\n </LoaderButton>\n )}\n </StyledButtonsRow>\n </StyledOverlayInner>\n </OverlayContainer>\n )\n}\n\nconst StyledOverlayInner = styled(OverlayInner)`\n justify-content: center;\n`\n\nconst Heading = styled.h3`\n margin-bottom: 8px;\n`\n\nconst Description = styled.p`\n margin-bottom: 8px;\n`\n\nconst ImageContainer = styled(OverlayImageContainer)`\n margin-top: 32px;\n`\n\nconst StyledButtonsRow = styled(ButtonsRow)`\n margin-top: 32px;\n`\n","import React, {\n ReactElement,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport useResizeObserver from 'use-resize-observer'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n FaceCaptureGuideOverlay,\n FaceCaptureGuideOverlayClassNames,\n} from '../face_liveness/FaceCaptureGuideOverlay'\nimport {\n Face,\n HighPerformanceSelfieGuidanceModelsContext,\n} from './HighPerformanceSelfieGuidanceModelsProvider'\nimport { PageContainer } from '../common/Page'\nimport {\n DebugStatsPane,\n ObjectDetectionDebugOverlay,\n SelfieCaptureFaceDebugBox,\n useDebugScalingDetails,\n} from '../common/debug'\nimport { ExitCaptureButton } from '../common/ExitCaptureButton'\nimport {\n GuidanceMessage,\n GuidanceMessageContainer,\n} from '../common/GuidanceMessage'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport {\n clearCanvas,\n drawToCanvas,\n InvisibleCanvas,\n} from '../common/InvisibleCanvas'\nimport {\n SelfieCaptureFallback,\n SelfieCaptureFallbackClassNames,\n} from '../fallback_flows/SelfieCapture'\n\ntype State = {\n videoWidth: number\n videoHeight: number\n\n capturing: boolean\n captured: boolean\n captureFailed: boolean\n\n frame: ImageBitmap | null\n faces: Face[]\n faceNotCentered: boolean\n faceLookingAway: boolean\n faceTooClose: boolean\n faceTooFar: boolean\n faceReady: boolean\n faceReadyAt: Date | null\n\n // TODO: remove good frames threshold\n goodFramesCount: number\n goodFramesThreshold: number\n goodFramesThresholdMet: boolean\n}\n\nconst initialState: State = {\n videoWidth: 0,\n videoHeight: 0,\n\n capturing: false,\n captured: false,\n captureFailed: false,\n\n frame: null,\n faces: [],\n faceNotCentered: false,\n faceLookingAway: false,\n faceTooClose: false,\n faceTooFar: false,\n faceReady: false,\n faceReadyAt: null,\n\n goodFramesCount: 0,\n goodFramesThreshold: 1,\n goodFramesThresholdMet: false,\n}\n\ntype Action =\n | { type: 'configure'; payload: { videoWidth: number; videoHeight: number } }\n | { type: 'capturing' }\n | { type: 'captured' }\n | { type: 'captureFailed' }\n | { type: 'facesDetected'; payload: { frame?: ImageBitmap; faces: Face[] } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'configure':\n return {\n ...state,\n videoWidth: action.payload.videoWidth,\n videoHeight: action.payload.videoHeight,\n }\n\n case 'capturing':\n return {\n ...state,\n capturing: true,\n captured: false,\n captureFailed: false,\n }\n\n case 'captured':\n return {\n ...state,\n capturing: false,\n captured: true,\n captureFailed: false,\n }\n\n case 'captureFailed':\n return {\n ...state,\n capturing: false,\n captured: false,\n captureFailed: true,\n }\n\n case 'facesDetected': {\n const { faces } = action.payload\n const face = faces[0]\n\n let faceNotCentered = true,\n faceLookingAway = false,\n faceTooClose = false,\n faceTooFar = false,\n faceReadyAt = state.faceReadyAt,\n goodFramesCount = state.goodFramesCount\n\n if (face) {\n // calculate centroids\n const vCX = state.videoWidth / 2\n const vCY = state.videoHeight / 2\n const fCX = (face.box.xMin + face.box.xMax) / 2\n const fCY = (face.box.yMin + face.box.yMax) / 2\n\n // calculate thresholds\n const vTX = state.videoWidth * 0.125\n const vTY = state.videoHeight * 0.125\n const fTW = face.box.width * 0.2\n const fTH = face.box.height * 0.2\n\n const nose = face.keypoints[2] //.find((k) => k.name === 'noseTip')\n if (nose) {\n faceNotCentered =\n Math.abs(vCX - fCX) > vTX || Math.abs(vCY + 50 - fCY) > vTY\n faceLookingAway =\n Math.abs(fCX - nose.x) > fTW || Math.abs(fCY - nose.y) > fTH\n }\n\n const isMobile = state.videoWidth < state.videoHeight\n\n const tooCloseMultiple = isMobile ? 2 : 4.5\n const tooFarMultiple = isMobile ? 6 : 7\n faceTooClose = face.box.width > state.videoWidth / tooCloseMultiple\n faceTooFar = face.box.width < state.videoWidth / tooFarMultiple\n }\n\n const faceReady =\n !faceNotCentered && !faceLookingAway && !faceTooClose && !faceTooFar\n\n if (!faceReady) {\n faceReadyAt = null\n goodFramesCount = 0\n } else if (!state.faceReady) {\n faceReadyAt = new Date()\n }\n\n return {\n ...state,\n faces,\n faceNotCentered,\n faceLookingAway,\n faceTooClose,\n faceTooFar,\n faceReady,\n faceReadyAt,\n goodFramesCount,\n }\n }\n }\n}\n\nexport type SelfieCaptureClassNames = {\n container?: string\n cameraFeed?: string\n guides?: FaceCaptureGuideOverlayClassNames\n guidanceMessageContainer?: string\n guidanceMessage?: string\n exitCaptureBtn?: string\n fallback?: SelfieCaptureFallbackClassNames\n}\n\nexport type SelfieCaptureColors = {\n guidesUnsatisfiedColor?: string\n guidesSatisfiedColor?: string\n guidanceMessagesSatisfiedBackgroundColor?: string\n guidanceMessagesUnsatisfiedBackgroundColor?: string\n guidanceMessagesSatisfiedTextColor?: string\n guidanceMessagesUnsatisfiedTextColor?: string\n}\n\nexport type SelfieCaptureVerbiage = {\n guidanceHoldStillText?: CustomerSuppliedVerbiage\n guidanceLookStraightText?: CustomerSuppliedVerbiage\n guidanceMoveBackText?: CustomerSuppliedVerbiage\n guidanceMoveForwardText?: CustomerSuppliedVerbiage\n guidanceMoveToCenterText?: CustomerSuppliedVerbiage\n}\n\nexport type SelfieCaptureProps = {\n onGuidanceSatisfied?: () => void\n onGuidanceNotSatisfied?: () => void\n onSelfieCaptured?: (frame: ImageData, face: Face) => void\n onTimeout?: () => void\n onExit?: () => void\n timeoutDurationMs?: number\n guidanceMessage?: string\n guidanceSatisfied?: boolean\n classNames?: SelfieCaptureClassNames\n colors?: SelfieCaptureColors\n verbiage?: SelfieCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const SelfieCapture = ({\n onGuidanceSatisfied,\n onGuidanceNotSatisfied,\n onSelfieCaptured,\n onTimeout,\n onExit,\n timeoutDurationMs = 15000,\n guidanceMessage,\n guidanceSatisfied,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: SelfieCaptureProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const [state, dispatch] = useReducer(reducer, initialState)\n const lastPredictionCanvas = useRef<HTMLCanvasElement | null>(null)\n const { cameraRef, cameraReady, videoRef } = useContext(CameraStateContext)\n const { onPredictionMade, error: guidanceError } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n\n useEffect(() => {\n if (cameraReady && videoRef.current && videoRef.current.videoWidth !== 0) {\n dispatch({\n type: 'configure',\n payload: {\n videoWidth: videoRef.current.videoWidth,\n videoHeight: videoRef.current.videoHeight,\n },\n })\n }\n }, [cameraReady, videoRef])\n\n useEffect(() => {\n onPredictionMade((prediction) => {\n dispatch({\n type: 'facesDetected',\n payload: { faces: prediction },\n })\n })\n }, [onPredictionMade])\n\n const [captureReady, setCaptureReady] = useState(false)\n useEffect(() => {\n let timer: NodeJS.Timer\n\n if (state.faceReady) {\n onGuidanceSatisfied?.()\n timer = setTimeout(() => {\n setCaptureReady(true)\n }, 1000)\n } else {\n onGuidanceNotSatisfied?.()\n }\n\n return () => {\n if (timer) clearTimeout(timer)\n }\n }, [onGuidanceNotSatisfied, onGuidanceSatisfied, state.faceReady])\n\n useEffect(() => {\n ;(async () => {\n if (\n captureReady &&\n videoRef.current &&\n lastPredictionCanvas.current &&\n state.faces.length > 0\n ) {\n drawToCanvas(lastPredictionCanvas.current, videoRef.current)\n const ctx = lastPredictionCanvas.current.getContext('2d')\n if (!ctx) return\n const imageData = ctx.getImageData(\n 0,\n 0,\n videoRef.current.videoWidth,\n videoRef.current.videoHeight\n )\n\n onSelfieCaptured?.(imageData, state.faces[0])\n clearCanvas(lastPredictionCanvas.current)\n }\n })()\n }, [captureReady, onSelfieCaptured, state.faces, videoRef])\n\n const { timedOut, timeoutStartedAt } = useTimeout(\n timeoutDurationMs,\n onTimeout\n )\n\n const debugScalingDetails = useDebugScalingDetails({\n enabled: debugMode,\n pageWidth: width,\n pageHeight: height,\n videoWidth: state.videoWidth,\n videoHeight: state.videoHeight,\n })\n\n colors.guidesUnsatisfiedColor ||= 'white'\n colors.guidesSatisfiedColor ||= 'green'\n\n const verbiage = useTranslations(rawVerbiage, {\n guidanceHoldStillText: 'Hold still for a few seconds...',\n guidanceLookStraightText: 'Look straight into the camera...',\n guidanceMoveBackText: 'Move back...',\n guidanceMoveForwardText: 'Move forward...',\n guidanceMoveToCenterText: 'Move to the center...',\n })\n\n let satisfied = state.faceReady\n if (typeof guidanceSatisfied === 'boolean') satisfied = guidanceSatisfied\n\n guidanceMessage ||= satisfied\n ? verbiage.guidanceHoldStillText\n : state.faceLookingAway\n ? verbiage.guidanceLookStraightText\n : state.faceTooClose\n ? verbiage.guidanceMoveBackText\n : state.faceTooFar\n ? verbiage.guidanceMoveForwardText\n : state.faceNotCentered\n ? verbiage.guidanceMoveToCenterText\n : ''\n\n if (guidanceError) {\n return <SelfieCaptureFallback classNames={classNames.fallback} />\n }\n\n return (\n <PageContainer ref={ref} className={`flex ${classNames.container ?? ''}`}>\n <InvisibleCanvas ref={lastPredictionCanvas} />\n <CameraVideoTag className={classNames.cameraFeed} />\n\n <FaceCaptureGuideOverlay\n classNames={classNames.guides}\n variant={satisfied ? 'satisfied' : 'unsatisfied'}\n />\n\n {guidanceMessage !== '' && (\n <GuidanceMessageContainer\n className={classNames.guidanceMessageContainer}\n >\n <GuidanceMessage\n $variant={satisfied ? 'positive' : 'negative'}\n className={classNames.guidanceMessage}\n >\n {guidanceMessage}\n </GuidanceMessage>\n </GuidanceMessageContainer>\n )}\n\n {debugMode && state.faces.length > 0 && (\n <ObjectDetectionDebugOverlay $flipX={!cameraRef.current?.isRearFacing}>\n {state.faces.map((face, i) => (\n <SelfieCaptureFaceDebugBox\n key={i}\n face={face}\n scaling={debugScalingDetails}\n flipX={!cameraRef.current?.isRearFacing}\n color={satisfied ? 'green' : 'red'}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n )}\n\n {debugMode && (\n <DebugStatsPane>\n {cameraRef.current ? (\n <>\n ✅ Camera: {cameraRef.current.label} ({cameraRef.current.width}x\n {cameraRef.current.height})\n </>\n ) : (\n '❌ Camera not ready'\n )}\n <br />\n {!state.faceNotCentered ? '✅' : '❌'} Face Centered\n <br />\n {!state.faceTooClose && !state.faceTooFar ? '✅' : '❌'} Face{' '}\n {state.faceTooClose\n ? 'Too Close'\n : state.faceTooFar\n ? 'Too Far'\n : 'Distance Correct'}\n <br />\n {!state.faceLookingAway ? '✅' : '❌'} Face Looking Forward\n <br />\n {state.goodFramesThresholdMet ? '✅' : '❌'} {state.goodFramesCount}{' '}\n Good Frames\n <br />\n {!timedOut ? '✅' : '❌'} Time Remaining:{' '}\n {Math.max(\n 0,\n timeoutDurationMs -\n (new Date().getTime() -\n (timeoutStartedAt ?? new Date()).getTime())\n )}\n ms\n </DebugStatsPane>\n )}\n\n <ExitCaptureButton\n onClick={onExit}\n className={classNames.exitCaptureBtn}\n />\n </PageContainer>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport { Face } from '@tensorflow-models/face-detection'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport {\n LiveCheckResponse,\n SubmissionContext,\n} from '../../contexts/SubmissionContext'\nimport {\n SelfieCapture,\n SelfieCaptureClassNames,\n SelfieCaptureColors,\n SelfieCaptureVerbiage,\n} from '../selfie_capture/SelfieCapture'\nimport { cropToShoulders } from '../../lib/utils/cropping'\nimport {\n SelfieProgressPreview,\n SelfieProgressPreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport { InvisibleCanvas } from '../common/InvisibleCanvas'\nimport { SelfieCaptureFallback } from '../fallback_flows/SelfieCapture'\nimport { HighPerformanceSelfieGuidanceModelsContext } from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\n\ntype LivenessCheckState =\n | 'CAPTURING'\n | 'CAPTURED'\n | 'IN_PROGRESS'\n | 'PASSED'\n | 'FAILED'\n | 'ERROR'\n\ntype State = {\n frame: ImageData | null\n face: Face | null\n requestState: LivenessCheckState\n requestError: Error | null\n imageUrl: string | null\n faceLive: boolean\n eyeCoveringDetected: boolean\n maskDetected: boolean\n headCoveringDetected: boolean\n phoneDetected: boolean\n timesLivenessCheckFailed: number\n}\n\nconst initialState: State = {\n frame: null,\n face: null,\n requestState: 'CAPTURING',\n requestError: null,\n imageUrl: null,\n faceLive: false,\n eyeCoveringDetected: false,\n maskDetected: false,\n headCoveringDetected: false,\n phoneDetected: false,\n timesLivenessCheckFailed: 0,\n}\n\ntype Action =\n | { type: 'livenessReady'; payload: { frame: ImageData; face: Face } }\n | { type: 'livenessChecking' }\n | {\n type: 'livenessChecked'\n payload: {\n frame?: ImageData\n face?: Face\n imageUrl: string\n response: LiveCheckResponse\n }\n }\n | { type: 'livenessCheckFailed'; payload: { error: Error } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'livenessReady': {\n const allowedStates = ['CAPTURING', 'FAILED', 'ERROR']\n if (allowedStates.includes(state.requestState)) {\n return {\n ...state,\n requestState: 'CAPTURED',\n frame: action.payload.frame,\n face: action.payload.face,\n }\n } else {\n return state\n }\n }\n\n case 'livenessChecking':\n return { ...state, requestState: 'IN_PROGRESS' }\n\n case 'livenessChecked': {\n const {\n status: { statusCode, statusMessage, errorData },\n resultData,\n } = action.payload.response\n\n if (statusCode !== '000') {\n return {\n ...state,\n requestState: 'ERROR',\n requestError: new Error(`${statusMessage}: ${errorData}`),\n }\n }\n\n const faceLive = resultData.verificationResult === 'Live Face Detected'\n const eyeCoveringDetected = resultData.eyeCovering === 'true'\n const maskDetected = resultData.faceMask === 'true'\n const headCoveringDetected = resultData.headCovering === 'true'\n const phoneDetected = resultData.cellPhone === 'true'\n\n const livenessCheckPassed =\n faceLive &&\n !eyeCoveringDetected &&\n !maskDetected &&\n !headCoveringDetected\n const requestState = livenessCheckPassed ? 'PASSED' : 'FAILED'\n\n let timesLivenessCheckFailed = state.timesLivenessCheckFailed\n if (livenessCheckPassed) {\n timesLivenessCheckFailed = 0\n } else {\n timesLivenessCheckFailed += 1\n }\n\n return {\n ...state,\n frame: action.payload.frame ?? null,\n face: action.payload.face ?? null,\n imageUrl: action.payload.imageUrl,\n requestState,\n faceLive,\n eyeCoveringDetected,\n maskDetected,\n headCoveringDetected,\n phoneDetected,\n timesLivenessCheckFailed,\n }\n }\n\n case 'livenessCheckFailed':\n return {\n ...state,\n requestState: 'ERROR',\n requestError: action.payload.error,\n }\n\n default:\n return state\n }\n}\n\nexport type FaceLivenessCaptureClassNames = SelfieCaptureClassNames & {\n imagePreview?: SelfieProgressPreviewClassNames\n}\n\nexport type FaceLivenessCaptureColors = SelfieCaptureColors\n\nexport type FaceLivenessCaptureVerbiage = SelfieCaptureVerbiage & {\n guidanceRemoveEyeCoveringsText?: CustomerSuppliedVerbiage\n guidanceRemoveHeadCoveringsText?: CustomerSuppliedVerbiage\n guidanceRemoveMaskText?: CustomerSuppliedVerbiage\n progressPreviewText?: CustomerSuppliedVerbiage\n}\n\nexport type FaceLivenessCaptureProps = {\n onCapture?: () => void\n onSuccess?: (faceCropImageUrl: string) => void\n onTimeout?: () => void\n onExit?: () => void\n timeoutDurationMs?: number\n classNames?: FaceLivenessCaptureClassNames\n colors?: FaceLivenessCaptureColors\n verbiage?: FaceLivenessCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const FaceLivenessCapture = ({\n onCapture,\n onSuccess,\n onTimeout,\n onExit,\n timeoutDurationMs = 15000,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode,\n}: FaceLivenessCaptureProps): ReactElement => {\n const { checkLiveness, submissionError } = useContext(SubmissionContext)\n const { error: modelsError } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n const [state, dispatch] = useReducer(reducer, initialState)\n const [imageUrl, setImageUrl] = useState<string | null>(null)\n const rawCanvas = useRef<HTMLCanvasElement | null>(null)\n const cropCanvas = useRef<HTMLCanvasElement | null>(null)\n\n const onSelfieCaptured = useCallback(\n (frame: ImageData, face: Face) => {\n onCapture?.()\n dispatch({ type: 'livenessReady', payload: { frame, face } })\n },\n [onCapture]\n )\n\n const { frame, face } = state\n const isReady = state.requestState === 'CAPTURED'\n const isPassed = state.requestState === 'PASSED'\n useEffect(() => {\n if (!frame || !face || !isReady || submissionError) return\n dispatch({ type: 'livenessChecking' })\n ;(async () => {\n try {\n const imageUrl = cropToShoulders(\n rawCanvas.current,\n cropCanvas.current,\n frame,\n face\n )\n setImageUrl(imageUrl)\n\n const response = await checkLiveness(await dataUrlToBase64(imageUrl))\n\n dispatch({\n type: 'livenessChecked',\n payload: { frame, face, imageUrl, response },\n })\n } catch (e) {\n dispatch({\n type: 'livenessCheckFailed',\n payload: { error: e as Error },\n })\n }\n })()\n }, [checkLiveness, face, frame, isReady, submissionError])\n\n const onFallbackImageCaptured = useCallback(\n async (imageUrl: string) => {\n dispatch({ type: 'livenessChecking' })\n\n try {\n const response = await checkLiveness(await dataUrlToBase64(imageUrl))\n dispatch({\n type: 'livenessChecked',\n payload: { imageUrl, response },\n })\n } catch (e) {\n dispatch({\n type: 'livenessCheckFailed',\n payload: { error: e as Error },\n })\n }\n },\n [checkLiveness]\n )\n\n useEffect(() => {\n if (isPassed && state.imageUrl) onSuccess?.(state.imageUrl)\n }, [onSuccess, state.imageUrl, isPassed])\n\n useEffect(() => {\n const allowedFailures = modelsError ? 1 : 2\n if (state.timesLivenessCheckFailed >= allowedFailures) {\n onTimeout?.()\n }\n }, [modelsError, onTimeout, state.timesLivenessCheckFailed])\n\n useTimeout(\n timeoutDurationMs,\n onTimeout,\n state.requestState === 'PASSED' || !!modelsError,\n state.requestState === 'IN_PROGRESS'\n )\n\n const verbiage = useTranslations(rawVerbiage, {\n guidanceRemoveEyeCoveringsText:\n 'Please remove your eye coverings (sunglasses, eye patch, etc.)...',\n guidanceRemoveHeadCoveringsText:\n 'Please remove your head coverings (hat, scarf, etc.)...',\n guidanceRemoveMaskText: 'Please remove your mask...',\n progressPreviewText: 'Processing...',\n })\n\n const guidanceMessage = state.eyeCoveringDetected\n ? verbiage.guidanceRemoveEyeCoveringsText\n : state.headCoveringDetected\n ? verbiage.guidanceRemoveHeadCoveringsText\n : state.maskDetected\n ? verbiage.guidanceRemoveMaskText\n : undefined\n\n if (modelsError) {\n return <SelfieCaptureFallback onFinished={onFallbackImageCaptured} />\n }\n\n return (\n <>\n <InvisibleCanvas ref={rawCanvas} />\n <InvisibleCanvas ref={cropCanvas} />\n\n <SelfieCapture\n onSelfieCaptured={onSelfieCaptured}\n onExit={onExit}\n timeoutDurationMs={timeoutDurationMs}\n guidanceMessage={guidanceMessage}\n guidanceSatisfied={guidanceMessage ? false : undefined}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n\n {imageUrl && (\n <SelfieProgressPreview\n classNames={classNames.imagePreview}\n imageUrl={imageUrl}\n text={verbiage.progressPreviewText ?? ''}\n />\n )}\n </>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport {\n FaceLivenessCapture,\n FaceLivenessCaptureClassNames,\n FaceLivenessCaptureColors,\n FaceLivenessCaptureVerbiage,\n} from './FaceLivenessCapture'\nimport {\n SelfieCaptureLoadingOverlay,\n SelfieCaptureLoadingOverlayAssets,\n SelfieCaptureLoadingOverlayClassNames,\n SelfieCaptureLoadingOverlayColors,\n SelfieCaptureLoadingOverlayVerbiage,\n} from '../selfie_capture/SelfieCaptureLoadingOverlay'\nimport {\n FaceLivenessSuccess,\n FaceLivenessSuccessClassNames,\n FaceLivenessSuccessColors,\n FaceLivenessSuccessVerbiage,\n} from './FaceLivenessSuccess'\nimport {\n FaceLivenessFailure,\n FaceLivenessFailureAssets,\n FaceLivenessFailureClassNames,\n FaceLivenessFailureColors,\n FaceLivenessFailureVerbiage,\n} from './FaceLivenessFailure'\nimport {\n LivenessCheckRequest,\n SubmissionContext,\n SubmissionResponse,\n} from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { useShowSuccessScreen } from '../common/useShowSuccessScreen'\n\ntype CaptureState = 'LOADING' | 'CAPTURING' | 'SUCCESS' | 'FAILED'\n\nexport type FaceLivenessAssets = {\n loadingOverlay?: SelfieCaptureLoadingOverlayAssets\n failure?: FaceLivenessFailureAssets\n}\n\nexport type FaceLivenessClassNames = {\n loadingOverlay?: SelfieCaptureLoadingOverlayClassNames\n capture?: FaceLivenessCaptureClassNames\n success?: FaceLivenessSuccessClassNames\n failure?: FaceLivenessFailureClassNames\n}\n\nexport type FaceLivenessColors = FaceLivenessCaptureColors & {\n loadingOverlay?: SelfieCaptureLoadingOverlayColors\n success?: FaceLivenessSuccessColors\n failure?: FaceLivenessFailureColors\n}\n\nexport type FaceLivenessVerbiage = FaceLivenessCaptureVerbiage & {\n loadingOverlay?: SelfieCaptureLoadingOverlayVerbiage\n success?: FaceLivenessSuccessVerbiage\n failure?: FaceLivenessFailureVerbiage\n}\n\nexport type FaceLivenessWizardProps = {\n onSuccess?: (resp: SubmissionResponse, req: LivenessCheckRequest) => void\n onComplete?: (\n resp: SubmissionResponse | null,\n req: LivenessCheckRequest | null\n ) => void\n onTimeout?: (\n resp: SubmissionResponse | null,\n req: LivenessCheckRequest | null\n ) => void\n onExitCapture?: () => void\n onExitAfterFailure?: (\n resp: SubmissionResponse | null,\n req: LivenessCheckRequest | null\n ) => void\n\n timeoutDurationMs?: number\n maxRetries?: number\n skipSuccessScreen?: boolean | (() => Promise<boolean>)\n releaseCameraAccessOnExit?: boolean\n\n assets?: FaceLivenessAssets\n classNames?: FaceLivenessClassNames\n colors?: FaceLivenessColors\n verbiage?: FaceLivenessVerbiage\n debugMode?: boolean\n}\n\nexport const FaceLivenessWizard = ({\n onComplete,\n onSuccess,\n onTimeout,\n onExitCapture,\n onExitAfterFailure,\n timeoutDurationMs = 15000,\n maxRetries = 2,\n skipSuccessScreen = false,\n releaseCameraAccessOnExit = true,\n assets = {},\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: FaceLivenessWizardProps): ReactElement => {\n const {\n submissionResponse,\n livenessCheckRequest,\n setSelfieImage,\n logSelfieCaptureAttempt,\n } = useContext(SubmissionContext)\n const { releaseCameraAccess } = useContext(CameraStateContext)\n const [faceCropImageUrl, setFaceCropImageUrl] = useState('')\n const [retryCount, setRetryCount] = useState(0)\n const [captureState, setCaptureState] = useState<CaptureState>('LOADING')\n const captureStartedAt = useRef<Date>()\n const captureEndedAt = useRef<Date>()\n const operationStartedAt = useRef<Date>()\n\n useEffect(() => {\n operationStartedAt.current = new Date()\n }, [])\n\n useEffect(() => {\n if (captureState === 'CAPTURING') {\n captureStartedAt.current = new Date()\n }\n }, [captureState])\n\n const onCapture = useCallback(() => {\n captureEndedAt.current = new Date()\n }, [])\n\n const logCaptureMetadata = useCallback(() => {\n logSelfieCaptureAttempt({\n autoCapture: 'Y',\n captureTime:\n (captureEndedAt.current ?? new Date()).getTime() -\n (captureStartedAt.current ?? new Date()).getTime(),\n operationTime:\n new Date().getTime() -\n (operationStartedAt.current ?? new Date()).getTime(),\n })\n\n operationStartedAt.current = new Date()\n }, [logSelfieCaptureAttempt])\n\n const onSuccessCallback = useCallback(\n async (faceCropImageUrl: string) => {\n if (!livenessCheckRequest || !submissionResponse) return\n setCaptureState('SUCCESS')\n setFaceCropImageUrl(faceCropImageUrl)\n setSelfieImage(await dataUrlToBase64(faceCropImageUrl))\n onSuccess?.(submissionResponse, livenessCheckRequest)\n },\n [onSuccess, setSelfieImage, livenessCheckRequest, submissionResponse]\n )\n\n const onTimeoutCallback = useCallback(() => {\n setCaptureState('FAILED')\n onTimeout?.(submissionResponse, livenessCheckRequest)\n }, [onTimeout, livenessCheckRequest, submissionResponse])\n\n const [attempt, setAttempt] = useState(0)\n const onExitCallback = useCallback(() => {\n setAttempt((n) => n + 1)\n setCaptureState('LOADING')\n onExitCapture?.()\n }, [onExitCapture])\n\n const onDoneCallback = useCallback(() => {\n logCaptureMetadata()\n releaseCameraAccessOnExit && releaseCameraAccess()\n setTimeout(() => {\n onComplete?.(submissionResponse, livenessCheckRequest)\n }, 0)\n }, [\n logCaptureMetadata,\n onComplete,\n releaseCameraAccess,\n releaseCameraAccessOnExit,\n livenessCheckRequest,\n submissionResponse,\n ])\n\n const showSuccessScreen = useShowSuccessScreen(\n skipSuccessScreen,\n captureState === 'SUCCESS',\n onDoneCallback\n )\n\n return (\n <>\n {captureState !== 'LOADING' &&\n (() => {\n switch (captureState) {\n case 'CAPTURING':\n return (\n <FaceLivenessCapture\n key={`capture${attempt}`}\n onCapture={onCapture}\n onSuccess={onSuccessCallback}\n onTimeout={onTimeoutCallback}\n onExit={onExitCallback}\n timeoutDurationMs={timeoutDurationMs}\n classNames={classNames.capture}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n )\n\n case 'SUCCESS':\n if (!showSuccessScreen) return null\n return (\n <FaceLivenessSuccess\n key=\"success\"\n imageUrl={faceCropImageUrl}\n classNames={classNames.success}\n colors={colors.success}\n verbiage={verbiage.success}\n onDoneClick={onDoneCallback}\n onRetryClick={() => {\n logCaptureMetadata()\n setCaptureState('CAPTURING')\n }}\n />\n )\n\n case 'FAILED':\n return (\n <FaceLivenessFailure\n key=\"failure\"\n assets={assets.failure}\n classNames={classNames.failure}\n colors={colors.failure}\n verbiage={verbiage.failure}\n canRetry={maxRetries > -1 && retryCount < maxRetries}\n onRetryClick={() => {\n logCaptureMetadata()\n setRetryCount((c) => c + 1)\n setCaptureState('CAPTURING')\n }}\n onExitClick={() => {\n releaseCameraAccessOnExit && releaseCameraAccess()\n setTimeout(() => {\n onExitAfterFailure?.(\n submissionResponse,\n livenessCheckRequest\n )\n }, 0)\n }}\n />\n )\n\n default:\n return null\n }\n })()}\n\n <SelfieCaptureLoadingOverlay\n key={attempt}\n assets={assets.loadingOverlay}\n classNames={classNames.loadingOverlay}\n colors={colors.loadingOverlay}\n verbiage={verbiage.loadingOverlay}\n onDismissed={() => {\n setCaptureState('CAPTURING')\n }}\n />\n </>\n )\n}\n","import React, { ReactElement, ReactNode, useCallback, useState } from 'react'\nimport {\n GuideOrientationContext,\n GuideOrientationState,\n} from '../contexts/GuideOrientationContext'\nimport useResizeObserver from 'use-resize-observer'\n\nexport const GuideOrientationProvider = ({\n children,\n}: {\n children: ReactNode\n}): ReactElement => {\n const [_, setDimensions] = useState({ width: 1, height: 1 })\n const [imageAspectRatio, setImageAspectRatio] = useState(1)\n const {\n ref: wrapperRef,\n width: wrapperWidth = 1,\n height: wrapperHeight = 1,\n } = useResizeObserver<HTMLDivElement>()\n\n const wrapperAspectRatio = wrapperWidth / wrapperHeight\n\n const onImageLoaded = useCallback((e: React.SyntheticEvent) => {\n const img = e.target as HTMLImageElement\n setImageAspectRatio(img.naturalWidth / img.naturalHeight)\n }, [])\n\n const orientation = 'landscape' //width > height ? 'landscape' : 'portrait'\n const value: GuideOrientationState = {\n orientation,\n wrapperWidth,\n wrapperHeight,\n wrapperAspectRatio,\n imageAspectRatio,\n setDimensions,\n wrapperRef,\n onImageLoaded,\n }\n\n return (\n <GuideOrientationContext.Provider value={value}>\n {children}\n </GuideOrientationContext.Provider>\n )\n}\n","import React, { ReactElement, useContext, useMemo, useState } from 'react'\nimport { SubmissionContext } from '../../contexts/SubmissionContext'\n\nexport const SubmissionSuccess = (): ReactElement => {\n const { submissionRequest, submissionResponse } =\n useContext(SubmissionContext)\n const [showRequestBody, setShowRequestBody] = useState(false)\n const [truncateImages, setTruncateImages] = useState(true)\n\n const requestBodyDisplay = useMemo(() => {\n const body = JSON.parse(JSON.stringify(submissionRequest))\n if (truncateImages) {\n if (body?.customerData?.idData?.idImageFront)\n body.customerData.idData.idImageFront = truncate(\n body.customerData.idData.idImageFront,\n 200\n )\n if (body?.customerData?.idData?.idImageBack)\n body.customerData.idData.idImageBack = truncate(\n body.customerData.idData.idImageBack,\n 200\n )\n if (body?.customerData?.biometricData?.selfie)\n body.customerData.biometricData.selfie = truncate(\n body.customerData.biometricData.selfie,\n 200\n )\n }\n return JSON.stringify(body, null, 2)\n }, [submissionRequest, truncateImages])\n\n return (\n <>\n <h3>Submission completed!</h3>\n\n <button\n onClick={() => {\n setShowRequestBody(!showRequestBody)\n }}\n >\n {showRequestBody ? 'Hide' : 'Show'} request body\n </button>\n\n {showRequestBody && (\n <>\n <button\n style={{ marginLeft: 8 }}\n onClick={() => {\n setTruncateImages(!truncateImages)\n }}\n >\n {truncateImages ? 'Display full images' : 'Truncate images'}\n </button>\n\n <h5>Request Body</h5>\n <pre>{requestBodyDisplay}</pre>\n </>\n )}\n\n <h5>Response Body</h5>\n <pre>{JSON.stringify(submissionResponse, null, 2)}</pre>\n </>\n )\n}\n\nfunction truncate(str: string, max_chars: number): string {\n let truncated = str.split('').splice(0, max_chars).join('')\n if (truncated.length < str.length) truncated += '...'\n return truncated\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport {\n contentDispositionFromDataUrl,\n dataUrlToBase64Sync,\n} from '../../lib/utils/dataUrlToBase64'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport styled from 'styled-components'\nimport { LoaderButton } from '../common/LoaderButton'\nimport { ButtonsRow } from '../common/ButtonsRow'\n\nexport type AdditionalDocument = {\n name: string\n description?: string\n skip?: () => Promise<boolean>\n}\n\nexport type UploadedDocument = {\n documentName: string\n additionalDocument: string | Record<string, string>\n}\n\nexport type AdditionalDocumentCaptureClassNames = {\n container?: string\n inner?: string\n heading?: string\n description?: string\n buttonsRow?: string\n captureBtn?: string\n nextBtn?: string\n}\n\nexport type AdditionalDocumentCaptureVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n captureBtnText?: CustomerSuppliedVerbiage\n nextBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type AdditionalDocumentCaptureProps = {\n document: AdditionalDocument\n onComplete?: (uploadedDocument: UploadedDocument) => void\n classNames?: AdditionalDocumentCaptureClassNames\n verbiage?: AdditionalDocumentCaptureVerbiage\n}\n\nexport const AdditionalDocumentCapture = ({\n document,\n onComplete,\n classNames = {},\n verbiage: rawVerbiage = {},\n}: AdditionalDocumentCaptureProps): ReactElement => {\n const fileInput = useRef<HTMLInputElement | null>(null)\n const [file, setFile] = useState<File | null>(null)\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: 'Additional document capture',\n captureBtnText: 'Capture',\n nextBtnText: 'Next',\n })\n\n function onFileSelected(e: React.ChangeEvent<HTMLInputElement>) {\n const file = e.target.files?.[0]\n if (file) setFile(file)\n }\n\n function onNextClicked() {\n if (!file) return\n\n const fileReader = new FileReader()\n fileReader.onloadend = () => {\n if (!fileReader.result) return\n const fileContent = fileReader.result.toString()\n onComplete?.({\n documentName: document.name,\n additionalDocument: {\n name: file.name,\n fileContent: dataUrlToBase64Sync(fileContent),\n type: contentDispositionFromDataUrl(fileContent),\n fileUploadType: 'Y',\n isImageControlData: 'N',\n fieldId: '',\n },\n })\n }\n fileReader.readAsDataURL(file)\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <Inner className={classNames.inner}>\n <Heading className={classNames.heading}>\n {verbiage.headingText}: {document.name}\n </Heading>\n\n {document.description && (\n <Description className={classNames.description}>\n {document.description}\n </Description>\n )}\n\n <input\n ref={fileInput}\n type=\"file\"\n accept=\"image/*,.pdf\"\n onChange={onFileSelected}\n hidden\n />\n\n <StyledButtonsRow className={classNames.buttonsRow}>\n {file ? (\n <LoaderButton\n variant=\"positive\"\n className={classNames.nextBtn}\n disabled={!file}\n finished\n onClick={onNextClicked}\n >\n {verbiage.nextBtnText}\n </LoaderButton>\n ) : (\n <LoaderButton\n variant=\"primary\"\n className={classNames.captureBtn}\n finished\n onClick={() => {\n fileInput.current?.click()\n }}\n >\n {verbiage.captureBtnText}\n </LoaderButton>\n )}\n </StyledButtonsRow>\n </Inner>\n </OverlayContainer>\n )\n}\n\nconst Inner = styled(OverlayInner)`\n justify-content: center;\n`\n\nconst Heading = styled.h3`\n margin-bottom: 8px;\n`\n\nconst Description = styled.p`\n margin-bottom: 8px;\n`\n\nconst StyledButtonsRow = styled(ButtonsRow)`\n margin-top: 32px;\n`\n","import React, { ReactElement, useEffect, useState } from 'react'\nimport {\n AdditionalDocument,\n AdditionalDocumentCapture,\n AdditionalDocumentCaptureClassNames,\n AdditionalDocumentCaptureVerbiage,\n UploadedDocument,\n} from './AdditionalDocumentCapture'\n\nexport type AdditionalDocumentCaptureWizardClassNames =\n AdditionalDocumentCaptureClassNames\n\nexport type AdditionalDocumentCaptureWizardVerbiage =\n AdditionalDocumentCaptureVerbiage\n\nexport type AdditionalDocumentCaptureWizardProps = {\n documents: AdditionalDocument[]\n onComplete?: (uploadedDocuments: UploadedDocument[]) => void\n classNames?: AdditionalDocumentCaptureWizardClassNames\n verbiage?: AdditionalDocumentCaptureWizardVerbiage\n}\n\nexport const AdditionalDocumentCaptureWizard = ({\n documents,\n onComplete,\n classNames = {},\n verbiage = {},\n}: AdditionalDocumentCaptureWizardProps): ReactElement => {\n const [uploadedDocuments, setUploadedDocuments] = useState<\n (UploadedDocument | null)[]\n >([])\n const documentIndex = uploadedDocuments.length\n const currentDocument = documents[documentIndex]\n const isComplete = documentIndex >= documents.length\n\n useEffect(() => {\n if (!currentDocument?.skip) return\n ;(async () => {\n if (await currentDocument.skip?.()) {\n setUploadedDocuments((f) => [...f, null])\n }\n })()\n }, [currentDocument])\n\n useEffect(() => {\n if (isComplete) {\n onComplete?.(uploadedDocuments.filter((d) => !!d) as UploadedDocument[])\n }\n }, [isComplete, onComplete, uploadedDocuments])\n\n if (isComplete) return <>Thanks, your documents have been received.</>\n\n return (\n <AdditionalDocumentCapture\n key={documentIndex}\n document={currentDocument}\n classNames={classNames}\n verbiage={verbiage}\n onComplete={(data) => {\n setUploadedDocuments((f) => [...f, data])\n }}\n />\n )\n}\n","import ReactSignatureCanvas from 'react-signature-canvas'\nimport { dataUrlToBase64Sync } from '../../lib/utils/dataUrlToBase64'\n\nexport type SignatureData = {\n clickX_simple: number[][]\n clickY_simple: number[][]\n time_simple: string[][]\n pressure: string\n fileContent: string\n}\n\nexport function signatureDataToIdmissionFormat(\n signatureCanvas: ReactSignatureCanvas\n): SignatureData {\n const dataURL = signatureCanvas.toDataURL() ?? null\n\n const signatureData: SignatureData = {\n clickX_simple: [],\n clickY_simple: [],\n time_simple: [],\n pressure: '',\n fileContent: dataURL ? dataUrlToBase64Sync(dataURL) : '',\n }\n\n signatureCanvas.toData().forEach((stroke) => {\n const xs: number[] = []\n const ys: number[] = []\n const times: string[] = []\n stroke.forEach((d) => {\n xs.push(d.x)\n ys.push(d.y)\n times.push(new Date(d.time).toString())\n })\n signatureData.clickX_simple.push(xs)\n signatureData.clickY_simple.push(ys)\n signatureData.time_simple.push(times)\n })\n\n return signatureData\n}\n","import styled from 'styled-components'\nimport { ButtonsRow } from './ButtonsRow'\n\nexport const SignaturePaperBacking = styled.div`\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n ${(props) =>\n props.theme.signatureCapture?.background\n ? `background: ${props.theme.signatureCapture?.background};`\n : ``}\n ${(props) =>\n props.theme.signatureCapture?.backgroundSize\n ? `background-size: ${props.theme.signatureCapture?.backgroundSize};`\n : ``}\n ${(props) =>\n props.theme.signatureCapture?.backgroundPosition\n ? `background-position: ${props.theme.signatureCapture?.backgroundPosition};`\n : ``}\n`\n\nexport const SignatureCanvasContainer = styled.div`\n position: absolute;\n top: 25%;\n left: 15%;\n width: 70%;\n height: 50%;\n\n @media (max-width: 800px) {\n top: 15%;\n left: 2%;\n width: 96%;\n height: 70%;\n }\n`\n\nexport const SignaturePad = styled.div`\n position: relative;\n background: ${(props) =>\n props.theme.signatureCapture?.canvas?.background ??\n 'rgba(255, 255, 255, 0.5)'};\n border: ${(props) =>\n props.theme.signatureCapture?.canvas?.border ?? `1px solid #dedede`};\n border-radius: ${(props) =>\n props.theme.signatureCapture?.canvas?.borderRadius ?? '16px'};\n flex-grow: 1;\n z-index: 100;\n height: 100%;\n`\n\nexport const SignatureButtonsContainer = styled(ButtonsRow)`\n flex-grow: 0;\n padding-top: 12px;\n display: flex;\n z-index: 1000;\n position: relative;\n`\n","import { useCallback, useRef, useState } from 'react'\nimport { Camera } from './Camera'\n\nexport const useVideoRecorder = (camera: Camera | null) => {\n const mediaRecorder = useRef<MediaRecorder | null>(null)\n const videoChunks = useRef<BlobPart[]>([])\n const [videoUrl, setVideoUrl] = useState<string | null>(null)\n const [isRecording, setIsRecording] = useState(false)\n\n const stream = camera?.stream\n const startRecording = useCallback(() => {\n if (!stream) return\n\n videoChunks.current = []\n setIsRecording(true)\n\n mediaRecorder.current = new MediaRecorder(stream)\n\n mediaRecorder.current.ondataavailable = (e) => {\n videoChunks.current.push(e.data)\n }\n\n mediaRecorder.current.onstop = () => {\n const blobFile = new Blob(videoChunks.current, { type: 'video/mp4' })\n videoChunks.current = []\n setVideoUrl(URL.createObjectURL(blobFile))\n setIsRecording(false)\n camera?.release()\n }\n\n mediaRecorder.current.start()\n }, [camera, stream])\n\n const stopRecording = useCallback(() => {\n mediaRecorder.current?.stop()\n }, [])\n\n return { isRecording, startRecording, stopRecording, videoUrl }\n}\n","import React, { useContext, useEffect, useRef, useState } from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { useVideoRecorder } from '../../lib/camera/useVideoRecorder'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport {\n SignatureData,\n signatureDataToIdmissionFormat,\n} from '../signature_capture/data'\nimport SignatureCanvas from 'react-signature-canvas'\nimport useResizeObserver from 'use-resize-observer'\nimport { HighPerformanceSelfieGuidanceModelsContext } from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport { PageContainer } from '../common/Page'\nimport {\n SignatureButtonsContainer,\n SignatureCanvasContainer,\n SignaturePad,\n} from '../common/signature'\nimport {\n GuidanceMessage,\n GuidanceMessageContainer,\n} from '../common/GuidanceMessage'\nimport { DebugStatsPane } from '../common/debug'\nimport { ExitCaptureButton } from '../common/ExitCaptureButton'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport { LoaderButton } from '../common/LoaderButton'\nimport styled from 'styled-components'\n\nexport type VideoSignatureCaptureClassNames = {\n container?: string\n cameraFeed?: string\n guidanceMessageContainer?: string\n guidanceMessage?: string\n canvasContainer?: string\n canvasInner?: string\n canvas?: string\n buttonsRow?: string\n acceptBtn?: string\n clearBtn?: string\n exitCaptureBtn?: string\n}\n\nexport type VideoSignatureCaptureColors = {\n guidanceMessageBackgroundColor?: string\n guidanceMessageTextColor?: string\n}\n\nexport type VideoSignatureCaptureVerbiage = {\n guidanceMessageText?: CustomerSuppliedVerbiage\n acceptBtnText?: CustomerSuppliedVerbiage\n clearBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type VideoSignatureCaptureProps = {\n onVideoCaptured?: (\n videoData: Blob,\n signatureData: SignatureData,\n signatureImageData: string\n ) => void\n onFaceNotDetected?: () => void\n onExit?: () => void\n classNames?: VideoSignatureCaptureClassNames\n colors?: VideoSignatureCaptureColors\n verbiage?: VideoSignatureCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const VideoSignatureCapture = ({\n onVideoCaptured,\n onFaceNotDetected,\n onExit,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: VideoSignatureCaptureProps): React.ReactElement => {\n const { cameraRef, videoRef } = useContext(CameraStateContext)\n const { ref, width, height } = useResizeObserver()\n const signaturePad = useRef<SignatureCanvas | null>(null)\n const signatureRecorder = useRef<MediaRecorder | null>(null)\n const recordedChunks = useRef<BlobPart[]>([])\n const [signatureVideoUrl, setSignatureVideoUrl] = useState<string | null>(\n null\n )\n const { onPredictionMade } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n\n const { isRecording, startRecording, stopRecording, videoUrl } =\n useVideoRecorder(cameraRef.current)\n const [signatureData, setSignatureData] = useState<SignatureData | null>(null)\n const [signatureDataUrl, setSignatureDataUrl] = useState<string | null>(null)\n const [signatureVideoData, setSignatureVideoData] = useState<Blob | null>(\n null\n )\n\n colors.guidanceMessageBackgroundColor ||= '#ccc'\n colors.guidanceMessageTextColor ||= 'black'\n\n const verbiage = useTranslations(rawVerbiage, {\n guidanceMessageText: 'Please sign the box below',\n acceptBtnText: 'Accept',\n clearBtnText: 'Clear',\n })\n\n const outputCanvas = useRef<HTMLCanvasElement | null>(null)\n\n useEffect(() => {\n // delay 100ms to make sure outputCanvas has rendered.\n setTimeout(() => {\n if (!isRecording && !videoUrl && !!outputCanvas.current) {\n startRecording()\n\n const stream = outputCanvas.current.captureStream(25 /* fps */)\n signatureRecorder.current = new MediaRecorder(stream, {\n // mimeType: 'video/mp4; codecs=\"avc1.424028, mp4a.40.2\"',\n })\n\n signatureRecorder.current.start()\n\n signatureRecorder.current.ondataavailable = function (event) {\n recordedChunks.current.push(event.data)\n if (signatureRecorder.current?.state === 'recording') {\n signatureRecorder.current.stop()\n }\n }\n\n signatureRecorder.current.onstop = function () {\n const blob = new Blob(recordedChunks.current, { type: 'video/mp4' })\n setSignatureVideoData(blob)\n const url = URL.createObjectURL(blob)\n setSignatureVideoUrl(url)\n }\n }\n }, 100)\n }, [isRecording, startRecording, videoUrl])\n\n useEffect(() => {\n if (signatureVideoData && signatureData && signatureDataUrl) {\n onVideoCaptured?.(signatureVideoData, signatureData, signatureDataUrl)\n }\n }, [onVideoCaptured, signatureData, signatureDataUrl, signatureVideoData])\n\n const animationFrame = useRef(0)\n useEffect(() => {\n if (\n !signaturePad.current ||\n !videoRef.current ||\n !outputCanvas.current ||\n !cameraRef.current ||\n !isRecording\n )\n return\n\n let [w, h] = [cameraRef.current.width, cameraRef.current.height]\n const isPortrait = window.innerWidth < window.innerHeight\n const cameraIsLandscape = w > h\n if (isPortrait && cameraIsLandscape) [w, h] = [h, w]\n outputCanvas.current.width = w\n outputCanvas.current.height = h\n\n const ctx = outputCanvas.current.getContext('2d')\n if (!ctx) return\n\n animationFrame.current = requestAnimationFrame(async function runFrame() {\n if (!signaturePad.current || !videoRef.current || !outputCanvas.current) {\n cancelAnimationFrame(animationFrame.current)\n return\n }\n\n const rect: [number, number, number, number] = [\n w * (isPortrait ? 0.02 : 0.15),\n h * (isPortrait ? 0.15 : 0.25),\n w * (isPortrait ? 0.96 : 0.7),\n h * (isPortrait ? 0.7 : 0.5),\n ]\n\n ctx.drawImage(videoRef.current, 0, 0, w, h)\n\n ctx.beginPath()\n ctx.fillStyle = 'rgba(255,255,255,0.5)'\n ctx.roundRect(...rect, 16)\n ctx.fill()\n\n ctx.drawImage(signaturePad.current.getCanvas(), ...rect)\n\n animationFrame.current = requestAnimationFrame(runFrame)\n })\n\n return () => {\n cancelAnimationFrame(animationFrame.current)\n }\n }, [cameraRef, isRecording, onFaceNotDetected, videoRef])\n\n const [numFramesWithoutFaces, setNumFramesWithoutFaces] = useState(0)\n useEffect(() => {\n onPredictionMade((faces) => {\n setNumFramesWithoutFaces((n) => (faces.length === 0 ? n + 1 : 0))\n })\n }, [onPredictionMade])\n\n useEffect(() => {\n if (numFramesWithoutFaces >= 2) {\n onFaceNotDetected?.()\n }\n }, [numFramesWithoutFaces, onFaceNotDetected])\n\n if (!isRecording && videoUrl) {\n return (\n <>\n {signatureVideoUrl && (\n <video src={signatureVideoUrl} controls={true} width=\"100%\" />\n )}\n {signatureDataUrl && <img src={signatureDataUrl} alt=\"signature\" />}\n {signatureData && (\n <textarea\n readOnly\n style={{ width: '100%', height: 500 }}\n value={JSON.stringify(signatureData, null, 2)}\n />\n )}\n </>\n )\n }\n\n function onAcceptClicked() {\n if (!signaturePad.current) return\n\n const signatureData = signatureDataToIdmissionFormat(signaturePad.current)\n setSignatureData(signatureData)\n setSignatureDataUrl(signaturePad.current.toDataURL())\n stopRecording()\n signatureRecorder.current?.stop()\n }\n\n return (\n <PageContainer className={`flex ${classNames.container ?? ''}`}>\n <CameraVideoTag className={classNames.cameraFeed} />\n\n {verbiage.guidanceMessageText && (\n <GuidanceMessageContainer\n $top=\"5vh\"\n className={classNames.guidanceMessageContainer}\n >\n <GuidanceMessage\n className={classNames.guidanceMessage}\n $background={colors.guidanceMessageBackgroundColor}\n $textColor={colors.guidanceMessageTextColor}\n >\n {verbiage.guidanceMessageText}\n </GuidanceMessage>\n </GuidanceMessageContainer>\n )}\n\n <SignatureCanvasContainer className={classNames.canvasContainer}>\n <SignaturePad ref={ref} className={classNames.canvasInner}>\n <SignatureCanvas\n ref={signaturePad}\n canvasProps={{ width, height, className: classNames.canvas }}\n />\n </SignaturePad>\n\n <SignatureButtonsContainer className={classNames.buttonsRow}>\n <LoaderButton\n variant=\"secondary\"\n className={classNames.clearBtn}\n onClick={signaturePad.current?.clear}\n finished\n >\n {verbiage.clearBtnText}\n </LoaderButton>\n\n <AcceptBtn\n variant=\"positive\"\n className={classNames.acceptBtn}\n style={{ marginLeft: 'auto' }}\n onClick={onAcceptClicked}\n finished\n >\n {verbiage.acceptBtnText}\n </AcceptBtn>\n </SignatureButtonsContainer>\n </SignatureCanvasContainer>\n\n {debugMode && (\n <DebugStatsPane>\n Video: {cameraRef.current?.width}x{cameraRef.current?.height}\n </DebugStatsPane>\n )}\n\n <ExitCaptureButton\n onClick={onExit}\n className={classNames.exitCaptureBtn}\n />\n\n <div style={{ display: 'none' }}>\n <canvas ref={outputCanvas} />\n </div>\n </PageContainer>\n )\n}\n\nconst AcceptBtn = styled(LoaderButton)`\n margin-left: auto;\n`\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport {\n VideoSignatureCapture,\n VideoSignatureCaptureClassNames,\n VideoSignatureCaptureColors,\n VideoSignatureCaptureVerbiage,\n} from './VideoSignatureCapture'\nimport {\n FaceLivenessCapture,\n FaceLivenessCaptureClassNames,\n} from '../face_liveness/FaceLivenessCapture'\nimport { HighPerformanceSelfieGuidanceModelsProvider } from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport { SubmissionContext } from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { SignatureData } from '../signature_capture/data'\nimport {\n VideoSignatureSuccess,\n VideoSignatureSuccessClassNames,\n VideoSignatureSuccessColors,\n VideoSignatureSuccessVerbiage,\n} from './VideoSignatureSuccess'\nimport {\n FaceLivenessColors,\n FaceLivenessVerbiage,\n} from '../face_liveness/FaceLivenessWizard'\nimport {\n SelfieCaptureLoadingOverlay,\n SelfieCaptureLoadingOverlayAssets,\n SelfieCaptureLoadingOverlayClassNames,\n SelfieCaptureLoadingOverlayVerbiage,\n} from '../selfie_capture/SelfieCaptureLoadingOverlay'\nimport { useShowSuccessScreen } from '../common/useShowSuccessScreen'\n\ntype CaptureState =\n | 'LOADING'\n | 'CHECKING_LIVENESS'\n | 'CAPTURING_SIGNATURE'\n | 'SUCCESS'\n | 'FAILED'\n\nexport type VideoSignatureAssets = {\n loadingOverlay?: SelfieCaptureLoadingOverlayAssets\n}\n\nexport type VideoSignatureClassNames = VideoSignatureCaptureClassNames & {\n loadingOverlay?: SelfieCaptureLoadingOverlayClassNames\n faceLiveness?: FaceLivenessCaptureClassNames\n success?: VideoSignatureSuccessClassNames\n}\n\nexport type VideoSignatureColors = VideoSignatureCaptureColors & {\n faceLiveness?: FaceLivenessColors\n success?: VideoSignatureSuccessColors\n}\n\nexport type VideoSignatureVerbiage = VideoSignatureCaptureVerbiage & {\n loadingOverlay?: SelfieCaptureLoadingOverlayVerbiage\n faceLiveness?: FaceLivenessVerbiage\n success?: VideoSignatureSuccessVerbiage\n}\n\nexport type VideoSignatureWizardProps = {\n onComplete?: () => void\n onVideoCaptured?: (\n videoData: Blob,\n signatureData: SignatureData,\n signatureImageData: string\n ) => void\n onRetryClicked?: () => void\n onExitCapture?: () => void\n skipSuccessScreen?: boolean | (() => Promise<boolean>)\n\n assets?: VideoSignatureAssets\n classNames?: VideoSignatureClassNames\n colors?: VideoSignatureColors\n verbiage?: VideoSignatureVerbiage\n debugMode?: boolean\n}\n\nexport const VideoSignatureWizard = ({\n onComplete,\n onVideoCaptured,\n onRetryClicked,\n onExitCapture,\n skipSuccessScreen = false,\n assets = {},\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: VideoSignatureWizardProps): ReactElement => {\n const {\n selfieImage,\n signatureVideoUrl,\n setSelfieImage,\n setSignatureData,\n setSignatureVideoUrl,\n logSelfieCaptureAttempt,\n } = useContext(SubmissionContext)\n const [captureState, setCaptureState] = useState<CaptureState>('LOADING')\n const operationStartedAt = useRef<Date>()\n const captureStartedAt = useRef<Date>()\n const captureEndedAt = useRef<Date>()\n\n useEffect(() => {\n operationStartedAt.current = new Date()\n }, [])\n\n useEffect(() => {\n if (captureState === 'CHECKING_LIVENESS') {\n captureStartedAt.current = new Date()\n }\n }, [captureState])\n\n const logCaptureMetadata = useCallback(() => {\n logSelfieCaptureAttempt({\n autoCapture: 'Y',\n captureTime:\n (captureEndedAt.current ?? new Date()).getTime() -\n (captureStartedAt.current ?? new Date()).getTime(),\n operationTime:\n new Date().getTime() -\n (operationStartedAt.current ?? new Date()).getTime(),\n })\n\n operationStartedAt.current = new Date()\n }, [logSelfieCaptureAttempt])\n\n const onLoadingOverlayDismissed = useCallback(() => {\n setCaptureState('CHECKING_LIVENESS')\n }, [])\n\n const onFaceCaptureSuccess = useCallback(\n async (faceCropImageUrl: string) => {\n setCaptureState('CAPTURING_SIGNATURE')\n logCaptureMetadata()\n if (!selfieImage) {\n setSelfieImage(await dataUrlToBase64(faceCropImageUrl))\n }\n },\n [logCaptureMetadata, selfieImage, setSelfieImage]\n )\n\n const onSignatureCaptureCompleted = useCallback(\n (\n videoData: Blob,\n signatureData: SignatureData,\n signatureImageData: string\n ) => {\n setSignatureData(signatureData)\n setSignatureVideoUrl(URL.createObjectURL(videoData))\n setCaptureState('SUCCESS')\n onVideoCaptured?.(videoData, signatureData, signatureImageData)\n },\n [onVideoCaptured, setSignatureData, setSignatureVideoUrl]\n )\n\n const onSignatureCaptureFacesNotDetected = useCallback(() => {\n setCaptureState('CHECKING_LIVENESS')\n }, [])\n\n const [attempt, setAttempt] = useState(0)\n const onExit = useCallback(() => {\n setAttempt((n) => n + 1)\n setCaptureState('LOADING')\n onExitCapture?.()\n }, [onExitCapture])\n const onRetry = useCallback(() => {\n onRetryClicked?.()\n onExit()\n }, [onExit, onRetryClicked])\n\n const showSuccessScreen = useShowSuccessScreen(\n skipSuccessScreen,\n captureState === 'SUCCESS',\n onComplete\n )\n\n return (\n <HighPerformanceSelfieGuidanceModelsProvider\n throttleMs={captureState === 'CAPTURING_SIGNATURE' ? 250 : 0}\n >\n {captureState !== 'LOADING' &&\n (() => {\n switch (captureState) {\n case 'CHECKING_LIVENESS':\n return (\n <FaceLivenessCapture\n onSuccess={onFaceCaptureSuccess}\n onExit={onExit}\n classNames={classNames.faceLiveness}\n colors={colors.faceLiveness}\n verbiage={verbiage.faceLiveness}\n debugMode={debugMode}\n />\n )\n\n case 'CAPTURING_SIGNATURE':\n return (\n <VideoSignatureCapture\n onVideoCaptured={onSignatureCaptureCompleted}\n onFaceNotDetected={onSignatureCaptureFacesNotDetected}\n onExit={onExit}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n )\n\n case 'SUCCESS':\n if (!showSuccessScreen) return\n return (\n <VideoSignatureSuccess\n videoUrl={signatureVideoUrl ?? ''}\n onDoneClick={onComplete}\n onRetryClick={onRetry}\n classNames={classNames.success}\n colors={colors.success}\n verbiage={verbiage.success}\n />\n )\n\n default:\n return null\n }\n })()}\n\n <SelfieCaptureLoadingOverlay\n key={attempt}\n assets={assets.loadingOverlay}\n classNames={classNames.loadingOverlay}\n verbiage={verbiage.loadingOverlay}\n onDismissed={onLoadingOverlayDismissed}\n />\n </HighPerformanceSelfieGuidanceModelsProvider>\n )\n}\n","import React, {\n CSSProperties,\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport useResizeObserver from 'use-resize-observer'\nimport { CameraStateContext } from '../camera/CameraProvider'\n\nexport type IdVideoCaptureFlipIdPromptAssets = {\n frontImageUrl?: string\n backImageUrl?: string\n}\nexport type IdVideoCaptureFlipIdPromptVerbiage = {\n instructionText?: CustomerSuppliedVerbiage\n}\n\nexport type IdVideoCaptureFlipIdPromptProps = {\n imageWidth?: number\n imageHeight?: number\n style?: CSSProperties\n assets?: IdVideoCaptureFlipIdPromptAssets\n verbiage?: IdVideoCaptureFlipIdPromptVerbiage\n}\n\nexport const IdVideoCaptureFlipIdPrompt = ({\n imageWidth,\n imageHeight,\n style = {},\n assets = {},\n verbiage = {},\n}: IdVideoCaptureFlipIdPromptProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const { cameraRef } = useContext(CameraStateContext)\n\n assets.frontImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.backImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n\n const instructionText = useVerbiage(\n verbiage.instructionText,\n 'Please flip your ID card...',\n )\n\n const padding = 0\n const borderWidth = 4\n const borderColor = 'white'\n const isMirrored = !cameraRef.current?.isRearFacing\n\n // const [imageLoaded, setImageLoaded] = useState(false)\n const onImageLoaded = useCallback(() => {\n // setImageLoaded(true)\n }, [])\n\n let imageStyle: React.CSSProperties = {\n height: height - padding * 2 - borderWidth * 2,\n }\n // if (imageAspectRatio >= wrapperAspectRatio) {\n imageStyle = {\n width: width - padding * 2 - borderWidth * 2,\n }\n // }\n\n const [transitionTime, setTransitionTime] = useState(1)\n const [rotationAngle, setRotationAngle] = useState(0)\n const frontTransforms = [`rotateY(${rotationAngle}deg)`]\n if (isMirrored) frontTransforms.push('scaleX(-1)')\n const backTransforms = [`rotateY(${180 - rotationAngle}deg)`]\n if (isMirrored) backTransforms.push('scaleX(-1)')\n\n useEffect(() => {\n const doFlip = () => {\n setTransitionTime(1)\n setRotationAngle(180)\n\n setTimeout(() => {\n setTransitionTime(0)\n setRotationAngle(0)\n }, 1500)\n }\n\n setTimeout(doFlip, 250)\n const interval = setInterval(doFlip, 2500)\n\n return () => {\n clearInterval(interval)\n }\n }, [])\n\n return (\n <div ref={ref} style={{ ...style, position: 'relative' }}>\n <div\n style={{\n display: 'flex',\n flexFlow: 'column nowrap',\n height: '100%',\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n }}\n >\n {instructionText}\n </span>\n </div>\n\n <div\n style={{\n position: 'relative',\n display: 'flex',\n flexFlow: 'row nowrap',\n alignItems: 'center',\n justifyItems: 'center',\n maxWidth: `calc(100%)`,\n maxHeight: `calc(100% - ${padding * 2}px - ${borderWidth * 2}px)`,\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n minWidth: padding,\n flexGrow: 1,\n }}\n />\n <div\n style={{\n maxWidth: `calc(100% - ${padding * 2}px - ${borderWidth * 2}px)`,\n maxHeight: height - padding * 2 - borderWidth * 2,\n }}\n >\n <div\n style={{\n position: 'relative',\n border: `${borderWidth}px solid ${borderColor}`,\n }}\n >\n <img\n src={assets.frontImageUrl}\n alt=\"\"\n width={imageWidth}\n height={imageHeight}\n onLoad={onImageLoaded}\n style={{\n backfaceVisibility: 'hidden',\n transition: `transform ${transitionTime}s`,\n transform: frontTransforms.join(' '),\n transformStyle: 'preserve-3d',\n position: 'relative',\n top: 0,\n left: 0,\n display: 'block',\n ...imageStyle,\n }}\n />\n\n <img\n src={assets.backImageUrl}\n alt=\"\"\n style={{\n backfaceVisibility: 'hidden',\n transition: `transform ${transitionTime}s`,\n transform: backTransforms.join(' '),\n transformStyle: 'preserve-3d',\n position: 'absolute',\n top: 0,\n left: 0,\n display: 'block',\n ...imageStyle,\n }}\n />\n </div>\n </div>\n <div\n style={{\n width: '100%',\n height: '100%',\n minWidth: padding,\n flexGrow: 1,\n }}\n />\n </div>\n\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n opacity: 0,\n }}\n >\n {instructionText}\n </span>\n </div>\n </div>\n </div>\n )\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { IdVideoCaptureFlipIdPrompt } from './IdVideoCaptureFlipIdPrompt'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\n\nexport type Action = 'SHOW_ID_FRONT' | 'FLIP_ID' | 'SHOW_ID_BACK' | 'READ_TEXT'\n\nexport type IdVideoCaptureGuidesAssets = {\n frontImageUrl?: string\n backImageUrl?: string\n}\n\nexport type IdVideoCaptureGuidesVerbiage = {\n idFrontInstructionText?: CustomerSuppliedVerbiage\n idBackInstructionText?: CustomerSuppliedVerbiage\n flipIdInstructionText?: CustomerSuppliedVerbiage\n}\n\nexport type IdVideoCaptureGuidesProps = {\n borderWidth?: number\n borderColor?: string\n requestedAction?: Action\n assets?: IdVideoCaptureGuidesAssets\n verbiage?: IdVideoCaptureGuidesVerbiage\n}\n\nexport const IdVideoCaptureGuides = ({\n requestedAction = 'SHOW_ID_FRONT',\n borderWidth = 3,\n borderColor = 'white',\n assets = {},\n verbiage: rawVerbiage = {},\n}: IdVideoCaptureGuidesProps): ReactElement => {\n const imageRef = useRef<HTMLImageElement | null>(null)\n const [imageWidth, setImageWidth] = useState(0)\n const [imageHeight, setImageHeight] = useState(0)\n assets.frontImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.backImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n\n const verbiage = useTranslations(rawVerbiage, {\n idFrontInstructionText: 'Display the front of your ID card...',\n idBackInstructionText: 'Display the back of your ID card...',\n })\n\n const instructionText =\n requestedAction === 'SHOW_ID_FRONT'\n ? verbiage.idFrontInstructionText\n : verbiage.idBackInstructionText\n\n const idGuideWidth = window.innerWidth > window.innerHeight ? '30%' : '75%'\n\n return (\n <>\n <div\n style={{\n position: 'absolute',\n zIndex: 1000,\n width: '100%',\n height: '100%',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n <div\n style={{\n borderWidth,\n borderColor,\n borderStyle: 'solid',\n borderRadius: '50%',\n aspectRatio: '1 / 1.618',\n height: '100%',\n margin: '4% auto auto',\n }}\n />\n\n {requestedAction === 'FLIP_ID' ? (\n <IdVideoCaptureFlipIdPrompt\n assets={assets}\n verbiage={{ instructionText: verbiage.flipIdInstructionText }}\n imageWidth={imageWidth}\n imageHeight={imageHeight}\n style={{ width: idGuideWidth, margin: '2% auto 2%' }}\n />\n ) : (\n <div\n style={{\n width: idGuideWidth,\n margin: '2% auto 2%',\n display: 'flex',\n flexFlow: 'column nowrap',\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n }}\n >\n {instructionText}\n </span>\n </div>\n\n <div style={{ border: `4px solid ${borderColor}` }}>\n <img\n ref={imageRef}\n src={\n requestedAction === 'SHOW_ID_BACK'\n ? assets.backImageUrl\n : assets.frontImageUrl\n }\n alt=\"\"\n style={{ width: '100%' }}\n onLoad={() => {\n if (!imageWidth) setImageWidth(imageRef.current?.width ?? 0)\n if (!imageHeight)\n setImageHeight(imageRef.current?.height ?? 0)\n }}\n />\n </div>\n\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n opacity: 0,\n }}\n >\n {instructionText}\n </span>\n </div>\n </div>\n )}\n </div>\n </>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport { PageContainer } from '../common/Page'\nimport {\n Face,\n HighPerformanceSelfieGuidanceModelsContext,\n} from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport {\n DebugStatsPane,\n IdCaptureDetectedObjectDebugBox,\n ObjectDetectionDebugOverlay,\n SelfieCaptureFaceDebugBox,\n useDebugScalingDetails,\n} from '../common/debug'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { DetectedObject } from '../../lib/models/DocumentDetection'\nimport useResizeObserver from 'use-resize-observer'\nimport { IdCaptureModelsContext } from '../id_capture/IdCaptureModelsProvider'\nimport {\n IdVideoCaptureGuides,\n IdVideoCaptureGuidesAssets,\n IdVideoCaptureGuidesVerbiage,\n} from './IdVideoCaptureGuides'\nimport { useVideoRecorder } from '../../lib/camera/useVideoRecorder'\nimport {\n CustomerSuppliedVerbiage,\n useTranslations,\n useVerbiage,\n} from '../../lib/locales'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\n\nexport type Action = 'SHOW_ID_FRONT' | 'FLIP_ID' | 'SHOW_ID_BACK' | 'READ_TEXT'\n\nexport type IdVideoCaptureAssets = {\n guides?: IdVideoCaptureGuidesAssets\n}\n\nexport type IdVideoCaptureColors = {\n guidesSatisfiedColor?: string\n guidesUnsatisfiedColor?: string\n readTextDoneBtn?: LoaderButtonColors\n}\n\nexport type IdVideoCaptureVerbiage = {\n guides?: IdVideoCaptureGuidesVerbiage\n readTextHeading?: CustomerSuppliedVerbiage\n readTextDoneBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type IdVideoCaptureProps = {\n onComplete?: (videoUrl: string) => void\n onFaceNotDetected?: () => void\n\n idCardFrontDetectionThreshold?: number\n idCardFrontFocusThreshold?: number\n goodIdCardFrontFramesThreshold?: number\n showIdCardBackDurationMs?: number\n skipShowIdCardBack?: boolean | (() => Promise<boolean>)\n readTextPrompt?: CustomerSuppliedVerbiage\n readTextTimeoutDurationMs?: number\n\n assets?: IdVideoCaptureAssets\n colors?: IdVideoCaptureColors\n verbiage?: IdVideoCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const IdVideoCapture = ({\n onComplete,\n onFaceNotDetected,\n\n idCardFrontDetectionThreshold = 0.48,\n idCardFrontFocusThreshold = 0.15,\n goodIdCardFrontFramesThreshold = 3,\n showIdCardBackDurationMs = 5000,\n skipShowIdCardBack = false,\n readTextPrompt,\n readTextTimeoutDurationMs = 15000,\n\n assets = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: IdVideoCaptureProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const { cameraRef, videoRef, videoLoaded, cameraReady } =\n useContext(CameraStateContext)\n const [detectedObjects, setDetectedObjects] = useState<DetectedObject[]>([])\n const [faces, setFaces] = useState<Face[]>([])\n const {\n ready: idModelsReady,\n working: idModelsWorking,\n makePrediction: makeIdPrediction,\n onPredictionMade: onIdPredictionMade,\n setThresholds,\n } = useContext(IdCaptureModelsContext)\n const { onPredictionMade: onSelfiePredictionMade } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n const { isRecording, startRecording, stopRecording, videoUrl } =\n useVideoRecorder(cameraRef.current)\n\n useEffect(() => {\n if (!isRecording && !videoUrl) startRecording()\n if (videoUrl) onComplete?.(videoUrl)\n }, [isRecording, onComplete, startRecording, videoUrl])\n\n const animationFrame = useRef(0)\n const shouldCaptureFrames = useRef(false)\n\n useEffect(() => {\n shouldCaptureFrames.current = videoLoaded && cameraReady && idModelsReady\n }, [cameraReady, idModelsReady, videoLoaded])\n\n const [requestedAction, setRequestedAction] =\n useState<Action>('SHOW_ID_FRONT')\n\n useEffect(() => {\n if (requestedAction !== 'SHOW_ID_FRONT') return\n if (!idModelsReady || !cameraReady || !videoLoaded) return\n\n animationFrame.current = requestAnimationFrame(async function runFrame() {\n if (shouldCaptureFrames.current && !idModelsWorking.current) {\n if (videoRef.current) makeIdPrediction(videoRef.current)\n }\n\n animationFrame.current = requestAnimationFrame(runFrame)\n })\n\n return () => {\n cancelAnimationFrame(animationFrame.current)\n }\n }, [\n cameraReady,\n idModelsReady,\n idModelsWorking,\n makeIdPrediction,\n requestedAction,\n videoLoaded,\n videoRef,\n ])\n\n useEffect(() => {\n setThresholds({\n document: idCardFrontDetectionThreshold,\n passport: 1,\n focus: idCardFrontFocusThreshold,\n })\n }, [idCardFrontDetectionThreshold, idCardFrontFocusThreshold, setThresholds])\n\n const [goodIdCardFrontFramesCount, setGoodFramesCount] = useState(0)\n const goodFramesThresholdMet =\n goodIdCardFrontFramesCount >= goodIdCardFrontFramesThreshold\n useEffect(() => {\n onIdPredictionMade((prediction) => {\n setDetectedObjects(prediction.detectedObjects)\n if (prediction.detectionThresholdMet && prediction.focusThresholdMet) {\n setGoodFramesCount((n) => n + 1)\n } else {\n setGoodFramesCount(0)\n }\n })\n }, [idCardFrontDetectionThreshold, onIdPredictionMade])\n\n const onIdBackCaptureComplete = useCallback(() => {\n if (readTextPrompt) {\n setRequestedAction('READ_TEXT')\n } else {\n stopRecording()\n }\n }, [readTextPrompt, stopRecording])\n\n useEffect(() => {\n ;(async () => {\n if (goodFramesThresholdMet && requestedAction == 'SHOW_ID_FRONT') {\n if (skipShowIdCardBack) {\n if (skipShowIdCardBack === true) {\n return onIdBackCaptureComplete()\n } else if (await skipShowIdCardBack()) {\n return onIdBackCaptureComplete()\n }\n }\n\n setRequestedAction('FLIP_ID')\n setTimeout(() => {\n setRequestedAction('SHOW_ID_BACK')\n }, 3500)\n }\n })()\n }, [\n goodFramesThresholdMet,\n onIdBackCaptureComplete,\n requestedAction,\n skipShowIdCardBack,\n ])\n\n useTimeout(\n showIdCardBackDurationMs,\n onIdBackCaptureComplete,\n requestedAction !== 'SHOW_ID_BACK',\n false,\n requestedAction === 'SHOW_ID_BACK'\n )\n\n const onReadTextTimeout = useCallback(() => {\n stopRecording()\n }, [stopRecording])\n\n const { timeoutStartedAt } = useTimeout(\n readTextTimeoutDurationMs,\n onReadTextTimeout,\n requestedAction !== 'READ_TEXT',\n false,\n requestedAction === 'READ_TEXT'\n )\n\n const [numFramesWithoutFaces, setNumFramesWithoutFaces] = useState(0)\n useEffect(() => {\n onSelfiePredictionMade((faces) => {\n setFaces(faces)\n setNumFramesWithoutFaces((n) => (faces.length === 0 ? n + 1 : 0))\n })\n }, [onSelfiePredictionMade])\n\n useEffect(() => {\n if (numFramesWithoutFaces >= 2) {\n onFaceNotDetected?.()\n }\n }, [numFramesWithoutFaces, onFaceNotDetected])\n\n colors.guidesSatisfiedColor ||= 'green'\n colors.guidesUnsatisfiedColor ||= 'white'\n\n const verbiage = useTranslations(rawVerbiage, {\n readTextHeading: 'Please read the following text aloud',\n readTextDoneBtnText: 'Done',\n })\n\n readTextPrompt = useVerbiage(readTextPrompt, '')\n\n const debugScalingDetails = useDebugScalingDetails({\n enabled: debugMode,\n pageWidth: width,\n pageHeight: height,\n videoWidth: videoRef.current?.videoWidth ?? 0,\n videoHeight: videoRef.current?.videoHeight ?? 0,\n })\n\n const timeRemaining = msToTime(\n Math.max(\n 0,\n readTextTimeoutDurationMs -\n (new Date().getTime() - (timeoutStartedAt ?? new Date()).getTime())\n )\n )\n\n const satisfied =\n requestedAction === 'SHOW_ID_BACK' || goodIdCardFrontFramesCount > 0\n\n return (\n <PageContainer ref={ref} className=\"flex\">\n <CameraVideoTag />\n\n {requestedAction === 'READ_TEXT' ? (\n <div\n style={{\n position: 'absolute',\n width: '100%',\n height: '100%',\n top: 0,\n left: 0,\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n <div\n style={{\n margin: 'auto auto 32px',\n background: 'rgba(255,255,255,0.5)',\n borderRadius: 8,\n padding: 20,\n fontWeight: 'bold',\n }}\n >\n {verbiage.readTextHeading}\n </div>\n\n <div\n style={{\n margin: '0 auto',\n textAlign: 'center',\n background: 'rgba(255,255,255,0.5)',\n borderRadius: 8,\n padding: 50,\n fontSize: 24,\n maxWidth: window.innerWidth > window.innerHeight ? '40%' : '90%',\n }}\n >\n {readTextPrompt}\n </div>\n\n <div style={{ display: 'flex', margin: '32px auto auto', gap: 20 }}>\n <div\n style={{\n background: 'rgba(255,255,255,0.5)',\n borderRadius: 4,\n padding: 20,\n }}\n >\n {timeRemaining}\n </div>\n\n <LoaderButton\n variant=\"positive\"\n finished\n onClick={stopRecording}\n colors={colors.readTextDoneBtn}\n >\n {verbiage.readTextDoneBtnText}\n </LoaderButton>\n </div>\n </div>\n ) : (\n <>\n <IdVideoCaptureGuides\n assets={assets.guides}\n verbiage={rawVerbiage.guides}\n requestedAction={requestedAction}\n borderColor={\n satisfied\n ? colors.guidesSatisfiedColor\n : colors.guidesUnsatisfiedColor\n }\n />\n\n {debugMode && requestedAction === 'SHOW_ID_FRONT' && (\n <>\n <ObjectDetectionDebugOverlay\n $flipX={!cameraRef.current?.isRearFacing}\n >\n {detectedObjects.map((obj, i) => (\n <IdCaptureDetectedObjectDebugBox\n key={i}\n obj={obj}\n scaling={debugScalingDetails}\n color=\"blue\"\n flipX={!cameraRef.current?.isRearFacing}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n\n <ObjectDetectionDebugOverlay\n $flipX={!cameraRef.current?.isRearFacing}\n >\n {faces.map((face, i) => (\n <SelfieCaptureFaceDebugBox\n key={i}\n face={face}\n scaling={debugScalingDetails}\n flipX={!cameraRef.current?.isRearFacing}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n </>\n )}\n </>\n )}\n\n {debugMode && (\n <DebugStatsPane>\n {cameraRef.current ? (\n <>\n ✅ Camera: {cameraRef.current.label} ({cameraRef.current.width}x\n {cameraRef.current.height})\n </>\n ) : (\n '❌ Camera not ready'\n )}\n <br />\n {isRecording ? '✅ Recording' : '❌ Not recording'}\n <br />\n {goodFramesThresholdMet ? '✅' : '❌'} Good Frame Count:{' '}\n {goodIdCardFrontFramesCount}/{goodIdCardFrontFramesThreshold}\n </DebugStatsPane>\n )}\n </PageContainer>\n )\n}\n\nfunction msToTime(s: number): string {\n const ms = s % 1000\n s = (s - ms) / 1000\n let secs = s % 60\n s = (s - secs) / 60\n const mins = s % 60\n secs += 1\n\n return mins + ':' + ('00' + secs).slice(-2)\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react'\nimport {\n IdCaptureSubmission,\n IdCaptureWizard,\n IdCaptureWizardProps,\n} from './id_capture/IdCaptureWizard'\nimport {\n FaceLivenessWizard,\n FaceLivenessWizardProps,\n} from './face_liveness/FaceLivenessWizard'\nimport { IdCaptureModelsProvider } from './id_capture/IdCaptureModelsProvider'\nimport { CameraProvider } from './camera/CameraProvider'\nimport { GuideOrientationProvider } from './GuideOrientationProvider'\nimport { SubmissionProvider } from './submission/SubmissionProvider'\nimport {\n LivenessCheckRequest,\n SubmissionAction,\n SubmissionContext,\n SubmissionEnvironment,\n SubmissionResponse,\n SubmissionStatus,\n} from '../contexts/SubmissionContext'\nimport { SubmissionSuccess } from './submission/SubmissionSuccess'\nimport { Spinner } from './common/spinner'\nimport {\n AdditionalDocumentCaptureWizard,\n AdditionalDocumentCaptureWizardProps,\n} from './additional_document_capture/AdditionalDocumentCaptureWizard'\nimport {\n SignatureCapture,\n SignatureCaptureProps,\n} from './signature_capture/SignatureCapture'\nimport { HighPerformanceSelfieGuidanceModelsProvider } from './selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport {\n VideoSignatureWizard,\n VideoSignatureWizardProps,\n} from './video_signature_capture/VideoSignatureWizard'\nimport { SignatureData } from './signature_capture/data'\nimport { UploadedDocument } from './additional_document_capture/AdditionalDocumentCapture'\nimport { PageContainer } from './common/Page'\nimport {\n VideoIdWizard,\n VideoIdWizardProps,\n} from './video_id/IdVideoCaptureWizard'\n\nexport type CompositeWizardCheck =\n | 'IdCapture'\n | 'FaceLiveness'\n | 'SignatureCapture'\n | 'VideoSignatureCapture'\n | 'AdditionalDocumentCapture'\n | 'VideoIdCapture'\n\nexport type CompositeWizardComponentProps = {\n checks: CompositeWizardCheck[]\n\n idCaptureProps?: IdCaptureWizardProps\n faceLivenessProps?: FaceLivenessWizardProps\n additionalDocumentCaptureProps?: AdditionalDocumentCaptureWizardProps\n signatureCaptureProps?: SignatureCaptureProps\n videoSignatureCaptureProps?: VideoSignatureWizardProps\n videoIdCaptureProps?: VideoIdWizardProps\n captureSignature?: boolean | (() => Promise<boolean>)\n captureSignatureVideo?: boolean | (() => Promise<boolean>)\n\n debugMode?: boolean\n}\n\nexport type CompositeWizardProps = CompositeWizardComponentProps & {\n submissionToken: string\n submissionAction?: SubmissionAction\n submissionEnvironment?: SubmissionEnvironment\n submissionUrl?: string\n onComplete?: (submissionResponse: SubmissionResponse) => void\n}\n\nexport const CompositeWizard = (props: CompositeWizardProps): ReactElement => (\n <SubmissionProvider\n token={props.submissionToken}\n action={props.submissionAction ?? SubmissionAction.VALIDATE}\n environment={props.submissionEnvironment ?? 'prod'}\n url={props.submissionUrl}\n onResponseReceived={props.onComplete}\n >\n <CompositeWizardComponent {...props} />\n </SubmissionProvider>\n)\n\nexport const CompositeWizardComponent = ({\n checks: userChecks,\n idCaptureProps = {},\n faceLivenessProps = {},\n additionalDocumentCaptureProps,\n signatureCaptureProps = {},\n videoSignatureCaptureProps = {},\n videoIdCaptureProps = {},\n captureSignature = false,\n captureSignatureVideo = false,\n debugMode = false,\n}: CompositeWizardComponentProps): ReactElement => {\n const { submit, submissionStatus, setSignatureData, setAdditionalDocuments } =\n useContext(SubmissionContext)\n const [checkIndex, setCheckIndex] = useState(0)\n const checks = useMemo(() => {\n const checks = [...userChecks]\n if (captureSignature && captureSignatureVideo) {\n throw new Error(\n 'captureSignature and captureSignatureVideo cannot be used together'\n )\n }\n if (captureSignature) {\n checks.push('SignatureCapture')\n }\n if (captureSignatureVideo) {\n checks.push('VideoSignatureCapture')\n // remove face liveness because video signature already has it.\n if (checks.includes('FaceLiveness'))\n checks.splice(checks.indexOf('FaceLiveness'), 1)\n }\n if (additionalDocumentCaptureProps?.documents?.length ?? 0 > 0) {\n checks.push('AdditionalDocumentCapture')\n }\n return checks\n }, [\n additionalDocumentCaptureProps?.documents?.length,\n captureSignature,\n captureSignatureVideo,\n userChecks,\n ])\n const currentCheck = checks[checkIndex]\n const isComplete = checkIndex >= checks.length\n\n useEffect(() => {\n if (\n currentCheck === 'SignatureCapture' &&\n typeof captureSignature === 'function'\n ) {\n captureSignature().then((shouldProceed) => {\n if (!shouldProceed) {\n setCheckIndex((i) => i + 1)\n }\n })\n } else if (\n currentCheck === 'VideoSignatureCapture' &&\n typeof captureSignatureVideo === 'function'\n ) {\n captureSignatureVideo().then((shouldProceed) => {\n if (!shouldProceed) {\n setCheckIndex((i) => i + 1)\n }\n })\n }\n }, [captureSignature, captureSignatureVideo, currentCheck])\n\n useEffect(() => {\n if (isComplete) submit()\n }, [isComplete, submit])\n\n const onIdCaptureSuccessProp = idCaptureProps.onSuccess\n const onIdCaptureSuccess = useCallback(\n (submission: IdCaptureSubmission) => {\n onIdCaptureSuccessProp?.(submission)\n setCheckIndex((i) => i + 1)\n },\n [onIdCaptureSuccessProp]\n )\n\n const onVideoIdCaptureCompleteProp = videoIdCaptureProps.onComplete\n const onVideoIdCaptureComplete = useCallback(() => {\n onVideoIdCaptureCompleteProp?.()\n setCheckIndex((i) => i + 1)\n }, [onVideoIdCaptureCompleteProp])\n\n const onFaceLivenessCompleteProp = faceLivenessProps.onComplete\n const onFaceLivenessComplete = useCallback(\n (resp: SubmissionResponse | null, req: LivenessCheckRequest | null) => {\n onFaceLivenessCompleteProp?.(resp, req)\n setCheckIndex((i) => i + 1)\n },\n [onFaceLivenessCompleteProp]\n )\n\n const onSignatureCaptureSuccess = useCallback(\n (signatureData: SignatureData) => {\n setSignatureData(signatureData)\n setCheckIndex((i) => i + 1)\n },\n [setSignatureData]\n )\n\n const onVideoSignatureCompleteProp = videoSignatureCaptureProps.onComplete\n const onVideoSignatureComplete = useCallback(() => {\n onVideoSignatureCompleteProp?.()\n setCheckIndex((i) => i + 1)\n }, [onVideoSignatureCompleteProp])\n const [videoSignatureAttempts, setVideoSignatureAttempts] = useState(0)\n const onVideoSignatureRetryProp = videoSignatureCaptureProps.onRetryClicked\n const onVideoSignatureRetry = useCallback(() => {\n onVideoSignatureRetryProp?.()\n setVideoSignatureAttempts((n) => n + 1)\n }, [onVideoSignatureRetryProp])\n\n const onAdditionalDocumentCaptureCompleteProp =\n additionalDocumentCaptureProps?.onComplete\n const onAdditionalDocumentCaptureComplete = useCallback(\n (uploadedDocuments: UploadedDocument[]) => {\n setAdditionalDocuments(uploadedDocuments)\n onAdditionalDocumentCaptureCompleteProp?.(uploadedDocuments)\n setCheckIndex((i) => i + 1)\n },\n [onAdditionalDocumentCaptureCompleteProp, setAdditionalDocuments]\n )\n\n const documents = useMemo(\n () => additionalDocumentCaptureProps?.documents ?? [],\n [additionalDocumentCaptureProps?.documents]\n )\n\n if (isComplete) {\n switch (submissionStatus) {\n case SubmissionStatus.SUBMITTING:\n return (\n <PageContainer className=\"flex\">\n <Spinner />\n </PageContainer>\n )\n\n case SubmissionStatus.SUBMITTED:\n return <SubmissionSuccess />\n\n case SubmissionStatus.FAILED:\n return <>Submission failed!</>\n\n default:\n return <>Complete!!</>\n }\n }\n\n switch (checks[checkIndex]) {\n case 'IdCapture':\n return (\n <IdCaptureModelsProvider\n documentDetectionModelUrl={\n idCaptureProps.assets?.documentDetectionModelUrl ?? ''\n }\n focusModelUrl={idCaptureProps.assets?.focusModelUrl ?? ''}\n logPredictions={debugMode}\n >\n <CameraProvider key=\"IdCaptureCamera\">\n <GuideOrientationProvider>\n <IdCaptureWizard\n {...idCaptureProps}\n onSuccess={onIdCaptureSuccess}\n />\n </GuideOrientationProvider>\n </CameraProvider>\n </IdCaptureModelsProvider>\n )\n\n case 'VideoIdCapture':\n return (\n <VideoIdWizard\n {...videoIdCaptureProps}\n onComplete={onVideoIdCaptureComplete}\n />\n )\n\n case 'FaceLiveness':\n return (\n <CameraProvider\n key=\"FaceLivenessCamera\"\n preferFrontFacingCamera={true}\n preferContinuityCamera={false}\n >\n <HighPerformanceSelfieGuidanceModelsProvider>\n <FaceLivenessWizard\n {...faceLivenessProps}\n onComplete={onFaceLivenessComplete}\n />\n </HighPerformanceSelfieGuidanceModelsProvider>\n </CameraProvider>\n )\n\n case 'SignatureCapture':\n return (\n <SignatureCapture\n {...signatureCaptureProps}\n onAccept={onSignatureCaptureSuccess}\n />\n )\n\n case 'VideoSignatureCapture':\n return (\n <CameraProvider\n key={`SignatureKycCamera-${videoSignatureAttempts}`}\n preferContinuityCamera={false}\n preferFrontFacingCamera={true}\n >\n <VideoSignatureWizard\n {...videoSignatureCaptureProps}\n onComplete={onVideoSignatureComplete}\n onRetryClicked={onVideoSignatureRetry}\n />\n </CameraProvider>\n )\n\n case 'AdditionalDocumentCapture':\n return (\n <AdditionalDocumentCaptureWizard\n {...additionalDocumentCaptureProps}\n documents={documents}\n onComplete={onAdditionalDocumentCaptureComplete}\n />\n )\n\n default:\n return <></>\n }\n}\n","import React, { ReactNode, useEffect } from \"react\";\nimport { DefaultTheme, ThemeProvider as ScThemeProvider } from \"styled-components\";\nimport { Color } from \"./color\";\n\nexport interface Theme {\n isFullscreen?: boolean\n fontFamily?: string\n background?: string\n padding?: string\n textAlign?: string\n textColor?: string\n\n colors?: {\n primary?: Color\n secondary?: Color\n positive?: Color\n negative?: Color\n warning?: Color\n }\n\n buttons?: {\n style?: 'bootstrap' | 'none'\n primary?: {\n backgroundColor?: string\n textColor?: string\n }\n secondary?: {\n backgroundColor?: string\n textColor?: string\n }\n positive?: {\n backgroundColor?: string\n textColor?: string\n }\n negative?: {\n backgroundColor?: string\n textColor?: string\n }\n warning?: {\n backgroundColor?: string\n textColor?: string\n }\n loading?: {\n backgroundColor?: string\n textColor?: string\n }\n }\n\n guidanceMessages?: {\n default?: {\n backgroundColor?: string\n textColor?: string\n }\n positive?: {\n backgroundColor?: string\n textColor?: string\n }\n negative?: {\n backgroundColor?: string\n textColor?: string\n }\n }\n\n idCapture?: {\n guideOverlay?: {\n backgroundColor?: string\n textColor?: string\n }\n guideBox?: {\n unsatisfiedColor?: string\n satisfiedColor?: string\n borderWidth?: number\n }\n }\n\n selfieCapture?: {\n guides?: {\n unsatisfiedColor?: string\n satisfiedColor?: string\n }\n }\n\n signatureCapture?: {\n background?: string\n backgroundSize?: string\n backgroundPosition?: string\n\n canvas?: {\n background?: string\n border?: string\n borderRadius?: string\n }\n }\n}\n\nconst noneTheme = {} satisfies Theme;\nconst defaultTheme = {\n fontFamily: `Inter, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif`,\n isFullscreen: true,\n background: \"white\",\n textColor: \"black\",\n textAlign: \"center\",\n padding: \"25px\",\n\n colors: {\n primary: {\n \"50\": \"#eef8ff\",\n \"100\": \"#d8eeff\",\n \"200\": \"#b9e0ff\",\n \"300\": \"#89cfff\",\n \"400\": \"#52b4ff\",\n \"500\": \"#2a91ff\",\n \"600\": \"#0d6efd\", // default\n \"700\": \"#0c5ae9\",\n \"800\": \"#1149bc\",\n \"900\": \"#144194\",\n \"950\": \"#11295a\"\n },\n secondary: {\n \"50\": \"#f6f6f6\",\n \"100\": \"#e7e7e7\",\n \"200\": \"#d1d1d1\",\n \"300\": \"#b0b0b0\",\n \"400\": \"#888888\",\n \"500\": \"#666666\", // default\n \"600\": \"#5d5d5d\",\n \"700\": \"#4f4f4f\",\n \"800\": \"#454545\",\n \"900\": \"#3d3d3d\",\n \"950\": \"#262626\"\n },\n positive: {\n \"50\": \"#f1fcf9\",\n \"100\": \"#cef9eb\",\n \"200\": \"#9df2d8\",\n \"300\": \"#65e3c2\",\n \"400\": \"#35cca9\",\n \"500\": \"#1cb090\",\n \"600\": \"#16a085\", // default\n \"700\": \"#147160\",\n \"800\": \"#155a4f\",\n \"900\": \"#164b42\",\n \"950\": \"#062d28\"\n },\n negative: {\n \"50\": \"#fff1f2\",\n \"100\": \"#ffe4e6\",\n \"200\": \"#fecdd3\",\n \"300\": \"#fda4af\",\n \"400\": \"#fb7185\",\n \"500\": \"#f43f5e\", // default\n \"600\": \"#e11d48\",\n \"700\": \"#be123c\",\n \"800\": \"#9f1239\",\n \"900\": \"#881337\",\n \"950\": \"#4c0519\"\n },\n warning: {\n \"50\": \"#fdf5ef\",\n \"100\": \"#fbe7d9\",\n \"200\": \"#f6cdb2\",\n \"300\": \"#f0ab81\",\n \"400\": \"#ea8557\", // default\n \"500\": \"#e35e2c\",\n \"600\": \"#d54621\",\n \"700\": \"#b1341d\",\n \"800\": \"#8d2b1f\",\n \"900\": \"#72261c\",\n \"950\": \"#3d100d\"\n }\n },\n\n buttons: {\n style: 'bootstrap',\n\n primary: {\n backgroundColor: \"var(--idm-color-primary-600)\",\n textColor: \"white\"\n },\n secondary: {\n backgroundColor: \"var(--idm-color-secondary-500)\",\n textColor: \"white\"\n },\n positive: {\n backgroundColor: \"var(--idm-color-positive-600)\",\n textColor: \"white\"\n },\n negative: {\n backgroundColor: \"var(--idm-color-negative-400)\",\n textColor: \"white\"\n },\n warning: {\n backgroundColor: \"var(--idm-color-warning-400)\",\n textColor: \"white\"\n },\n loading: {\n backgroundColor: \"gray\",\n textColor: \"white\"\n }\n },\n\n guidanceMessages: {\n default: {\n backgroundColor: 'var(--idm-color-secondary-200)',\n textColor: 'black',\n },\n positive: {\n backgroundColor: 'var(--idm-color-positive-700)',\n textColor: 'white',\n },\n negative: {\n backgroundColor: 'var(--idm-color-negative-600)',\n textColor: 'white',\n },\n },\n\n idCapture: {\n guideOverlay: {\n backgroundColor: 'rgba(0,0,0,0.5)',\n textColor: 'white',\n },\n guideBox: {\n unsatisfiedColor: \"white\",\n satisfiedColor: \"var(--idm-color-positive-500)\",\n borderWidth: 4,\n },\n },\n\n selfieCapture: {\n guides: {\n unsatisfiedColor: \"white\",\n satisfiedColor: \"var(--idm-color-positive-500)\",\n }\n },\n\n signatureCapture: {\n background: 'radial-gradient(#444cf7 0.5px, transparent 0.5px), radial-gradient(#444cf7 0.5px, #e5e5f7 0.5px)',\n backgroundSize: '20px 20px',\n backgroundPosition: '0 0, 10px 10px',\n },\n} satisfies Theme;\n\nexport const themes = {\n default: defaultTheme,\n none: noneTheme\n};\n\nexport type ThemeInput = keyof typeof themes | Theme\n\nexport const resolveTheme = (input: ThemeInput): DefaultTheme => {\n if (typeof input === \"string\") {\n if (input in themes) return themes[input];\n return themes.none;\n }\n\n return input;\n};\n\nexport const ThemeProvider = ({\n children,\n theme: themeInput,\n}: {\n children: ReactNode\n theme: ThemeInput\n}) => {\n const theme = resolveTheme(themeInput);\n const colors = theme.colors;\n\n useEffect(() => {\n for (const name in colors) {\n const variants = colors[name as keyof typeof colors];\n for (const num in variants) {\n const color = variants[num as keyof typeof variants];\n document.documentElement.style.setProperty(`--idm-color-${name}-${num}`, color)\n }\n }\n }, [colors]);\n\n return <ScThemeProvider theme={theme}>{children}</ScThemeProvider>;\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport {\n SubmissionContext,\n SubmissionRequest,\n SubmissionResponse,\n} from '../../contexts/SubmissionContext'\nimport {\n SelfieCapture,\n SelfieCaptureClassNames,\n SelfieCaptureColors,\n SelfieCaptureVerbiage,\n} from '../selfie_capture/SelfieCapture'\nimport { Face } from '@tensorflow-models/face-detection'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { cropToShoulders } from '../../lib/utils/cropping'\nimport {\n SelfieProgressPreview,\n SelfieProgressPreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { InvisibleCanvas } from '../common/InvisibleCanvas'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\n\nconst ALLOWED_RETRIES = 0\n\ntype IdentificationState =\n | 'CAPTURING'\n | 'CAPTURED'\n | 'VERIFYING'\n | 'VERIFIED'\n | 'REJECTED'\n | 'ERROR'\n\ntype State = {\n frame: ImageData | null\n face: Face | null\n imageUrl: string | null\n requestState: IdentificationState\n requestError: Error | null\n unverifiedTimes: number\n}\n\nconst initialState: State = {\n frame: null,\n face: null,\n imageUrl: null,\n requestState: 'CAPTURING',\n requestError: null,\n unverifiedTimes: 0,\n}\n\ntype Action =\n | {\n type: 'verificationReady'\n payload: { frame: ImageData; face: Face }\n }\n | { type: 'verifying'; payload: { imageUrl: string } }\n | {\n type: 'verificationCompleted'\n payload: { response: SubmissionResponse }\n }\n | { type: 'verificationFailed'; payload: { error: Error } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'verificationReady': {\n const allowedStates = ['CAPTURING', 'ERROR']\n if (allowedStates.includes(state.requestState)) {\n return {\n ...state,\n requestState: 'CAPTURED',\n frame: action.payload.frame,\n face: action.payload.face,\n }\n } else {\n return state\n }\n }\n\n case 'verifying':\n return {\n ...state,\n requestState: 'VERIFYING',\n imageUrl: action.payload.imageUrl,\n }\n\n case 'verificationCompleted': {\n const {\n status: { statusCode, statusMessage, errorData },\n resultData,\n } = action.payload.response\n\n if (statusCode !== '000') {\n return {\n ...state,\n requestState: 'ERROR',\n requestError: new Error(`${statusMessage}: ${errorData}`),\n }\n }\n\n let { requestState, unverifiedTimes } = state\n const customerMatched = resultData.verificationResultCode === '00'\n if (customerMatched) {\n requestState = 'VERIFIED'\n } else {\n if (unverifiedTimes < ALLOWED_RETRIES) {\n requestState = 'CAPTURING'\n unverifiedTimes += 1\n } else {\n requestState = 'REJECTED'\n }\n }\n\n return { ...state, requestState, unverifiedTimes }\n }\n\n case 'verificationFailed':\n return {\n ...state,\n requestState: 'ERROR',\n requestError: action.payload.error,\n }\n\n default:\n return state\n }\n}\n\nexport type CustomerVerificationCaptureClassNames = SelfieCaptureClassNames & {\n imagePreview?: SelfieProgressPreviewClassNames\n}\n\nexport type CustomerVerificationCaptureColors = SelfieCaptureColors\n\nexport type CustomerVerificationCaptureVerbiage = SelfieCaptureVerbiage & {\n progressPreviewText?: CustomerSuppliedVerbiage\n}\n\nexport type CustomerVerificationCaptureProps = {\n onCustomerMatched?: (resp: SubmissionResponse, req: SubmissionRequest) => void\n onCustomerNotMatched?: (\n resp: SubmissionResponse,\n req: SubmissionRequest\n ) => void\n onCaptureGuidanceTimeout?: () => void\n onExit?: () => void\n captureGuidanceTimeoutDurationMs?: number\n classNames?: CustomerVerificationCaptureClassNames\n colors?: CustomerVerificationCaptureColors\n verbiage?: CustomerVerificationCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const CustomerVerificationCapture = ({\n onCustomerMatched,\n onCustomerNotMatched,\n onCaptureGuidanceTimeout,\n onExit,\n captureGuidanceTimeoutDurationMs,\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: CustomerVerificationCaptureProps): ReactElement => {\n const [state, dispatch] = useReducer(reducer, initialState)\n const { frame, face } = state\n const {\n submit,\n submissionRequest,\n submissionResponse,\n submissionError,\n selfieImage,\n setSelfieImage,\n } = useContext(SubmissionContext)\n const [imageUrl, setImageUrl] = useState<string | null>(null)\n const rawCanvas = useRef<HTMLCanvasElement | null>(null)\n const cropCanvas = useRef<HTMLCanvasElement | null>(null)\n\n const onSelfieCaptured = useCallback((frame: ImageData, face: Face) => {\n dispatch({ type: 'verificationReady', payload: { frame, face } })\n }, [])\n\n const isReady = state.requestState === 'CAPTURED'\n useEffect(() => {\n if (!frame || !face || submissionError) return\n\n const imageUrl = cropToShoulders(\n rawCanvas.current,\n cropCanvas.current,\n frame,\n face\n )\n setImageUrl(imageUrl)\n\n dataUrlToBase64(imageUrl).then((img) => {\n setSelfieImage(img)\n })\n }, [face, frame, setSelfieImage, submissionError])\n\n useEffect(() => {\n if (!isReady || !selfieImage || submissionError) return\n ;(async () => {\n try {\n dispatch({ type: 'verifying', payload: { imageUrl: selfieImage } })\n const submissionResponse = await submit()\n if (!submissionResponse) throw new Error('submission failed!')\n\n dispatch({\n type: 'verificationCompleted',\n payload: { response: submissionResponse },\n })\n } catch (e) {\n dispatch({\n type: 'verificationFailed',\n payload: { error: e as Error },\n })\n }\n })()\n }, [\n isReady,\n onCustomerMatched,\n onCustomerNotMatched,\n selfieImage,\n state.requestState,\n submissionError,\n submit,\n ])\n\n useEffect(() => {\n if (!submissionRequest || !submissionResponse) return\n if (state.requestState === 'VERIFIED') {\n onCustomerMatched?.(submissionResponse, submissionRequest)\n } else if (state.requestState === 'REJECTED') {\n onCustomerNotMatched?.(submissionResponse, submissionRequest)\n }\n }, [\n onCustomerMatched,\n onCustomerNotMatched,\n state.requestState,\n submissionRequest,\n submissionResponse,\n ])\n\n useTimeout(\n captureGuidanceTimeoutDurationMs,\n onCaptureGuidanceTimeout,\n ['VERIFIED', 'REJECTED'].includes(state.requestState),\n state.requestState === 'VERIFYING'\n )\n\n const progressPreviewText = useVerbiage(\n verbiage.progressPreviewText,\n 'Processing...'\n )\n\n return (\n <>\n <InvisibleCanvas ref={rawCanvas} />\n <InvisibleCanvas ref={cropCanvas} />\n\n <SelfieCapture\n onSelfieCaptured={onSelfieCaptured}\n onExit={onExit}\n timeoutDurationMs={captureGuidanceTimeoutDurationMs}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n\n {imageUrl && (\n <SelfieProgressPreview\n imageUrl={imageUrl}\n text={progressPreviewText}\n classNames={classNames.imagePreview}\n />\n )}\n </>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport {\n SelfieCapture,\n SelfieCaptureClassNames,\n SelfieCaptureColors,\n SelfieCaptureVerbiage,\n} from '../selfie_capture/SelfieCapture'\nimport { Face } from '@tensorflow-models/face-detection'\nimport {\n SubmissionContext,\n SubmissionRequest,\n SubmissionResponse,\n} from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { cropToShoulders } from '../../lib/utils/cropping'\nimport {\n SelfieProgressPreview,\n SelfieProgressPreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { InvisibleCanvas } from '../common/InvisibleCanvas'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\n\nconst ALLOWED_RETRIES = 0\n\ntype IdentificationState =\n | 'CAPTURING'\n | 'CAPTURED'\n | 'IDENTIFYING'\n | 'FOUND'\n | 'NOT_FOUND'\n | 'ERROR'\n\ntype State = {\n frame: ImageData | null\n face: Face | null\n imageUrl: string | null\n requestState: IdentificationState\n requestError: Error | null\n notFoundTimes: number\n}\n\nconst initialState: State = {\n frame: null,\n face: null,\n imageUrl: null,\n requestState: 'CAPTURING',\n requestError: null,\n notFoundTimes: 0,\n}\n\ntype Action =\n | {\n type: 'identificationReady'\n payload: { frame: ImageData; face: Face }\n }\n | { type: 'identifying'; payload: { imageUrl: string } }\n | {\n type: 'identificationCompleted'\n payload: { response: SubmissionResponse }\n }\n | { type: 'identificationFailed'; payload: { error: Error } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'identificationReady': {\n const allowedStates = ['CAPTURING', 'ERROR']\n if (allowedStates.includes(state.requestState)) {\n return {\n ...state,\n requestState: 'CAPTURED',\n frame: action.payload.frame,\n face: action.payload.face,\n }\n } else {\n return state\n }\n }\n\n case 'identifying':\n return {\n ...state,\n requestState: 'IDENTIFYING',\n imageUrl: action.payload.imageUrl,\n }\n\n case 'identificationCompleted': {\n const {\n status: { statusCode, statusMessage, errorData },\n resultData,\n } = action.payload.response\n\n if (statusCode !== '000') {\n return {\n ...state,\n requestState: 'ERROR',\n requestError: new Error(`${statusMessage}: ${errorData}`),\n }\n }\n\n let { requestState, notFoundTimes } = state\n const customerMatched = resultData.verificationResultCode === '46'\n if (customerMatched) {\n requestState = 'FOUND'\n } else if (notFoundTimes < ALLOWED_RETRIES) {\n requestState = 'CAPTURING'\n notFoundTimes += 1\n } else {\n requestState = 'NOT_FOUND'\n }\n\n return { ...state, requestState, notFoundTimes }\n }\n\n case 'identificationFailed':\n return {\n ...state,\n requestState: 'ERROR',\n requestError: action.payload.error,\n }\n\n default:\n return state\n }\n}\n\nexport type CustomerIdentificationCaptureClassNames =\n SelfieCaptureClassNames & {\n imagePreview?: SelfieProgressPreviewClassNames\n }\n\nexport type CustomerIdentificationCaptureColors = SelfieCaptureColors\n\nexport type CustomerIdentificationCaptureVerbiage = SelfieCaptureVerbiage & {\n progressPreviewText?: CustomerSuppliedVerbiage\n}\n\nexport type CustomerIdentificationCaptureProps = {\n onCustomerMatched?: (resp: SubmissionResponse, req: SubmissionRequest) => void\n onCustomerNotMatched?: (\n resp: SubmissionResponse,\n req: SubmissionRequest\n ) => void\n onCaptureGuidanceTimeout?: () => void\n onExit?: () => void\n captureGuidanceTimeoutDurationMs?: number\n classNames?: CustomerIdentificationCaptureClassNames\n colors?: CustomerIdentificationCaptureColors\n verbiage?: CustomerIdentificationCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const CustomerIdentificationCapture = ({\n onCustomerMatched,\n onCustomerNotMatched,\n onCaptureGuidanceTimeout,\n onExit,\n captureGuidanceTimeoutDurationMs,\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: CustomerIdentificationCaptureProps): ReactElement => {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {\n submit,\n submissionRequest,\n submissionResponse,\n submissionError,\n selfieImage,\n setSelfieImage,\n } = useContext(SubmissionContext)\n const [imageUrl, setImageUrl] = useState<string | null>(null)\n const rawCanvas = useRef<HTMLCanvasElement | null>(null)\n const cropCanvas = useRef<HTMLCanvasElement | null>(null)\n\n const onSelfieCaptured = useCallback((frame: ImageData, face: Face) => {\n dispatch({ type: 'identificationReady', payload: { frame, face } })\n }, [])\n\n const { frame, face } = state\n const isReady = state.requestState === 'CAPTURED'\n useEffect(() => {\n if (!frame || !face || submissionError) return\n\n const imageUrl = cropToShoulders(\n rawCanvas.current,\n cropCanvas.current,\n frame,\n face\n )\n setImageUrl(imageUrl)\n\n dataUrlToBase64(imageUrl).then((img) => {\n setSelfieImage(img)\n })\n }, [face, frame, setSelfieImage, submissionError])\n\n useEffect(() => {\n if (!isReady || !selfieImage || submissionError) return\n ;(async () => {\n try {\n dispatch({ type: 'identifying', payload: { imageUrl: selfieImage } })\n const submissionResponse = await submit()\n if (!submissionResponse) throw new Error('submission failed!')\n\n dispatch({\n type: 'identificationCompleted',\n payload: { response: submissionResponse },\n })\n } catch (e) {\n dispatch({\n type: 'identificationFailed',\n payload: { error: e as Error },\n })\n }\n })()\n }, [\n isReady,\n onCustomerMatched,\n onCustomerNotMatched,\n selfieImage,\n state.requestState,\n submissionError,\n submit,\n ])\n\n useEffect(() => {\n if (!submissionRequest || !submissionResponse) return\n if (state.requestState === 'FOUND') {\n onCustomerMatched?.(submissionResponse, submissionRequest)\n } else if (state.requestState === 'NOT_FOUND') {\n onCustomerNotMatched?.(submissionResponse, submissionRequest)\n }\n }, [\n onCustomerMatched,\n onCustomerNotMatched,\n state.requestState,\n submissionRequest,\n submissionResponse,\n ])\n\n useTimeout(\n captureGuidanceTimeoutDurationMs,\n onCaptureGuidanceTimeout,\n ['FOUND', 'NOT_FOUND'].includes(state.requestState),\n state.requestState === 'IDENTIFYING'\n )\n\n const progressPreviewText = useVerbiage(\n verbiage.progressPreviewText,\n 'Processing...'\n )\n\n return (\n <>\n <InvisibleCanvas ref={rawCanvas} />\n <InvisibleCanvas ref={cropCanvas} />\n\n <SelfieCapture\n onSelfieCaptured={onSelfieCaptured}\n onExit={onExit}\n timeoutDurationMs={captureGuidanceTimeoutDurationMs}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n\n {imageUrl && (\n <SelfieProgressPreview\n text={progressPreviewText}\n imageUrl={imageUrl}\n classNames={classNames.imagePreview}\n />\n )}\n </>\n )\n}\n","import { loadDocumentDetectionModel } from './DocumentDetection'\nimport { loadFocusModel } from './Focus'\nimport { DEFAULT_CDN_URL } from '../../components/common/cdn'\nimport { loadHighPerformanceFaceDetector } from '../../components/selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\n\nexport const preloadModels = async ({\n documentDetectionModel = true,\n focusModel = true,\n faceDetectionModel = true,\n}: {\n documentDetectionModel?: string | boolean\n focusModel?: string | boolean\n faceDetectionModel?: boolean\n}): Promise<void> => {\n if (documentDetectionModel) {\n if (documentDetectionModel === true)\n documentDetectionModel = `${DEFAULT_CDN_URL}/models/documentdetection448/model.json`\n await loadDocumentDetectionModel(documentDetectionModel)\n }\n\n if (focusModel) {\n if (focusModel === true)\n focusModel = `${DEFAULT_CDN_URL}/models/focus/model.json`\n await loadFocusModel(focusModel)\n }\n\n if (faceDetectionModel) {\n await loadHighPerformanceFaceDetector()\n }\n}\n","import React, { FC, PropsWithChildren, ReactNode } from 'react'\nimport * as ReactDOM from 'react-dom/client'\nimport {\n IdValidation,\n IdValidationProps,\n} from './components/customer_flows/IdValidation'\nimport {\n FaceValidation,\n FaceValidationProps,\n} from './components/customer_flows/FaceValidation'\nimport {\n IdAndFaceValidation,\n IdAndFaceValidationProps,\n} from './components/customer_flows/IdAndFaceValidation'\nimport {\n CustomerEnrollmentProps,\n CustomerIdAndBiometricsEnrollment,\n} from './components/customer_flows/CustomerIdAndBiometricsEnrollment'\nimport {\n CustomerVerification,\n CustomerVerificationProps,\n} from './components/customer_flows/CustomerVerification'\nimport {\n CustomerIdentification,\n CustomerIdentificationProps,\n} from './components/customer_flows/CustomerIdentification'\nimport {\n SignatureKYC,\n SignatureKYCProps,\n} from './components/customer_flows/SignatureKYC'\nimport {\n VideoIdValidation,\n VideoIdValidationProps,\n} from './components/customer_flows/VideoIdValidation'\nimport { preloadModels } from './lib/models/preloadModels'\nimport { initializeI18n } from './lib/locales'\nimport { CustomerBiometricsEnrollment } from './components/customer_flows/CustomerBiometricsEnrollment'\nimport { OverlayContainer } from './components/common/overlay'\nimport { webSdkVersion } from './version'\nimport { themes } from './themes'\n\ninitializeI18n()\n\ntype TargetElement = Element | DocumentFragment | string | undefined\n\nfunction renderElement(\n component: ReactNode,\n targetElement?: TargetElement\n): Element | DocumentFragment {\n if (typeof targetElement === 'string') {\n const result = document.querySelector(targetElement)\n if (!result) throw new Error(`targetElement ${targetElement} not found`)\n targetElement = result\n } else if (!targetElement) {\n targetElement = document.createElement('div')\n document.body.append(targetElement)\n }\n\n const root = ReactDOM.createRoot(targetElement)\n root.render(<OverlayContainer>{component}</OverlayContainer>)\n\n if ('remove' in targetElement) {\n const originalRemove = targetElement.remove\n targetElement.remove = () => {\n try {\n root.unmount()\n originalRemove()\n } catch (e) {}\n }\n }\n\n return targetElement\n}\n\nfunction renderComponent<T extends PropsWithChildren>(\n Component: FC<T>,\n targetElement: TargetElement | T,\n options?: T\n): Element | DocumentFragment {\n if (!options) {\n options = targetElement as T\n targetElement = undefined\n }\n\n return renderElement(\n <Component {...options} />,\n targetElement as TargetElement\n )\n}\n\nexport const renderIdValidation = (\n optionsOrTargetElement: TargetElement | IdValidationProps,\n options?: IdValidationProps\n) => renderComponent(IdValidation, optionsOrTargetElement, options)\n\nexport const renderFaceValidation = (\n optionsOrTargetElement: TargetElement | FaceValidationProps,\n options?: FaceValidationProps\n) => renderComponent(FaceValidation, optionsOrTargetElement, options)\n\nexport const renderIdAndFaceValidation = (\n optionsOrTargetElement: TargetElement | IdAndFaceValidationProps,\n options?: IdAndFaceValidationProps\n) => renderComponent(IdAndFaceValidation, optionsOrTargetElement, options)\n\nexport const renderCustomerIdAndBiometricsEnrollment = (\n optionsOrTargetElement: TargetElement | CustomerEnrollmentProps,\n options?: CustomerEnrollmentProps\n) =>\n renderComponent(\n CustomerIdAndBiometricsEnrollment,\n optionsOrTargetElement,\n options\n )\n\nexport const renderCustomerBiometricsEnrollment = (\n optionsOrTargetElement: TargetElement | CustomerEnrollmentProps,\n options?: CustomerEnrollmentProps\n) =>\n renderComponent(CustomerBiometricsEnrollment, optionsOrTargetElement, options)\n\nexport const renderCustomerVerification = (\n optionsOrTargetElement: TargetElement | CustomerVerificationProps,\n options?: CustomerVerificationProps\n) => renderComponent(CustomerVerification, optionsOrTargetElement, options)\n\nexport const renderCustomerIdentification = (\n optionsOrTargetElement: TargetElement | CustomerIdentificationProps,\n options?: CustomerIdentificationProps\n) => renderComponent(CustomerIdentification, optionsOrTargetElement, options)\n\nexport const renderSignatureKYC = (\n optionsOrTargetElement: TargetElement | SignatureKYCProps,\n options?: SignatureKYCProps\n) => renderComponent(SignatureKYC, optionsOrTargetElement, options)\n\nexport const renderVideoIdValidation = (\n optionsOrTargetElement: TargetElement | VideoIdValidationProps,\n options?: VideoIdValidationProps\n) => renderComponent(VideoIdValidation, optionsOrTargetElement, options)\n\nexport type IDmissionSDK = {\n renderIdValidation: typeof renderIdValidation\n renderFaceValidation: typeof renderFaceValidation\n renderIdAndFaceValidation: typeof renderIdAndFaceValidation\n renderCustomerIdAndBiometricsEnrollment: typeof renderCustomerIdAndBiometricsEnrollment\n renderCustomerBiometricsEnrollment: typeof renderCustomerBiometricsEnrollment\n renderCustomerVerification: typeof renderCustomerVerification\n renderCustomerIdentification: typeof renderCustomerIdentification\n renderSignatureKYC: typeof renderSignatureKYC\n renderVideoIdValidation: typeof renderVideoIdValidation\n\n preloadModels: typeof preloadModels\n themes: typeof themes\n version: string\n ready: boolean\n}\n\ndeclare global {\n // eslint-disable-next-line no-var\n var IDmissionSDK: IDmissionSDK\n}\n\nglobalThis.IDmissionSDK = {\n renderIdValidation,\n renderFaceValidation,\n renderIdAndFaceValidation,\n renderCustomerIdAndBiometricsEnrollment,\n renderCustomerBiometricsEnrollment,\n renderCustomerVerification,\n renderCustomerIdentification,\n renderSignatureKYC,\n renderVideoIdValidation,\n preloadModels,\n themes,\n version: webSdkVersion,\n ready: true,\n}\n\nexport {\n preloadModels,\n themes,\n IdValidation,\n FaceValidation,\n IdAndFaceValidation,\n CustomerIdAndBiometricsEnrollment,\n CustomerBiometricsEnrollment,\n CustomerVerification,\n CustomerIdentification,\n SignatureKYC,\n VideoIdValidation,\n}\n"],"names":["React","useState","styled","useRef","ENV","base.checkConversionForErrors","base.isPromise","util.now","util.rightPad","util.arraysEqual","util.sizeFromShape","util.assert","util.getArrayFromDType","opHandler","util.decodeString","log.warn","util.isString","util.encodeString","util.bytesPerElement","util.makeZerosTypedArray","add","util.isFunction","device_util.isBrowser","util.isTypedArray","maybeStripScheme","util.assertNonNegativeIntegerDimensions","util.isValidDtype","__awaiter","templateObject_1","__makeTemplateObject","__assign","useContext"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO;;;;;;;;;;;;;;;;;;ACID,SAAU;;8FACyB,EAAE,MAAA,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,EAAA;AAC3C;;;;;;;;;ACUA;;;;;;;;;QAyLsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/Jf,iDACL,+NAmB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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gEC3Ne,CAAA;;mBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wCCiEtB;qFAM6B;;;IAY7B;;;EAU8E;MAE1E,CAAC;MAUD;+CAMJ;;;;;;;;sBAkCkB;;mDAMnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"sdk2.cjs.development.js","sources":["../src/version.ts","../src/lib/utils/dataUrlToBase64.ts","../src/contexts/SubmissionContext.ts","../src/components/common/Page.tsx","../src/components/common/overlay.tsx","../src/components/common/LoaderButton.tsx","../src/components/submission/GeolocationAccessDeniedOverlay.tsx","../src/components/submission/Errors.ts","../src/components/submission/SubmissionErrorOverlay.tsx","../src/components/submission/TokenMissingErrorOverlay.tsx","../src/components/submission/TokenInvalidFormatErrorOverlay.tsx","../src/components/submission/TokenInvalidSignatureErrorOverlay.tsx","../src/components/submission/TokenExpiredErrorOverlay.tsx","../src/components/submission/TokenPublicKeyErrorOverlay.tsx","../src/components/submission/SubmissionProvider.tsx","../src/lib/models/DocumentDetection.ts","../../tfjs-core/src/device_util.ts","../src/components/id_capture/DocumentCaptureGuideOverlay.tsx","../src/lib/barcode/Native.js","../src/lib/barcode/ZXing.js","../src/lib/barcode/Scan.ts","../src/lib/utils/getBlobDimensions.ts","../src/lib/utils/deviceDetection.ts","../src/lib/camera/Camera.ts","../src/components/camera/CameraProvider.tsx","../src/lib/models/Focus.ts","../../tfjs-core/src/backends/backend.ts","../../tfjs-core/src/util_base.ts","../../tfjs-core/src/environment.ts","../../tfjs-core/src/global_util.ts","../../tfjs-core/src/kernel_names.ts","../../tfjs-core/src/log.ts","../../tfjs-core/src/kernel_registry.ts","../../tfjs-core/src/platforms/is_typed_array_browser.ts","../../tfjs-core/src/util.ts","../../tfjs-core/src/profiler.ts","../../tfjs-core/src/tape.ts","../../tfjs-core/src/tensor_format.ts","../../tfjs-core/src/tensor.ts","../../tfjs-core/src/types.ts","../../tfjs-core/src/tensor_util.ts","../../tfjs-core/src/engine.ts","../../tfjs-core/src/flags.ts","../../tfjs-core/src/tensor_util_env.ts","../../tfjs-core/src/ops/operation.ts","../../tfjs-core/src/ops/tensor_ops_util.ts","../../tfjs-core/src/io/composite_array_buffer.ts","../../tfjs-core/src/io/io_utils.ts","../../tfjs-core/src/io/router_registry.ts","../../tfjs-core/src/io/indexed_db.ts","../../tfjs-core/src/io/local_storage.ts","../../tfjs-core/src/io/model_management.ts","../../tfjs-core/src/platforms/platform_browser.ts","../../tfjs-core/src/platforms/platform_node.ts","../../tfjs-core/src/ops/buffer.ts","../../tfjs-core/src/ops/cast.ts","../../tfjs-core/src/ops/clone.ts","../../tfjs-core/src/ops/print.ts","../../tfjs-core/src/base_side_effects.ts","../../tfjs-core/src/globals.ts","../../tfjs-core/src/ops/add.ts","../../tfjs-core/src/ops/floorDiv.ts","../../tfjs-core/src/ops/div.ts","../../tfjs-core/src/ops/mul.ts","../../tfjs-core/src/ops/abs.ts","../../tfjs-core/src/ops/fill.ts","../../tfjs-core/src/ops/broadcast_util.ts","../../tfjs-core/src/ops/zeros_like.ts","../../tfjs-core/src/ops/pow.ts","../../tfjs-core/src/ops/scalar.ts","../../tfjs-core/src/ops/sqrt.ts","../../tfjs-core/src/ops/square.ts","../../tfjs-core/src/gradients.ts","../../tfjs-core/src/ops/sub.ts","../../tfjs-core/src/ops/maximum.ts","../../tfjs-core/src/serialization.ts","../../tfjs-core/src/optimizers/optimizer.ts","../../tfjs-core/src/optimizers/adadelta_optimizer.ts","../../tfjs-core/src/optimizers/adagrad_optimizer.ts","../../tfjs-core/src/optimizers/adam_optimizer.ts","../../tfjs-core/src/optimizers/adamax_optimizer.ts","../../tfjs-core/src/optimizers/sgd_optimizer.ts","../../tfjs-core/src/optimizers/momentum_optimizer.ts","../../tfjs-core/src/optimizers/rmsprop_optimizer.ts","../../tfjs-core/src/optimizers/register_optimizers.ts","../../tfjs-core/src/index.ts","../../tfjs-backend-webgl/src/canvas_util.ts","../src/components/common/cdn.ts","../src/lib/utils/getFrameDimensions.ts","../src/components/common/InvisibleCanvas.tsx","../src/lib/utils/cropping.ts","../src/components/id_capture/IdCaptureModelsProvider.tsx","../src/components/common/debug.tsx","../src/components/common/ExitCaptureButton.tsx","../src/components/common/spinner.tsx","../src/components/common/SelfieProgressPreview.tsx","../src/lib/locales/en/translation.js","../src/lib/locales/es/translation.js","../src/lib/locales/index.ts","../src/components/common/GuidanceMessage.tsx","../src/components/id_capture/IdCapture.tsx","../src/components/id_capture/IdCaptureLoadingOverlay.tsx","../src/components/id_capture/FlipIdPrompt.tsx","../src/components/common/ButtonsRow.tsx","../src/components/camera/CameraVideoTag.tsx","../src/components/common/useShowSuccessScreen.ts","../src/components/fallback_flows/IdCapture.tsx","../src/components/id_capture/IdCaptureWizard.tsx","../src/components/selfie_capture/HighPerformanceSelfieGuidanceModelsProvider.tsx","../src/lib/utils/useTimeout.ts","../src/components/fallback_flows/SelfieCapture.tsx","../src/components/selfie_capture/SelfieCapture.tsx","../src/components/face_liveness/FaceLivenessCapture.tsx","../src/components/face_liveness/FaceLivenessWizard.tsx","../src/components/GuideOrientationProvider.tsx","../src/components/submission/SubmissionSuccess.tsx","../src/components/additional_document_capture/AdditionalDocumentCapture.tsx","../src/components/additional_document_capture/AdditionalDocumentCaptureWizard.tsx","../src/components/signature_capture/data.ts","../src/components/common/signature.tsx","../src/lib/camera/useVideoRecorder.ts","../src/components/video_signature_capture/VideoSignatureCapture.tsx","../src/components/video_signature_capture/VideoSignatureWizard.tsx","../src/components/video_id/IdVideoCaptureFlipIdPrompt.tsx","../src/components/video_id/IdVideoCaptureGuides.tsx","../src/components/video_id/IdVideoCapture.tsx","../src/components/CompositeWizard.tsx","../src/themes/index.tsx","../src/components/customer_verification/CustomerVerificationCapture.tsx","../src/components/customer_identification/CustomerIdentificationCapture.tsx","../src/lib/models/preloadModels.ts","../src/index.tsx"],"sourcesContent":["export const webSdkVersion = '1.0.78';\n","export async function dataUrlToBase64(url: string): Promise<string> {\n return url.replace(/^data:image\\/(png|jpeg);base64,/, '')\n}\n\nexport function dataUrlToBase64Sync(url: string): string {\n return url.replace(/^data:.*;base64,/, '')\n}\n\nexport function contentDispositionFromDataUrl(url: string): string {\n return url.match(/^(data:.*;base64),/)?.[1] ?? ''\n}\n","import { UploadedDocument } from '../components/additional_document_capture/AdditionalDocumentCapture'\nimport { webSdkVersion } from '../version'\nimport { getPlatform } from '../lib/utils/platform'\nimport { dataUrlToBase64Sync } from '../lib/utils/dataUrlToBase64'\n\nexport enum SubmissionAction {\n NONE = 'NONE',\n ENROLL = 'ENROLL',\n IDENTIFY = 'IDENTIFY',\n VALIDATE = 'VALIDATE',\n VERIFY = 'VERIFY',\n}\n\nexport enum SubmissionStatus {\n READY = 'READY',\n SUBMITTING = 'SUBMITTING',\n SUBMITTED = 'SUBMITTED',\n FAILED = 'FAILED',\n}\n\nexport type SubmissionEnvironment = 'prod' | 'demo'\n\nexport const submissionHosts = {\n prod: 'https://api.idmission.com',\n demo: 'https://apidemo.idmission.com',\n}\n\nexport type SubmissionRequest = {\n securityData: {\n userName: string\n password: string\n merchantId: number\n }\n customerData: {\n idData: {\n idImageFront?: string\n idImageBack?: string\n\n idType: 'NSP'\n idCountry: 'NSP'\n idState: ''\n }\n personalData?: PersonalData\n cardData?: CardData\n biometricData?: {\n selfie?: string\n }\n signatureData?: {\n signatureImage?: string\n }\n additionalDocuments?: UploadedDocument[]\n }\n biometricData?: {\n selfie?: string\n videoData?: string\n }\n additionalData: {\n uniqueRequestId: string\n clientTraceId?: string\n manualReviewRequired: 'Y' | 'N'\n bypassAgeValidation: 'Y' | 'N'\n deDuplicationRequired: 'Y' | 'N'\n bypassNameMatching: 'Y' | 'N'\n postDataAPIRequired: 'Y' | 'N'\n postDataOnReviewRequired: 'Y' | 'N'\n sendInputImagesInPost: 'Y' | 'N'\n sendProcessedImagesInPost: 'Y' | 'N'\n needImmediateResponse: 'Y' | 'N'\n deduplicationSynchronous: 'Y' | 'N'\n verifyDataWithHost: 'Y' | 'N'\n idBackImageRequired: 'Y' | 'N'\n stripSpecialCharacters: 'Y' | 'N'\n idImageResolutionCheck: 'Y' | 'N'\n metadata?: string\n }\n employee?: { companyId?: string }\n}\n\nexport type CaptureAttemptMetadata = {\n autoCapture: 'Y' | 'N' // always Y until we add support for manual capture\n captureTime: number // time from start of the camera start to camera stop in ms\n operationTime?: number // time from start of the selfie detection or ID detection to capture in ms\n}\n\nexport type PersonalData = {\n uniqueNumber?: string\n name?: string\n phone?: string\n phoneCountryCode?: string\n email?: string\n dob?: string // date of birth, formatted DD/MM/YYYY, e.g. 31/12/2019\n gender?: 'M' | 'F'\n addressLine1?: string\n addressLine2?: string\n city?: string\n district?: string // two-letter code indicating state if USA, e.g. CA\n postalCode?: string\n country?: string // three-letter code indicating country, e.g. USA\n}\n\nexport type CardData = {\n cardToken?: string\n cardLast4?: string\n cardExpDate?: string\n nameOnCard?: string\n}\n\nexport type SubmissionMetadata = {\n selfie: CaptureAttemptMetadata[]\n back: CaptureAttemptMetadata[]\n front: CaptureAttemptMetadata[]\n sdkVersion: string\n isRealIDCheckRequired: 'true' | 'false'\n os?: string\n osVersion?: string\n browserVersion?: string\n Resolution?: string\n GeoLocation?: string\n}\n\nexport type SubmissionResponseStatus = {\n statusCode: string\n statusMessage?: string\n errorData?: string\n}\n\nexport type SubmissionResponse = {\n status: SubmissionResponseStatus\n resultData: Record<string, unknown>\n}\n\nexport type LivenessCheckRequest = {\n securityData: {\n userName: string\n password: string\n merchantId: number\n }\n customerData: {\n biometricData: {\n selfie: string\n }\n }\n additionalData: {\n uniqueRequestId: string\n stripSpecialCharacters: 'Y' | 'N'\n estimateAge: 'Y' | 'N'\n predictGender: 'Y' | 'N'\n metadata?: string\n }\n}\nexport type LiveCheckResponse = {\n status: { statusCode: string; statusMessage: string; errorData: string }\n resultData: {\n verificationResult: string\n eyeCovering: 'true' | 'false'\n faceMask: 'true' | 'false'\n headCovering: 'true' | 'false'\n cellPhone: 'true' | 'false'\n }\n}\n\nexport function parseJwt(token: string): Record<string, unknown> {\n const base64Url = token.split('.')[1]\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')\n const jsonPayload = decodeURIComponent(\n window\n .atob(base64)\n .split('')\n .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join('')\n )\n\n return JSON.parse(jsonPayload)\n}\n\nexport function determineSubmissionHost(\n environment: SubmissionEnvironment,\n token?: string\n): string {\n if (token) {\n switch (parseJwt(token)['iss']) {\n case 'https://auth.idmission.com/auth/realms/identity':\n return submissionHosts.prod\n case 'https://demoauth.idmission.com/auth/realms/identity':\n return submissionHosts.demo\n }\n }\n\n const host = submissionHosts[environment]\n if (!host)\n throw new Error(`unrecognized SubmissionEnvironment ${environment}`)\n return host\n}\n\nexport function determineSubmissionEndpoint(\n action: SubmissionAction,\n hasId: boolean,\n hasSelfie: boolean,\n hasToken: boolean\n): string {\n const v = hasToken ? 'v4' : 'v3'\n switch (action) {\n case SubmissionAction.ENROLL:\n return hasId\n ? `/${v}/customer/enroll`\n : `/${v}/customer/enroll-biometrics`\n\n case SubmissionAction.IDENTIFY:\n return `/${v}/customer/identify`\n\n case SubmissionAction.VALIDATE:\n return hasSelfie\n ? `/${v}/customer/validate-id-match-face`\n : `/${v}/customer/validate-id`\n\n case SubmissionAction.VERIFY:\n return `/${v}/customer/verify`\n\n default:\n throw new Error(`unrecognized SubmissionAction ${action}`)\n }\n}\n\nexport function liveCheckEndpoint(hasToken: boolean): string {\n const v = hasToken ? 'v4' : 'v3'\n return `/${v}/customer/live-check`\n}\n\nexport function apiHeaders(token?: string): HeadersInit {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n Origin: '*',\n }\n if (token) {\n headers['Authorization'] = `Bearer ${token}`\n }\n return headers\n}\n\nexport function attachMetadataToRequest(\n request: SubmissionRequest | LivenessCheckRequest,\n {\n selfieCaptureAttempts,\n idFrontCaptureAttempts,\n idBackCaptureAttempts,\n geolocationResult,\n }: {\n selfieCaptureAttempts: CaptureAttemptMetadata[]\n idFrontCaptureAttempts: CaptureAttemptMetadata[]\n idBackCaptureAttempts: CaptureAttemptMetadata[]\n geolocationResult: GeolocationPosition | null\n }\n) {\n const metadata: SubmissionMetadata = {\n selfie: selfieCaptureAttempts,\n front: idFrontCaptureAttempts,\n back: idBackCaptureAttempts,\n isRealIDCheckRequired: 'false',\n sdkVersion: `WebSDK_${webSdkVersion}`,\n Resolution: `${window.innerWidth} x ${window.innerHeight}`,\n }\n const platform = getPlatform()\n if (platform) {\n metadata.os = platform.os.family\n metadata.osVersion = platform.os.version\n metadata.browserVersion = `${platform.name} ${platform.version}`\n }\n if (geolocationResult) {\n metadata.GeoLocation = JSON.stringify(geolocationResult)\n }\n request.additionalData.metadata = JSON.stringify(metadata)\n}\n\nexport function videoDataUrlToB64(url: string): Promise<string> {\n return new Promise((resolve) => {\n const reader = new FileReader()\n reader.onloadend = () => {\n resolve(dataUrlToBase64Sync(reader.result as string))\n }\n fetch(url)\n .then((resp) => resp.blob())\n .then((blob) => reader.readAsDataURL(blob))\n })\n}\n","import React, {\n CSSProperties,\n forwardRef,\n ReactElement,\n ReactNode,\n RefCallback,\n useEffect,\n useState,\n} from 'react'\nimport styled from 'styled-components'\n\nexport const PageContainerDiv = styled.div<{\n $heightOffset?: number\n}>`\n ${(props) =>\n props.theme.isFullscreen === false\n ? ``\n : `\n position: fixed;\n top: 0;\n left: 0;\n width: var(--app-width);\n height: calc(\n var(--app-height) - ${props.$heightOffset ?? 0}px\n );\n overflow-x: hidden;\n overflow-y: auto;\n `}\n\n ${(props) =>\n props.theme.fontFamily ? `font-family: ${props.theme.fontFamily};` : ``}\n\n &.flex {\n display: flex;\n }\n\n &.padded {\n box-sizing: border-box;\n padding: 16px 24px;\n }\n`\n\nexport const PageContainer = forwardRef(\n (\n {\n children,\n className,\n heightOffset = 0,\n style,\n onClick,\n }: {\n ref?: RefCallback<HTMLDivElement>\n children: ReactNode\n className?: string\n heightOffset?: number\n style?: CSSProperties\n onClick?: () => void\n },\n ref: React.ForwardedRef<HTMLDivElement>\n ): ReactElement => {\n const [dimensionsCalculated, setDimensionsCalculated] = useState(false)\n\n useEffect(() => {\n setDimensionsCalculated(false)\n const calcAppDimensions = () => {\n const doc = document.documentElement\n doc.style.setProperty('--app-width', `${window.innerWidth}px`)\n doc.style.setProperty('--app-height', `${window.innerHeight}px`)\n }\n window.addEventListener('resize', calcAppDimensions)\n calcAppDimensions()\n setDimensionsCalculated(true)\n\n return () => {\n window.removeEventListener('resize', calcAppDimensions)\n }\n }, [])\n\n return (\n <PageContainerDiv\n ref={ref}\n style={style}\n onClick={onClick}\n className={className}\n $heightOffset={heightOffset}\n >\n {dimensionsCalculated && children}\n </PageContainerDiv>\n )\n }\n)\n\nPageContainer.displayName = 'PageContainer'\n","import styled from 'styled-components'\nimport { PageContainer } from './Page'\n\nexport const OverlayContainer = styled(PageContainer)`\n background: ${(props) =>\n props.theme.background ? `${props.theme.background}` : `white`};\n ${(props) =>\n props.theme.textColor ? `color: ${props.theme.textColor};` : ``}\n z-index: 10000;\n`\n\nexport const OverlayInner = styled.div`\n text-align: ${(props) => props.theme.textAlign ?? 'center'};\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n max-height: var(--app-height);\n height: 100%;\n ${(props) =>\n props.theme.padding\n ? `box-sizing: border-box; padding: ${props.theme.padding};`\n : ``}\n`\n\nexport const OverlayImageContainer = styled.div`\n position: relative;\n display: flex;\n flex-grow: 1;\n padding-bottom: 25px;\n max-width: var(--app-width);\n max-height: var(--app-height);\n overflow: hidden;\n\n & > img {\n margin: 0 auto;\n width: max-content;\n max-width: 100%;\n max-height: 100%;\n aspect-ratio: initial;\n object-fit: contain;\n display: block;\n }\n`\n\nexport const OverlayImageRow = styled.div`\n display: flex;\n margin: auto;\n\n & > div {\n max-height: calc(100vh - 320px);\n\n & > img {\n width: 100%;\n max-height: 100%;\n height: auto;\n object-fit: contain;\n }\n }\n`\n","import React, {\n CSSProperties,\n ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { LaddaButton } from 'ladda'\nimport styled from 'styled-components'\n\nexport type LoaderButtonVariant =\n | 'primary'\n | 'secondary'\n | 'positive'\n | 'negative'\n | 'warning'\n\nexport type LoaderButtonColors = {\n backgroundColor?: string\n textColor?: string\n loadingBackgroundColor?: string\n loadingTextColor?: string\n}\n\nexport type LoaderButtonProps = {\n children?: ReactNode\n className?: string\n disabled?: boolean\n finished?: boolean\n colors?: LoaderButtonColors\n onClick?: () => void\n style?: CSSProperties\n variant?: LoaderButtonVariant\n}\n\nexport const LoaderButton = ({\n children,\n className,\n colors = {},\n disabled,\n finished,\n onClick,\n style,\n variant = 'primary',\n}: LoaderButtonProps) => {\n const buttonRef = useRef<HTMLButtonElement | null>(null)\n const laddaRef = useRef<LaddaButton | null>(null)\n const [laddaLoaded, setLaddaLoaded] = useState(false)\n\n useEffect(() => {\n let interval: NodeJS.Timeout\n\n import('ladda').then((Ladda) => {\n if (!buttonRef.current) return\n laddaRef.current = Ladda.create(buttonRef.current)\n laddaRef.current.start()\n setLaddaLoaded(true)\n\n let currentProgress = 0\n interval = setInterval(() => {\n if (currentProgress < 0.9) currentProgress += 0.1\n laddaRef.current?.setProgress(currentProgress)\n }, 250)\n })\n\n return () => {\n laddaRef.current?.remove()\n clearInterval(interval)\n }\n }, [])\n\n useEffect(() => {\n if (laddaLoaded && finished) laddaRef.current?.stop()\n }, [finished, laddaLoaded])\n\n return (\n <StyledButton\n className={`ladda-button ${className}`}\n data-style=\"expand-right\"\n disabled={disabled}\n ref={buttonRef}\n onClick={onClick}\n $backgroundColor={colors.backgroundColor}\n $textColor={colors.textColor}\n $disabledBackgroundColor={colors.loadingBackgroundColor}\n $disabledTextColor={colors.loadingTextColor}\n $variant={variant}\n style={style}\n >\n <span className=\"ladda-label\">{children}</span>\n </StyledButton>\n )\n}\n\nconst StyledButton = styled.button<{\n $backgroundColor?: string\n $textColor?: string\n $disabledBackgroundColor?: string\n $disabledTextColor?: string\n $variant?: LoaderButtonVariant\n}>`\n ${(props) =>\n props.theme.buttons?.style === 'bootstrap' &&\n `\n border-radius: 0;\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n text-transform: none;\n -webkit-appearance: button;\n \n &:not(:disabled),\n &[type='button']:not(:disabled),\n &[type='reset']:not(:disabled),\n &[type='submit']:not(:disabled) {\n cursor: pointer;\n }\n \n &:focus:not(:focus-visible) {\n outline: 0;\n }\n \n --bs-btn-padding-x: 0.75rem;\n --bs-btn-padding-y: 0.375rem;\n --bs-btn-font-family: ;\n --bs-btn-font-size: 1rem;\n --bs-btn-font-weight: 400;\n --bs-btn-line-height: 1.5;\n --bs-btn-color: var(--bs-body-color);\n --bs-btn-bg: transparent;\n --bs-btn-border-width: var(--bs-border-width);\n --bs-btn-border-color: transparent;\n --bs-btn-border-radius: var(--bs-border-radius);\n --bs-btn-hover-border-color: transparent;\n --bs-btn-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15),\n 0 1px 1px rgba(0, 0, 0, 0.075);\n --bs-btn-disabled-opacity: 0.65;\n --bs-btn-focus-box-shadow: 0 0 0 0.25rem\n rgba(var(--bs-btn-focus-shadow-rgb), 0.5);\n display: inline-block;\n padding: var(--bs-btn-padding-y) var(--bs-btn-padding-x);\n font-family: var(--bs-btn-font-family);\n font-size: var(--bs-btn-font-size);\n font-weight: var(--bs-btn-font-weight);\n line-height: var(--bs-btn-line-height);\n color: var(--bs-btn-color);\n text-align: center;\n text-decoration: none;\n vertical-align: middle;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: var(--bs-btn-border-width) solid var(--bs-btn-border-color);\n border-radius: var(--bs-btn-border-radius);\n background-color: var(--bs-btn-bg);\n //transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,\n // border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;\n \n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n \n &:hover {\n filter: brightness(1.15);\n }\n \n &:focus-visible {\n color: var(--bs-btn-hover-color);\n background-color: var(--bs-btn-hover-bg);\n border-color: var(--bs-btn-hover-border-color);\n outline: 0;\n box-shadow: var(--bs-btn-focus-box-shadow);\n }\n \n &:disabled,\n &.disabled,\n fieldset:disabled & {\n color: var(--bs-btn-disabled-color);\n pointer-events: none;\n background-color: var(--bs-btn-disabled-bg);\n border-color: var(--bs-btn-disabled-border-color);\n opacity: var(--bs-btn-disabled-opacity);\n }\n \n --bs-btn-color: ${\n props.$textColor ??\n props.theme.buttons?.[props.$variant ?? 'primary']?.textColor ??\n '#fff'\n };\n --bs-btn-bg: ${\n props.$backgroundColor ??\n props.theme.buttons?.[props.$variant ?? 'primary']?.backgroundColor ??\n '#0d6efd'\n };\n --bs-btn-border-color: ${props.$backgroundColor ?? '#0d6efd'};\n --bs-btn-focus-shadow-rgb: 49, 132, 253;\n --bs-btn-active-color: #fff;\n --bs-btn-active-bg: #0a58ca;\n --bs-btn-active-border-color: #0a53be;\n --bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n --bs-btn-disabled-color: ${\n props.$disabledTextColor ??\n props.theme.buttons?.loading?.textColor ??\n '#fff'\n };\n --bs-btn-disabled-bg: ${\n props.$disabledBackgroundColor ??\n props.theme.buttons?.loading?.backgroundColor ??\n 'gray'\n };\n --bs-btn-disabled-border-color: ${\n props.$disabledBackgroundColor ?? '#0d6efd'\n };\n \n --bs-btn-padding-y: 14px;\n --bs-btn-padding-x: 1rem;\n --bs-btn-font-size: 18px;\n --bs-btn-border-radius: 4px;\n `}\n\n /*!\n * Ladda\n * http://lab.hakim.se/ladda\n * MIT licensed\n *\n * Copyright (C) 2018 Hakim El Hattab, http://hakim.se\n */\n @keyframes ladda-spinner-line-fade {\n 0%,\n 100% {\n opacity: 0.22;\n }\n 1% {\n opacity: 1;\n }\n }\n\n position: relative;\n\n .ladda-spinner {\n position: absolute;\n z-index: 2;\n display: inline-block;\n width: 32px;\n top: 50%;\n margin-top: 0;\n opacity: 0;\n pointer-events: none;\n }\n .ladda-label {\n position: relative;\n z-index: 3;\n }\n .ladda-progress {\n position: absolute;\n width: 0;\n height: 100%;\n left: 0;\n top: 0;\n background: rgba(0, 0, 0, 0.2);\n display: none;\n transition: 0.1s linear all !important;\n }\n &[data-loading] .ladda-progress {\n display: block;\n }\n\n transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;\n\n .ladda-spinner,\n .ladda-label {\n transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;\n }\n &[data-style='zoom-in'],\n &[data-style='zoom-in'] .ladda-spinner,\n &[data-style='zoom-in'] .ladda-label,\n &[data-style='zoom-out'],\n &[data-style='zoom-out'] .ladda-spinner,\n &[data-style='zoom-out'] .ladda-label {\n transition: 0.3s ease all !important;\n }\n &[data-style='expand-right'] .ladda-spinner {\n right: -6px;\n }\n &[data-style='expand-right'][data-size='s'] .ladda-spinner,\n &[data-style='expand-right'][data-size='xs'] .ladda-spinner {\n right: -12px;\n }\n &[data-style='expand-right'][data-loading] {\n padding-right: 56px;\n }\n &[data-style='expand-right'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='expand-right'][data-loading][data-size='s'],\n &[data-style='expand-right'][data-loading][data-size='xs'] {\n padding-right: 40px;\n }\n &[data-style='expand-left'] .ladda-spinner {\n left: 26px;\n }\n &[data-style='expand-left'][data-size='s'] .ladda-spinner,\n &[data-style='expand-left'][data-size='xs'] .ladda-spinner {\n left: 4px;\n }\n &[data-style='expand-left'][data-loading] {\n padding-left: 56px;\n }\n &[data-style='expand-left'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='expand-left'][data-loading][data-size='s'],\n &[data-style='expand-left'][data-loading][data-size='xs'] {\n padding-left: 40px;\n }\n &[data-style='expand-up'] {\n overflow: hidden;\n }\n &[data-style='expand-up'] .ladda-spinner {\n top: -32px;\n left: 50%;\n margin-left: 0;\n }\n &[data-style='expand-up'][data-loading] {\n padding-top: 54px;\n }\n &[data-style='expand-up'][data-loading] .ladda-spinner {\n opacity: 1;\n top: 26px;\n margin-top: 0;\n }\n &[data-style='expand-up'][data-loading][data-size='s'],\n &[data-style='expand-up'][data-loading][data-size='xs'] {\n padding-top: 32px;\n }\n &[data-style='expand-up'][data-loading][data-size='s'] .ladda-spinner,\n &[data-style='expand-up'][data-loading][data-size='xs'] .ladda-spinner {\n top: 4px;\n }\n &[data-style='expand-down'] {\n overflow: hidden;\n }\n &[data-style='expand-down'] .ladda-spinner {\n top: 62px;\n left: 50%;\n margin-left: 0;\n }\n &[data-style='expand-down'][data-size='s'] .ladda-spinner,\n &[data-style='expand-down'][data-size='xs'] .ladda-spinner {\n top: 40px;\n }\n &[data-style='expand-down'][data-loading] {\n padding-bottom: 54px;\n }\n &[data-style='expand-down'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='expand-down'][data-loading][data-size='s'],\n &[data-style='expand-down'][data-loading][data-size='xs'] {\n padding-bottom: 32px;\n }\n &[data-style='slide-left'] {\n overflow: hidden;\n }\n &[data-style='slide-left'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-left'] .ladda-spinner {\n left: 100%;\n margin-left: 0;\n }\n &[data-style='slide-left'][data-loading] .ladda-label {\n opacity: 0;\n left: -100%;\n }\n &[data-style='slide-left'][data-loading] .ladda-spinner {\n opacity: 1;\n left: 50%;\n }\n &[data-style='slide-right'] {\n overflow: hidden;\n }\n &[data-style='slide-right'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-right'] .ladda-spinner {\n right: 100%;\n margin-left: 0;\n left: 16px;\n }\n [dir='rtl'] &[data-style='slide-right'] .ladda-spinner {\n right: auto;\n }\n &[data-style='slide-right'][data-loading] .ladda-label {\n opacity: 0;\n left: 100%;\n }\n &[data-style='slide-right'][data-loading] .ladda-spinner {\n opacity: 1;\n left: 50%;\n }\n &[data-style='slide-up'] {\n overflow: hidden;\n }\n &[data-style='slide-up'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-up'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n margin-top: 1em;\n }\n &[data-style='slide-up'][data-loading] .ladda-label {\n opacity: 0;\n top: -1em;\n }\n &[data-style='slide-up'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-top: 0;\n }\n &[data-style='slide-down'] {\n overflow: hidden;\n }\n &[data-style='slide-down'] .ladda-label {\n position: relative;\n }\n &[data-style='slide-down'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n margin-top: -2em;\n }\n &[data-style='slide-down'][data-loading] .ladda-label {\n opacity: 0;\n top: 1em;\n }\n &[data-style='slide-down'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-top: 0;\n }\n &[data-style='zoom-out'] {\n overflow: hidden;\n }\n &[data-style='zoom-out'] .ladda-spinner {\n left: 50%;\n margin-left: 32px;\n transform: scale(2.5);\n }\n &[data-style='zoom-out'] .ladda-label {\n position: relative;\n display: inline-block;\n }\n &[data-style='zoom-out'][data-loading] .ladda-label {\n opacity: 0;\n transform: scale(0.5);\n }\n &[data-style='zoom-out'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-left: 0;\n transform: none;\n }\n &[data-style='zoom-in'] {\n overflow: hidden;\n }\n &[data-style='zoom-in'] .ladda-spinner {\n left: 50%;\n margin-left: -16px;\n transform: scale(0.2);\n }\n &[data-style='zoom-in'] .ladda-label {\n position: relative;\n display: inline-block;\n }\n &[data-style='zoom-in'][data-loading] .ladda-label {\n opacity: 0;\n transform: scale(2.2);\n }\n &[data-style='zoom-in'][data-loading] .ladda-spinner {\n opacity: 1;\n margin-left: 0;\n transform: none;\n }\n &[data-style='contract'] {\n overflow: hidden;\n width: 100px;\n }\n &[data-style='contract'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n }\n &[data-style='contract'][data-loading] {\n border-radius: 50%;\n width: 52px;\n }\n &[data-style='contract'][data-loading] .ladda-label {\n opacity: 0;\n }\n &[data-style='contract'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n &[data-style='contract-overlay'] {\n overflow: hidden;\n width: 100px;\n box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0);\n }\n &[data-style='contract-overlay'] .ladda-spinner {\n left: 50%;\n margin-left: 0;\n }\n &[data-style='contract-overlay'][data-loading] {\n border-radius: 50%;\n width: 52px;\n box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0.8);\n }\n &[data-style='contract-overlay'][data-loading] .ladda-label {\n opacity: 0;\n }\n &[data-style='contract-overlay'][data-loading] .ladda-spinner {\n opacity: 1;\n }\n [dir='rtl'] .ladda-spinner > div {\n left: 25% !important;\n }\n`\n","import React, { ReactElement, useContext } from 'react'\nimport {\n OverlayContainer,\n OverlayImageContainer,\n OverlayInner,\n} from '../common/overlay'\nimport { useTranslation } from 'react-i18next'\nimport { LoaderButton } from '../common/LoaderButton'\nimport { SubmissionContext } from './SubmissionProvider'\n\nexport type GeolocationAccessDeniedOverlayProps = {\n accessBlockedImageUrl?: string\n}\n\nexport const GeolocationAccessDeniedOverlay = ({\n accessBlockedImageUrl,\n}: GeolocationAccessDeniedOverlayProps): ReactElement => {\n const { t } = useTranslation()\n const { retryLocationAccess } = useContext(SubmissionContext)\n\n return (\n <OverlayContainer>\n <div style={{ display: 'flex', height: '100%' }}>\n <OverlayInner style={{ maxWidth: 500, height: 'auto', margin: 'auto' }}>\n <OverlayImageContainer style={{ flexGrow: 0 }}>\n <img src={accessBlockedImageUrl} alt={''} />\n </OverlayImageContainer>\n\n <h3>{t('Your location access is disabled')}</h3>\n <p style={{ lineHeight: 1.5, marginBottom: 50 }}>\n {t(\n 'This application requires access to your location to continue. ' +\n 'Please accept the permission once prompted by the browser. ' +\n 'If the browser does not prompt for location permissions, you must go to settings ' +\n 'and provide location access to the current browser.'\n )}\n </p>\n\n <LoaderButton\n variant=\"primary\"\n onClick={retryLocationAccess}\n style={{ width: 200, marginLeft: 'auto', marginRight: 'auto' }}\n finished\n >\n {t('Retry')}\n </LoaderButton>\n </OverlayInner>\n </div>\n </OverlayContainer>\n )\n}\n","import { SubmissionResponseStatus } from '../../contexts/SubmissionContext'\n\nexport class SubmissionError extends Error {\n constructor(public status: SubmissionResponseStatus) {\n super(status.statusMessage)\n }\n}\n\nexport class NetworkError extends Error {}\n\nexport class TokenPublicKeyError extends Error {\n constructor(public err: Error, public host: string) {\n super(err.message)\n }\n}\n","import React, { ReactElement } from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\nimport { NetworkError, SubmissionError } from './Errors'\nimport { LoaderButton } from '../common/LoaderButton'\nimport { useTranslation } from 'react-i18next'\n\nexport type SubmissionErrorOverlayProps = {\n error: SubmissionError | NetworkError\n onRetry?: () => void\n}\n\nexport const SubmissionErrorOverlay = ({\n error,\n onRetry,\n}: SubmissionErrorOverlayProps): ReactElement => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n {error instanceof NetworkError ? (\n <NetworkErrorContent error={error} onRetry={onRetry} />\n ) : (\n <SubmissionErrorContent error={error} />\n )}\n </OverlayInner>\n </OverlayContainer>\n )\n}\n\nconst SubmissionErrorContent = ({ error }: { error: SubmissionError }) => {\n const { t } = useTranslation()\n\n const headingText = t(`We're sorry, an unexpected error has occurred.`)\n\n return (\n <>\n <h3 style={{ marginBottom: 8 }}>{headingText}</h3>\n {error.status.statusCode && (\n <p style={{ marginBottom: 0 }}>\n <code>Status: {error.status.statusCode}</code>\n </p>\n )}\n <p style={{ marginBottom: 0 }}>\n Message: <code>{error.message}</code>\n </p>\n {error.status.errorData && (\n <p style={{ marginBottom: 0 }}>\n Data: <code>{error.status.errorData}</code>\n </p>\n )}\n </>\n )\n}\n\nconst NetworkErrorContent = ({\n onRetry,\n}: {\n error: NetworkError\n onRetry?: () => void\n}) => {\n const { t } = useTranslation()\n const headingText = t('Network unreachable')\n const messageText = t(\n `We're having trouble reaching our services, please check your connection and try again.`\n )\n const retryText = t('Retry')\n\n return (\n <>\n <h3 style={{ marginBottom: 8 }}>{headingText}</h3>\n <p style={{ marginBottom: 0 }}>{messageText}</p>\n\n {onRetry && (\n <div style={{ marginTop: 32 }}>\n <LoaderButton variant=\"warning\" finished onClick={onRetry}>\n {retryText}\n </LoaderButton>\n </div>\n )}\n </>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenMissingErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> is missing.\n </p>\n <p style={{ lineHeight: '1.5rem' }}>\n Please refer to the{' '}\n <a\n href=\"https://www.npmjs.com/package/idmission-web-sdk#getting-started\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n Getting Started\n </a>{' '}\n section of the documentation for information on how to use your\n credentials to generate a valid{' '}\n <a href=\"https://jwt.io\" target=\"_blank\" rel=\"noreferrer\">\n JSON Web Token\n </a>{' '}\n for your IDmission account. Every usage of the IDmission WebSDK must\n be authorized with a valid JWT from IDmission's servers.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenInvalidFormatErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> is invalid.\n </p>\n <p>\n JSON Web Tokens consist of three parts separated by dots (\n <code>.</code>), which are:\n </p>\n <div style={{ display: 'flex' }}>\n <ul style={{ display: 'inline', margin: '0 auto' }}>\n <li>Header</li>\n <li>Payload</li>\n <li>Signature</li>\n </ul>\n </div>\n <p>\n Therefore, a JWT typically looks like the following:{' '}\n <code>xxxxx.yyyyy.zzzzz</code>\n </p>\n <p style={{ lineHeight: '1.5rem' }}>\n Please refer to the{' '}\n <a\n href=\"https://www.npmjs.com/package/idmission-web-sdk#getting-started\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n Getting Started\n </a>{' '}\n section of the documentation for information on how to use your\n credentials to generate a valid{' '}\n <a href=\"https://jwt.io\" target=\"_blank\" rel=\"noreferrer\">\n JSON Web Token\n </a>{' '}\n for your IDmission account. Every usage of the IDmission WebSDK must\n be authorized with a valid JWT from IDmission's servers.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenInvalidSignatureErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> could not be validated.\n </p>\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n The signature of your token could not be validated. Check your token\n generation routine, it's possible that some malicious behavior is\n at play. This can also happen if you attempt to manually modify your\n token before passing it to the IDmission WebSDK.\n </p>\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n If you believe you have reached this page in error, please contact us\n at <a href=\"mailto:support@idmission.com\">support@idmission.com</a>.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\n\nexport const TokenExpiredErrorOverlay = () => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n Required property <code>submissionToken</code> is expired.\n </p>\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n Ensure you are generating a fresh token for each request to the\n IDmission WebSDK.\n </p>\n <p style={{ lineHeight: '1.5rem' }}>\n Please refer to the{' '}\n <a\n href=\"https://www.npmjs.com/package/idmission-web-sdk#getting-started\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n Getting Started\n </a>{' '}\n section of the documentation for information on how to use your\n credentials to generate a valid{' '}\n <a href=\"https://jwt.io\" target=\"_blank\" rel=\"noreferrer\">\n JSON Web Token\n </a>{' '}\n for your IDmission account. Every usage of the IDmission WebSDK must\n be authorized with a valid JWT from IDmission's servers.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React from 'react'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\nimport { TokenPublicKeyError } from './Errors'\n\nexport const TokenPublicKeyErrorOverlay = ({\n error,\n}: {\n error: TokenPublicKeyError | null\n}) => {\n return (\n <OverlayContainer>\n <OverlayInner style={{ justifyContent: 'center' }}>\n <h3 style={{ marginBottom: 8 }}>IDmission WebSDK failed to load</h3>\n <p style={{ marginBottom: 0 }}>\n {error?.host ? (\n <>\n Failed to reach <code>{error.host}</code>.\n </>\n ) : (\n <>\n Failed to obtain public key for <code>submissionToken</code>.\n </>\n )}\n </p>\n {error?.message && (\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n <code>{error.message}</code>\n </p>\n )}\n <p style={{ marginBottom: 0, lineHeight: '1.5rem' }}>\n Please ensure that IDmission's servers can be reached. If you\n believe you have reached this page in error, please contact us at{' '}\n <a href=\"mailto:support@idmission.com\">support@idmission.com</a>.\n </p>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React, {\n createContext,\n ReactElement,\n useCallback,\n useEffect,\n useState,\n} from 'react'\nimport {\n apiHeaders,\n attachMetadataToRequest,\n CaptureAttemptMetadata,\n CardData,\n determineSubmissionEndpoint,\n determineSubmissionHost,\n liveCheckEndpoint,\n LiveCheckResponse,\n LivenessCheckRequest,\n parseJwt,\n PersonalData,\n SubmissionAction,\n SubmissionEnvironment,\n SubmissionRequest,\n SubmissionResponse,\n SubmissionStatus,\n videoDataUrlToB64,\n} from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { UploadedDocument } from '../additional_document_capture/AdditionalDocumentCapture'\nimport { SignatureData } from '../signature_capture/data'\nimport { GeolocationAccessDeniedOverlay } from './GeolocationAccessDeniedOverlay'\nimport { SubmissionErrorOverlay } from './SubmissionErrorOverlay'\nimport { NetworkError, SubmissionError, TokenPublicKeyError } from './Errors'\nimport { TokenMissingErrorOverlay } from './TokenMissingErrorOverlay'\nimport { TokenInvalidFormatErrorOverlay } from './TokenInvalidFormatErrorOverlay'\nimport { TokenInvalidSignatureErrorOverlay } from './TokenInvalidSignatureErrorOverlay'\nimport { TokenExpiredErrorOverlay } from './TokenExpiredErrorOverlay'\nimport { TokenPublicKeyErrorOverlay } from './TokenPublicKeyErrorOverlay'\n\nexport type TokenState =\n | 'NOT_PARSED'\n | 'PARSING'\n | 'GOOD'\n | 'EXPIRED'\n | 'INVALID_FORMAT'\n | 'INVALID_SIGNATURE'\n | 'MISSING'\n | 'PUBLIC_KEY_LOAD_FAILED'\n\nexport type SubmissionState = {\n submit: () => Promise<SubmissionResponse | null>\n submissionStatus: SubmissionStatus\n submissionRequest: SubmissionRequest | null\n submissionResponse: SubmissionResponse | null\n submissionError: SubmissionError | NetworkError | null\n submissionEnvironment: SubmissionEnvironment\n\n idFrontImage: string | null\n idBackImage: string | null\n passportImage: string | null\n selfieImage: string | null\n signatureData: SignatureData | null\n signatureVideoUrl: string | null\n idCaptureVideoUrl: string | null\n idCaptureVideoIdFrontImage: string | null\n idCaptureVideoIdBackImage: string | null\n additionalDocuments: UploadedDocument[] | null\n\n setIdFrontImage: (image: string) => void\n setIdBackImage: (image: string) => void\n setPassportImage: (image: string) => void\n setSelfieImage: (image: string) => void\n setSignatureData: (signatureData: SignatureData) => void\n setSignatureVideoUrl: (videoDataUrl: string) => void\n setIdCaptureVideoUrl: (videoDataUrl: string) => void\n setIdCaptureVideoIdFrontImage: (image: string) => void\n setIdCaptureVideoIdBackImage: (image: string) => void\n setAdditionalDocuments: (uploadedDocuments: UploadedDocument[]) => void\n\n logIdFrontCaptureAttempt: (attempt: CaptureAttemptMetadata) => void\n logIdBackCaptureAttempt: (attempt: CaptureAttemptMetadata) => void\n logSelfieCaptureAttempt: (attempt: CaptureAttemptMetadata) => void\n\n livenessCheckRequest: LivenessCheckRequest | null\n checkLiveness: (imageDataUrl: string) => Promise<LiveCheckResponse>\n\n retryLocationAccess: () => void\n}\n\nexport const SubmissionContext = createContext<SubmissionState>({\n submit: async () => null,\n submissionStatus: SubmissionStatus.READY,\n submissionRequest: null,\n submissionResponse: null,\n submissionError: null,\n submissionEnvironment: 'prod',\n\n idFrontImage: null,\n idBackImage: null,\n passportImage: null,\n selfieImage: null,\n signatureData: null,\n signatureVideoUrl: null,\n idCaptureVideoUrl: null,\n idCaptureVideoIdFrontImage: null,\n idCaptureVideoIdBackImage: null,\n additionalDocuments: null,\n\n setIdFrontImage: () => null,\n setIdBackImage: () => null,\n setPassportImage: () => null,\n setSelfieImage: () => null,\n setSignatureData: () => null,\n setSignatureVideoUrl: () => null,\n setIdCaptureVideoUrl: () => null,\n setIdCaptureVideoIdFrontImage: () => null,\n setIdCaptureVideoIdBackImage: () => null,\n setAdditionalDocuments: () => null,\n\n logIdFrontCaptureAttempt: () => null,\n logIdBackCaptureAttempt: () => null,\n logSelfieCaptureAttempt: () => null,\n\n livenessCheckRequest: null,\n checkLiveness: async () => {\n throw new Error('checkLiveness is not implemented')\n },\n\n retryLocationAccess: () => null,\n})\n\nexport type SubmissionProviderProps = {\n action: SubmissionAction\n children: ReactElement\n token: string\n url?: string\n environment?: SubmissionEnvironment\n companyId?: string\n enrollmentId?: string\n personalData?: PersonalData\n cardData?: CardData\n bypassAgeValidation?: boolean\n bypassNameMatching?: boolean\n needImmediateResponse?: boolean\n manualReviewRequired?: boolean\n idBackImageRequired?: boolean\n idImageResolutionCheck?: boolean\n verifyIdWithExternalDatabases?: boolean\n deduplicationEnabled?: boolean\n deduplicationSynchronous?: boolean\n geolocationEnabled?: boolean\n geolocationRequired?: boolean\n webhooksEnabled?: boolean\n webhooksClientTraceId?: string\n webhooksStripSpecialCharacters?: boolean\n webhooksSendInputImages?: boolean\n webhooksSendProcessedImages?: boolean\n webhooksFireOnReview?: boolean\n onSubmit?: (payload: SubmissionRequest) => void\n onBeforeSubmit?: (req: SubmissionRequest) => Promise<SubmissionRequest>\n onBeforeLivenessCheck?: (\n req: LivenessCheckRequest\n ) => Promise<LivenessCheckRequest>\n onResponseReceived?: (res: SubmissionResponse, req: SubmissionRequest) => void\n onRequestFailure?: (err: Error) => void\n}\n\nexport const SubmissionProvider = ({\n action,\n children,\n url,\n environment = 'prod',\n token,\n companyId,\n enrollmentId,\n personalData,\n cardData,\n bypassAgeValidation = false,\n bypassNameMatching = true,\n needImmediateResponse = false,\n manualReviewRequired = false,\n idBackImageRequired = true,\n idImageResolutionCheck = true,\n verifyIdWithExternalDatabases = false,\n deduplicationEnabled = false,\n deduplicationSynchronous = false,\n geolocationEnabled = true,\n geolocationRequired = false,\n webhooksEnabled = false,\n webhooksClientTraceId,\n webhooksStripSpecialCharacters = true,\n webhooksSendInputImages = false,\n webhooksSendProcessedImages = false,\n webhooksFireOnReview = false,\n onSubmit,\n onBeforeSubmit,\n onBeforeLivenessCheck,\n onResponseReceived,\n onRequestFailure,\n}: SubmissionProviderProps): ReactElement => {\n const [submissionStatus, setSubmissionStatus] = useState<SubmissionStatus>(\n SubmissionStatus.READY\n )\n const [submissionRequest, setSubmissionRequest] =\n useState<SubmissionRequest | null>(null)\n const [submissionResponse, setSubmissionResponse] =\n useState<SubmissionResponse | null>(null)\n const [submissionError, setSubmissionError] = useState<\n SubmissionError | NetworkError | null\n >(null)\n const [retrySubmission, setRetrySubmission] = useState<(() => void) | null>(\n null\n )\n const [livenessCheckRequest, setLivenessCheckRequest] =\n useState<LivenessCheckRequest | null>(null)\n\n const [idFrontImage, setIdFrontImage] = useState<string | null>(null)\n const [idBackImage, setIdBackImage] = useState<string | null>(null)\n const [passportImage, setPassportImage] = useState<string | null>(null)\n const [selfieImage, setSelfieImage] = useState<string | null>(null)\n const [signatureData, setSignatureData] = useState<SignatureData | null>(null)\n const [signatureVideoUrl, setSignatureVideoUrl] = useState<string | null>(\n null\n )\n const [idCaptureVideoUrl, setIdCaptureVideoUrl] = useState<string | null>(\n null\n )\n const [idCaptureVideoIdFrontImage, setIdCaptureVideoIdFrontImage] = useState<\n string | null\n >(null)\n const [idCaptureVideoIdBackImage, setIdCaptureVideoIdBackImage] = useState<\n string | null\n >(null)\n const [additionalDocuments, setAdditionalDocuments] = useState<\n UploadedDocument[] | null\n >(null)\n\n const [geolocationResult, setGeolocationResult] =\n useState<GeolocationPosition | null>(null)\n const [geolocationAttempts, setGeolocationAttempts] = useState(0)\n const [geolocationBlocked, setGeolocationBlocked] = useState(false)\n\n const [idFrontCaptureAttempts, setIdFrontCaptureAttempts] = useState<\n CaptureAttemptMetadata[]\n >([])\n const [idBackCaptureAttempts, setIdBackCaptureAttempts] = useState<\n CaptureAttemptMetadata[]\n >([])\n const [selfieCaptureAttempts, setSelfieCaptureAttempts] = useState<\n CaptureAttemptMetadata[]\n >([])\n\n const logIdFrontCaptureAttempt = useCallback(\n (attempt: CaptureAttemptMetadata) => {\n setIdFrontCaptureAttempts((attempts) => [...attempts, attempt])\n },\n []\n )\n const logIdBackCaptureAttempt = useCallback(\n (attempt: CaptureAttemptMetadata) => {\n setIdBackCaptureAttempts((attempts) => [...attempts, attempt])\n },\n []\n )\n const logSelfieCaptureAttempt = useCallback(\n (attempt: CaptureAttemptMetadata) => {\n setSelfieCaptureAttempts((attempts) => [...attempts, attempt])\n },\n []\n )\n\n const buildSubmissionPayload = useCallback(async () => {\n let submissionRequest: SubmissionRequest = {\n securityData: { userName: '', password: '', merchantId: 0 },\n customerData: {\n idData: { idType: 'NSP', idCountry: 'NSP', idState: '' },\n },\n additionalData: {\n uniqueRequestId: new Date().getTime().toString(),\n manualReviewRequired: manualReviewRequired ? 'Y' : 'N',\n bypassAgeValidation: bypassAgeValidation ? 'Y' : 'N',\n bypassNameMatching: bypassNameMatching ? 'Y' : 'N',\n postDataAPIRequired: webhooksEnabled ? 'Y' : 'N',\n postDataOnReviewRequired: webhooksFireOnReview ? 'Y' : 'N',\n sendInputImagesInPost: webhooksSendInputImages ? 'Y' : 'N',\n sendProcessedImagesInPost: webhooksSendProcessedImages ? 'Y' : 'N',\n needImmediateResponse: needImmediateResponse ? 'Y' : 'N',\n deDuplicationRequired: deduplicationEnabled ? 'Y' : 'N',\n deduplicationSynchronous: deduplicationSynchronous ? 'Y' : 'N',\n verifyDataWithHost: verifyIdWithExternalDatabases ? 'Y' : 'N',\n idBackImageRequired: idBackImageRequired ? 'Y' : 'N',\n stripSpecialCharacters: webhooksStripSpecialCharacters ? 'Y' : 'N',\n idImageResolutionCheck: idImageResolutionCheck ? 'Y' : 'N',\n },\n }\n\n if (idFrontImage) {\n submissionRequest.customerData.idData.idImageFront = idFrontImage\n }\n if (idBackImage) {\n submissionRequest.customerData.idData.idImageBack = idBackImage\n }\n if (passportImage) {\n submissionRequest.customerData.idData.idImageFront = passportImage\n }\n if (selfieImage) {\n if (action === SubmissionAction.IDENTIFY) {\n submissionRequest.biometricData = { selfie: selfieImage }\n } else {\n submissionRequest.customerData.biometricData = { selfie: selfieImage }\n }\n }\n if (companyId) {\n submissionRequest.employee = { companyId }\n }\n if (personalData) {\n submissionRequest.customerData.personalData = personalData\n }\n if (cardData) {\n submissionRequest.customerData.cardData = cardData\n }\n if (enrollmentId) {\n submissionRequest.customerData.personalData ||= {}\n submissionRequest.customerData.personalData.uniqueNumber = enrollmentId\n }\n if (webhooksClientTraceId) {\n submissionRequest.additionalData.clientTraceId = webhooksClientTraceId\n }\n if (signatureData) {\n submissionRequest.customerData.signatureData = {\n signatureImage: JSON.stringify(signatureData),\n // signatureImage: signatureData.fileContent,\n }\n }\n if (additionalDocuments) {\n submissionRequest.customerData.additionalDocuments =\n additionalDocuments.map((d) => ({\n ...d,\n additionalDocument: JSON.stringify({\n ...(d.additionalDocument as Record<string, string>),\n uniqueId: submissionRequest.additionalData.uniqueRequestId,\n }),\n }))\n }\n if (idCaptureVideoUrl || signatureVideoUrl) {\n submissionRequest.biometricData ||= {}\n submissionRequest.biometricData.videoData = await videoDataUrlToB64(\n idCaptureVideoUrl ?? signatureVideoUrl ?? ''\n )\n }\n\n attachMetadataToRequest(submissionRequest, {\n selfieCaptureAttempts,\n idFrontCaptureAttempts,\n idBackCaptureAttempts,\n geolocationResult,\n })\n\n if (onBeforeSubmit) {\n const onBeforeSubmitResult = await onBeforeSubmit(submissionRequest)\n if (onBeforeSubmitResult) submissionRequest = onBeforeSubmitResult\n }\n\n return submissionRequest\n }, [\n action,\n additionalDocuments,\n bypassAgeValidation,\n bypassNameMatching,\n cardData,\n companyId,\n deduplicationEnabled,\n deduplicationSynchronous,\n enrollmentId,\n geolocationResult,\n idBackCaptureAttempts,\n idBackImage,\n idBackImageRequired,\n idCaptureVideoUrl,\n idFrontCaptureAttempts,\n idFrontImage,\n idImageResolutionCheck,\n manualReviewRequired,\n needImmediateResponse,\n onBeforeSubmit,\n passportImage,\n personalData,\n selfieCaptureAttempts,\n selfieImage,\n signatureData,\n signatureVideoUrl,\n verifyIdWithExternalDatabases,\n webhooksClientTraceId,\n webhooksEnabled,\n webhooksFireOnReview,\n webhooksSendInputImages,\n webhooksSendProcessedImages,\n webhooksStripSpecialCharacters,\n ])\n\n const defaultOnSubmit = useCallback(async () => {\n if (action === SubmissionAction.NONE) {\n const submissionResponse = {\n status: { statusCode: '000' },\n resultData: {},\n }\n setSubmissionStatus(SubmissionStatus.SUBMITTED)\n setSubmissionResponse(submissionResponse)\n return submissionResponse\n }\n\n setSubmissionStatus(SubmissionStatus.SUBMITTING)\n\n try {\n const payload = await buildSubmissionPayload()\n const host = url || determineSubmissionHost(environment, token)\n const endpoint = determineSubmissionEndpoint(\n action,\n !!(idFrontImage || idBackImage || passportImage),\n !!selfieImage,\n !!token\n )\n const response = await fetch(host + endpoint, {\n method: 'POST',\n headers: apiHeaders(token),\n body: JSON.stringify(payload),\n }).catch((e) => {\n throw new NetworkError(e.message)\n })\n\n if (!response || !response.ok) {\n const statusMessage = await response?.text()\n\n if (!statusMessage || statusMessage === 'Load failed')\n throw new NetworkError(statusMessage)\n\n throw new SubmissionError({\n statusCode: response?.statusText ?? '???',\n statusMessage,\n })\n }\n\n const submissionResponse = await response.json()\n if (submissionResponse.status.statusCode !== '000') {\n throw new SubmissionError(submissionResponse.status)\n }\n\n setSubmissionRequest(payload)\n setSubmissionResponse(submissionResponse)\n setSubmissionStatus(SubmissionStatus.SUBMITTED)\n onResponseReceived?.(submissionResponse, payload)\n return submissionResponse\n } catch (e) {\n const err = e as Error\n setSubmissionStatus(SubmissionStatus.FAILED)\n setSubmissionError(\n e instanceof SubmissionError || e instanceof NetworkError\n ? e\n : err.message === 'Load failed'\n ? new NetworkError()\n : new SubmissionError({ statusCode: '', statusMessage: err.message })\n )\n setRetrySubmission(() =>\n ['VERIFY', 'IDENTIFY'].includes(action) ? () => null : defaultOnSubmit\n )\n onRequestFailure?.(err)\n throw err\n }\n }, [\n action,\n buildSubmissionPayload,\n environment,\n idBackImage,\n idFrontImage,\n onRequestFailure,\n onResponseReceived,\n passportImage,\n selfieImage,\n token,\n url,\n ])\n\n const submit = useCallback(async () => {\n if (onSubmit) return onSubmit(await buildSubmissionPayload())\n return await defaultOnSubmit()\n }, [buildSubmissionPayload, defaultOnSubmit, onSubmit])\n\n const checkLiveness = useCallback(\n async (imageDataUrl: string) => {\n try {\n let request: LivenessCheckRequest = {\n securityData: { userName: '', password: '', merchantId: 0 },\n customerData: {\n biometricData: { selfie: await dataUrlToBase64(imageDataUrl) },\n },\n additionalData: {\n uniqueRequestId: new Date().getTime().toString(),\n stripSpecialCharacters: webhooksStripSpecialCharacters ? 'Y' : 'N',\n estimateAge: 'N',\n predictGender: 'N',\n },\n }\n\n attachMetadataToRequest(request, {\n selfieCaptureAttempts,\n idFrontCaptureAttempts,\n idBackCaptureAttempts,\n geolocationResult,\n })\n\n setLivenessCheckRequest(request)\n\n if (onBeforeLivenessCheck) {\n const onBeforeLivenessCheckResult = await onBeforeLivenessCheck(\n request\n )\n if (onBeforeLivenessCheckResult) request = onBeforeLivenessCheckResult\n }\n\n const host = url || determineSubmissionHost(environment, token)\n const endpoint = liveCheckEndpoint(!!token)\n const response = await fetch(host + endpoint, {\n method: 'POST',\n headers: apiHeaders(token),\n body: JSON.stringify(request),\n }).catch((e) => {\n throw new NetworkError(e.message)\n })\n\n if (!response.ok) {\n const statusMessage = await response.text()\n\n if (!statusMessage || statusMessage === 'Load failed')\n throw new NetworkError(statusMessage)\n\n throw new SubmissionError({\n statusCode: response.statusText,\n statusMessage,\n })\n }\n\n const submissionResponse = await response.json()\n if (submissionResponse.status.statusCode !== '000') {\n throw new SubmissionError(submissionResponse.status)\n }\n\n setSubmissionResponse(submissionResponse)\n return submissionResponse\n } catch (e) {\n const err = e as Error\n setSubmissionStatus(SubmissionStatus.FAILED)\n setSubmissionError(\n e instanceof SubmissionError || e instanceof NetworkError\n ? e\n : err.message === 'Load failed'\n ? new NetworkError()\n : new SubmissionError({\n statusCode: '',\n statusMessage: err.message,\n })\n )\n // the face liveness routine will call again, so don't repeat the call here.\n setRetrySubmission(() => () => null)\n onRequestFailure?.(err)\n throw err\n }\n },\n [\n environment,\n geolocationResult,\n idBackCaptureAttempts,\n idFrontCaptureAttempts,\n onBeforeLivenessCheck,\n onRequestFailure,\n selfieCaptureAttempts,\n token,\n url,\n webhooksStripSpecialCharacters,\n ]\n )\n\n const retryLocationAccess = useCallback(() => {\n setGeolocationAttempts((n) => n + 1)\n }, [])\n\n useEffect(() => {\n if (!geolocationEnabled) return\n\n console.log('making geolocation attempt', geolocationAttempts)\n navigator.geolocation.getCurrentPosition(\n (position) => {\n setGeolocationResult(position)\n setGeolocationBlocked(false)\n },\n (positionError) => {\n if (positionError.code === 1) {\n setGeolocationBlocked(true)\n } else {\n throw new Error(positionError.message)\n }\n }\n )\n }, [geolocationAttempts, geolocationEnabled, geolocationRequired])\n\n const onRetry = useCallback(() => {\n if (!retrySubmission) return\n setSubmissionError(null)\n setSubmissionStatus(SubmissionStatus.READY)\n retrySubmission()\n }, [retrySubmission])\n\n const [tokenState, setTokenState] = useState<TokenState>('NOT_PARSED')\n const [tokenError, setTokenError] = useState<TokenPublicKeyError | null>(null)\n useEffect(() => {\n ;(async () => {\n setTokenState('PARSING')\n if (!token) return setTokenState('MISSING')\n\n let parsed: Record<string, unknown>\n try {\n parsed = parseJwt(token)\n } catch (e) {\n console.error('error parsing token', e)\n return setTokenState('INVALID_FORMAT')\n }\n\n const iss = parsed.iss as string\n let publicKey: CryptoKey\n try {\n const resp = await fetch(iss).then((r) => r.json())\n publicKey = await importRsaKey(\n `-----BEGIN PUBLIC KEY-----\\n${resp.public_key}\\n-----END PUBLIC KEY-----`\n )\n } catch (e) {\n console.error('error fetching public key', e)\n setTokenError(new TokenPublicKeyError(e as Error, iss))\n return setTokenState('PUBLIC_KEY_LOAD_FAILED')\n }\n\n let valid = false\n try {\n const parts = token.split('.')\n await window.crypto.subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey, //from generateKey or importKey above\n str2ab(parts[1]), //ArrayBuffer of the signature\n str2ab(parts[2]) //ArrayBuffer of the data\n )\n valid = true\n } catch (e) {\n console.error('error validating token', e)\n }\n if (!valid) return setTokenState('INVALID_SIGNATURE')\n\n const exp = parsed.exp\n if (Date.now() >= (exp as number) * 1000) {\n return setTokenState('EXPIRED')\n }\n\n setTokenState('GOOD')\n })()\n }, [token])\n\n const value: SubmissionState = {\n submit,\n submissionStatus,\n submissionRequest,\n submissionResponse,\n submissionError,\n submissionEnvironment: environment,\n\n idFrontImage,\n idBackImage,\n passportImage,\n selfieImage,\n signatureData,\n signatureVideoUrl,\n idCaptureVideoUrl,\n idCaptureVideoIdFrontImage,\n idCaptureVideoIdBackImage,\n additionalDocuments,\n\n setIdFrontImage,\n setIdBackImage,\n setPassportImage,\n setSelfieImage,\n setSignatureData,\n setSignatureVideoUrl,\n setIdCaptureVideoUrl,\n setIdCaptureVideoIdFrontImage,\n setIdCaptureVideoIdBackImage,\n setAdditionalDocuments,\n\n logIdFrontCaptureAttempt,\n logIdBackCaptureAttempt,\n logSelfieCaptureAttempt,\n\n livenessCheckRequest,\n checkLiveness,\n retryLocationAccess,\n }\n\n if (tokenState === 'MISSING') {\n return <TokenMissingErrorOverlay />\n }\n\n if (tokenState === 'INVALID_FORMAT') {\n return <TokenInvalidFormatErrorOverlay />\n }\n\n if (tokenState === 'INVALID_SIGNATURE') {\n return <TokenInvalidSignatureErrorOverlay />\n }\n\n if (tokenState === 'EXPIRED') {\n return <TokenExpiredErrorOverlay />\n }\n\n if (tokenState === 'PUBLIC_KEY_LOAD_FAILED') {\n return <TokenPublicKeyErrorOverlay error={tokenError} />\n }\n\n return (\n <SubmissionContext.Provider value={value}>\n {geolocationRequired && geolocationBlocked ? (\n <GeolocationAccessDeniedOverlay />\n ) : (\n children\n )}\n\n {submissionError && (\n <SubmissionErrorOverlay error={submissionError} onRetry={onRetry} />\n )}\n </SubmissionContext.Provider>\n )\n}\n\nfunction str2ab(str: string) {\n const buf = new ArrayBuffer(str.length)\n const bufView = new Uint8Array(buf)\n for (let i = 0, strLen = str.length; i < strLen; i++) {\n bufView[i] = str.charCodeAt(i)\n }\n return buf\n}\n\nfunction importRsaKey(pem: string) {\n // fetch the part of the PEM string between header and footer\n const pemHeader = '-----BEGIN PUBLIC KEY-----'\n const pemFooter = '-----END PUBLIC KEY-----'\n const pemContents = pem.substring(\n pemHeader.length,\n pem.length - pemFooter.length - 1\n )\n // base64 decode the string to get the binary data\n const binaryDerString = window.atob(pemContents)\n // convert from a binary string to an ArrayBuffer\n const binaryDer = str2ab(binaryDerString)\n\n return window.crypto.subtle.importKey(\n 'spki',\n binaryDer,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: 'SHA-256',\n },\n true,\n ['verify']\n )\n}\n","import * as tf from '@tensorflow/tfjs'\n\nexport enum DocumentType {\n NONE = 'NONE',\n ID_CARD = 'ID_CARD',\n ID_CARD_FRONT = 'ID_CARD_FRONT',\n ID_CARD_BACK = 'ID_CARD_BACK',\n PASSPORT = 'PASSPORT',\n}\n\nexport let documentDetectionModel: tf.GraphModel | null\n\nexport async function loadDocumentDetectionModel(\n url: string\n): Promise<tf.GraphModel> {\n if (documentDetectionModel) return documentDetectionModel\n\n documentDetectionModel = await tf.loadGraphModel(url)\n await tf.ready()\n\n // warm the model by predicting on an empty image\n const zeroes = tf.zeros([448, 448, 3])\n const tfInt32 = tf.cast(zeroes, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(tfInt32.dataSync()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n tf.dispose(await documentDetectionModel.executeAsync(tf4d))\n\n tfInt32.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(zeroes)\n\n return documentDetectionModel\n}\n\nexport function unloadDocumentDetectionModel(): void {\n documentDetectionModel = null\n}\n\nexport type RawEdgeDetectionResult = tf.Tensor<tf.Rank>[]\n\nexport async function makeDocumentDetectionPredictions(\n model: tf.GraphModel,\n image: ImageBitmap | ImageData | HTMLImageElement\n): Promise<[RawEdgeDetectionResult, () => void]> {\n const tfImg = tf.browser.fromPixels(image)\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n const tfInt32 = tf.cast(tfResize, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(tfInt32.dataSync()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n const predictions = (await model.executeAsync(tf4d)) as RawEdgeDetectionResult\n const cleanup = () => {\n tfInt32.dispose()\n tfImg.dispose()\n tfResize.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(predictions)\n }\n return [predictions, cleanup]\n}\n\nexport type DocumentDetectionResults = {\n boxes: number[][]\n scores: number[]\n labels: number[]\n}\n\nexport const labelMap: { [id: number]: Label } = {\n 1: 'Document',\n 2: 'MRZ',\n 3: 'PDF417',\n 4: 'Primary face',\n 5: 'Secondary face',\n 6: 'Glare',\n 7: 'Punch Hole',\n 8: 'Passport Page',\n}\n\nexport type Label =\n | 'Document'\n | 'MRZ'\n | 'PDF417'\n | 'Primary face'\n | 'Secondary face'\n | 'Glare'\n | 'Punch Hole'\n | 'Passport Page'\n\nexport async function runDocumentDetection(\n model: tf.GraphModel,\n image: ImageBitmap | ImageData | HTMLImageElement\n): Promise<DocumentDetectionResults> {\n const [predictions, cleanup] = await makeDocumentDetectionPredictions(\n model,\n image\n )\n\n const [boxes] = (await predictions[2].array()) as number[][][]\n const [scores] = (await predictions[6].array()) as number[][]\n const [labels] = (await predictions[4].array()) as number[][]\n\n cleanup()\n\n return { boxes, scores, labels }\n}\n\nexport type DetectedObject = {\n score: number\n bbox: number[]\n label: Label\n}\n\nexport function bboxToDetectedObjectUnscaled(\n box: number[],\n score: number,\n label: number\n): DetectedObject {\n const [minY, minX, maxY, maxX] = box\n const bbox = [minX, minY, maxX - minX, maxY - minY]\n return { score, bbox, label: labelMap[label] }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nlet isMobileMockValue: boolean|undefined;\n\nexport function mockIsMobile(value: boolean|undefined) {\n isMobileMockValue = value;\n}\n\nexport function isMobile(nav?: Navigator): boolean {\n if (isMobileMockValue !== undefined) {\n return isMobileMockValue;\n }\n if (nav || _isNavigatorDefined()) {\n if (!nav) {\n nav = navigator;\n }\n if (nav.product === 'ReactNative') {\n return true;\n }\n\n const a = nav.userAgent || nav.vendor ||\n // tslint:disable-next-line:no-any\n (typeof window !== 'undefined' ? (window as any).opera : '');\n // Use `navigator.userAgentData.mobile` as fallback.\n if (!a) {\n // tslint:disable-next-line:no-any\n const navAny = nav as any;\n return navAny.userAgentData && navAny.userAgentData.mobile;\n }\n // tslint:disable-next-line:max-line-length\n return /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n","import React, { ReactElement, useContext, useEffect } from 'react'\nimport { GuideOrientationContext } from '../../contexts/GuideOrientationContext'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport { PageContainer } from '../common/Page'\nimport styled, { useTheme } from 'styled-components'\n\nexport const GuidesContainer = styled.div`\n display: flex;\n flex-flow: column nowrap;\n width: 100%;\n height: 100%;\n`\n\nexport const GuideCenterRow = styled.div`\n position: relative;\n display: flex;\n flex-flow: row nowrap;\n align-items: center;\n justify-items: center;\n box-sizing: border-box;\n max-width: 100%;\n max-height: 100%;\n`\n\nexport const GuideRegion = styled.div<{\n $minWidth?: number\n $minHeight?: number\n}>`\n display: flex;\n flex-direction: column;\n justify-content: end;\n width: 100%;\n height: 100%;\n flex-grow: 1;\n background: ${(props) =>\n props.theme?.idCapture?.guideOverlay?.backgroundColor ??\n 'rgba(0, 0, 0, 0.5)'};\n color: ${(props) =>\n props.theme?.idCapture?.guideOverlay?.textColor ?? 'white'};\n text-align: center;\n ${(props) => (props.$minWidth ? `min-width: ${props.$minWidth}px;` : ``)}\n ${(props) => (props.$minHeight ? `min-width: ${props.$minHeight}px;` : ``)}\n`\n\nexport const GuideCenterRegion = styled.div<{ $isMirrored?: boolean }>`\n ${(props) => (props.$isMirrored ? 'transform: scaleX(-1);' : '')}\n box-sizing: border-box;\n`\n\nexport const GuideCenterBorder = styled.div<{\n $borderWidth: number\n $borderColor?: string\n}>`\n position: relative;\n border: ${(props) =>\n `${props.$borderWidth ?? 4}px solid ${props.$borderColor ?? 'white'}`};\n`\n\nexport const GuideText = styled.span`\n align-content: center;\n margin-top: 12px;\n margin-bottom: 12px;\n`\n\nexport const GuideImage = styled.img<{\n $width?: number\n $height?: number\n}>`\n display: block;\n ${(props) =>\n props.$width\n ? `width: ${props.$width}px; max-width: ${props.$width}px;`\n : `max-width: none;`}\n ${(props) =>\n props.$height\n ? `height: ${props.$height}px; max-height: ${props.$height}px;`\n : `max-width: none;`}\n`\n\nexport type DocumentCaptureGuideOverlayClassNames = {\n container?: string\n inner?: string\n dimmingRegion?: string\n dimmingRegionTop?: string\n dimmingRegionLeft?: string\n dimmingRegionRight?: string\n dimmingRegionBottom?: string\n centerRow?: string\n centerRegion?: string\n centerRegionInner?: string\n image?: string\n guideText?: string\n}\n\nexport type DocumentCaptureGuideOverlayProps = {\n classNames?: DocumentCaptureGuideOverlayClassNames\n width?: number\n height?: number\n padding?: number\n borderWidth?: number\n borderColor?: string\n isMirrored?: boolean\n instruction?: string\n portraitGuidesImageUrl?: string\n landscapeGuidesImageUrl?: string\n onClick?: () => void\n}\n\nexport const DocumentCaptureGuideOverlay = ({\n classNames = {},\n width = 0,\n height = 0,\n padding = isMobile() ? 0 : 50,\n borderWidth,\n borderColor,\n isMirrored = false,\n instruction = '',\n portraitGuidesImageUrl,\n landscapeGuidesImageUrl,\n onClick,\n}: DocumentCaptureGuideOverlayProps): ReactElement => {\n const {\n orientation,\n wrapperRef,\n wrapperWidth,\n wrapperHeight,\n imageAspectRatio,\n wrapperAspectRatio,\n onImageLoaded,\n setDimensions,\n } = useContext(GuideOrientationContext)\n\n const theme = useTheme()\n if (borderWidth === undefined)\n borderWidth = theme.idCapture?.guideBox?.borderWidth ?? 4\n\n if (width == 0) width = wrapperWidth\n if (height == 0) height = wrapperHeight\n\n useEffect(() => {\n setDimensions({ width, height })\n }, [height, setDimensions, width])\n\n const paddingAndBorderPx = padding * 2 + borderWidth * 2\n const imgSrc =\n orientation === 'portrait'\n ? portraitGuidesImageUrl\n : landscapeGuidesImageUrl\n\n let imageWidth: number | undefined = undefined,\n imageHeight: number | undefined = undefined\n if (imageAspectRatio >= wrapperAspectRatio) {\n imageWidth = wrapperWidth - paddingAndBorderPx\n } else {\n imageHeight = wrapperHeight - paddingAndBorderPx\n }\n\n return (\n <StyledPageContainer\n ref={wrapperRef}\n onClick={onClick}\n className={classNames.container}\n >\n <GuidesContainer className={classNames.inner}>\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Top')}\n >\n {instruction !== '' && (\n <GuideText className={classNames.guideText}>\n {instruction}\n </GuideText>\n )}\n </GuideRegion>\n\n <GuideCenterRow className={classNames.centerRow}>\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Left')}\n />\n\n <GuideCenterRegion\n $isMirrored={isMirrored}\n className={classNames.centerRegion}\n >\n <GuideCenterBorder\n $borderWidth={borderWidth}\n $borderColor={borderColor}\n className={classNames.centerRegionInner}\n >\n <GuideImage\n src={imgSrc}\n alt=\"\"\n onLoad={onImageLoaded}\n className={classNames.image}\n $width={imageWidth}\n $height={imageHeight}\n />\n </GuideCenterBorder>\n </GuideCenterRegion>\n\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Right')}\n />\n </GuideCenterRow>\n\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Bottom')}\n >\n {instruction !== '' && (\n <GuideText style={{ opacity: 0 }}>{instruction}</GuideText>\n )}\n </GuideRegion>\n </GuidesContainer>\n </StyledPageContainer>\n )\n}\n\nconst StyledPageContainer = styled(PageContainer)`\n z-index: 1000;\n`\n\nconst regionClsx = (\n classNames: DocumentCaptureGuideOverlayClassNames,\n which: 'Top' | 'Left' | 'Right' | 'Bottom'\n): string =>\n [classNames.dimmingRegion, classNames[`dimmingRegion${which}`]]\n .filter((v) => v)\n .join(' ')\n","export async function getNativeBarcodeReaderResult(image) {\n if (!('BarcodeDetector' in window)) return []\n const barcodeDetector = new BarcodeDetector({ formats: ['pdf417'] })\n console.log('this is a real native result!')\n return await barcodeDetector.detect(image)\n}\n","export async function getZxingBarcodeReaderResult(image, rotate = false) {\n let canvas, ctx, imageWidth, imageHeight\n\n const actualImage = await new Promise((resolve) => {\n imageWidth = image.naturalWidth\n imageHeight = image.naturalHeight\n canvas = document.createElement('canvas')\n ctx = canvas.getContext('2d')\n if (!ctx) return []\n\n if (rotate) {\n console.log('rotating!!')\n canvas.width = imageHeight\n canvas.height = imageWidth\n ctx.setTransform(0, 1, -1, 0, canvas.width, 0)\n ctx.drawImage(image, 0, 0, imageWidth, imageHeight)\n const newImage = new Image()\n newImage.width = canvas.width\n newImage.height = canvas.height\n newImage.onload = () => {\n resolve(newImage)\n }\n\n canvas.toBlob((blob) => {\n if (blob) newImage.src = URL.createObjectURL(blob)\n })\n } else {\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height)\n resolve(image)\n }\n })\n\n const source = new ZXing.BitmapLuminanceSource(ctx, actualImage)\n const binarizer = new ZXing.Common.HybridBinarizer(source)\n const bitmap = new ZXing.BinaryBitmap(binarizer)\n const results = ZXing.PDF417.PDF417Reader.decode(bitmap, null, false)\n\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n canvas.remove()\n\n return results\n}\n","import { getNativeBarcodeReaderResult, PDF417DetectionResult } from './Native'\nimport { getZxingBarcodeReaderResult } from './ZXing'\n\nexport function supportsNativeBarcodeScanning(): boolean {\n return 'BarcodeDetector' in window\n}\n\nexport function scanBarcode(\n blob: Blob,\n bbox?: number[]\n): Promise<PDF417DetectionResult | null> {\n return new Promise((resolve) => {\n const image = new Image()\n image.onload = async () => {\n if (supportsNativeBarcodeScanning()) {\n const result = await getNativeBarcodeReaderResult(image)\n console.log('native result', result, `${image.width}x${image.height}`)\n if (result.length > 0) {\n resolve({ ...result[0], Source: 'native' })\n } else {\n resolve(null)\n }\n } else {\n const shouldRotate = (bbox?.[2] ?? 0) < (bbox?.[3] ?? 0)\n const result = await getZxingBarcodeReaderResult(image, shouldRotate)\n console.log('zxing result', result)\n if (result.length > 0) {\n resolve({ ...result[0], Source: 'zxing' })\n } else {\n resolve(null)\n }\n }\n }\n image.src = URL.createObjectURL(blob)\n })\n}\n","export function getBlobDimensions(blob: Blob): Promise<[number, number]> {\n return new Promise((resolve) => {\n const image = new Image()\n image.onload = () => {\n resolve([image.naturalWidth, image.naturalHeight])\n }\n image.src = URL.createObjectURL(blob)\n })\n}\n","export function iOS(): boolean {\n return (\n [\n 'iPad Simulator',\n 'iPhone Simulator',\n 'iPod Simulator',\n 'iPad',\n 'iPhone',\n 'iPod',\n ].includes(navigator.platform) ||\n // iPad on iOS 13 detection\n (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n )\n}\n\nexport function wideAngleIsBetter(): boolean {\n if (!iOS()) return false\n\n const smallerSide = smallerSideIos()\n const realWidth = window.screen.width * window.devicePixelRatio\n const realHeight = window.screen.height * window.devicePixelRatio\n\n return (\n (realWidth == 1179 && realHeight == 2556) ||\n (realWidth == 1290 &&\n realHeight == 2796 &&\n (smallerSide == 393 || smallerSide == 430))\n )\n}\n\nfunction smallerSideIos() {\n return window.screen.width < window.screen.height\n ? window.screen.width\n : window.screen.height\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport { wideAngleIsBetter } from '../utils/deviceDetection'\nimport { getPlatform } from '../utils/platform'\n\nexport type Camera = {\n stream: MediaStream\n isRearFacing: boolean\n release: () => void\n label: string\n width: number\n height: number\n}\n\nexport type CameraResolution = 'LOW' | 'MID' | 'MAX'\n\nlet choosingCamera = false\n\nexport async function selectAndOpenCamera(\n resolution: CameraResolution = 'MID'\n): Promise<Camera> {\n if (choosingCamera) {\n await new Promise((resolve) => {\n const interval = setInterval(() => {\n if (!choosingCamera) {\n clearInterval(interval)\n resolve(null)\n }\n }, 10)\n })\n }\n\n choosingCamera = true\n\n const video: MediaTrackConstraints = {\n facingMode: { ideal: 'environment' },\n focusMode: 'continuous',\n }\n if (resolution === 'LOW') {\n video.width = { ideal: 640 }\n } else if (resolution === 'MID') {\n video.width = { ideal: 1920 }\n }\n\n const stream = await navigator.mediaDevices.getUserMedia({ video })\n let mediaTrackSettings = stream.getVideoTracks()[0].getSettings()\n const camera: Camera = {\n // you only get the labels for each camera if you call getUserMedia first.\n stream,\n isRearFacing: false,\n release: () => {\n camera.stream.getTracks().forEach((track) => track.stop())\n },\n width: mediaTrackSettings.width ?? 0,\n height: mediaTrackSettings.height ?? 0,\n label: '',\n }\n\n let chosenLabel = ''\n let bestResDevice: [string, number, number] = ['', 0, 0]\n const videoDevices = (await navigator.mediaDevices.enumerateDevices()).filter(\n (deviceInfo) => deviceInfo.kind === 'videoinput'\n )\n\n await Promise.all(\n videoDevices.map(async (deviceInfo) => {\n console.log('checking out', deviceInfo.label, resolution)\n const { width: maxWidth, height: maxHeight } =\n await getVideoDeviceMaxDimensions(deviceInfo)\n console.log('device', deviceInfo.label, 'max dimensions', {\n maxWidth,\n maxHeight,\n })\n if (maxWidth > bestResDevice[1]) {\n bestResDevice = [deviceInfo.deviceId, maxWidth, maxHeight]\n }\n if (deviceInfo.label) {\n const label = deviceInfo.label.toLocaleLowerCase().split(' ').join('')\n if (\n labelMatches(label, rearLabels) &&\n !labelMatches(label, backUltraWideLabels)\n ) {\n camera.label = label\n camera.isRearFacing = true\n video.deviceId = deviceInfo.deviceId\n chosenLabel = label\n if (resolution === 'MAX') {\n console.log('going for max!', `${maxWidth}x${maxHeight}`)\n video.width = { exact: maxWidth }\n video.height = { exact: maxHeight }\n }\n }\n }\n })\n )\n\n if (resolution === 'MAX' && chosenLabel === '') {\n chosenLabel = bestResDevice[0]\n video.deviceId = bestResDevice[0]\n video.width = { ideal: bestResDevice[1] }\n video.height = { ideal: bestResDevice[2] }\n }\n console.log('chose device', chosenLabel, resolution)\n\n camera.label = chosenLabel\n\n if (video.deviceId) {\n camera.release()\n camera.stream = await navigator.mediaDevices.getUserMedia({ video })\n mediaTrackSettings = camera.stream.getVideoTracks()[0].getSettings()\n camera.width = mediaTrackSettings.width ?? 0\n camera.height = mediaTrackSettings.height ?? 0\n }\n\n console.log('SETTINGS', camera.stream.getVideoTracks()[0].getSettings())\n\n choosingCamera = false\n return camera\n}\n\n// interface HasCapabilities {\n// getCapabilities?: () => {\n// width: { max: number }\n// height: { max: number }\n// }\n// }\nexport async function getVideoDeviceMaxDimensions(\n deviceInfo: MediaDeviceInfo\n): Promise<{\n width: number\n height: number\n}> {\n const best = await bestAvailableResolution(deviceInfo)\n if (!best) return { width: 1, height: 1 }\n return { width: best.width, height: best.height }\n // try {\n // const {\n // width: { max: width },\n // height: { max: height },\n // } = (deviceInfo as HasCapabilities).getCapabilities?.() ?? {\n // width: { max: 1920 },\n // height: { max: 1080 },\n // }\n //\n // return { width, height }\n // } catch (e) {\n // console.error(e)\n // return { width: 1, height: 1 }\n // }\n}\n\ntype Resolution = {\n label: string\n width: number\n height: number\n ratio: string\n}\nexport const quickScan: Resolution[] = [\n // {\n // label: '4K(UHD)',\n // width: 3840,\n // height: 2160,\n // ratio: '16:9',\n // },\n {\n label: '1080p(FHD)',\n width: 1920,\n height: 1080,\n ratio: '16:9',\n },\n {\n label: 'UXGA',\n width: 1600,\n height: 1200,\n ratio: '4:3',\n },\n {\n label: '720p(HD)',\n width: 1280,\n height: 720,\n ratio: '16:9',\n },\n {\n label: 'SVGA',\n width: 800,\n height: 600,\n ratio: '4:3',\n },\n {\n label: 'VGA',\n width: 640,\n height: 480,\n ratio: '4:3',\n },\n {\n label: '360p(nHD)',\n width: 640,\n height: 360,\n ratio: '16:9',\n },\n {\n label: 'CIF',\n width: 352,\n height: 288,\n ratio: '4:3',\n },\n {\n label: 'QVGA',\n width: 320,\n height: 240,\n ratio: '4:3',\n },\n {\n label: 'QCIF',\n width: 176,\n height: 144,\n ratio: '4:3',\n },\n {\n label: 'QQVGA',\n width: 160,\n height: 120,\n ratio: '4:3',\n },\n]\n\nasync function bestAvailableResolution(\n deviceInfo: MediaDeviceInfo\n): Promise<Resolution | null> {\n for (let i = 0; i !== quickScan.length; ++i) {\n if (await isResolutionAvailable(quickScan[i], deviceInfo)) {\n return quickScan[i]\n }\n }\n\n return null\n}\n\nfunction isResolutionAvailable(\n candidate: Resolution,\n deviceInfo: MediaDeviceInfo\n): Promise<boolean> {\n return new Promise((resolve) => {\n // const devices = []\n // const deviceInfos = await navigator.mediaDevices.enumerateDevices()\n //\n // for (let i = 0; i !== deviceInfos.length; ++i) {\n // const deviceInfo = deviceInfos[i]\n // if (deviceInfo.kind === 'videoinput') {\n // devices.push(deviceInfo)\n // }\n // }\n\n const video = document.createElement('video')\n const windowWithStream = window as unknown as { stream: MediaStream }\n const existingStream = windowWithStream.stream\n if (existingStream) {\n existingStream.getTracks().forEach((track) => {\n track.stop()\n })\n }\n\n const constraints = {\n audio: false,\n video: {\n deviceId: deviceInfo.deviceId,\n // ? { exact: deviceInfo.deviceId }\n // : undefined,\n width: { exact: candidate.width }, //new syntax\n height: { exact: candidate.height }, //new syntax\n },\n }\n\n setTimeout(\n () => {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(gotStream)\n .catch((error) => {\n console.log('getUserMedia error!', error, candidate)\n resolve(false)\n })\n },\n windowWithStream.stream ? 200 : 0\n ) //official examples had this at 200\n\n function gotStream(mediaStream: MediaStream) {\n //change the video dimensions\n console.log(\n 'Display size for ' +\n candidate.label +\n ': ' +\n candidate.width +\n 'x' +\n candidate.height\n )\n video.width = candidate.width\n video.height = candidate.height\n\n windowWithStream.stream = mediaStream // make globally available\n video.srcObject = mediaStream\n\n resolve(true)\n }\n })\n}\n\nexport type FacingMode = 'user' | 'environment' | 'left' | 'right'\n\nexport async function listAvailableCameras(\n facingMode?: FacingMode,\n requestMicAccess: boolean = false\n): Promise<MediaDeviceInfo[]> {\n // The first thing we need to do is call getUserMedia() so that the subsequent call to enumerateDevices() works.\n let cameraEnumerationStream: MediaStream | null =\n await navigator.mediaDevices.getUserMedia({\n video: { facingMode: { exact: facingMode } },\n audio: requestMicAccess,\n })\n\n // This lists all available cameras attached to the user's device.\n const videoDevices = (await navigator.mediaDevices.enumerateDevices()).filter(\n ({ kind }) => kind === 'videoinput'\n )\n\n // Release the access to the user's camera that we obtained for enumeration purposes.\n cameraEnumerationStream.getVideoTracks().forEach((track) => {\n track.enabled = false\n track.stop()\n })\n\n cameraEnumerationStream = null\n\n return videoDevices\n}\n\nconst frontLabels = [\n 'front',\n 'avant',\n 'anteriore',\n 'cameraaanvoorzijde',\n 'kamerapåframsidan',\n 'forsidekamera',\n 'kamerapåforsiden',\n 'aparatprzedni',\n 'etukamera',\n 'kameradepan',\n 'ÖnKamera',\n 'cameramặttrước',\n 'camerăfață',\n 'prednákamera',\n 'prednjakamera',\n 'előlapikamera',\n 'přednífotoaparát',\n 'μπροστινήκάμερα',\n 'переднякамера',\n 'передняякамера',\n 'преднакамера',\n 'алдыңғыкамера',\n 'מצלמה קדמית',\n 'الكاميرا الأمامية',\n 'फ़्रंटकैमरा',\n '前置相机',\n '前置鏡頭',\n '前面カメラ',\n '전면카메라',\n 'กล้องด้านหน้า',\n].map((s) => s.toLocaleLowerCase().split(' ').join(''))\nconst rearLabels = [\n 'back',\n 'rear',\n 'posterior',\n 'trasera',\n 'traseira',\n 'arrière',\n 'rückkamera',\n 'fotocamera(posteriore)',\n 'cameraaanachterzijde',\n 'kamerapåbaksidan',\n 'kamerapåbaksiden',\n 'bagsidekamera',\n 'aparattylny',\n 'takakamera',\n 'arkakamera',\n 'kamerabelakang',\n 'cameramặtsau',\n 'camerăspate',\n 'stražnjakamera',\n 'zadnákamera',\n 'hátoldalikamera',\n 'zadnífotoaparát',\n 'πίσωκάμερα',\n 'заднякамера',\n 'Задняякамера',\n 'заднакамера',\n 'артқыкамера',\n 'מצלמה אחורית',\n 'الكاميرا الخلفية',\n 'बैककैमरा',\n '后置相机',\n '後置鏡頭',\n '背面カメラ',\n '후면카메라',\n 'กล้องด้านหลัง',\n].map((s) => s.toLocaleLowerCase().split(' ').join(''))\nconst backUltraWideLabels = [\n 'backultrawidecamera',\n 'ultraampliaposterior',\n 'ultra-angulartraseira',\n 'ultragrandeangulartraseira',\n 'ultragrandangle',\n 'ultragranangular',\n 'ultra-weitwinkelkamera',\n 'ultra-grandangolo',\n 'ultrabredecameraaanachterzijde',\n 'ultravidvinkelkamerapåbaksidan',\n 'ultravidvinkelkameraetpåbagsiden',\n 'ultravidvinkelkamerabak',\n 'ultragenişkameraarkayüzü',\n 'ultralaajakulmainentakakamera',\n 'tylnyaparatultraszerokokątny',\n 'cameracựcrộngmặtsau',\n 'camerăcuobiectivultra‑superangularspate',\n 'ultraszéleslátószögűkamera',\n 'kameraultralebarbelakang',\n 'stražnjaultraširokakamera',\n 'zadníultraširokoúhlýfotoaparát',\n 'ultraširokouhlá',\n 'πίσωυπερευρείακάμερα',\n 'заднянадширококутнакамера',\n 'Задняясверхширокоугольнаякамера',\n 'Задна свръх широкоъгълна камера',\n 'артқыультракеңбұрыштыкамера',\n 'מצלמה אולטרה רחבה אחורית',\n 'كاميرا خلفية عريضة جدًا',\n 'बैकअल्ट्रावाइडकैमरा',\n '后置超广角相机',\n '後置超廣角鏡頭相機',\n '背面超広角カメラ',\n '후면울트라와이드카메라',\n 'กล้องด้านหลังอัลตร้าไวด์',\n].map((s) => s.toLocaleLowerCase().split(' ').join(''))\n\nconst labelMatches = (\n labelOrDevice: string | MediaDeviceInfo,\n labelSetOrLabel: string | string[]\n) => {\n const label =\n labelOrDevice instanceof MediaDeviceInfo\n ? getDeviceLabel(labelOrDevice)\n : labelOrDevice\n\n const labelSet =\n typeof labelSetOrLabel === 'string' ? [labelSetOrLabel] : labelSetOrLabel\n\n return labelSet.some((l) => label.includes(l))\n}\n\nconst getDeviceLabel = (deviceInfo: MediaDeviceInfo) =>\n deviceInfo.label.toLocaleLowerCase().split(' ').join('')\n\nlet currentCamera: Camera | undefined\n\nexport function obtainCameraAccess(\n stream: MediaStream,\n deviceLabel: string,\n video?: HTMLVideoElement | null\n): Camera {\n releaseCameraAccess()\n\n console.log('obtaining camera access...')\n let { width, height } = stream.getVideoTracks()[0].getSettings()\n const label = deviceLabel.toLocaleLowerCase().split(' ').join('')\n const isRearFacing = labelMatches(label, [\n ...rearLabels,\n ...backUltraWideLabels,\n 'iphone',\n ])\n const release = () => {\n stream.getTracks().forEach((track) => {\n track.enabled = false\n track.stop()\n })\n if (video) {\n video.pause()\n video.srcObject = null\n video.src = ''\n }\n }\n\n width ||= 0\n height ||= 0\n\n currentCamera = {\n label: deviceLabel,\n stream,\n width,\n height,\n isRearFacing,\n release,\n }\n if (video) video.srcObject = stream\n\n return currentCamera\n}\n\nexport function releaseCameraAccess() {\n if (!currentCamera) return\n console.log('releasing camera access...')\n currentCamera.release()\n currentCamera = undefined\n}\n\nexport const useHighestResCaptureDevice = (\n {\n preferFrontFacingCamera = false,\n preferContinuityCamera = true,\n requestMicrophoneAccess = false,\n }: {\n preferFrontFacingCamera: boolean\n preferContinuityCamera: boolean\n requestMicrophoneAccess: boolean\n } = {\n preferFrontFacingCamera: false,\n preferContinuityCamera: true,\n requestMicrophoneAccess: false,\n }\n) => {\n const videoRef = useRef<HTMLVideoElement | null>(null)\n const cameraRef = useRef<Camera | null>(null)\n const [cameraReady, setCameraReady] = useState(false)\n const [videoDevice, setVideoDevice] = useState<MediaDeviceInfo | null>(null)\n const [videoLoaded, setVideoLoaded] = useState(false)\n const [iphoneContinuityCameraAvailable, setIphoneContinuityCameraAvailable] =\n useState(false)\n const [iphoneContinuityCameraAllowed, setIphoneContinuityCameraAllowed] =\n useState(preferContinuityCamera)\n const [iphoneContinuityCameraDenied, setIphoneContinuityCameraDenied] =\n useState(false)\n const [cameraAccessDenied, setCameraAccessDenied] = useState(false)\n\n useEffect(() => {\n console.log(\n 'iphone continuity camera allowed changed',\n iphoneContinuityCameraAllowed\n )\n releaseCameraAccess()\n cameraRef.current = null\n setVideoLoaded(false)\n }, [iphoneContinuityCameraAllowed])\n\n const retryCameraAccess = useCallback(() => {\n setCameraAccessDenied(false)\n }, [])\n\n useEffect(() => {\n if (cameraAccessDenied) return\n\n setCameraReady(false)\n listAvailableCameras()\n .then((availableCameras) => {\n let selectedCamera: MediaDeviceInfo | undefined\n\n const platform = getPlatform()\n if (\n !iphoneContinuityCameraDenied &&\n (!platform || platform.os.family === 'OS X')\n ) {\n const iphoneContinuityCamera = availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, 'iphone')\n )\n setIphoneContinuityCameraAvailable(!!iphoneContinuityCamera)\n if (iphoneContinuityCamera && iphoneContinuityCameraAllowed) {\n selectedCamera = iphoneContinuityCamera\n }\n } else if (platform?.os.family === 'Android') {\n availableCameras.reverse()\n }\n\n if (preferFrontFacingCamera) {\n selectedCamera = availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, frontLabels)\n )\n }\n\n if (wideAngleIsBetter()) {\n selectedCamera ||= availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, backUltraWideLabels)\n )\n } else {\n selectedCamera ||= availableCameras.find(\n (deviceInfo) =>\n labelMatches(deviceInfo, rearLabels) &&\n !labelMatches(deviceInfo, backUltraWideLabels)\n )\n }\n\n selectedCamera ||= availableCameras.find((deviceInfo) =>\n labelMatches(deviceInfo, rearLabels)\n )\n\n // on iOS, the front facing camera always is at the first position in the list, so we skip it if all else fails.\n if (\n !preferFrontFacingCamera &&\n platform?.os.family === 'iOS' &&\n availableCameras.length > 0\n ) {\n selectedCamera ||= availableCameras[1]\n }\n\n selectedCamera ||= availableCameras[0]\n\n setVideoDevice(selectedCamera)\n })\n .catch((e) => {\n if ((e as { name: string }).name === 'NotAllowedError') {\n console.error('camera access has been blocked by the user', e)\n setCameraAccessDenied(true)\n } else {\n console.error('camera access encountered some other error', e)\n throw e\n }\n })\n }, [\n cameraAccessDenied,\n iphoneContinuityCameraAllowed,\n iphoneContinuityCameraDenied,\n preferFrontFacingCamera,\n ])\n\n useEffect(() => {\n if (!videoDevice) return\n\n const cleanup = () => {\n releaseCameraAccess()\n cameraRef.current = null\n setVideoLoaded(false)\n }\n\n if (!navigator.mediaDevices?.getUserMedia) return cleanup\n ;(async () => {\n let stream: MediaStream | null = null\n try {\n stream = await navigator.mediaDevices.getUserMedia({\n audio: requestMicrophoneAccess,\n video: {\n deviceId: { exact: videoDevice.deviceId },\n width: { ideal: 1920 },\n aspectRatio: 1.777777778,\n },\n })\n } catch (e) {\n if ((e as { name: string }).name === 'NotAllowedError') {\n if (iphoneContinuityCameraAllowed) {\n setIphoneContinuityCameraAvailable(false)\n setIphoneContinuityCameraDenied(true)\n } else {\n setCameraAccessDenied(true)\n }\n return\n }\n }\n\n if (!stream) {\n try {\n stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: true,\n })\n\n console.log('opened stream with no width and height constraints')\n } catch (e) {\n console.log('cannot open stream at all')\n }\n }\n\n if (!stream) {\n throw new Error('failed to open camera')\n }\n\n const handleStreamEnded = () => {\n if (iphoneContinuityCameraAvailable && iphoneContinuityCameraAllowed) {\n console.log('someone unplugged the continuity camera')\n releaseCameraAccess()\n cameraRef.current = null\n setIphoneContinuityCameraAvailable(false)\n setIphoneContinuityCameraDenied(true)\n setVideoDevice(null)\n } else {\n console.log('someone unplugged the webcam')\n releaseCameraAccess()\n cameraRef.current = null\n setVideoLoaded(false)\n setCameraAccessDenied(true)\n }\n }\n\n videoRef.current?.addEventListener('ended', handleStreamEnded)\n stream.getVideoTracks().forEach((track) => {\n track.onended = handleStreamEnded\n })\n\n cameraRef.current = obtainCameraAccess(\n stream,\n videoDevice.label,\n videoRef.current\n )\n })()\n\n return cleanup\n }, [\n iphoneContinuityCameraAllowed,\n iphoneContinuityCameraAvailable,\n requestMicrophoneAccess,\n videoDevice,\n ])\n\n useEffect(() => {\n setCameraReady(false)\n\n if (videoDevice && videoLoaded) {\n setCameraReady(true)\n }\n }, [videoLoaded, videoDevice])\n\n const takePhoto = useCallback(async (): Promise<Blob | null> => {\n const canvas = document.createElement('canvas')\n const ctx = canvas.getContext('2d')\n if (!ctx || !cameraRef.current || !videoRef.current) return null\n\n canvas.width = videoRef.current?.videoWidth\n canvas.height = videoRef.current?.videoHeight\n ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height)\n const photoURL = canvas.toDataURL('image/jpeg', 0.98)\n const data = await fetch(photoURL)\n return await data.blob()\n }, [])\n\n return {\n videoRef,\n videoDevice,\n videoLoaded,\n setVideoLoaded,\n cameraRef,\n cameraReady,\n cameraAccessDenied,\n retryCameraAccess,\n releaseCameraAccess,\n iphoneContinuityCameraAvailable,\n iphoneContinuityCameraAllowed,\n setIphoneContinuityCameraAllowed,\n takePhoto,\n }\n}\n\nexport const useDualResCaptureDevice = () => {\n const {\n videoRef: maxVideoRef,\n videoDevice,\n videoLoaded: maxVideoLoaded,\n setVideoLoaded: setMaxVideoLoaded,\n cameraRef: maxCameraRef,\n cameraReady: maxCameraReady,\n takePhoto: takeFullResPhoto,\n } = useHighestResCaptureDevice()\n\n const minVideoRef = useRef<HTMLVideoElement | null>(null)\n const [minCamera, setMinCamera] = useState<Camera | null>(null)\n const [minVideoLoaded, setMinVideoLoaded] = useState(false)\n\n useEffect(() => {\n if (!videoDevice || !maxCameraRef.current) return\n\n let cam: Camera\n const cleanup = () => {\n cam?.release()\n setMinCamera(null)\n setMinVideoLoaded(false)\n }\n\n if (!minVideoRef.current) return cleanup\n if (!navigator.mediaDevices?.getUserMedia) return cleanup\n ;(async () => {\n if (!maxCameraRef.current) return\n\n let idealWidth = 448\n let idealHeight = 448\n\n if (maxCameraRef.current.width < maxCameraRef.current.height) {\n idealHeight =\n 448 * (maxCameraRef.current.height / maxCameraRef.current.width)\n } else {\n idealWidth =\n 448 * (maxCameraRef.current.width / maxCameraRef.current.height)\n }\n\n console.log('min dimensions', idealWidth, idealHeight)\n\n const constraints = {\n audio: false,\n video: {\n deviceId: { exact: videoDevice.deviceId },\n width: { ideal: idealWidth },\n height: { ideal: idealHeight },\n },\n }\n\n const stream = await navigator.mediaDevices.getUserMedia(constraints)\n cam = obtainCameraAccess(stream, videoDevice.label, minVideoRef.current)\n setMinCamera(cam)\n })()\n\n return cleanup\n }, [maxCameraRef, videoDevice])\n\n return {\n minVideoRef,\n maxVideoRef,\n minCamera,\n maxCamera: maxCameraRef.current,\n maxCameraReady,\n minVideoLoaded,\n maxVideoLoaded,\n setMinVideoLoaded,\n setMaxVideoLoaded,\n takeFullResPhoto,\n }\n}\n","import React, {\n createContext,\n MutableRefObject,\n ReactElement,\n useEffect,\n} from 'react'\nimport { Camera, useHighestResCaptureDevice } from '../../lib/camera/Camera'\n\nexport type CameraState = {\n videoRef: MutableRefObject<HTMLVideoElement | null>\n videoLoaded: boolean\n setVideoLoaded: (value: boolean) => void\n cameraRef: MutableRefObject<Camera | null>\n cameraReady: boolean\n cameraAccessDenied: boolean\n retryCameraAccess: () => void\n releaseCameraAccess: () => void\n iphoneContinuityCameraAvailable: boolean\n iphoneContinuityCameraAllowed: boolean\n setIphoneContinuityCameraAllowed: (value: boolean) => void\n takePhoto: () => Promise<Blob | null>\n}\n\nexport const CameraStateContext = createContext<CameraState>({\n videoRef: { current: null },\n videoLoaded: false,\n cameraRef: { current: null },\n cameraReady: false,\n cameraAccessDenied: false,\n retryCameraAccess: () => null,\n releaseCameraAccess: () => null,\n iphoneContinuityCameraAvailable: false,\n iphoneContinuityCameraAllowed: true,\n setIphoneContinuityCameraAllowed: () => null,\n takePhoto: () => Promise.resolve(null),\n setVideoLoaded: () => null,\n})\n\nexport type CameraProviderProps = {\n children: ReactElement\n preferFrontFacingCamera?: boolean\n preferContinuityCamera?: boolean\n requestMicrophoneAccess?: boolean\n}\n\nexport const CameraProvider = ({\n children,\n preferFrontFacingCamera = false,\n preferContinuityCamera = true,\n requestMicrophoneAccess = false,\n}: CameraProviderProps): ReactElement => {\n const {\n videoRef,\n videoLoaded,\n setVideoLoaded,\n cameraRef,\n cameraReady,\n cameraAccessDenied,\n retryCameraAccess,\n releaseCameraAccess,\n iphoneContinuityCameraAvailable,\n iphoneContinuityCameraAllowed,\n setIphoneContinuityCameraAllowed,\n takePhoto,\n } = useHighestResCaptureDevice({\n preferFrontFacingCamera,\n preferContinuityCamera,\n requestMicrophoneAccess,\n })\n\n useEffect(() => {\n return () => {\n releaseCameraAccess()\n }\n }, [releaseCameraAccess])\n\n const value = {\n videoRef,\n videoLoaded,\n setVideoLoaded,\n cameraRef,\n cameraReady,\n cameraAccessDenied,\n releaseCameraAccess,\n retryCameraAccess,\n iphoneContinuityCameraAvailable,\n iphoneContinuityCameraAllowed,\n setIphoneContinuityCameraAllowed,\n takePhoto,\n }\n\n return (\n <CameraStateContext.Provider value={value}>\n {children}\n </CameraStateContext.Provider>\n )\n}\n","import * as tf from '@tensorflow/tfjs'\n\nexport let focusModel: tf.LayersModel | null\n\nexport async function loadFocusModel(url: string): Promise<tf.LayersModel> {\n if (focusModel) return focusModel\n\n focusModel = await tf.loadLayersModel(url)\n await tf.ready()\n\n // warm the model by predicting on an empty image...\n const zeroes = tf.zeros([448, 448, 3])\n const tfInt32 = tf.cast(zeroes, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(await tfInt32.data()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n const warmupResult = (await focusModel.predict(tf4d)) as tf.Tensor<tf.Rank>\n await warmupResult.data()\n tf.dispose(warmupResult)\n\n tfInt32.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(zeroes)\n\n return focusModel\n}\n\nexport function unloadFocusModel(): void {\n focusModel = null\n}\n\n// The model outputs a binary classification: [blurry, focused]\n// the outputs are just the inverse of one another e.g. b=1-f or f=1-b\ntype BlurScore = number\ntype FocusScore = number\nexport type FocusPrediction = [BlurScore, FocusScore]\n\nexport async function makeFocusPrediction(\n model: tf.LayersModel,\n imageData: ImageBitmap | ImageData\n): Promise<[FocusPrediction, () => void]> {\n const tfImg = tf.browser.fromPixels(imageData)\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n const tfInt32 = tf.cast(tfResize, 'int32')\n const tf4d_ = tf.tensor4d(Array.from(await tfInt32.data()), [1, 448, 448, 3])\n const tf4d = tf.cast(tf4d_, 'int32')\n const predictions = (await model.predict(tf4d)) as tf.Tensor<tf.Rank>\n const [focusPrediction] = (await predictions.array()) as FocusPrediction[]\n const cleanup = () => {\n tfInt32.dispose()\n tfImg.dispose()\n tfResize.dispose()\n tf4d.dispose()\n tf4d_.dispose()\n tf.dispose(predictions)\n }\n\n return [focusPrediction, cleanup]\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Backend, DataToGPUOptions, GPUData, Tensor} from '../tensor';\nimport {DataId} from '../tensor_info';\nimport {BackendValues, DataType, WebGLData, WebGPUData} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n kernelMs: number|{error: string};\n getExtraProfileInfo?(): string; // a field for additional timing information\n // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n read(dataId: DataId): Promise<BackendValues>;\n readSync(dataId: DataId): BackendValues;\n disposeData(dataId: DataId, force?: boolean): boolean;\n write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void;\n memory(): {unreliable: boolean;}; // Backend-specific information.\n /** Returns number of data ids currently in the storage. */\n numDataIds(): number;\n refCount(dataId: DataId): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage<T> {\n private data = new WeakMap<DataId, T>();\n private dataIdsCount = 0;\n\n constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n get(dataId: DataId) {\n if (!this.data.has(dataId)) {\n this.dataMover.moveData(this.backend, dataId);\n }\n return this.data.get(dataId);\n }\n\n set(dataId: DataId, value: T): void {\n this.dataIdsCount++;\n this.data.set(dataId, value);\n }\n\n has(dataId: DataId): boolean {\n return this.data.has(dataId);\n }\n\n delete(dataId: DataId): boolean {\n this.dataIdsCount--;\n return this.data.delete(dataId);\n }\n\n numDataIds(): number {\n return this.dataIdsCount;\n }\n}\n\nexport interface DataMover {\n /**\n * To be called by backends whenever they see a dataId that they don't own.\n * Upon calling this method, the mover will fetch the tensor from another\n * backend and register it with the current active backend.\n */\n moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n // check if backend timer is available\n timerAvailable(): boolean;\n time(f: () => void): Promise<BackendTimingInfo>;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n refCount(dataId: DataId): number {\n return notYetImplemented('refCount');\n }\n incRef(dataId: DataId): void {\n return notYetImplemented('incRef');\n }\n timerAvailable(): boolean {\n return true;\n }\n time(f: () => void): Promise<BackendTimingInfo> {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise<BackendValues> {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n readToGPU(dataId: object, options?: DataToGPUOptions): GPUData {\n return notYetImplemented('readToGPU');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object, force?: boolean): boolean {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n return notYetImplemented('move');\n }\n\n createTensorFromGPUData(\n values: WebGLData|WebGPUData, shape: number[], dtype: DataType): Tensor {\n return notYetImplemented('createTensorFromGPUData');\n }\n\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, TensorLike, TypedArray, WebGLData, WebGPUData} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n swap(array, counter, index);\n }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n * as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n // tslint:disable-next-line:no-any\n array: any[]|Uint32Array|Int32Array|Float32Array,\n // tslint:disable-next-line:no-any\n array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n if (array.length !== array2.length) {\n throw new Error(\n `Array sizes must match to be shuffled together ` +\n `First array length was ${array.length}` +\n `Second array length was ${array2.length}`);\n }\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element of each array with it\n swap(array, counter, index);\n swap(array2, counter, index);\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap<T>(\n object: {[index: number]: T}, left: number, right: number) {\n const temp = object[left];\n object[left] = object[right];\n object[right] = temp;\n}\n\nexport function sum(arr: number[]): number {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n const r = Math.random();\n return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n const diff = Number(a[i]) - Number(b[i]);\n result += diff * diff;\n }\n return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n * error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n if (!expr) {\n throw new Error(typeof msg === 'string' ? msg : msg());\n }\n}\n\nexport function assertShapesMatch(\n shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n assert(\n arraysEqual(shapeA, shapeB),\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n assert(\n a != null,\n () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n if (shape.length === 0) {\n // Scalar.\n return 1;\n }\n let size = shape[0];\n for (let i = 1; i < shape.length; i++) {\n size *= shape[i];\n }\n return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n return shape.length === 0;\n}\n\nexport function arraysEqualWithNull(n1: number[], n2: number[]) {\n if (n1 === n2) {\n return true;\n }\n\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n if (n1 === n2) {\n return true;\n }\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function isInt(a: number): boolean {\n return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n // tslint:disable-next-line:no-any\n if ((Math as any).tanh != null) {\n // tslint:disable-next-line:no-any\n return (Math as any).tanh(x);\n }\n if (x === Infinity) {\n return 1;\n } else if (x === -Infinity) {\n return -1;\n } else {\n const e2x = Math.exp(2 * x);\n return (e2x - 1) / (e2x + 1);\n }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n const width = Math.ceil(Math.sqrt(size));\n return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indices to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indices to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number,\n scheduleFn?: (functionRef: Function, delay: number) =>\n void): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let tryCount = 0;\n\n const tryFn = () => {\n if (checkFn()) {\n resolve();\n return;\n }\n\n tryCount++;\n\n const nextBackoff = delayFn(tryCount);\n\n if (maxCounter != null && tryCount >= maxCounter) {\n reject();\n return;\n }\n\n if (scheduleFn != null) {\n scheduleFn(tryFn, nextBackoff);\n } else {\n // google3 does not allow assigning another variable to setTimeout.\n // Don't refactor this so scheduleFn has a default value of setTimeout.\n setTimeout(tryFn, nextBackoff);\n }\n };\n\n tryFn();\n });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n shape: number[], size: number): number[] {\n let shapeProd = 1;\n let implicitIdx = -1;\n\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] >= 0) {\n shapeProd *= shape[i];\n } else if (shape[i] === -1) {\n if (implicitIdx !== -1) {\n throw Error(\n `Shapes can only have 1 implicit size. ` +\n `Found -1 at dim ${implicitIdx} and dim ${i}`);\n }\n implicitIdx = i;\n } else if (shape[i] < 0) {\n throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n }\n }\n\n if (implicitIdx === -1) {\n if (size > 0 && size !== shapeProd) {\n throw Error(`Size(${size}) must match the product of shape ${shape}`);\n }\n return shape;\n }\n\n if (shapeProd === 0) {\n throw Error(\n `Cannot infer the missing size in [${shape}] when ` +\n `there are 0 elements`);\n }\n if (size % shapeProd !== 0) {\n throw Error(\n `The implicit shape can't be a fractional number. ` +\n `Got ${size} / ${shapeProd}`);\n }\n\n const newShape = shape.slice();\n newShape[implicitIdx] = size / shapeProd;\n return newShape;\n}\n\nexport function parseAxisParam(\n axis: number|number[], shape: number[]): number[] {\n const rank = shape.length;\n\n // Normalize input\n axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n // Check for valid range\n assert(\n axis.every(ax => ax >= -rank && ax < rank),\n () =>\n `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n `got axis ${axis}`);\n\n // Check for only integers\n assert(\n axis.every(ax => isInt(ax)),\n () => `All values in axis param must be integers but ` +\n `got axis ${axis}`);\n\n // Handle negative axis.\n return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n {newShape: number[], keptDims: number[]} {\n const newShape: number[] = [];\n const keptDims: number[] = [];\n const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n const axes = (axis == null || isEmptyArray) ?\n null :\n parseAxisParam(axis, shape).sort();\n let j = 0;\n for (let i = 0; i < shape.length; ++i) {\n if (axes != null) {\n if (axes[j] === i && shape[i] !== 1) {\n throw new Error(\n `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n }\n if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n if (axes[j] <= i) {\n j++;\n }\n }\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n }\n return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType<D extends NumericDataType>(\n dtype: D, size: number): DataTypeMap[D] {\n return getArrayFromDType<D>(dtype, size);\n}\n\nexport function getArrayFromDType<D extends DataType>(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else if (dtype === 'string') {\n values = new Array<string>(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors<D extends DataType>(\n vals: DataTypeMap[D]|number[], dtype: D): void {\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n }\n }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n if (newType === 'complex64') {\n return false;\n }\n if (newType === 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'bool' && oldType === 'bool') {\n return false;\n }\n return true;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS\n * is not possible since it depends on the encoding of the html page that\n * serves the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike|WebGLData|WebGPUData): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (\n values instanceof Int32Array || values instanceof Uint8Array ||\n values instanceof Uint8ClampedArray) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\nfunction createNestedArray(\n offset: number, shape: number[], a: TypedArray, isComplex = false) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0] * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n shape: number[], a: TypedArray, isComplex = false) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}${\n isComplex ? ' for a complex tensor' : ''}.`);\n }\n\n return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function convertBackendValuesAndArrayBuffer(\n data: BackendValues|ArrayBuffer, dtype: DataType) {\n // If is type Uint8Array[], return it directly.\n if (Array.isArray(data)) {\n return data;\n }\n if (dtype === 'float32') {\n return data instanceof Float32Array ? data : new Float32Array(data);\n } else if (dtype === 'int32') {\n return data instanceof Int32Array ? data : new Int32Array(data);\n } else if (dtype === 'bool' || dtype === 'string') {\n return Uint8Array.from(new Int32Array(data));\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\nexport function makeOnesTypedArray<D extends DataType>(\n size: number, dtype: D): DataTypeMap[D] {\n const array = makeZerosTypedArray(size, dtype);\n for (let i = 0; i < array.length; i++) {\n array[i] = 1;\n }\n return array;\n}\n\nexport function makeZerosTypedArray<D extends DataType>(\n size: number, dtype: D): DataTypeMap[D] {\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(size) as DataTypeMap[D];\n } else if (dtype === 'int32') {\n return new Int32Array(size) as DataTypeMap[D];\n } else if (dtype === 'bool') {\n return new Uint8Array(size) as DataTypeMap[D];\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray<D extends DataType>(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a\n * tensor/multidimentional array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise<unknown> {\n // We chose to not use 'obj instanceOf Promise' for two reasons:\n // 1. It only reliably works for es6 Promise, not other Promise\n // implementations.\n // 2. It doesn't work with framework that uses zone.js. zone.js monkey\n // patch the async calls, so it is possible the obj (patched) is\n // comparing to a pre-patched Promise.\n return object && object.then && typeof object.then === 'function';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean|string;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise<FlagValue>);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // Jasmine spies on this in 'environment_test.ts'\n getQueryParams = getQueryParams;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platformName}.`);\n }\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because\n // the environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n }\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise<FlagValue> {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (isPromise(flagValue)) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue;\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n getString(flagName: string): string {\n return this.get(flagName) as string;\n }\n\n getFlags(): Flags {\n return this.flags;\n }\n // For backwards compatibility.\n get features(): Flags {\n return this.flags;\n }\n\n set(flagName: string, value: FlagValue): void {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot set flag ${flagName} as it has not been registered.`);\n }\n this.flags[flagName] = value;\n if (this.flagRegistry[flagName].setHook != null) {\n this.flagRegistry[flagName].setHook(value);\n }\n }\n\n private evaluateFlag(flagName: string): FlagValue|Promise<FlagValue> {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = this.getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n const lowerCaseValue = value.toLowerCase();\n if (lowerCaseValue === 'true' || lowerCaseValue === 'false') {\n return lowerCaseValue === 'true';\n } else if (`${+ lowerCaseValue}` === lowerCaseValue) {\n return +lowerCaseValue;\n } else {\n return value;\n }\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map<string, any>};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map<string, any>} {\n if (globalNameSpace == null) {\n // tslint:disable-next-line:no-any\n let ns: any;\n if (typeof (window) !== 'undefined') {\n ns = window;\n } else if (typeof (global) !== 'undefined') {\n ns = global;\n } else if (typeof (process) !== 'undefined') {\n ns = process;\n } else if (typeof (self) !== 'undefined') {\n ns = self;\n } else {\n throw new Error('Could not find a global object');\n }\n globalNameSpace = ns;\n }\n return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map<string, any> {\n const ns = getGlobalNamespace();\n if (ns._tfGlobals == null) {\n ns._tfGlobals = new Map();\n }\n return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n * the first time it is fetched.\n */\nexport function getGlobal<T>(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {TensorInfo} from './tensor_info';\nimport {DataType, DrawOptions, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMinAttrs {\n axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolGrad = 'AvgPoolGrad';\nexport type AvgPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPoolGradAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n dataFormat: 'NDHWC'|'NCDHW';\n}\n\nexport const AvgPool3DGrad = 'AvgPool3DGrad';\nexport type AvgPool3DGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPool3DGradAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface BincountAttrs {\n size: number;\n}\n\nexport const BitwiseAnd = 'BitwiseAnd';\nexport type BitwiseAndInputs = BinaryInputs;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick<NamedTensorInfoMap, 's0'|'s1'>;\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n clipValueMin: number;\n clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick<NamedTensorInfoMap, 'real'|'imag'>;\n\nexport const ComplexAbs = 'ComplexAbs';\nexport type ComplexAbsInputs = UnaryInputs;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface Conv2DBackpropFilterAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n filterShape: [number, number, number, number];\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv2DBackpropInputAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv3DAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterV2Inputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\n\nexport interface Conv3DBackpropFilterV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n filterShape: [number, number, number, number, number];\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputV2Inputs =\n Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv3DBackpropInputV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumprod = 'Cumprod';\nexport type CumprodInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumprodAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick<NamedTensorInfoMap, 'image'|'boxes'|'boxInd'>;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface DenseBincountAttrs {\n size: number;\n binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface DepthwiseConv2dNativeAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n 'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface DepthwiseConv2dNativeBackpropFilterAttrs {\n strides: [number, number]|number;\n dilations: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n filterShape: [number, number, number, number];\n}\n\nexport const DepthwiseConv2dNativeBackpropInput =\n 'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface DepthwiseConv2dNativeBackpropInputAttrs {\n strides: [number, number]|number;\n dilations: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Dilation2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Draw = 'Draw';\nexport type DrawInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface DrawAttrs {\n canvas: HTMLCanvasElement;\n options?: DrawOptions;\n}\n\nexport const RealDiv = 'RealDiv';\nexport type RealDivInputs = BinaryInputs;\n\nexport const Einsum = 'Einsum';\nexport type EinsumInputs = TensorInfo[];\nexport interface EinsumAttrs {\n equation: string;\n}\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick<NamedTensorInfoMap, 'dy'|'y'>;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const ExpandDims = 'ExpandDims';\nexport type ExpandDimsInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface ExpandDimsAttrs {\n dim: number;\n}\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n shape: number[];\n value: number|string;\n dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick<NamedTensorInfoMap, 'image'>;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n Pick<NamedTensorInfoMap, 'x'|'scale'|'offset'|'mean'|'variance'>;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick<NamedTensorInfoMap, 'x'|'indices'>;\nexport interface GatherV2Attrs {\n axis: number;\n batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick<NamedTensorInfoMap, 'params'|'indices'>;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const LeakyRelu = 'LeakyRelu';\nexport type LeakyReluInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LeakyReluAttrs {\n alpha: number;\n}\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n start: number;\n stop: number;\n num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogicalXor = 'LogicalXor';\nexport type LogicalXorInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LowerBound = 'LowerBound';\nexport type LowerBoundInputs =\n Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LRNAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const LRNGrad = 'LRNGrad';\nexport type LRNGradInputs = Pick<NamedTensorInfoMap, 'x'|'y'|'dy'>;\nexport interface LRNGradAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const MatrixBandPart = 'MatrixBandPart';\nexport type MatrixBandPartInputs =\n Pick<NamedTensorInfoMap, 'input'|'numLower'|'numUpper'>;\nexport interface MatrixBandPartAttrs {}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxAttrs {\n reductionIndices: number|number[];\n keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolGrad = 'MaxPoolGrad';\nexport type MaxPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPoolGradAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NDHWC'|'NCDHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DGrad = 'MaxPool3DGrad';\nexport type MaxPool3DGradInputs =\n Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPool3DGradAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolWithArgmaxAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MinAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const MirrorPad = 'MirrorPad';\nexport type MirrorPadInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MirrorPadAttrs {\n paddings: Array<[number, number]>;\n mode: 'reflect'|'symmetric';\n}\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multinomial = 'Multinomial';\nexport type MultinomialInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface MultinomialAttrs {\n numSamples: number;\n seed: number;\n normalized: boolean;\n}\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Neg = 'Neg';\nexport type NegInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV4Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV5Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick<NamedTensorInfoMap, 'indices'>;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n dtype: DataType;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick<NamedTensorInfoMap, 'x'|'alpha'>;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const RaggedGather = 'RaggedGather';\nexport type RaggedGatherInputs = {\n paramsNestedSplits: TensorInfo[]\n}&Pick<NamedTensorInfoMap, 'paramsDenseValues'|'indices'>;\nexport interface RaggedGatherAttrs {\n outputRaggedRank: number;\n}\n\nexport const RaggedRange = 'RaggedRange';\nexport type RaggedRangeInputs =\n Pick<NamedTensorInfoMap, 'starts'|'limits'|'deltas'>;\n\nexport const RaggedTensorToTensor = 'RaggedTensorToTensor';\nexport type RaggedTensorToTensorInputs =\n Pick<NamedTensorInfoMap, 'shape'|'values'|'defaultValue'>&\n {rowPartitionTensors: TensorInfo[]};\nexport interface RaggedTensorToTensorAttrs {\n rowPartitionTypes: string[];\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReverseAttrs {\n dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick<NamedTensorInfoMap, 'indices'|'updates'>;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const TensorScatterUpdate = 'TensorScatterUpdate';\nexport type TensorScatterUpdateInputs =\n Pick<NamedTensorInfoMap, 'tensor'|'indices'|'updates'>;\nexport interface TensorScatterUpdateAttrs {}\n\nexport const SearchSorted = 'SearchSorted';\nexport type SearchSortedInputs =\n Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\nexport interface SearchSortedAttrs {\n side: 'left'|'right';\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick<NamedTensorInfoMap, 'condition'|'t'|'e'>;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SliceAttrs {\n begin: number|number[];\n size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n Pick<NamedTensorInfoMap, 'indices'|'values'|'denseShape'|'defaultValue'>;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n Pick<NamedTensorInfoMap, 'inputIndices'|'inputShape'|'newShape'>;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick<NamedTensorInfoMap, 'sparseIndices'|'sparseValues'|'defaultValue'>;\nexport interface SparseToDenseAttrs {\n outputShape: number[];\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const StaticRegexReplace = 'StaticRegexReplace';\nexport type StaticRegexReplaceInputs = UnaryInputs;\nexport interface StaticRegexReplaceAttrs {\n pattern: string;\n rewrite: string;\n replaceGlobal: boolean;\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface StridedSliceAttrs {\n begin: number[];\n end: number[];\n strides: number[];\n beginMask: number;\n endMask: number;\n ellipsisMask: number;\n newAxisMask: number;\n shrinkAxisMask: number;\n}\n\nexport const StringNGrams = 'StringNGrams';\nexport type StringNGramsInputs = Pick<NamedTensorInfoMap, 'data'|'dataSplits'>;\nexport interface StringNGramsAttrs {\n separator: string;\n nGramWidths: number[];\n leftPad: string;\n rightPad: string;\n padWidth: number;\n preserveShortSequences: boolean;\n}\n\nexport const StringSplit = 'StringSplit';\nexport type StringSplitInputs = Pick<NamedTensorInfoMap, 'input'|'delimiter'>;\nexport interface StringSplitAttrs {\n skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface StringToHashBucketFastAttrs {\n numBuckets: number;\n}\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick<NamedTensorInfoMap, 'image'|'transforms'>;\nexport interface TransformAttrs {\n interpolation: 'nearest'|'bilinear';\n fillMode: 'constant'|'reflect'|'wrap'|'nearest';\n fillValue: number;\n outputShape?: [number, number];\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick<NamedTensorInfoMap, 'value'>;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick<NamedTensorInfoMap, 'x'|'segmentIds'>;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const UpperBound = 'UpperBound';\nexport type UpperBoundInputs =\n Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap;\n}\nexport interface FromPixelsAttrs {\n numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(...msg);\n }\n}\n\nexport function log(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.log(...msg);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {TensorInfo} from './tensor_info';\nimport {RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map<`${string}_${string}`,\n KernelConfig>());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map<string, GradConfig>());\n\ntype AttributeValue =\n number | number[] | boolean | boolean[] | string | string[] | NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue | RecursiveArray<AttributeValue>;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n inputs: NamedTensorInfoMap,\n backend: {},\n attrs?: NamedAttrMap,\n}) => TensorInfo | TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n (dy: Tensor | Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n kernelName: string;\n backendName: string;\n kernelFunc: KernelFunc;\n setupFunc?: KernelSetupFunc;\n disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n kernelName: string;\n inputsToSave?: string[];\n // When saveAllInputs is true, all inputs will be saved. Only use this flag\n // if inputs is an array of Tensors.\n saveAllInputs?: boolean;\n outputsToSave?: boolean[];\n gradFunc: GradFunc;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo|undefined;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n log.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n log.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string,\n backendName: string): `${string}_${string}` {\n return `${backendName}_${kernelName}`;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport function isTypedArrayBrowser(a: unknown): a is Uint8Array\n | Float32Array | Int32Array | Uint8ClampedArray {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {isTypedArrayBrowser} from './platforms/is_typed_array_browser';\nimport {BackendValues, DataType, RecursiveArray, TensorLike, TypedArray} from './types';\nimport * as base from './util_base';\nexport * from './util_base';\nexport * from './hash_util';\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n value: DataType, dtype: DataType): BackendValues {\n if (dtype === 'string') {\n return encodeString(value);\n }\n\n return toTypedArray([value], dtype);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n return (a instanceof Float32Array && dtype === 'float32') ||\n (a instanceof Int32Array && dtype === 'int32') ||\n (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n if (dtype === 'string') {\n throw new Error('Cannot convert a string[] to a TypedArray');\n }\n if (Array.isArray(a)) {\n a = flatten(a);\n }\n\n if (env().getBool('DEBUG')) {\n base.checkConversionForErrors(a as number[], dtype);\n }\n if (noConversionNeeded(a, dtype)) {\n return a as TypedArray;\n }\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(a as number[]);\n } else if (dtype === 'int32') {\n return new Int32Array(a as number[]);\n } else if (dtype === 'bool') {\n const bool = new Uint8Array((a as number[]).length);\n for (let i = 0; i < bool.length; ++i) {\n if (Math.round((a as number[])[i]) !== 0) {\n bool[i] = 1;\n }\n }\n return bool;\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n return env().platform.now();\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n path: string, requestInits?: RequestInit): Promise<Response> {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array|\n Uint8ClampedArray {\n // TODO(mattsoulanille): Remove this fallback in 5.0.0\n if (env().platform.isTypedArray != null) {\n return env().platform.isTypedArray(a);\n } else {\n return isTypedArrayBrowser(a);\n }\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten<number>().\n/**\n * Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n * @param arr The nested array to flatten.\n * @param result The destination array which holds the elements.\n * @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n * to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten<T extends number|boolean|string|Promise<number>|TypedArray>(\n arr: T|RecursiveArray<T>, result: T[] = [], skipTypedArray = false): T[] {\n if (result == null) {\n result = [];\n }\n if (typeof arr === 'boolean' || typeof arr === 'number' ||\n typeof arr === 'string' || base.isPromise(arr) || arr == null ||\n isTypedArray(arr) && skipTypedArray) {\n result.push(arr as T);\n } else if (Array.isArray(arr) || isTypedArray(arr)) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n let maxIndex = -1;\n for (const key of Object.keys(arr)) {\n // 0 or positive integer.\n if (/^([1-9]+[0-9]*|0)$/.test(key)) {\n maxIndex = Math.max(maxIndex, Number(key));\n }\n }\n for (let i = 0; i <= maxIndex; i++) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n flatten((arr as RecursiveArray<T>)[i], result, skipTypedArray);\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer, BackendTimingInfo} from './backends/backend';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n kernelName: string,\n outputs: Tensor[],\n inputs: NamedTensorMap,\n timeMs: Promise<number|{error: string}>,\n extraInfo: Promise<string>\n};\n\nexport class Profiler {\n constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n if (logger == null) {\n this.logger = new Logger();\n }\n }\n\n profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n KernelProfile {\n let outputs: Tensor[];\n const holdResultWrapperFn = () => {\n outputs = f();\n };\n let timer: Promise<BackendTimingInfo>;\n const start = util.now();\n if (this.backendTimer.timerAvailable()) {\n timer = this.backendTimer.time(holdResultWrapperFn);\n } else {\n holdResultWrapperFn();\n for (const output of outputs) {\n output.dataSync();\n }\n timer = Promise.resolve({kernelMs: util.now() - start});\n }\n if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {\n for (let i = 0; i < outputs.length; i++) {\n const output = outputs[i];\n // Dangling promise here because we don't want to propagate up\n // asynchronicity.\n output.data().then(tensorVals => {\n checkComputationForErrors(tensorVals, output.dtype, kernelName);\n });\n }\n }\n\n const kernelProfile = {\n kernelName,\n outputs,\n inputs,\n timeMs: timer.then(timing => timing.kernelMs),\n extraInfo: timer.then(\n timing => timing.getExtraProfileInfo != null ?\n timing.getExtraProfileInfo() :\n '')\n };\n return kernelProfile;\n }\n\n logKernelProfile(kernelProfile: KernelProfile): void {\n const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n outputs.forEach(result => {\n Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n this.logger.logKernelProfile(\n kernelName, result, valueContainer[0], valueContainer[1], inputs,\n valueContainer[2]);\n });\n });\n }\n}\n\nexport function checkComputationForErrors<D extends DataType>(\n vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n if (dtype !== 'float32') {\n // Only floating point computations will generate NaN values\n return false;\n }\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n // Throwing custom exception so behavior is testable.\n console.warn(`Found ${num} in the result of '${kernelName}'`);\n return true;\n }\n }\n return false;\n}\n\nexport class Logger {\n logKernelProfile(\n name: string, result: Tensor, vals: TypedArray,\n timeMs: number|{error: string}, inputs: NamedTensorMap,\n extraInfo?: string) {\n const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n timeMs['error'];\n const paddedName = util.rightPad(name, 25);\n const rank = result.rank;\n const size = result.size;\n const shape = util.rightPad(result.shape.toString(), 14);\n let inputShapesDescription = '';\n\n for (const name in inputs) {\n const input = inputs[name];\n if (input != null) {\n // The input might be a non-tensor (e.g HTMLImageElement), in which case\n // we claim the output shape as input shape.\n const inputShape = input.shape || result.shape;\n const inputRank = inputShape.length;\n inputShapesDescription +=\n `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n }\n }\n\n console.log(\n `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n inputShapesDescription}\\t%c${extraInfo}`,\n 'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n 'color: green', 'color: steelblue');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n id: number;\n kernelName: string;\n outputs: Tensor[];\n inputs: NamedTensorMap;\n // Optional params, defined only for ops with gradient impl.\n gradient?: (dys: Tensor[]) => NamedGradientMap;\n saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n // Forward pass to compute all the nodes and Tensors that are transitively a\n // function of x.\n const tensorsFromX: {[tensorId: number]: boolean} = {};\n const nodesFromX: {[nodeId: number]: boolean} = {};\n for (let i = 0; i < xs.length; i++) {\n tensorsFromX[xs[i].id] = true;\n }\n\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n for (const inputName in nodeInputs) {\n const input = nodeInputs[inputName];\n\n let anyInputFromX = false;\n for (let j = 0; j < xs.length; j++) {\n if (tensorsFromX[input.id]) {\n node.outputs.forEach(output => tensorsFromX[output.id] = true);\n anyInputFromX = true;\n nodesFromX[node.id] = true;\n break;\n }\n }\n\n if (anyInputFromX) {\n break;\n }\n }\n }\n\n // Backward pass to find all of the nodes and Tensors that lead to y.\n const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n tensorsLeadToY[y.id] = true;\n const nodesToY: {[nodeId: number]: boolean} = {};\n\n for (let i = tape.length - 1; i >= 0; i--) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n\n // If any of the outputs lead to y, mark all of the inputs as leading to y.\n for (let j = 0; j < node.outputs.length; j++) {\n if (tensorsLeadToY[node.outputs[j].id]) {\n for (const inputName in nodeInputs) {\n tensorsLeadToY[nodeInputs[inputName].id] = true;\n nodesToY[node.id] = true;\n }\n break;\n }\n }\n }\n\n // Return the paths that come from x and lead to y.\n const filteredTape: TapeNode[] = [];\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n\n if (nodesFromX[node.id] && nodesToY[node.id]) {\n // Prune the inputs from the node that aren't a function of x.\n const prunedInputs: {[inputName: string]: Tensor} = {};\n for (const inputName in node.inputs) {\n const nodeInput = node.inputs[inputName];\n if (tensorsFromX[nodeInput.id]) {\n prunedInputs[inputName] = nodeInput;\n }\n }\n\n // Copy the node and overwrite inputsAndArgs to the pruned version.\n const prunedNode = Object.assign({}, node);\n prunedNode.inputs = prunedInputs;\n prunedNode.outputs = node.outputs;\n\n filteredTape.push(prunedNode);\n }\n }\n\n return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n add: (a: Tensor, b: Tensor) => Tensor) {\n // Walk the tape backward and keep a map of Tensor to its gradient.\n for (let i = filteredTape.length - 1; i >= 0; i--) {\n const node = filteredTape[i];\n\n const dys: Tensor[] = [];\n node.outputs.forEach(o => {\n const gradTensor = tensorAccumulatedGradientMap[o.id];\n if (gradTensor != null) {\n dys.push(gradTensor);\n } else {\n // This particular output is not in the back-propagation subgraph, so it\n // does not affect the final output, thus we put null for its dy.\n dys.push(null);\n }\n });\n\n if (node.gradient == null) {\n throw new Error(\n `Cannot compute gradient: gradient function not found ` +\n `for ${node.kernelName}.`);\n }\n\n // Backprop dy through this node and accumulate gradients over the inputs.\n const inputGradients = node.gradient(dys);\n\n for (const inputName in node.inputs) {\n if (!(inputName in inputGradients)) {\n throw new Error(\n `Cannot backprop through input ${inputName}. ` +\n `Available gradients found: ${Object.keys(inputGradients)}.`);\n }\n\n // Call the gradient function.\n const dx = tidy(() => inputGradients[inputName]());\n if (dx.dtype !== 'float32') {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n }\n const x = node.inputs[inputName];\n if (!util.arraysEqual(dx.shape, x.shape)) {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `'${inputName}' has shape '${dx.shape}', which does not match ` +\n `the shape of the input '${x.shape}'`);\n }\n\n if (tensorAccumulatedGradientMap[x.id] == null) {\n tensorAccumulatedGradientMap[x.id] = dx;\n } else {\n const curGradient = tensorAccumulatedGradientMap[x.id];\n tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n curGradient.dispose();\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n verbose: boolean) {\n const strides = computeStrides(shape);\n const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n const rank = shape.length;\n const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n const lines = ['Tensor'];\n if (verbose) {\n lines.push(` dtype: ${dtype}`);\n lines.push(` rank: ${rank}`);\n lines.push(` shape: [${shape}]`);\n lines.push(` values:`);\n }\n lines.push(valsLines.map(l => ' ' + l).join('\\n'));\n return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[]): number[] {\n const n = sizeFromShape(shape);\n const numCols = strides[strides.length - 1];\n const padPerCol = new Array(numCols).fill(0);\n const rank = shape.length;\n const valuesOrTuples =\n dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n if (rank > 1) {\n for (let row = 0; row < n / numCols; row++) {\n const offset = row * numCols;\n for (let j = 0; j < numCols; j++) {\n padPerCol[j] = Math.max(\n padPerCol[j],\n valToString(valuesOrTuples[offset + j], 0, dtype).length);\n }\n }\n }\n return padPerCol;\n}\n\nfunction valToString(\n val: number|string|[number, number], pad: number, dtype: DataType) {\n let valStr: string;\n if (Array.isArray(val)) {\n valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n } else if (isString(val)) {\n valStr = `'${val}'`;\n } else if (dtype === 'bool') {\n valStr = boolNumToString(val);\n } else {\n valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n }\n\n return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[], padPerCol: number[], isLast = true): string[] {\n const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n const size = shape[0];\n const rank = shape.length;\n if (rank === 0) {\n if (dtype === 'complex64') {\n const complexTuple = createComplexTuples(vals);\n return [valToString(complexTuple[0], 0, dtype)];\n }\n if (dtype === 'bool') {\n return [boolNumToString(vals[0] as number)];\n }\n return [vals[0].toString()];\n }\n\n if (rank === 1) {\n if (size > FORMAT_LIMIT_NUM_VALS) {\n const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n let firstVals = Array.from<number|string|[number, number]>(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from<number|string|[number, number]>(vals.slice(\n (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n size * storagePerElement));\n if (dtype === 'complex64') {\n firstVals = createComplexTuples(firstVals);\n lastVals = createComplexTuples(lastVals);\n }\n return [\n '[' +\n firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ', ..., ' +\n lastVals\n .map(\n (x, i) => valToString(\n x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n .join(', ') +\n ']'\n ];\n }\n const displayVals: Array<number|string|[number, number]> =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from<number|string>(vals);\n\n return [\n '[' +\n displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ']'\n ];\n }\n\n // The array is rank 2 or more.\n const subshape = shape.slice(1);\n const substrides = strides.slice(1);\n const stride = strides[0] * storagePerElement;\n const lines: string[] = [];\n if (size > FORMAT_LIMIT_NUM_VALS) {\n for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n false /* isLast */));\n }\n lines.push('...');\n for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n } else {\n for (let i = 0; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n }\n const sep = rank === 2 ? ',' : '';\n lines[0] = '[' + (size > 0 ? lines[0] + sep : '');\n for (let i = 1; i < lines.length - 1; i++) {\n lines[i] = ' ' + lines[i] + sep;\n }\n let newLineSep = ',\\n';\n for (let i = 2; i < rank; i++) {\n newLineSep += '\\n';\n }\n lines[lines.length - 1] =\n ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n TypedArray): Array<[number, number]> {\n const complexTuples: Array<[number, number]> = [];\n for (let i = 0; i < vals.length; i += 2) {\n complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n }\n return complexTuples;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265\n/// <reference types=\"@webgpu/types/dist\" />\n\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\nimport {DataId, TensorInfo} from './tensor_info';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData<D extends DataType> {\n dataId?: DataId;\n values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer<R extends Rank, D extends DataType = 'float32'> {\n size: number;\n shape: ShapeMap[R];\n strides: number[];\n values: DataTypeMap[D];\n\n constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n this.shape = shape.slice() as ShapeMap[R];\n this.size = util.sizeFromShape(shape);\n\n if (values != null) {\n const n = values.length;\n util.assert(\n n === this.size,\n () => `Length of values '${n}' does not match the size ` +\n `inferred by the shape '${this.size}'.`);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `complex64 dtype TensorBuffers are not supported. Please create ` +\n `a TensorBuffer for the real and imaginary parts separately and ` +\n `call tf.complex(real, imag).`);\n }\n this.values = values || util.getArrayFromDType(dtype, this.size);\n this.strides = computeStrides(shape);\n }\n\n /**\n * Sets a value in the buffer at a given location.\n *\n * @param value The value to set.\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n set(value: SingleValueMap[D], ...locs: number[]): void {\n if (locs.length === 0) {\n locs = [0];\n }\n util.assert(\n locs.length === this.rank,\n () => `The number of provided coordinates (${locs.length}) must ` +\n `match the rank (${this.rank})`);\n\n const index = this.locToIndex(locs);\n this.values[index] = value as number;\n }\n\n /**\n * Returns the value in the buffer at the provided location.\n *\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n get(...locs: number[]): SingleValueMap[D] {\n if (locs.length === 0) {\n locs = [0];\n }\n let i = 0;\n for (const loc of locs) {\n if (loc < 0 || loc >= this.shape[i]) {\n const msg = `Requested out of range element at ${locs}. ` +\n ` Buffer shape=${this.shape}`;\n throw new Error(msg);\n }\n i++;\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return this.values[index] as SingleValueMap[D];\n }\n\n locToIndex(locs: number[]): number {\n if (this.rank === 0) {\n return 0;\n } else if (this.rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return index;\n }\n\n indexToLoc(index: number): number[] {\n if (this.rank === 0) {\n return [];\n } else if (this.rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(this.shape.length);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / this.strides[i]);\n index -= locs[i] * this.strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n }\n\n get rank() {\n return this.shape.length;\n }\n\n /**\n * Creates an immutable `tf.Tensor` object from the buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n toTensor(): Tensor<R> {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor<R>;\n }\n}\n\nexport interface DataToGPUWebGLOption {\n customTexShape?: [number, number];\n}\n\nexport type DataToGPUOptions = DataToGPUWebGLOption;\n\nexport interface GPUData {\n tensorRef: Tensor;\n texture?: WebGLTexture;\n buffer?: GPUBuffer;\n texShape?: [number, number];\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise<BackendValues>;\n readSync(dataId: DataId): BackendValues;\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast<T extends Tensor>(x: T, dtype: DataType): T;\n buffer<R extends Rank, D extends DataType>(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer<R, D>;\n print<T extends Tensor>(x: T, verbose: boolean): void;\n clone<T extends Tensor>(x: T): T;\n // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n deprecationWarningFn = fn;\n}\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * For performance reasons, functions that create tensors do not necessarily\n * perform a copy of the data passed to them (e.g. if the data is passed as a\n * `Float32Array`), and changes to the data will change the tensor. This is not\n * a feature and is not supported. To avoid this behavior, use the tensor before\n * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor<R extends Rank = Rank> implements TensorInfo {\n /** Unique id of this tensor. */\n readonly id: number;\n /**\n * Id of the bucket holding the data for this tensor. Multiple arrays can\n * point to the same bucket (e.g. when calling array.reshape()).\n */\n dataId: DataId;\n /** The shape of the tensor. */\n readonly shape: ShapeMap[R];\n /** Number of elements in the tensor. */\n readonly size: number;\n /** The data type for the array. */\n readonly dtype: DataType;\n /** The rank type for the array (see `Rank` enum). */\n readonly rankType: R;\n\n /** Whether this tensor has been globally kept. */\n kept = false;\n /** The id of the scope this tensor is being tracked in. */\n scopeId: number;\n\n /**\n * Number of elements to skip in each dimension when indexing. See\n * https://docs.scipy.org/doc/numpy/reference/generated/\\\n * numpy.ndarray.strides.html\n */\n readonly strides: number[];\n\n constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n this.shape = shape.slice() as ShapeMap[R];\n this.dtype = dtype || 'float32';\n this.size = util.sizeFromShape(shape);\n this.strides = computeStrides(shape);\n this.dataId = dataId;\n this.id = id;\n this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n }\n\n get rank(): number {\n return this.shape.length;\n }\n\n /**\n * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async buffer<D extends DataType = 'float32'>(): Promise<TensorBuffer<R, D>> {\n const vals = await this.data<D>();\n return opHandler.buffer(this.shape, this.dtype as D, vals);\n }\n\n /**\n * Returns a `tf.TensorBuffer` that holds the underlying data.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n bufferSync<D extends DataType = 'float32'>(): TensorBuffer<R, D> {\n return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * asynchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async array(): Promise<ArrayMap[R]> {\n const vals = await this.data();\n return toNestedArray(this.shape, vals, this.dtype === 'complex64') as\n ArrayMap[R];\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * synchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n arraySync(): ArrayMap[R] {\n return toNestedArray(\n this.shape, this.dataSync(), this.dtype === 'complex64') as\n ArrayMap[R];\n }\n\n /**\n * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n * promise of `TypedArray` that resolves when the computation has finished.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]> {\n this.throwIfDisposed();\n const data = trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n const bytes = await data as Uint8Array[];\n try {\n return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as Promise<DataTypeMap[D]>;\n }\n\n /**\n * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`\n * and `data()`, this method prevents data from being downloaded to CPU.\n *\n * For WebGL backend, the data will be stored on a densely packed texture.\n * This means that the texture will use the RGBA channels to store value.\n *\n * For WebGPU backend, the data will be stored on a buffer. There is no\n * parameter, so can not use a user-defined size to create the buffer.\n *\n * @param options:\n * For WebGL,\n * - customTexShape: Optional. If set, will use the user defined\n * texture shape to create the texture.\n *\n * @returns For WebGL backend, a GPUData contains the new texture and\n * its information.\n * {\n * tensorRef: The tensor that is associated with this texture,\n * texture: WebGLTexture,\n * texShape: [number, number] // [height, width]\n * }\n *\n * For WebGPU backend, a GPUData contains the new buffer.\n * {\n * tensorRef: The tensor that is associated with this buffer,\n * buffer: GPUBuffer,\n * }\n *\n * Remember to dispose the GPUData after it is used by\n * `res.tensorRef.dispose()`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataToGPU(options?: DataToGPUOptions): GPUData {\n this.throwIfDisposed();\n return trackerFn().readToGPU(this.dataId, options);\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D] {\n this.throwIfDisposed();\n const data = trackerFn().readSync(this.dataId);\n if (this.dtype === 'string') {\n try {\n return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as DataTypeMap[D];\n }\n\n /** Returns the underlying bytes of the tensor's data. */\n async bytes(): Promise<Uint8Array[]|Uint8Array> {\n this.throwIfDisposed();\n const data = await trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n return data as Uint8Array[];\n } else {\n return new Uint8Array((data as TypedArray).buffer);\n }\n }\n\n /**\n * Disposes `tf.Tensor` from memory.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n trackerFn().disposeTensor(this);\n this.isDisposedInternal = true;\n }\n\n protected isDisposedInternal = false;\n get isDisposed(): boolean {\n return this.isDisposedInternal;\n }\n\n throwIfDisposed() {\n if (this.isDisposed) {\n throw new Error(`Tensor is disposed.`);\n }\n }\n\n /**\n * Prints the `tf.Tensor`. See `tf.print` for details.\n *\n * @param verbose Whether to print verbose information about the tensor,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n print(verbose = false): void {\n return opHandler.print(this, verbose);\n }\n\n /**\n * Returns a copy of the tensor. See `tf.clone` for details.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n clone<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return opHandler.clone(this);\n }\n\n /**\n * Returns a human-readable description of the tensor. Useful for logging.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n toString(verbose = false): string {\n const vals = this.dataSync();\n return tensorToString(vals, this.shape, this.dtype, verbose);\n }\n\n cast<T extends this>(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable<R> {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable<R>;\n }\n}\n\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport function getGlobalTensorClass() {\n // Use getGlobal so that we can augment the Tensor class across package\n // boundaries becase the node resolution alg may result in different modules\n // being returned for this file depending on the path they are loaded from.\n return getGlobal('Tensor', () => {\n return Tensor;\n });\n}\n\n// Global side effect. Cache global reference to Tensor class\ngetGlobalTensorClass();\n\nexport interface NumericTensor<R extends Rank = Rank> extends Tensor<R> {\n dtype: NumericDataType;\n dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D];\n data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]>;\n dataToGPU(options?: DataToGPUOptions): GPUData;\n}\n\nexport interface StringTensor<R extends Rank = Rank> extends Tensor<R> {\n dtype: 'string';\n dataSync<D extends DataType = 'string'>(): DataTypeMap[D];\n data<D extends DataType = 'string'>(): Promise<DataTypeMap[D]>;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor<Rank.R0>;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor<Rank.R1>;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor<Rank.R2>;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor<Rank.R3>;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor<Rank.R4>;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor<Rank.R5>;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor<Rank.R6>;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable<R extends Rank = Rank> extends Tensor<R> {\n name: string;\n\n constructor(\n initialValue: Tensor<R>, public trainable: boolean, name: string,\n tensorId: number) {\n super(\n initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n this.name = name;\n }\n\n /**\n * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n * the same shape and dtype as the old `tf.Tensor`.\n *\n * @param newValue New tensor to be assigned to this variable.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n assign(newValue: Tensor<R>): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n override dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n R0: number[];\n R1: [number];\n R2: [number, number];\n R3: [number, number, number];\n R4: [number, number, number, number];\n R5: [number, number, number, number, number];\n R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n R0: number;\n R1: number[];\n R2: number[][];\n R3: number[][][];\n R4: number[][][][];\n R5: number[][][][][];\n R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n float32: Float32Array;\n int32: Int32Array;\n bool: Uint8Array;\n complex64: Float32Array;\n string: string[];\n}\n\nexport interface SingleValueMap {\n bool: boolean;\n int32: number;\n float32: number;\n complex64: number;\n string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\n\nexport type DataTypeFor<T extends number|string|boolean> =\n T extends number|boolean ? NumericDataType : T extends string ? 'string' :\n never;\n\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n R0 = 'R0',\n R1 = 'R1',\n R2 = 'R2',\n R3 = 'R3',\n R4 = 'R4',\n R5 = 'R5',\n R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray<T> =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray<T extends any> {\n [index: number]: T|RecursiveArray<T>;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'int32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'bool',\n 'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n 'float32' = 'float32',\n 'int32' = 'float32',\n 'bool' = 'float32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n 'float32' = 'complex64',\n 'int32' = 'complex64',\n 'bool' = 'complex64',\n 'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n 'float32': UpcastFloat32AndMap,\n 'int32': UpcastInt32AndMap,\n 'bool': UpcastBoolAndMap,\n 'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n if (typeA === 'string' || typeB === 'string') {\n if (typeA === 'string' && typeB === 'string') {\n return 'string';\n }\n throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n }\n return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n TypedArray|number|boolean|string|RecursiveArray<number|number[]|TypedArray>|\n RecursiveArray<boolean>|RecursiveArray<string>|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\n/**\n * Type for representing all permutations and combinations of 'RGBA' channels.\n */\nexport type WebGLChannels = 'A'|'B'|'G'|'R'|'AB'|'AG'|'AR'|'BA'|'BG'|'BR'|'GA'|\n 'GB'|'GR'|'RA'|'RB'|'RG'|'ABG'|'ABR'|'AGB'|'AGR'|'ARB'|'ARG'|'BAG'|'BAR'|\n 'BGA'|'BGR'|'BRA'|'BRG'|'GAB'|'GAR'|'GBA'|'GBR'|'GRA'|'GRB'|'RAB'|'RAG'|\n 'RBA'|'RBG'|'RGA'|'RGB'|'ABGR'|'ABRG'|'AGBR'|'AGRB'|'ARBG'|'ARGB'|'BAGR'|\n 'BARG'|'BGAR'|'BGRA'|'BRAG'|'BRGA'|'GABR'|'GARB'|'GBAR'|'GBRA'|'GRAB'|\n 'GRBA'|'RABG'|'RAGB'|'RBAG'|'RBGA'|'RGAB'|'RGBA';\n\n/** Type for representing a texture data to create a tensor. */\nexport interface WebGLData {\n texture: WebGLTexture;\n height: number;\n width: number;\n channels: WebGLChannels;\n}\n\n/**\n * Type for representing a buffer data to create a tensor. Buffer usage should\n * at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC. When\n * zeroCopy is false or undefined (default), this GPUBuffer will be copied to\n * the tensor's resource buffer. When zeroCopy is true, tensor will use this\n * GPUBuffer as tensor's resource buffer, user should not destroy this GPUBuffer\n * until all access is done. If not specified at creating a tensor, tensor type\n * is float32.\n */\nexport interface WebGPUData {\n buffer: GPUBuffer;\n zeroCopy?: boolean;\n}\n\nexport function isWebGLData(values: unknown): values is WebGLData {\n return values != null && typeof values === 'object' && 'texture' in values &&\n values.texture instanceof WebGLTexture;\n}\nexport function isWebGPUData(values: unknown): values is WebGPUData {\n return typeof GPUBuffer !== 'undefined' && values != null &&\n typeof values === 'object' && 'buffer' in values &&\n values.buffer instanceof GPUBuffer;\n}\n\nexport interface ImageOptions {\n /**\n * Optional. A number in range [0-1]. If the image is a 2D tensor or a 3D\n * tensor with 1 or 3 channels, the alpha channels would set as its value;\n * otherwise, it would not make effects.\n */\n alpha?: number;\n}\n\nexport interface ContextOptions {\n /**\n * Optional. If the canvas has created a context, it would not make effects.\n * If it is not set, it would be variable based on the current backend.\n */\n contextType?: string;\n /**\n * Optional. A WebGLContextAttributes configuration. If the canvas has created\n * a context, it would not make effects.\n */\n contextAttributes?: WebGLContextAttributes;\n}\n\nexport interface DrawOptions {\n /**\n * Optional. An object of options to customize the values of image tensor.\n */\n imageOptions?: ImageOptions;\n /**\n * Optional. An object to configure the context of the canvas to draw to.\n */\n contextOptions?: ContextOptions;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch<T extends Tensor>(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport { getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap } from './kernel_registry';\nimport { TensorInfo } from './tensor_info';\nimport * as log from './log';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataToGPUOptions, GPUData, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {DataId} from './tensor_info';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc<T> = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n * value: Tensor,\n * gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc<T extends Tensor> =\n (...inputs: Array<Tensor|GradSaveFunc>) => {\n value: T;\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n };\n\nexport type MemoryInfo = {\n numTensors: number; numDataBuffers: number; numBytes: number;\n unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n name: string; bytesAdded: number; totalBytesSnapshot: number;\n tensorsAdded: number;\n totalTensorsSnapshot: number;\n inputShapes: number[][];\n outputShapes: number[][];\n kernelTimeMs: number | {error: string} | Promise<number|{error: string}>;\n extraInfo: string | Promise<string>;\n};\n\nexport type ProfileInfo = {\n newBytes: number; newTensors: number; peakBytes: number;\n kernels: KernelInfo[];\n result: TensorContainer;\n kernelNames: string[];\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn<T extends TensorContainer> = () => T;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\ninterface RegisteredKernelInvocation<I extends NamedTensorMap> {\n kernelName: string;\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation<T extends Tensor|Tensor[],\n I extends NamedTensorMap> {\n forwardFunc: ForwardFunc<T>;\n backwardsFunc: (dy: T, saved: Tensor[]) => {\n [P in keyof I]: () => I[P]\n };\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation<T extends Tensor|Tensor[],\n I extends NamedTensorMap>(\n kernelInvocation: RegisteredKernelInvocation<I>|\n CustomGradKernelInvocation<T, I>):\n kernelInvocation is RegisteredKernelInvocation<I> {\n return (kernelInvocation as RegisteredKernelInvocation<I>).kernelName != null;\n}\n\nclass EngineState {\n // Public since optimizers will use it.\n registeredVariables: NamedVariableMap = {};\n\n nextTapeNodeId = 0;\n numBytes = 0;\n numTensors = 0;\n numStringTensors = 0;\n numDataBuffers = 0;\n\n activeTape: TapeNode[];\n // Number of nested tf.grad() statements when computing higher-order\n // gradients. E.g. `1` for first-order gradients and `2` for second-order\n // gradients. Used to track if the tape should be removed after a backprop.\n gradientDepth = 0;\n // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n // off the tape.\n kernelDepth = 0;\n\n // Keep Tensors that parallel the tapes.\n activeScope: ScopeState;\n scopeStack: ScopeState[] = [];\n /**\n * Keeps track of the number of data moves during a kernel execution. We\n * maintain a stack since kernels can call other kernels, recursively.\n */\n numDataMovesStack: number[] = [];\n nextScopeId = 0;\n\n tensorInfo = new WeakMap<DataId, {\n backend: KernelBackend,\n bytes: number,\n dtype: DataType,\n shape: number[]\n }>();\n\n profiling = false;\n activeProfile: ProfileInfo = {\n newBytes: 0,\n newTensors: 0,\n peakBytes: 0,\n kernels: [],\n result: null,\n get kernelNames():\n string[] {\n return Array.from(new Set(this.kernels.map(k => k.name)));\n }\n };\n\n dispose() {\n for (const variableName in this.registeredVariables) {\n this.registeredVariables[variableName].dispose();\n }\n }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n state: EngineState;\n backendName: string;\n registry: {[id: string]: KernelBackend} = {};\n registryFactory: {\n [id: string]: {\n factory: () => KernelBackend | Promise<KernelBackend>,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise<boolean>;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise<void> {\n if (this.pendingBackendInit != null) {\n return this.pendingBackendInit.then(() => {});\n }\n if (this.backendInstance != null) {\n return;\n }\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const success = await this.initializeBackend(backendName).success;\n if (success) {\n await this.setBackend(backendName);\n return;\n }\n }\n\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n get backend(): KernelBackend {\n if (this.pendingBackendInit != null) {\n throw new Error(\n `Backend '${this.backendName}' has not yet been initialized. Make ` +\n `sure to await tf.ready() or await tf.setBackend() before calling ` +\n `other methods`);\n }\n if (this.backendInstance == null) {\n const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n if (asyncInit) {\n throw new Error(\n `The highest priority backend '${name}' has not yet been ` +\n `initialized. Make sure to await tf.ready() or ` +\n `await tf.setBackend() before calling other methods`);\n }\n this.setBackend(name);\n }\n return this.backendInstance;\n }\n\n backendNames(): string[] {\n return Object.keys(this.registryFactory);\n }\n\n findBackend(backendName: string): KernelBackend {\n if (!(backendName in this.registry)) {\n // If the backend hasn't been initialized but we have a registry entry for\n // it, initialize it and return it.\n if (backendName in this.registryFactory) {\n const {asyncInit} = this.initializeBackend(backendName);\n if (asyncInit) {\n // Backend is not ready yet.\n return null;\n }\n } else {\n return null;\n }\n }\n return this.registry[backendName];\n }\n\n findBackendFactory(backendName: string):\n () => KernelBackend | Promise<KernelBackend> {\n if (!(backendName in this.registryFactory)) {\n return null;\n }\n return this.registryFactory[backendName].factory;\n }\n\n registerBackend(\n backendName: string,\n factory: () => KernelBackend | Promise<KernelBackend>,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n log.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise<boolean> {\n if (this.registryFactory[backendName] == null) {\n throw new Error(`Backend name '${backendName}' not found in registry`);\n }\n this.backendName = backendName;\n if (this.registry[backendName] == null) {\n this.backendInstance = null;\n const {success, asyncInit} = this.initializeBackend(backendName);\n const result = asyncInit ? await success : success;\n if (!result) {\n return false;\n }\n }\n this.backendInstance = this.registry[backendName];\n this.setupRegisteredKernels();\n // Reset the profiler.\n this.profiler = new Profiler(this.backendInstance);\n\n return true;\n }\n\n private setupRegisteredKernels(): void {\n const kernels = getKernelsForBackend(this.backendName);\n kernels.forEach(kernel => {\n if (kernel.setupFunc != null) {\n kernel.setupFunc(this.backendInstance);\n }\n });\n }\n\n private disposeRegisteredKernels(backendName: string): void {\n const kernels = getKernelsForBackend(backendName);\n kernels.forEach(kernel => {\n if (kernel.disposeFunc != null) {\n kernel.disposeFunc(this.registry[backendName]);\n }\n });\n }\n\n /**\n * Initializes a backend by looking up the backend name in the factory\n * registry and calling the factory method. Returns a boolean representing\n * whether the initialization of the backend suceeded. Throws an error if\n * there is no backend in the factory registry.\n */\n private initializeBackend(backendName: string):\n {success: boolean|Promise<boolean>, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend) &&\n typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n const refCount = srcBackend.refCount(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId, true);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype, refCount);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy<T extends TensorContainer>(nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>):\n T {\n let name: string = null;\n if (fn == null) {\n // Called with only 1 argument.\n if (typeof nameOrFn !== 'function') {\n throw new Error('Please provide a function to tidy()');\n }\n fn = nameOrFn;\n } else {\n // Called with 2 arguments.\n if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n throw new Error(\n 'When calling with two arguments, the first argument ' +\n 'to tidy() must be a string');\n }\n if (typeof fn !== 'function') {\n throw new Error(\n 'When calling with two arguments, the 2nd argument ' +\n 'to tidy() must be a function');\n }\n name = nameOrFn as string;\n // TODO(nsthorat,smilkov): Do operation logging and performance\n // profiling.\n }\n let result: T;\n return this.scopedRun(\n () => this.startScope(name), () => this.endScope(result), () => {\n result = fn();\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n return result;\n });\n }\n\n private scopedRun<T>(start: () => void, end: () => void, f: () => T): T {\n start();\n try {\n const res = f();\n end();\n return res;\n } catch (ex) {\n end();\n throw ex;\n }\n }\n\n private static nextTensorId = 0;\n private nextTensorId(): number {\n return Engine.nextTensorId++;\n }\n\n private static nextVariableId = 0;\n private nextVariableId(): number {\n return Engine.nextVariableId++;\n }\n\n /**\n * This method is called instead of the public-facing tensor.clone() when\n * saving a tensor for backwards pass. It makes sure to add the clone\n * operation to the tape regardless of being called inside a kernel\n * execution.\n */\n private clone(x: Tensor): Tensor {\n const y: Tensor = ENGINE.runKernel(Identity,\n {x} as unknown as NamedTensorMap);\n const inputs = {x};\n const grad = (dy: Tensor) => ({\n x: () => {\n const dtype = 'float32';\n const gradInputs = {x: dy};\n const attrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, gradInputs as unknown as NamedTensorMap,\n // tslint:disable-next-line: no-unnecessary-type-assertion\n attrs as unknown as NamedAttrMap) as Tensor;\n }\n });\n const saved: Tensor[] = [];\n this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n return y;\n }\n\n /**\n * Execute a kernel with the given name and return the output tensor.\n *\n * @param kernelName The name of the kernel to execute.\n * @param inputs A map of input names to tensors.\n * @param attrs A map of attribute names to their values. An attribute is a\n * primitive (non-tensor) input to the kernel.\n * @param inputsToSave A list of tensors, inputs to save for the backprop\n * computation.\n * @param outputsToSave A list of booleans, specifying which output to save\n * for the backprop computation. These are booleans since the output\n * tensors are not visible to the user.\n */\n runKernel<T extends Tensor|Tensor[]>(\n kernelName: string, inputs: NamedTensorMap, attrs?: NamedAttrMap): T {\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const hasKernel = getKernel(kernelName, this.backendName) != null;\n if (!hasKernel) {\n throw new Error(`Kernel '${kernelName}' not registered for backend '${\n this.backendName}'`);\n }\n return this.runKernelFunc({kernelName, inputs, attrs});\n }\n\n private shouldCheckForMemLeaks(): boolean {\n return this.ENV.getBool('IS_TEST');\n }\n\n private checkKernelForMemLeak(\n kernelName: string, numDataIdsBefore: number,\n outInfos: TensorInfo[]): void {\n const numDataIdsAfter = this.backend.numDataIds();\n\n // Count the number of data ids associated with the result of the kernel.\n let numOutputDataIds = 0;\n outInfos.forEach(info => {\n // Complex numbers allocate 3 data ids, one for 'real', one for\n // 'imaginary', and one for the container that holds the former two.\n numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n });\n\n // Account for the number of moves during kernel execution. A \"data move\"\n // can happen in the middle of a kernel execution, placing a new (key,value)\n // pair in the data storage. Since data moves have net zero effect (we\n // always remove the data from the old backend), we have to cancel them out\n // when detecting memory leaks.\n const numMoves =\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n const dataIdsLeaked =\n numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n if (dataIdsLeaked > 0) {\n throw new Error(\n `Backend '${this.backendName}' has an internal memory leak ` +\n `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n }\n }\n\n /**\n * Internal helper method to execute a kernel Func\n *\n * Use `runKernel` to execute kernels from outside of engine.\n */\n private runKernelFunc<T extends Tensor|Tensor[], I extends NamedTensorMap>(\n kernelParams: RegisteredKernelInvocation<I>|\n CustomGradKernelInvocation<T, I>): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n\n let out: TensorInfo|TensorInfo[];\n\n const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n kernelParams.kernelName :\n this.state.activeScope != null ? this.state.activeScope.name : '';\n\n // Create the kernelFunc from either a registered kernel OR passed in\n // forward/backward functions (used by custom grad). In this context a\n // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n if (isRegisteredKernelInvocation(kernelParams)) {\n const {kernelName, inputs, attrs} = kernelParams;\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const kernel = getKernel(kernelName, this.backendName);\n util.assert(\n kernel != null,\n () => `Cannot find registered kernel '${kernelName}' for backend '${\n this.backendName}'`);\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n\n const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n // todo (yassogba) remove this option (Tensor) when node backend\n // methods have been modularized and they all return tensorInfo.\n // TensorInfos do not have a rank attribute.\n if ((outInfo as Tensor).rank != null) {\n return outInfo as Tensor;\n }\n return this.makeTensorFromTensorInfo(outInfo);\n });\n\n // Save any required inputs and outputs.\n\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since there would be no backprop for these tensors\n // (which would otherwise dispose them).\n if (isTapeOn) {\n const tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const {forwardFunc} = kernelParams;\n // Running a customGrad op.\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n // Scope name is used to print a more helpful error message if needed.\n this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n //\n // Run the kernelFunc. Optionally profiling it.\n //\n const {inputs, attrs} = kernelParams;\n const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n null :\n kernelParams.backwardsFunc;\n\n let kernelProfile: KernelProfile;\n this.scopedRun(\n // Stop recording to a tape when running a kernel.\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelOrScopeName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelOrScopeName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // We return an empty list rather than throw an error because the kernel we\n // are looking up may not actually be relevant to backproping through the\n // overall function\n //\n // See 'does not error if irrelevant (pruned) ops are missing grads' test\n // in gradients_test.ts for an example.\n return [];\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n * @deprecated\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const tensorInfo: TensorInfo = {dataId, shape, dtype};\n return this.makeTensorFromTensorInfo(tensorInfo, backend);\n }\n\n /**\n * Internal method used by backends. Makes a new tensor that is a wrapper\n * around an existing data id in TensorInfo. It doesn't create a new data id,\n * only increments the ref count used in memory tracking.\n */\n makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend):\n Tensor {\n const {dataId, shape, dtype} = tensorInfo;\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n trackTensor(a: Tensor, backend: KernelBackend): void {\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.numBytes += bytes;\n\n if (!this.state.tensorInfo.has(a.dataId)) {\n this.state.numDataBuffers++;\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes\n });\n }\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n // Track the tensor by dataId and increase the refCount for the dataId in the\n // backend.\n // TODO(pyu10055): This is currently used by makeVariable method, to increase\n // refCount on the backend for the dataId. It can potentially be replaced with\n // Identity op indead of calling backend directly.\n incRef(a: Tensor, backend: KernelBackend): void {\n this.trackTensor(a, backend);\n this.backend.incRef(a.dataId);\n }\n\n removeDataId(dataId: DataId, backend: KernelBackend) {\n if (this.state.tensorInfo.has(dataId) &&\n this.state.tensorInfo.get(dataId).backend === backend) {\n this.state.tensorInfo.delete(dataId);\n this.state.numDataBuffers--;\n }\n }\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n this.state.numBytes -= info.bytes;\n }\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n const bytes = a.size * util.bytesPerElement(a.dtype);\n this.state.numBytes -= bytes;\n }\n\n // Remove the reference to dataId if backend dispose the data successfully\n if (info.backend.disposeData(a.dataId)) {\n this.removeDataId(a.dataId, info.backend);\n }\n\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise<TensorContainer>)):\n Promise<ProfileInfo> {\n this.state.profiling = true;\n\n const startBytes = this.state.numBytes;\n const startNumTensors = this.state.numTensors;\n\n this.state.activeProfile.kernels = [];\n this.state.activeProfile.result = await query();\n\n this.state.profiling = false;\n\n this.state.activeProfile.peakBytes = Math.max(\n ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n this.state.activeProfile.newTensors =\n this.state.numTensors - startNumTensors;\n for (const kernel of this.state.activeProfile.kernels) {\n kernel.kernelTimeMs = await kernel.kernelTimeMs;\n kernel.extraInfo = await kernel.extraInfo;\n }\n return this.state.activeProfile;\n }\n\n isTapeOn(): boolean {\n return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n }\n\n private addTapeNode(\n kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n const tapeNode: TapeNode =\n {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n gradientsFunc = gradConfig.gradFunc;\n }\n if (gradientsFunc != null) {\n tapeNode.gradient = (dys: Tensor[]) => {\n // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n // the backprop graph to the user as null instead of zeros\n dys = dys.map((dy, i) => {\n if (dy == null) {\n const output = outputs[i];\n const vals = util.makeZerosTypedArray(output.size, output.dtype);\n return this.makeTensor(vals, output.shape, output.dtype);\n }\n return dy;\n });\n // Grad functions of ops with single outputs expect a dy, while ops\n // with multiple outputs expect dys (array of dy).\n return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n };\n }\n this.state.activeTape.push(tapeNode);\n }\n\n keep<T extends Tensor>(result: T): T {\n result.kept = true;\n return result;\n }\n\n private startTape() {\n if (this.state.gradientDepth === 0) {\n this.state.activeTape = [];\n }\n this.state.gradientDepth++;\n }\n\n private endTape() {\n this.state.gradientDepth--;\n }\n\n /**\n * Start a scope. Use this with endScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n startScope(name?: string) {\n const scopeInfo: ScopeState = {\n track: [],\n name: 'unnamed scope',\n id: this.state.nextScopeId++\n };\n if (name) {\n scopeInfo.name = name;\n }\n this.state.scopeStack.push(scopeInfo);\n this.state.activeScope = scopeInfo;\n }\n\n /**\n * End a scope. Use this with startScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n endScope(result?: TensorContainer) {\n const tensorsToTrackInParent = getTensorsInContainer(result);\n const tensorsToTrackInParentSet =\n new Set(tensorsToTrackInParent.map(t => t.id));\n\n // Dispose the arrays tracked in this scope.\n for (let i = 0; i < this.state.activeScope.track.length; i++) {\n const tensor = this.state.activeScope.track[i];\n if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n tensor.dispose();\n }\n }\n\n const oldScope = this.state.scopeStack.pop();\n this.state.activeScope = this.state.scopeStack.length === 0 ?\n null :\n this.state.scopeStack[this.state.scopeStack.length - 1];\n\n // Track the current result in the parent scope.\n tensorsToTrackInParent.forEach(tensor => {\n // Only track the tensor if was allocated in the inner scope and is not\n // globally kept.\n if (!tensor.kept && tensor.scopeId === oldScope.id) {\n this.track(tensor);\n }\n });\n }\n\n /**\n * Returns gradients of `f` with respect to each of the `xs`. The gradients\n * returned are of the same length as `xs`, but some might be null if `f`\n * was not a function of that `x`. It also takes optional dy to multiply the\n * gradient, which defaults to `1`.\n */\n gradients<T extends Tensor>(\n f: () => T, xs: Tensor[], dy?: T,\n allowNoGradients = false): {value: T, grads: Tensor[]} {\n util.assert(\n xs.length > 0, () => 'gradients() received an empty list of xs.');\n if (dy != null && dy.dtype !== 'float32') {\n throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n }\n\n const y = this.scopedRun(\n () => this.startTape(), () => this.endTape(),\n () => this.tidy('forward', f));\n\n util.assert(\n y instanceof Tensor,\n () => 'The result y returned by f() must be a tensor.');\n // Filter out the nodes that don't connect x => y.\n const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n throw new Error(\n 'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n 'that the f you passed encloses all operations that lead from x ' +\n 'to y.');\n }\n\n return this.tidy('backward', () => {\n const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n // Backprop gradients through the filtered nodes.\n backpropagateGradients(\n accumulatedGradientMap, filteredTape,\n // Pass the tidy function to avoid circular dep with `tape.ts`.\n f => this.tidy(f as ScopeFn<Tensor>),\n // Pass an add function to avoide a circular dep with `tape.ts`.\n add);\n const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n if (this.state.gradientDepth === 0) {\n // This means that we are not computing higher-order gradients\n // and can clean up the tape.\n this.state.activeTape.forEach(node => {\n for (const tensor of node.saved) {\n tensor.dispose();\n }\n });\n this.state.activeTape = null;\n }\n return {value: y, grads};\n });\n }\n\n customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n (...args: Array<Tensor|GradSaveFunc>) => T {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in customGrad(f) must be a function.');\n return (...inputs: Tensor[]): T => {\n util.assert(\n inputs.every(t => t instanceof Tensor),\n () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n 'tensors');\n\n let res: {\n value: T,\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n };\n const inputMap: NamedTensorMap = {};\n inputs.forEach((input, i) => {\n inputMap[i] = input;\n });\n\n const forwardFunc: ForwardFunc<T> = (_, save) => {\n res = f(...[...inputs, save]);\n util.assert(\n res.value instanceof Tensor,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.value` is a tensor');\n util.assert(\n util.isFunction(res.gradFunc),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function.');\n return res.value;\n };\n\n const backwardsFunc = (dy: T, saved: Tensor[]) => {\n const gradRes = res.gradFunc(dy, saved);\n const grads: Tensor[] = Array.isArray(gradRes) ? gradRes : [gradRes];\n util.assert(\n grads.length === inputs.length,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'the same number of tensors as inputs passed to f(...).');\n util.assert(\n grads.every(t => t instanceof Tensor),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'a list of only tensors.');\n const gradMap: {[key: string]: () => Tensor} = {};\n grads.forEach((grad, i) => {\n gradMap[i] = () => grad;\n });\n return gradMap;\n };\n\n return this.runKernelFunc({\n forwardFunc,\n backwardsFunc,\n inputs: inputMap,\n });\n };\n }\n\n readSync(dataId: DataId): BackendValues {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readSync(dataId);\n }\n read(dataId: DataId): Promise<BackendValues> {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readToGPU(dataId, options);\n }\n\n async time(query: () => void): Promise<TimingInfo> {\n const start = now();\n const timingInfo = await this.backend.time(query) as TimingInfo;\n timingInfo.wallMs = now() - start;\n return timingInfo;\n }\n\n /**\n * Tracks a Tensor in the current scope to be automatically cleaned up\n * when the current scope ends, and returns the value.\n *\n * @param result The Tensor to track in the current scope.\n */\n private track<T extends Tensor>(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as unknown as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/** Whether this browser is Safari. */\nENV.registerFlag(\n 'IS_SAFARI',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Safari/.test(navigator.userAgent) &&\n /Apple/.test(navigator.vendor));\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n\n/** Whether to check computation result for errors. */\nENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => ENV.getBool('DEBUG'));\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);\n\n/** Whether to enable canvas2d willReadFrequently for GPU backends */\nENV.registerFlag('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU', () => false);\n\n/** Whether to use setTimeoutCustom */\nENV.registerFlag('USE_SETTIMEOUTCUSTOM', () => false);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {DataType, isWebGLData, isWebGPUData, TensorLike, WebGLData, WebGPUData} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\nimport {bytesPerElement} from './util_base';\n\nexport function inferShape(\n val: TensorLike|WebGLData|WebGPUData, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\n }\n\n if (isWebGLData(val)) {\n const usedChannels = val.channels || 'RGBA';\n return [val.height, val.width * usedChannels.length];\n } else if (isWebGPUData(val)) {\n return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];\n }\n if (!Array.isArray(val)) {\n return []; // Scalar.\n }\n const shape: number[] = [];\n\n while (Array.isArray(firstElem) ||\n isTypedArray(firstElem) && dtype !== 'string') {\n shape.push(firstElem.length);\n firstElem = firstElem[0];\n }\n if (Array.isArray(val) &&\n env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n deepAssertShapeConsistency(val, shape, []);\n }\n\n return shape;\n}\n\nfunction deepAssertShapeConsistency(\n val: TensorLike, shape: number[], indices: number[]) {\n indices = indices || [];\n if (!(Array.isArray(val)) && !isTypedArray(val)) {\n assert(\n shape.length === 0,\n () => `Element arr[${indices.join('][')}] is a primitive, ` +\n `but should be an array/TypedArray of ${shape[0]} elements`);\n return;\n }\n assert(\n shape.length > 0,\n () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n `but is an array of ${val.length} elements`);\n assert(\n val.length === shape[0],\n () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n `elements, but has ${val.length} elements`);\n const subShape = shape.slice(1);\n for (let i = 0; i < val.length; ++i) {\n deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n }\n}\n\nfunction assertDtype(\n expectedDtype: DataType|'numeric'|'string_or_numeric',\n actualDType: DataType, argName: string, functionName: string) {\n if (expectedDtype === 'string_or_numeric') {\n return;\n }\n if (expectedDtype == null) {\n throw new Error(`Expected dtype cannot be null.`);\n }\n if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n expectedDtype === 'numeric' && actualDType === 'string') {\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must ` +\n `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n }\n}\n\nexport function convertToTensor<T extends Tensor>(\n x: T|TensorLike, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T {\n if (x instanceof Tensor) {\n assertDtype(parseAsDtype, x.dtype, argName, functionName);\n return x;\n }\n let inferredDtype = inferDtype(x);\n // If the user expects a bool/int/float, use that info to update the\n // inferredDtype when it is not a string.\n if (inferredDtype !== 'string' &&\n ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n inferredDtype = parseAsDtype as DataType;\n }\n assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n if ((x == null) ||\n (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n typeof x !== 'boolean' && typeof x !== 'string')) {\n const type = x == null ? 'null' : (x as {}).constructor.name;\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must be a ` +\n `Tensor or TensorLike, but got '${type}'`);\n }\n const inferredShape = inferShape(x, inferredDtype);\n if (!isTypedArray(x) && !Array.isArray(x)) {\n x = [x] as number[];\n }\n const skipTypedArray = true;\n const values = inferredDtype !== 'string' ?\n toTypedArray(x, inferredDtype as DataType) :\n flatten(x as string[], [], skipTypedArray) as string[];\n return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray<T extends Tensor>(\n arg: Array<T|TensorLike>, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T[] {\n if (!Array.isArray(arg)) {\n throw new Error(\n `Argument ${argName} passed to ${functionName} must be a ` +\n '`Tensor[]` or `TensorLike[]`');\n }\n const tensors = arg as T[];\n return tensors.map(\n (t, i) =>\n convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op<T extends Function>(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (isPromise(result)) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {isWebGLData, isWebGPUData, TensorLike, TypedArray, WebGLData, WebGPUData} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike|WebGLData|WebGPUData, shape: number[],\n inferredShape: number[], dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n } else if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n\n if (isWebGPUData(values) || isWebGLData(values)) {\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new Error(\n `Creating tensor from GPU data only supports ` +\n `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n }\n return ENGINE.backend.createTensorFromGPUData(\n values, shape || inferredShape, dtype);\n }\n\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n // Verify that the shape matches the inferred shape.\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n","/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {TypedArray} from '../types';\nimport * as util from '../util';\n\ntype BufferShard = {\n start: number,\n end: number,\n buffer: ArrayBuffer,\n};\n\n/**\n * Wraps a list of ArrayBuffers into a `slice()`-able object without allocating\n * a large ArrayBuffer.\n *\n * Allocating large ArrayBuffers (~2GB) can be unstable on Chrome. TFJS loads\n * its weights as a list of (usually) 4MB ArrayBuffers and then slices the\n * weight tensors out of them. For small models, it's safe to concatenate all\n * the weight buffers into a single ArrayBuffer and then slice the weight\n * tensors out of it, but for large models, a different approach is needed.\n */\n\nexport class CompositeArrayBuffer {\n private shards: BufferShard[] = [];\n private previousShardIndex = 0;\n private bufferUniformSize?: number;\n public readonly byteLength: number;\n\n /**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n * ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n */\n static join(buffers?: ArrayBuffer[] | ArrayBuffer) {\n return new CompositeArrayBuffer(buffers).slice();\n }\n\n constructor(buffers?: ArrayBuffer | ArrayBuffer[] | TypedArray |\n TypedArray[]) {\n if (buffers == null) {\n return;\n }\n // Normalize the `buffers` input to be `ArrayBuffer[]`.\n if (!(buffers instanceof Array)) {\n buffers = [buffers];\n }\n buffers = buffers.map((bufferOrTypedArray) => {\n if (util.isTypedArray(bufferOrTypedArray)) {\n return bufferOrTypedArray.buffer;\n }\n return bufferOrTypedArray;\n });\n\n // Skip setting up shards if there are no buffers.\n if (buffers.length === 0) {\n return;\n }\n\n this.bufferUniformSize = buffers[0].byteLength;\n let start = 0;\n\n for (let i = 0; i < buffers.length; i++) {\n const buffer = buffers[i];\n // Check that all buffers except the last one have the same length.\n if (i !== buffers.length - 1 &&\n buffer.byteLength !== this.bufferUniformSize) {\n // Unset the buffer uniform size, since the buffer sizes are not\n // uniform.\n this.bufferUniformSize = undefined;\n }\n\n // Create the shards, including their start and end points.\n const end = start + buffer.byteLength;\n this.shards.push({ buffer, start, end });\n start = end;\n }\n\n // Set the byteLenghth\n if (this.shards.length === 0) {\n this.byteLength = 0;\n }\n this.byteLength = this.shards[this.shards.length - 1].end;\n }\n\n slice(start = 0, end = this.byteLength): ArrayBuffer {\n // If there are no shards, then the CompositeArrayBuffer was initialized\n // with no data.\n if (this.shards.length === 0) {\n return new ArrayBuffer(0);\n }\n\n // NaN is treated as zero for slicing. This matches ArrayBuffer's behavior.\n start = isNaN(Number(start)) ? 0 : start;\n end = isNaN(Number(end)) ? 0 : end;\n\n // Fix the bounds to within the array.\n start = Math.max(0, start);\n end = Math.min(this.byteLength, end);\n if (end <= start) {\n return new ArrayBuffer(0);\n }\n\n const startShardIndex = this.findShardForByte(start);\n if (startShardIndex === -1) {\n // This should not happen since the start and end indices are always\n // within 0 and the composite array's length.\n throw new Error(`Could not find start shard for byte ${start}`);\n }\n\n const size = end - start;\n const outputBuffer = new ArrayBuffer(size);\n const outputArray = new Uint8Array(outputBuffer);\n let sliced = 0;\n for (let i = startShardIndex; i < this.shards.length; i++) {\n const shard = this.shards[i];\n\n const globalStart = start + sliced;\n const localStart = globalStart - shard.start;\n const outputStart = sliced;\n\n const globalEnd = Math.min(end, shard.end);\n const localEnd = globalEnd - shard.start;\n\n const outputSlice = new Uint8Array(shard.buffer, localStart,\n localEnd - localStart);\n outputArray.set(outputSlice, outputStart);\n sliced += outputSlice.length;\n\n if (end < shard.end) {\n break;\n }\n }\n return outputBuffer;\n }\n\n /**\n * Get the index of the shard that contains the byte at `byteIndex`.\n */\n private findShardForByte(byteIndex: number): number {\n if (this.shards.length === 0 || byteIndex < 0 ||\n byteIndex >= this.byteLength) {\n return -1;\n }\n\n // If the buffers have a uniform size, compute the shard directly.\n if (this.bufferUniformSize != null) {\n this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);\n return this.previousShardIndex;\n }\n\n // If the buffers don't have a uniform size, we need to search for the\n // shard. That means we need a function to check where the byteIndex lies\n // relative to a given shard.\n function check(shard: BufferShard) {\n if (byteIndex < shard.start) {\n return -1;\n }\n if (byteIndex >= shard.end) {\n return 1;\n }\n return 0;\n }\n\n // For efficiency, try the previous shard first.\n if (check(this.shards[this.previousShardIndex]) === 0) {\n return this.previousShardIndex;\n }\n\n // Otherwise, use a generic search function.\n // This should almost never end up being used in practice since the weight\n // entries should always be in order.\n const index = search(this.shards, check);\n if (index === -1) {\n return -1;\n }\n\n this.previousShardIndex = index;\n return this.previousShardIndex;\n }\n}\n\n/**\n * Search for an element of a sorted array.\n *\n * @param sortedArray The sorted array to search\n * @param compare A function to compare the current value against the searched\n * value. Return 0 on a match, negative if the searched value is less than\n * the value passed to the function, and positive if the searched value is\n * greater than the value passed to the function.\n * @returns The index of the element, or -1 if it's not in the array.\n */\nexport function search<T>(sortedArray: T[], compare: (t: T) => number): number {\n // Binary search\n let min = 0;\n let max = sortedArray.length;\n\n while (min <= max) {\n const middle = Math.floor((max - min) / 2) + min;\n const side = compare(sortedArray[middle]);\n\n if (side === 0) {\n return middle;\n } else if (side < 0) {\n max = middle;\n } else {\n min = middle + 1;\n }\n }\n return -1;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightData, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array<Promise<TypedArray>> = [];\n\n const names: string[] = Array.isArray(tensors) ?\n tensors.map(tensor => tensor.name) :\n Object.keys(tensors);\n\n for (let i = 0; i < names.length; ++i) {\n const name = names[i];\n const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n t.dtype !== 'string' && t.dtype !== 'complex64') {\n throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n }\n const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n if (t.dtype === 'string') {\n const utf8bytes = new Promise<TypedArray>(async resolve => {\n const vals = await t.bytes() as Uint8Array[];\n const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n NUM_BYTES_STRING_LENGTH * vals.length;\n const bytes = new Uint8Array(totalNumBytes);\n let offset = 0;\n for (let i = 0; i < vals.length; i++) {\n const val = vals[i];\n const bytesOfLength =\n new Uint8Array(new Uint32Array([val.length]).buffer);\n bytes.set(bytesOfLength, offset);\n offset += NUM_BYTES_STRING_LENGTH;\n bytes.set(val, offset);\n offset += val.length;\n }\n resolve(bytes);\n });\n dataPromises.push(utf8bytes);\n } else {\n dataPromises.push(t.data());\n }\n if (group != null) {\n spec.group = group;\n }\n specs.push(spec);\n }\n\n const tensorValues = await Promise.all(dataPromises);\n return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param weightData A flat ArrayBuffer or an array of ArrayBuffers carrying the\n * binary values of the tensors concatenated in the order specified in\n * `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n * whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n * to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n weightData: WeightData,\n specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const compositeBuffer = new CompositeArrayBuffer(weightData);\n const out: NamedTensorMap = {};\n let float16Decode: (buffer: Uint16Array) => Float32Array | undefined;\n let offset = 0;\n for (const spec of specs) {\n const name = spec.name;\n const dtype = spec.dtype;\n const shape = spec.shape;\n const size = sizeFromShape(shape);\n let values: TypedArray|string[]|Uint8Array[];\n\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n if (!('min' in quantization && 'scale' in quantization)) {\n throw new Error(\n `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n `doesn't have corresponding metadata min and scale.`);\n }\n } else if (quantization.dtype === 'float16') {\n if (dtype !== 'float32') {\n throw new Error(\n `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n `which only supports weights of type float32 not ${dtype}.`);\n }\n } else {\n throw new Error(\n `Weight ${spec.name} has unknown ` +\n `quantization dtype ${quantization.dtype}. ` +\n `Supported quantization dtypes are: ` +\n `'uint8', 'uint16', and 'float16'.`);\n }\n const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n const byteBuffer =\n compositeBuffer.slice(offset, offset + size * quantizationSizeFactor);\n const quantizedArray = (quantization.dtype === 'uint8') ?\n new Uint8Array(byteBuffer) :\n new Uint16Array(byteBuffer);\n if (dtype === 'float32') {\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n values = new Float32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = v * quantization.scale + quantization.min;\n }\n } else if (quantization.dtype === 'float16') {\n if (float16Decode === undefined) {\n float16Decode = getFloat16Decoder();\n }\n values = float16Decode(quantizedArray as Uint16Array);\n } else {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type float32.`);\n }\n } else if (dtype === 'int32') {\n if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type int32.`);\n }\n values = new Int32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = Math.round(v * quantization.scale + quantization.min);\n }\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * quantizationSizeFactor;\n } else if (dtype === 'string') {\n const size = sizeFromShape(spec.shape);\n values = [];\n for (let i = 0; i < size; i++) {\n const byteLength = new Uint32Array(\n compositeBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(\n compositeBuffer.slice(offset, offset + byteLength));\n (values as Uint8Array[]).push(bytes);\n offset += byteLength;\n }\n } else {\n const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n const byteBuffer = compositeBuffer.slice(offset,\n offset + size * dtypeFactor);\n\n if (dtype === 'float32') {\n values = new Float32Array(byteBuffer);\n } else if (dtype === 'int32') {\n values = new Int32Array(byteBuffer);\n } else if (dtype === 'bool') {\n values = new Uint8Array(byteBuffer);\n } else if (dtype === 'complex64') {\n values = new Float32Array(byteBuffer);\n const real = new Float32Array(values.length / 2);\n const image = new Float32Array(values.length / 2);\n for (let i = 0; i < real.length; i++) {\n real[i] = values[i * 2];\n image[i] = values[i * 2 + 1];\n }\n const realTensor = tensor(real, shape, 'float32');\n const imageTensor = tensor(image, shape, 'float32');\n out[name] = complex(realTensor, imageTensor);\n realTensor.dispose();\n imageTensor.dispose();\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n if (dtype !== 'complex64') {\n out[name] = tensor(values, shape, dtype);\n }\n }\n return out;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n // TODO(adarob, cais): Support quantization.\n if (xs === null) {\n throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n }\n\n let totalByteLength = 0;\n\n // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n // can have a different byte length from that of the `TypedArray` itself,\n // for example, when the `TypedArray` is created from an offset in an\n // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n // the `TypedArray` in byte length. If an element of `xs` does not show\n // this property, a new `TypedArray` that satisfy this property will be\n // constructed and pushed into `normalizedXs`.\n const normalizedXs: TypedArray[] = [];\n xs.forEach((x: TypedArray) => {\n totalByteLength += x.byteLength;\n // tslint:disable:no-any\n normalizedXs.push(\n x.byteLength === x.buffer.byteLength ? x :\n new (x.constructor as any)(x));\n if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n x as any instanceof Uint8Array)) {\n throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n }\n // tslint:enable:no-any\n });\n\n const y = new Uint8Array(totalByteLength);\n let offset = 0;\n normalizedXs.forEach((x: TypedArray) => {\n y.set(new Uint8Array(x.buffer), offset);\n offset += x.byteLength;\n });\n\n return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n if (useNodeBuffer) {\n return Buffer.byteLength(str, 'utf8');\n }\n return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n if (useNodeBuffer) {\n return Buffer.from(buffer).toString('base64');\n }\n const buf = new Uint8Array(buffer);\n let s = '';\n for (let i = 0, l = buf.length; i < l; i++) {\n s += String.fromCharCode(buf[i]);\n }\n return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n if (useNodeBuffer) {\n const buf = Buffer.from(str, 'base64');\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const s = atob(str);\n const buffer = new Uint8Array(s.length);\n for (let i = 0; i < s.length; ++i) {\n buffer.set([s.charCodeAt(i)], i);\n }\n return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n * ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n *\n * @deprecated Use tf.io.CompositeArrayBuffer.join() instead.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]\n | ArrayBuffer): ArrayBuffer {\n return CompositeArrayBuffer.join(buffers);\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n const SEPARATOR = '/';\n path = path.trim();\n while (path.endsWith(SEPARATOR)) {\n path = path.slice(0, path.length - 1);\n }\n const items = path.split(SEPARATOR);\n return items[items.length - 1];\n}\n\n/**\n * Create `ModelJSON` from `ModelArtifacts`.\n *\n * @param artifacts Model artifacts, describing the model and its weights.\n * @param manifest Weight manifest, describing where the weights of the\n * `ModelArtifacts` are stored, and some metadata about them.\n * @returns Object representing the `model.json` file describing the model\n * artifacts and weights\n */\nexport function getModelJSONForModelArtifacts(\n artifacts: ModelArtifacts, manifest: WeightsManifestConfig): ModelJSON {\n const result: ModelJSON = {\n modelTopology: artifacts.modelTopology,\n format: artifacts.format,\n generatedBy: artifacts.generatedBy,\n convertedBy: artifacts.convertedBy,\n weightsManifest: manifest\n };\n if (artifacts.signature != null) {\n result.signature = artifacts.signature;\n }\n if (artifacts.userDefinedMetadata != null) {\n result.userDefinedMetadata = artifacts.userDefinedMetadata;\n }\n if (artifacts.modelInitializer != null) {\n result.modelInitializer = artifacts.modelInitializer;\n }\n if (artifacts.initializerSignature != null) {\n result.initializerSignature = artifacts.initializerSignature;\n }\n if (artifacts.trainingConfig != null) {\n result.trainingConfig = artifacts.trainingConfig;\n }\n return result;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file and weights.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param weightSpecs The list of WeightsManifestEntry for the model. Must be\n * passed if the modelJSON has a weightsManifest.\n * @param weightData An ArrayBuffer or array of ArrayBuffers of weight data for\n * the model corresponding to the weights in weightSpecs. Must be passed if\n * the modelJSON has a weightsManifest.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport function getModelArtifactsForJSONSync(\n modelJSON: ModelJSON, weightSpecs?: WeightsManifestEntry[],\n weightData?: WeightData): ModelArtifacts {\n\n const modelArtifacts: ModelArtifacts = {\n modelTopology: modelJSON.modelTopology,\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy\n };\n\n if (modelJSON.trainingConfig != null) {\n modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n }\n if (modelJSON.weightsManifest != null) {\n if (!weightSpecs) {\n throw new Error('modelJSON has weightsManifest but weightSpecs is null');\n }\n if (!weightData) {\n throw new Error('modelJSON has weightsManifest but weightData is null');\n }\n modelArtifacts.weightSpecs = weightSpecs;\n modelArtifacts.weightData = weightData;\n }\n if (modelJSON.signature != null) {\n modelArtifacts.signature = modelJSON.signature;\n }\n if (modelJSON.userDefinedMetadata != null) {\n modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n }\n if (modelJSON.modelInitializer != null) {\n modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n }\n if (modelJSON.initializerSignature != null) {\n modelArtifacts.initializerSignature = modelJSON.initializerSignature;\n }\n\n return modelArtifacts;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n * reads weights from the listed path(s), and returns a Promise of the\n * weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n modelJSON: ModelJSON,\n loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n /* weightSpecs */ WeightsManifestEntry[], WeightData,\n ]>): Promise<ModelArtifacts> {\n let weightSpecs: WeightsManifestEntry[] | undefined;\n let weightData: WeightData | undefined;\n\n if (modelJSON.weightsManifest != null) {\n [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);\n }\n\n return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n new CompositeArrayBuffer(modelArtifacts.weightData).byteLength,\n };\n}\n\n/**\n * Concatenate the weights stored in a WeightsManifestConfig into a list of\n * WeightsManifestEntry\n *\n * @param weightsManifest The WeightsManifestConfig to extract weights from.\n * @returns A list of WeightsManifestEntry of the weights in the weightsManifest\n */\nexport function getWeightSpecs(weightsManifest: WeightsManifestConfig):\n WeightsManifestEntry[] {\n const weightSpecs: WeightsManifestEntry[] = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n return weightSpecs;\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise<void> {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise<void>((resolve, reject) => {\n const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n deleteRequest.onsuccess = () => resolve();\n deleteRequest.onerror = error => reject(error);\n });\n}\n\nfunction getIndexedDBFactory(): IDBFactory {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Add more info about what IOHandler subtypes are available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'Failed to obtain IndexedDB factory because the current environment' +\n 'is not a web browser.');\n }\n // tslint:disable-next-line:no-any\n const theWindow: any = typeof window === 'undefined' ? self : window;\n const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n theWindow.shimIndexedDB;\n if (factory == null) {\n throw new Error(\n 'The current browser does not appear to support IndexedDB.');\n }\n return factory;\n}\n\nfunction setUpDatabase(openRequest: IDBRequest) {\n const db = openRequest.result as IDBDatabase;\n db.createObjectStore(MODEL_STORE_NAME, {keyPath: 'modelPath'});\n db.createObjectStore(INFO_STORE_NAME, {keyPath: 'modelPath'});\n}\n\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB implements IOHandler {\n protected readonly indexedDB: IDBFactory;\n protected readonly modelPath: string;\n\n static readonly URL_SCHEME = 'indexeddb://';\n\n constructor(modelPath: string) {\n this.indexedDB = getIndexedDBFactory();\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For IndexedDB, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n // TODO(cais): Support saving GraphDef models.\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n return this.databaseAction(this.modelPath, modelArtifacts) as\n Promise<SaveResult>;\n }\n\n async load(): Promise<ModelArtifacts> {\n return this.databaseAction(this.modelPath) as Promise<ModelArtifacts>;\n }\n\n /**\n * Perform database action to put model artifacts into or read model artifacts\n * from IndexedDB object store.\n *\n * Whether the action is put or get depends on whether `modelArtifacts` is\n * specified. If it is specified, the action will be put; otherwise the action\n * will be get.\n *\n * @param modelPath A unique string path for the model.\n * @param modelArtifacts If specified, it will be the model artifacts to be\n * stored in IndexedDB.\n * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n * of `ModelArtifacts`, if the action is get.\n */\n private databaseAction(modelPath: string, modelArtifacts?: ModelArtifacts):\n Promise<ModelArtifacts|SaveResult> {\n return new Promise<ModelArtifacts|SaveResult>((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n } else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n } else {\n // Put model into object store.\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n let putInfoRequest: IDBRequest<IDBValidKey>;\n try {\n putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n } catch (error) {\n return reject(error);\n }\n let modelTx: IDBTransaction;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n let putModelRequest: IDBRequest<IDBValidKey>;\n try {\n putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n } catch (error) {\n // Sometimes, the serialized value is too large to store.\n return reject(error);\n }\n putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),\n * which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath: string): IOHandler {\n return new BrowserIndexedDB(modelPath);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n key;\n}\n\nexport class BrowserIndexedDBManager implements ModelStoreManager {\n private indexedDB: IDBFactory;\n\n constructor() {\n this.indexedDB = getIndexedDBFactory();\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n return new Promise<{[path: string]: ModelArtifactsInfo}>(\n (resolve, reject) => {\n const openRequest =\n this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n const store = tx.objectStore(INFO_STORE_NAME);\n // tslint:disable:max-line-length\n // Need to cast `store` as `any` here because TypeScript's DOM\n // library does not have the `getAll()` method even though the\n // method is supported in the latest version of most mainstream\n // browsers:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n // tslint:enable:max-line-length\n // tslint:disable-next-line:no-any\n const getAllInfoRequest = (store as any).getAll() as IDBRequest;\n getAllInfoRequest.onsuccess = () => {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n for (const item of getAllInfoRequest.result) {\n out[item.modelPath] = item.modelArtifactsInfo;\n }\n resolve(out);\n };\n getAllInfoRequest.onerror = error => {\n db.close();\n return reject(getAllInfoRequest.error);\n };\n tx.oncomplete = () => db.close();\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n\n async removeModel(path: string): Promise<ModelArtifactsInfo> {\n path = maybeStripScheme(path);\n return new Promise<ModelArtifactsInfo>((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n const getInfoRequest = infoStore.get(path);\n let modelTx: IDBTransaction;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n } else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () =>\n resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error =>\n reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error(\n 'purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths: string[] = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\n\ntype LocalStorageKeys = {\n /** Key of the localStorage entry storing `ModelArtifactsInfo`. */\n info: string,\n /**\n * Key of the localStorage entry storing the 'modelTopology' key of\n * `model.json`\n */\n topology: string,\n /**\n * Key of the localStorage entry storing the `weightsManifest.weights` entries\n * of `model.json`\n */\n weightSpecs: string,\n /** Key of the localStorage entry storing the weight data in Base64 */\n weightData: string,\n /**\n * Key of the localStorage entry storing the remaining fields of `model.json`\n * @see {@link ModelMetadata}\n */\n modelMetadata: string,\n};\n\ntype ModelMetadata = Omit<ModelJSON, 'modelTopology'|'weightsManifest'>;\n\nfunction getModelKeys(path: string): LocalStorageKeys {\n return {\n info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n modelMetadata:\n [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n };\n}\n\nfunction removeItems(keys: LocalStorageKeys): void {\n for (const key of Object.values(keys)) {\n window.localStorage.removeItem(key);\n }\n}\n\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key: string) {\n const items = key.split(PATH_SEPARATOR);\n if (items.length < 3) {\n throw new Error(`Invalid key format: ${key}`);\n }\n return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n key;\n}\n\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage implements IOHandler {\n protected readonly LS: Storage;\n protected readonly modelPath: string;\n protected readonly keys: LocalStorageKeys;\n\n static readonly URL_SCHEME = 'localstorage://';\n\n constructor(modelPath: string) {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n // TODO(cais): Add more info about what IOHandler subtypes are\n // available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'The current environment does not support local storage.');\n }\n this.LS = window.localStorage;\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For local storage, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n this.keys = getModelKeys(this.modelPath);\n }\n\n /**\n * Save model artifacts to browser local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @param modelArtifacts The model artifacts to be stored.\n * @returns An instance of SaveResult.\n */\n async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n\n // TODO(mattsoulanille): Support saving models over 2GB that exceed\n // Chrome's ArrayBuffer size limit.\n const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(\n this.keys.weightData,\n arrayBufferToBase64String(weightBuffer));\n\n // Note that JSON.stringify doesn't write out keys that have undefined\n // values, so for some keys, we set undefined instead of a null-ish\n // value.\n const metadata: Required<ModelMetadata> = {\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n signature: modelArtifacts.signature != null ?\n modelArtifacts.signature :\n undefined,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ?\n modelArtifacts.userDefinedMetadata :\n undefined,\n modelInitializer: modelArtifacts.modelInitializer != null ?\n modelArtifacts.modelInitializer :\n undefined,\n initializerSignature: modelArtifacts.initializerSignature != null ?\n modelArtifacts.initializerSignature :\n undefined,\n trainingConfig: modelArtifacts.trainingConfig != null ?\n modelArtifacts.trainingConfig :\n undefined\n };\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));\n\n return {modelArtifactsInfo};\n } catch (err) {\n // If saving failed, clean up all items saved so far.\n removeItems(this.keys);\n\n throw new Error(\n `Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load(): Promise<ModelArtifacts> {\n const info =\n JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n if (info == null) {\n throw new Error(\n `In local storage, there is no model with name '${this.modelPath}'`);\n }\n\n if (info.modelTopologyType !== 'JSON') {\n throw new Error(\n 'BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n\n const out: ModelArtifacts = {};\n\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(\n `In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(\n `In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString) as ModelMetadata;\n out.format = metadata.format;\n out.generatedBy = metadata.generatedBy;\n out.convertedBy = metadata.convertedBy;\n if (metadata.signature != null) {\n out.signature = metadata.signature;\n }\n if (metadata.userDefinedMetadata != null) {\n out.userDefinedMetadata = metadata.userDefinedMetadata;\n }\n if (metadata.modelInitializer != null) {\n out.modelInitializer = metadata.modelInitializer;\n }\n if (metadata.initializerSignature != null) {\n out.initializerSignature = metadata.initializerSignature;\n }\n if (metadata.trainingConfig != null) {\n out.trainingConfig = metadata.trainingConfig;\n }\n }\n\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(\n `In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n return out;\n }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(\n url.slice(BrowserLocalStorage.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n private readonly LS: Storage;\n\n constructor() {\n assert(\n env().getBool('IS_BROWSER'),\n () => 'Current environment is not a web browser');\n assert(\n typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined',\n () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n }\n }\n return out;\n }\n\n async removeModel(path: string): Promise<ModelArtifactsInfo> {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n removeItems(keys);\n return info;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = ModelStoreManagerRegistry.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(ModelStoreManagerRegistry.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise<ModelArtifactsInfo> {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a registered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise<ModelArtifactsInfo> {\n const schemeAndPath = parseURL(url);\n const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n return manager.removeModel(schemeAndPath.path);\n}\n\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function copyModel(\n sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {\n const deleteSource = false;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function moveModel(\n sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\nimport {isTypedArrayBrowser} from './is_typed_array_browser';\n\nexport class PlatformBrowser implements Platform {\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n private textEncoder: TextEncoder;\n\n // For setTimeoutCustom\n private readonly messageName = 'setTimeoutCustom';\n private functionRefs: Function[] = [];\n private handledMessageCount = 0;\n private hasEventListener = false;\n\n fetch(path: string, init?: RequestInit): Promise<Response> {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n\n // If the setTimeout nesting level is greater than 5 and timeout is less\n // than 4ms, timeout will be clamped to 4ms, which hurts the perf.\n // Interleaving window.postMessage and setTimeout will trick the browser and\n // avoid the clamp.\n setTimeoutCustom(functionRef: Function, delay: number): void {\n if (typeof window === 'undefined' ||\n !env().getBool('USE_SETTIMEOUTCUSTOM')) {\n setTimeout(functionRef, delay);\n return;\n }\n\n this.functionRefs.push(functionRef);\n setTimeout(() => {\n window.postMessage(\n {name: this.messageName, index: this.functionRefs.length - 1}, '*');\n }, delay);\n\n if (!this.hasEventListener) {\n this.hasEventListener = true;\n window.addEventListener('message', (event: MessageEvent) => {\n if (event.source === window && event.data.name === this.messageName) {\n event.stopPropagation();\n const functionRef = this.functionRefs[event.data.index];\n functionRef();\n this.handledMessageCount++;\n if (this.handledMessageCount === this.functionRefs.length) {\n this.functionRefs = [];\n this.handledMessageCount = 0;\n }\n }\n }, true);\n }\n }\n\n isTypedArray(a: unknown): a is Uint8Array | Float32Array | Int32Array\n | Uint8ClampedArray {\n return isTypedArrayBrowser(a);\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise<Response>;\nlet systemFetch: FetchFn;\n// These getters and setters are for testing so we don't export a mutable\n// variable.\nexport function resetSystemFetch() {\n systemFetch = null;\n}\nexport function setSystemFetch(fetchFn: FetchFn) {\n systemFetch = fetchFn;\n}\nexport function getSystemFetch(): FetchFn {\n return systemFetch;\n}\n\nexport class PlatformNode implements Platform {\n private textEncoder: TextEncoder;\n // tslint:disable-next-line:no-any\n util: any;\n\n constructor() {\n // tslint:disable-next-line:no-require-imports\n this.util = require('util');\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n this.textEncoder = new this.util.TextEncoder();\n }\n\n fetch(path: string, requestInits?: RequestInit): Promise<Response> {\n if (env().global.fetch != null) {\n return env().global.fetch(path, requestInits);\n }\n\n if (systemFetch == null) {\n systemFetch = getNodeFetch.importFetch();\n }\n return systemFetch(path, requestInits);\n }\n\n now(): number {\n const time = process.hrtime();\n return time[0] * 1000 + time[1] / 1000000;\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Node built-in encoder only supports utf-8, but got ${encoding}`);\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n if (bytes.length === 0) {\n return '';\n }\n return new this.util.TextDecoder(encoding).decode(bytes);\n }\n isTypedArray(a: unknown): a is Float32Array | Int32Array | Uint8Array\n | Uint8ClampedArray {\n return this.util.types.isFloat32Array(a)\n || this.util.types.isInt32Array(a)\n || this.util.types.isUint8Array(a)\n || this.util.types.isUint8ClampedArray(a);\n }\n}\n\nif (env().get('IS_NODE') && !env().get('IS_BROWSER')) {\n env().setPlatform('node', new PlatformNode());\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer<R extends Rank, D extends DataType = 'float32'>(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer<R, D> {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer<R, D>(shape, dtype, values);\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_<T extends Tensor>(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const cast = /* @__PURE__ */ op({cast_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernel(Identity, inputs as unknown as NamedTensorMap);\n}\n\nexport const clone = /* @__PURE__ */ op({clone_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print<T extends Tensor>(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n env().set('DEPRECATION_WARNINGS_ENABLED', false);\n console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n console.warn(\n msg + ' You can disable deprecation warnings with ' +\n 'tf.disableDeprecationWarnings().');\n }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n * (undisposed) at this time, which is ≤ the number of tensors\n * (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n * data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n * `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n * `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n * this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n * const x = tf.tensor1d([1, 2, 3]);\n * let x2 = x.square();\n * x2.dispose();\n * x2 = x.square();\n * x2.dispose();\n * return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise<TensorContainer>)):\n Promise<ProfileInfo> {\n return ENGINE.profile(f);\n}\n\n/**\n * Executes the provided function `fn` and after it is executed, cleans up all\n * intermediate tensors allocated by `fn` except those returned by `fn`.\n * `fn` must not return a Promise (async functions not allowed). The returned\n * result can be a complex object.\n *\n * Using this method helps avoid memory leaks. In general, wrap calls to\n * operations in `tf.tidy` for automatic memory cleanup.\n *\n * NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to\n * dispose variables, please use `tf.disposeVariables` or call dispose()\n * directly on variables.\n *\n * ```js\n * // y = 2 ^ 2 + 1\n * const y = tf.tidy(() => {\n * // a, b, and one will be cleaned up when the tidy ends.\n * const one = tf.scalar(1);\n * const a = tf.scalar(2);\n * const b = a.square();\n *\n * console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n * // The value returned inside the tidy function will return\n * // through the tidy, in this case to the variable y.\n * return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * y.print();\n * ```\n *\n * @param nameOrFn The name of the closure, or the function to execute.\n * If a name is provided, the 2nd argument should be the function.\n * If debug mode is on, the timing and the memory usage of the function\n * will be tracked and displayed on the console using the provided name.\n * @param fn The function to execute.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function tidy<T extends TensorContainer>(\n nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>): T {\n return ENGINE.tidy(nameOrFn, fn);\n}\n\n/**\n * Disposes any `tf.Tensor`s found within the provided object.\n *\n * @param container an object that may be a `tf.Tensor` or may directly\n * contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If\n * the object is not a `tf.Tensor` or does not contain `Tensors`, nothing\n * happens. In general it is safe to pass any object here, except that\n * `Promise`s are not supported.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function dispose(container: TensorContainer) {\n const tensors = getTensorsInContainer(container);\n tensors.forEach(tensor => tensor.dispose());\n}\n\n/**\n * Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed\n * automatically.\n *\n * ```js\n * let b;\n * const y = tf.tidy(() => {\n * const one = tf.scalar(1);\n * const a = tf.scalar(2);\n *\n * // b will not be cleaned up by the tidy. a and one will be cleaned up\n * // when the tidy ends.\n * b = tf.keep(a.square());\n *\n * console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n * // The value returned inside the tidy function will return\n * // through the tidy, in this case to the variable y.\n * return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * console.log('y:');\n * y.print();\n * console.log('b:');\n * b.print();\n * ```\n *\n * @param result The tensor to keep from being disposed.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function keep<T extends Tensor>(result: T): T {\n return ENGINE.keep(result);\n}\n\n/**\n * Executes `f()` and returns a promise that resolves with timing\n * information.\n *\n * The result is an object with the following properties:\n *\n * - `wallMs`: Wall execution time.\n * - `kernelMs`: Kernel execution time, ignoring data transfer. If using the\n * WebGL backend and the query timer extension is not available, this will\n * return an error object.\n * - On `WebGL` The following additional properties exist:\n * - `uploadWaitMs`: CPU blocking time on texture uploads.\n * - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).\n *\n * ```js\n * const x = tf.randomNormal([20, 20]);\n * const time = await tf.time(() => x.matMul(x));\n *\n * console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);\n * ```\n *\n * @param f The function to execute and time.\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nexport function time(f: () => void): Promise<TimingInfo> {\n return ENGINE.time(f);\n}\n\n/**\n * Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and\n * executing operations on those tensors. Returns a promise that resolves\n * to a boolean if the backend initialization was successful.\n *\n * Note this disposes the current backend, if any, as well as any tensors\n * associated with it. A new backend is initialized, even if it is of the\n * same type as the previous one.\n *\n * @param backendName The name of the backend. Currently supports\n * `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js\n * (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).\n *\n * @doc {heading: 'Backends'}\n */\nexport function setBackend(backendName: string): Promise<boolean> {\n return ENGINE.setBackend(backendName);\n}\n\n/**\n * Returns a promise that resolves when the currently selected backend (or the\n * highest priority one) has initialized. Await this promise when you are using\n * a backend that has async initialization.\n *\n * @doc {heading: 'Backends'}\n */\nexport function ready(): Promise<void> {\n return ENGINE.ready();\n}\n\n/**\n * Returns the current backend name (cpu, webgl, etc). The backend is\n * responsible for creating tensors and executing operations on those tensors.\n *\n * @doc {heading: 'Backends'}\n */\nexport function getBackend(): string {\n return ENGINE.backendName;\n}\n\n/**\n * Removes a backend and the registered factory.\n *\n * @doc {heading: 'Backends'}\n */\nexport function removeBackend(name: string): void {\n ENGINE.removeBackend(name);\n}\n\n/**\n * Finds the backend registered under the provided name. Returns null if the\n * name is not in the registry, or the registration hasn't finished yet.\n */\nexport function findBackend(name: string): KernelBackend {\n return ENGINE.findBackend(name);\n}\n\n/**\n * Finds the backend factory registered under the provided name. Returns a\n * function that produces a new backend when called. Returns null if the name\n * is not in the registry.\n */\nexport function findBackendFactory(name: string): () =>\n KernelBackend | Promise<KernelBackend> {\n return ENGINE.findBackendFactory(name);\n}\n\n/**\n * Registers a global backend. The registration should happen when importing\n * a module file (e.g. when importing `backend_webgl.ts`), and is used for\n * modular builds (e.g. custom tfjs bundle with only webgl support).\n *\n * @param factory The backend factory function. When called, it should\n * return a backend instance, or a promise of an instance.\n * @param priority The priority of the backend (higher = more important).\n * In case multiple backends are registered, the priority is used to find\n * the best backend. Defaults to 1.\n * @return False if there is already a registered backend under this name, true\n * if not.\n *\n * @doc {heading: 'Backends'}\n */\nexport function registerBackend(\n name: string, factory: () => KernelBackend | Promise<KernelBackend>,\n priority = 1): boolean {\n return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n env().setPlatform(platformName, platform);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Add, AddInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print(); // or tf.add(a, b)\n * ```\n *\n * ```js\n * // Broadcast add a with b.\n * const a = tf.scalar(5);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print(); // or tf.add(a, b)\n * ```\n * @param a The first `tf.Tensor` to add.\n * @param b The second `tf.Tensor` to add. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction add_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'add');\n let $b = convertToTensor(b, 'b', 'add');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: AddInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n\nexport const add = /* @__PURE__ */ op({add_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FloorDiv, FloorDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n * The result is rounded with floor function.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.floorDiv(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.floorDiv(b).print(); // or tf.floorDiv(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction floorDiv_<T extends Tensor>(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'floorDiv');\n let $b = convertToTensor(b, 'b', 'floorDiv');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: FloorDivInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(FloorDiv, inputs as unknown as NamedTensorMap);\n}\n\nexport const floorDiv = /* @__PURE__ */ op({floorDiv_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RealDiv, RealDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {floorDiv} from './floorDiv';\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction div_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'div');\n let $b = convertToTensor(b, 'b', 'div');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'int32' && $b.dtype === 'int32') {\n return floorDiv($a, $b);\n }\n\n const inputs: RealDivInputs = {a: $a, b: $b};\n const attrs = {};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(RealDiv,\n inputs as unknown as NamedTensorMap, attrs) as T;\n}\n\nexport const div = /* @__PURE__ */ op({div_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multiply, MultiplyInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.\n *\n * We also expose `tf.mulStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([2, 3, 4, 5]);\n *\n * a.mul(b).print(); // or tf.mul(a, b)\n * ```\n *\n * ```js\n * // Broadcast mul a with b.\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.scalar(5);\n *\n * a.mul(b).print(); // or tf.mul(a, b)\n * ```\n * @param a The first tensor to multiply.\n * @param b The second tensor to multiply. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mul_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'mul');\n let $b = convertToTensor(b, 'b', 'mul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: MultiplyInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Multiply, inputs as unknown as NamedTensorMap);\n}\nexport const mul = /* @__PURE__ */ op({mul_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Abs, AbsInputs, ComplexAbs, ComplexAbsInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes absolute value element-wise: `abs(x)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.abs().print(); // or tf.abs(x)\n * ```\n * @param x The input `tf.Tensor`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction abs_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'abs');\n\n if ($x.dtype === 'complex64') {\n const inputs: ComplexAbsInputs = {x: $x};\n return ENGINE.runKernel(ComplexAbs, inputs as unknown as NamedTensorMap);\n } else {\n const inputs: AbsInputs = {x: $x};\n return ENGINE.runKernel(Abs, inputs as unknown as NamedTensorMap);\n }\n}\n\nexport const abs = /* @__PURE__ */ op({abs_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Fill, FillAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {inferDtype} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\n/**\n * Creates a `tf.Tensor` filled with a scalar value.\n *\n * ```js\n * tf.fill([2, 2], 4).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param value The scalar value to fill the tensor with.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n * 'float32' if the given param value is a number, otherwise 'string'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction fill<R extends Rank>(\n shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor<R> {\n assertNonNegativeIntegerDimensions(shape);\n\n dtype = dtype || inferDtype(value);\n const attrs: FillAttrs = {shape, value, dtype};\n\n return ENGINE.runKernel(Fill, {}, attrs as unknown as NamedAttrMap);\n}\n\nexport {fill};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(\n inShape: number[], outShape: number[]): number[] {\n const inRank = inShape.length;\n const dims: number[] = [];\n for (let i = 0; i < inRank; i++) {\n const dim = inRank - 1 - i;\n const a = inShape[dim] || 1;\n const b = outShape[outShape.length - 1 - i] || 1;\n if (b > 1 && a === 1) {\n dims.unshift(dim);\n }\n }\n return dims;\n}\n\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(\n inShape: number[], outShape: number[]): number[] {\n const result: number[] = [];\n for (let i = 0; i < outShape.length; i++) {\n const inDim = inShape[inShape.length - i - 1];\n const outAxis = outShape.length - i - 1;\n const outDim = outShape[outAxis];\n if (inDim == null || (inDim === 1 && outDim > 1)) {\n result.unshift(outAxis);\n }\n }\n return result;\n}\n\nexport function assertAndGetBroadcastShape(\n shapeA: number[], shapeB: number[]): number[] {\n const l = Math.max(shapeA.length, shapeB.length);\n const result = new Array(l);\n\n for (let i = 0; i < l; i++) {\n let a = shapeA[shapeA.length - i - 1];\n if (a == null) {\n a = 1;\n }\n let b = shapeB[shapeB.length - i - 1];\n if (b == null) {\n b = 1;\n }\n if (a === 1) {\n result[l - i - 1] = b;\n } else if (b === 1) {\n result[l - i - 1] = a;\n } else if (a !== b) {\n const errMsg = `Operands could not be broadcast together with shapes ` +\n `${shapeA} and ${shapeB}.`;\n throw Error(errMsg);\n } else {\n result[l - i - 1] = a;\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ZerosLike, ZerosLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.zerosLike(x).print();\n * ```\n *\n * @param x The tensor of required shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction zerosLike_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'zerosLike');\n const inputs: ZerosLikeInputs = {x: $x};\n return ENGINE.runKernel(ZerosLike, inputs as unknown as NamedTensorMap);\n}\nexport const zerosLike = /* @__PURE__ */ op({zerosLike_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Pow, PowInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the power of one `tf.Tensor` to another. Supports broadcasting.\n *\n * Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for\n * corresponding elements in x and y. The result's dtype will be the upcasted\n * type of the `base` and `exp` dtypes.\n *\n * ```js\n * const a = tf.tensor([[2, 3], [4, 5]])\n * const b = tf.tensor([[1, 2], [3, 0]]).toInt();\n *\n * a.pow(b).print(); // or tf.pow(a, b)\n * ```\n *\n * ```js\n * const a = tf.tensor([[1, 2], [3, 4]])\n * const b = tf.tensor(2).toInt();\n *\n * a.pow(b).print(); // or tf.pow(a, b)\n * ```\n * We also expose `powStrict` which has the same signature as this op and\n * asserts that `base` and `exp` are the same shape (does not broadcast).\n *\n * @param base The base `tf.Tensor` to pow element-wise.\n * @param exp The exponent `tf.Tensor` to pow element-wise.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction pow_<T extends Tensor>(\n base: Tensor|TensorLike, exp: Tensor|TensorLike): T {\n let $base = convertToTensor(base, 'base', 'pow');\n let $exp = convertToTensor(exp, 'exp', 'pow');\n [$base, $exp] = makeTypesMatch($base, $exp);\n\n const inputs: PowInputs = {a: $base, b: $exp};\n\n return ENGINE.runKernel(Pow, inputs as unknown as NamedTensorMap);\n}\n\nexport const pow = /* @__PURE__ */ op({pow_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar} from '../tensor';\nimport {DataType} from '../types';\nimport {isTypedArray} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.scalar` as it makes the code more readable.\n *\n * ```js\n * tf.scalar(3.14).print();\n * ```\n *\n * @param value The value of the scalar.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function scalar(\n value: number|boolean|string|Uint8Array, dtype?: DataType): Scalar {\n if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&\n dtype !== 'complex64') {\n throw new Error(\n 'Error creating a new Scalar: value must be a primitive ' +\n '(number|boolean|string)');\n }\n if (dtype === 'string' && isTypedArray(value) &&\n !(value instanceof Uint8Array)) {\n throw new Error(\n 'When making a scalar from encoded string, ' +\n 'the value must be `Uint8Array`.');\n }\n const shape: number[] = [];\n const inferredShape: number[] = [];\n return makeTensor(value, shape, inferredShape, dtype) as Scalar;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sqrt, SqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.sqrt().print(); // or tf.sqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sqrt_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sqrt', 'float32');\n\n const inputs: SqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Sqrt, inputs as unknown as NamedTensorMap);\n}\nexport const sqrt = /* @__PURE__ */ op({sqrt_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Computes square of `x` element-wise: `x ^ 2`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);\n *\n * x.square().print(); // or tf.square(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction square_<T extends Tensor>(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'square');\n const attrs = {};\n return ENGINE.runKernel('Square', {x: $x}, attrs);\n}\n\nexport const square = /* @__PURE__ */ op({square_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CustomGradientFunc, ENGINE} from './engine';\nimport {Scalar, Tensor, Variable} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {convertToTensor, convertToTensorArray} from './tensor_util_env';\nimport {TensorLike} from './types';\nimport * as util from './util';\n\n/**\n * Provided `f(x)`, returns another function `g(x, dy?)`, which gives the\n * gradient of `f(x)` with respect to `x`.\n *\n * If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to\n * `x` is computed instead. `f(x)` must take a single tensor `x` and return a\n * single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.grad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * g(x).print();\n * ```\n *\n * ```js\n * // f(x) = x ^ 3\n * const f = x => x.pow(tf.scalar(3, 'int32'));\n * // f'(x) = 3x ^ 2\n * const g = tf.grad(f);\n * // f''(x) = 6x\n * const gg = tf.grad(g);\n *\n * const x = tf.tensor1d([2, 3]);\n * gg(x).print();\n * ```\n *\n * @param f The function f(x), to compute gradient for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grad(f: (x: Tensor) => Tensor): (\n x: TensorLike|Tensor, dy?: TensorLike|Tensor) => Tensor {\n util.assert(\n util.isFunction(f), () => 'The f passed in grad(f) must be a function');\n return (x: TensorLike|Tensor, dy?: TensorLike|Tensor): Tensor => {\n // x can be of any dtype, thus null as the last argument.\n const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');\n const $dy: Tensor =\n (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;\n return ENGINE.tidy(() => {\n const {value, grads} = ENGINE.gradients(() => f($x), [$x], $dy);\n if ($dy != null) {\n util.assertShapesMatch(\n value.shape, $dy.shape,\n 'The shape of dy passed in grad(f)(x, dy) must match the shape ' +\n 'returned by f(x)');\n }\n checkGrads(grads);\n return grads[0];\n });\n };\n}\n\n/**\n * Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,\n * which gives an array of gradients of `f()` with respect to each input\n * [`x1`,`x2`,...].\n *\n * If `dy` is passed when calling `g()`, the gradient of\n * `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.\n * The provided `f` must take one or more tensors and return a single tensor\n * `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df / da = b, df / db = a\n * const g = tf.grads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const [da, db] = g([a, b]);\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @param f The function `f(x1, x2,...)` to compute gradients for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grads(f: (...args: Tensor[]) => Tensor): (\n args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike) => Tensor[] {\n util.assert(\n util.isFunction(f), () => 'The f passed in grads(f) must be a function');\n return (args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike): Tensor[] => {\n util.assert(\n Array.isArray(args),\n () => 'The args passed in grads(f)(args) must be an array ' +\n 'of `Tensor`s or `TensorLike`s');\n // args can be of any dtype, thus null as the last argument.\n const $args =\n convertToTensorArray(args, 'args', 'tf.grads', 'string_or_numeric');\n const $dy: Tensor =\n (dy != null) ? convertToTensor(dy, 'dy', 'tf.grads') : null;\n return ENGINE.tidy(() => {\n const {value, grads} = ENGINE.gradients(() => f(...$args), $args, $dy);\n if ($dy != null) {\n util.assertShapesMatch(\n value.shape, $dy.shape,\n 'The shape of dy passed in grads(f)([x1,...], dy) must ' +\n 'match the shape returned by f([x1,...])');\n }\n checkGrads(grads);\n return grads;\n });\n };\n}\n\n/**\n * Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grad: The gradient of `f(x)` w.r.t. `x` (result of `tf.grad`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.valueAndGrad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * const {value, grad} = g(x);\n *\n * console.log('value');\n * value.print();\n * console.log('grad');\n * grad.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrad<I extends Tensor, O extends Tensor>(f: (x: I) => O): (\n x: I, dy?: O) => {\n value: O;\n grad: I;\n} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in valueAndGrad(f) must be a function');\n return (x: I, dy?: O) => {\n util.assert(\n x instanceof Tensor,\n () => 'The x passed in valueAndGrad(f)(x) must be a tensor');\n util.assert(\n dy == null || dy instanceof Tensor,\n () => 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');\n const {grads, value} = ENGINE.gradients(() => f(x), [x], dy);\n checkGrads(grads);\n return {grad: grads[0] as I, value};\n };\n}\n\n/**\n * Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grads: The gradients of `f()` w.r.t. each input (result of `tf.grads`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df/da = b, df/db = a\n * const g = tf.valueAndGrads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const {value, grads} = g([a, b]);\n *\n * const [da, db] = grads;\n *\n * console.log('value');\n * value.print();\n *\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrads<O extends Tensor>(f: (...args: Tensor[]) => O): (\n args: Tensor[], dy?: O) => {\n grads: Tensor[];\n value: O;\n} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in valueAndGrads(f) must be a function');\n return (args: Tensor[], dy?: O) => {\n util.assert(\n Array.isArray(args) && args.every(arg => arg instanceof Tensor),\n () => 'The args passed in valueAndGrads(f)(args) must be array of ' +\n 'tensors');\n util.assert(\n dy == null || dy instanceof Tensor,\n () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');\n const res = ENGINE.gradients(() => f(...args), args, dy);\n if (dy != null) {\n util.assertShapesMatch(\n res.value.shape, dy.shape,\n 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +\n 'match the shape returned by f([x1,...])');\n }\n checkGrads(res.grads);\n return res;\n };\n}\n\n/**\n * Computes and returns the gradient of f(x) with respect to the list of\n * trainable variables provided by `varList`. If no list is provided, it\n * defaults to all trainable variables.\n *\n * ```js\n * const a = tf.variable(tf.tensor1d([3, 4]));\n * const b = tf.variable(tf.tensor1d([5, 6]));\n * const x = tf.tensor1d([1, 2]);\n *\n * // f(a, b) = a * x ^ 2 + b * x\n * const f = () => a.mul(x.square()).add(b.mul(x)).sum();\n * // df/da = x ^ 2, df/db = x\n * const {value, grads} = tf.variableGrads(f);\n *\n * Object.keys(grads).forEach(varName => grads[varName].print());\n * ```\n *\n * @param f The function to execute. f() should return a scalar.\n * @param varList The list of variables to compute the gradients with respect\n * to. Defaults to all trainable variables.\n * @returns An object with the following keys and values:\n * - `value`: The value of the function `f`.\n * - `grads`: A map from the names of the variables to the gradients.\n * If the `varList` argument is provided explicitly and contains a subset of\n * non-trainable variables, this map in the return value will contain keys\n * that map the names of the non-trainable variables to `null`.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction variableGrads(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in variableGrads(f) must be a function');\n util.assert(\n varList == null ||\n Array.isArray(varList) && varList.every(v => v instanceof Variable),\n () =>\n 'The varList passed in variableGrads(f, varList) must be an array ' +\n 'of variables');\n\n const specifiedVarList = varList != null;\n if (!specifiedVarList) {\n // Get all of the trainable variables.\n varList = [];\n for (const varName in ENGINE.registeredVariables) {\n varList.push(ENGINE.registeredVariables[varName]);\n }\n }\n\n const specifiedNonTrainable: Variable[] =\n specifiedVarList ? varList.filter(variable => !variable.trainable) : null;\n\n // Prune non-trainable variables.\n const originalVarCount = varList.length;\n varList = varList.filter(variable => variable.trainable);\n util.assert(\n varList.length > 0,\n () => `variableGrads() expects at least one of the input variables to ` +\n `be trainable, but none of the ${originalVarCount} variables is ` +\n `trainable.`);\n\n const allowNoGradients = true;\n const {value, grads} = ENGINE.gradients(f, varList, null, allowNoGradients);\n\n util.assert(\n grads.some(g => g != null),\n () => 'Cannot find a connection between any variable and the result of ' +\n 'the loss function y=f(x). Please make sure the operations that ' +\n 'use variables are inside the function f passed to minimize().');\n util.assert(\n value.rank === 0,\n () => `The f passed in variableGrads(f) must return a scalar, but it ` +\n `returned a rank-${value.rank} tensor`);\n\n const namedGrads: NamedTensorMap = {};\n varList.forEach((v, i) => {\n if (grads[i] != null) {\n namedGrads[v.name] = grads[i];\n }\n });\n if (specifiedNonTrainable != null) {\n // If varList is explicitly provided and contains non-trainable values,\n // add them to the returned gradients with `null` values.\n specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);\n }\n return {value, grads: namedGrads};\n}\n\n/**\n * Overrides the gradient computation of a function `f`.\n *\n * Takes a function\n * `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`\n * and returns another function `g(...inputs)` which takes the same inputs as\n * `f`. When called, `g` returns `f().value`. In backward mode, custom gradients\n * with respect to each input of `f` are computed using `f().gradFunc`.\n *\n * The `save` function passed to `f` should be used for saving tensors needed\n * in the gradient. And the `saved` passed to the `gradFunc` is a\n * `NamedTensorMap`, which contains those saved tensors.\n *\n * ```js\n * const customOp = tf.customGrad((x, save) => {\n * // Save x to make sure it's available later for the gradient.\n * save([x]);\n * // Override gradient of our custom x ^ 2 op to be dy * abs(x);\n * return {\n * value: x.square(),\n * // Note `saved.x` which points to the `x` we saved earlier.\n * gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]\n * };\n * });\n *\n * const x = tf.tensor1d([-1, -2, 3]);\n * const dx = tf.grad(x => customOp(x));\n *\n * console.log(`f(x):`);\n * customOp(x).print();\n * console.log(`f'(x):`);\n * dx(x).print();\n * ```\n *\n * @param f The function to evaluate in forward mode, which should return\n * `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`\n * returns the custom gradients of `f` with respect to its inputs.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n (...args: Tensor[]) => T {\n return ENGINE.customGrad(f);\n}\n\nfunction checkGrads(grads: Tensor[]) {\n const numNullGradients = grads.filter(g => g == null).length;\n if (numNullGradients > 0) {\n throw new Error(\n `Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.`);\n }\n}\n\nexport {\n customGrad,\n variableGrads,\n valueAndGrad,\n valueAndGrads,\n grad,\n grads,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Sub, SubInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.sub(b).print(); // or tf.sub(a, b)\n * ```\n *\n * ```js\n * // Broadcast subtract a with b.\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.scalar(5);\n *\n * a.sub(b).print(); // or tf.sub(a, b)\n * ```\n * @param a The first `tf.Tensor` to subtract from.\n * @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction sub_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'sub');\n let $b = convertToTensor(b, 'b', 'sub');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: SubInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Sub, inputs as unknown as NamedTensorMap);\n}\n\nexport const sub = /* @__PURE__ */ op({sub_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Maximum, MaximumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the max of a and b (`a > b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `tf.maximumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.maximum(b).print(); // or tf.maximum(a, b)\n * ```\n *\n * ```js\n * // Broadcast maximum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.maximum(b).print(); // or tf.maximum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction maximum_<T extends Tensor>(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'maximum');\n let $b = convertToTensor(b, 'b', 'maximum');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'bool') {\n $a = cast($a, 'int32');\n $b = cast($b, 'int32');\n }\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: MaximumInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Maximum, inputs as unknown as NamedTensorMap);\n}\n\nexport const maximum = /* @__PURE__ */ op({maximum_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from './util';\n\n/**\n * Types to support JSON-esque data structures internally.\n *\n * Internally ConfigDict's use camelCase keys and values where the\n * values are class names to be instantiated. On the python side, these\n * will be snake_case. Internally we allow Enums into the values for better\n * type safety, but these need to be converted to raw primitives (usually\n * strings) for round-tripping with python.\n *\n * toConfig returns the TS-friendly representation. model.toJSON() returns\n * the pythonic version as that's the portable format. If you need to\n * python-ify a non-model level toConfig output, you'll need to use a\n * convertTsToPythonic from serialization_utils in -Layers.\n *\n */\nexport declare type ConfigDictValue =\n boolean | number | string | null | ConfigDictArray | ConfigDict;\nexport declare interface ConfigDict {\n [key: string]: ConfigDictValue;\n}\nexport declare interface ConfigDictArray extends Array<ConfigDictValue> {}\n\n/**\n * Type to represent the class-type of Serializable objects.\n *\n * Ie the class prototype with access to the constructor and any\n * static members/methods. Instance methods are not listed here.\n *\n * Source for this idea: https://stackoverflow.com/a/43607255\n */\nexport declare type SerializableConstructor<T extends Serializable> = {\n // tslint:disable-next-line:no-any\n new (...args: any[]): T; className: string; fromConfig: FromConfigMethod<T>;\n};\nexport declare type FromConfigMethod<T extends Serializable> =\n (cls: SerializableConstructor<T>, config: ConfigDict) => T;\n\n/**\n * Serializable defines the serialization contract.\n *\n * TFJS requires serializable classes to return their className when asked\n * to avoid issues with minification.\n */\nexport abstract class Serializable {\n /**\n * Return the class name for this class to use in serialization contexts.\n *\n * Generally speaking this will be the same thing that constructor.name\n * would have returned. However, the class name needs to be robust\n * against minification for serialization/deserialization to work properly.\n *\n * There's also places such as initializers.VarianceScaling, where\n * implementation details between different languages led to different\n * class hierarchies and a non-leaf node is used for serialization purposes.\n */\n getClassName(): string {\n return (this.constructor as SerializableConstructor<Serializable>)\n .className;\n }\n\n /**\n * Return all the non-weight state needed to serialize this object.\n */\n abstract getConfig(): ConfigDict;\n\n /**\n * Creates an instance of T from a ConfigDict.\n *\n * This works for most descendants of serializable. A few need to\n * provide special handling.\n * @param cls A Constructor for the class to instantiate.\n * @param config The Configuration for the object.\n */\n /** @nocollapse */\n static fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config);\n }\n}\n\n/**\n * Maps string keys to class constructors.\n *\n * Used during (de)serialization from the cross-language JSON format, which\n * requires the class name in the serialization format matches the class\n * names as used in Python, should it exist.\n */\nexport class SerializationMap {\n private static instance: SerializationMap;\n classNameMap: {\n [className: string]:\n [SerializableConstructor<Serializable>, FromConfigMethod<Serializable>]\n };\n\n private constructor() {\n this.classNameMap = {};\n }\n\n /**\n * Returns the singleton instance of the map.\n */\n static getMap(): SerializationMap {\n if (SerializationMap.instance == null) {\n SerializationMap.instance = new SerializationMap();\n }\n return SerializationMap.instance;\n }\n\n /**\n * Registers the class as serializable.\n */\n static register<T extends Serializable>(cls: SerializableConstructor<T>) {\n SerializationMap.getMap().classNameMap[cls.className] =\n [cls, cls.fromConfig];\n }\n}\n\n/**\n * Register a class with the serialization map of TensorFlow.js.\n *\n * This is often used for registering custom Layers, so they can be\n * serialized and deserialized.\n *\n * Example:\n *\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n * static className = 'MyCustomLayer';\n *\n * constructor(config) {\n * super(config);\n * }\n * }\n * tf.serialization.registerClass(MyCustomLayer);\n * ```\n *\n * @param cls The class to be registered. It must have a public static member\n * called `className` defined and the value must be a non-empty string.\n *\n * @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true}\n */\nexport function registerClass<T extends Serializable>(\n cls: SerializableConstructor<T>) {\n assert(\n cls.className != null,\n () => `Class being registered does not have the static className ` +\n `property defined.`);\n assert(\n typeof cls.className === 'string',\n () => `className is required to be a string, but got type ` +\n typeof cls.className);\n assert(\n cls.className.length > 0,\n () => `Class being registered has an empty-string as its className, ` +\n `which is disallowed.`);\n\n SerializationMap.register(cls);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {dispose} from '../globals';\nimport {variableGrads} from '../gradients';\nimport {scalar} from '../ops/ops';\nimport {Serializable} from '../serialization';\nimport {Scalar, Variable} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\n/**\n * A variable that belongs to an optimizer.\n *\n * The `originalName` field is required for keeping track of the canonical\n * name of the variable, which is usually the name of the model weight that\n * the variable is related to plus a suffix, e.g., 'dense1/kernel/momentum'.\n * The name of the `Variable` object itself cannot be used directly due to\n * possible deduplication: Every `Variable` must have a unique name but more\n * than one optimizer objects of the same type may be created for the same model\n * or the same `Variable`.\n */\nexport interface OptimizerVariable {\n originalName: string;\n variable: Variable;\n}\n\n/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */\nexport abstract class Optimizer extends Serializable {\n protected iterations_: number;\n\n /**\n * Executes `f()` and minimizes the scalar output of `f()` by computing\n * gradients of y with respect to the list of trainable variables provided by\n * `varList`. If no list is provided, it defaults to all trainable variables.\n *\n * @param f The function to execute and whose output to minimize.\n * @param returnCost Whether to return the scalar cost value produced by\n * executing `f()`.\n * @param varList An optional list of variables to update. If specified, only\n * the trainable variables in varList will be updated by minimize. Defaults to\n * all trainable variables.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n minimize(f: () => Scalar, returnCost = false, varList?: Variable[]): Scalar\n |null {\n const {value, grads} = this.computeGradients(f, varList);\n\n if (varList != null) {\n const gradArray: NamedTensor[] =\n varList.map(v => ({name: v.name, tensor: grads[v.name]}));\n this.applyGradients(gradArray);\n } else {\n this.applyGradients(grads);\n }\n\n // Dispose gradients.\n dispose(grads);\n\n if (returnCost) {\n return value;\n } else {\n value.dispose();\n return null;\n }\n }\n\n /**\n * The number of iterations that this optimizer instance has been invoked for.\n */\n get iterations(): number {\n if (this.iterations_ == null) {\n this.iterations_ = 0;\n }\n return this.iterations_;\n }\n\n protected incrementIterations() {\n this.iterations_ = this.iterations + 1;\n }\n\n /**\n * Executes f() and computes the gradient of the scalar output of f() with\n * respect to the list of trainable variables provided by `varList`. If no\n * list is provided, it defaults to all trainable variables.\n *\n * @param f The function to execute and whose output to use for computing\n * gradients with respect to variables.\n * @param varList An optional list of variables to compute gradients with\n * respect to. If specified, only the trainable variables in varList will have\n * gradients computed with respect to. Defaults to all trainable variables.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n computeGradients(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n return variableGrads(f, varList);\n }\n\n /**\n * Updates variables by using the computed gradients.\n *\n * @param variableGradients A mapping of variable name to its gradient value.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n abstract applyGradients(variableGradients: NamedTensorMap|\n NamedTensor[]): void;\n\n /**\n * Dispose the variables (if any) owned by this optimizer instance.\n */\n dispose(): void {\n if (this.iterations_ != null) {\n dispose(this.iterations_);\n }\n }\n\n async saveIterations(): Promise<NamedTensor> {\n if (this.iterations_ == null) {\n this.iterations_ = 0;\n }\n return {\n name: 'iter', // Named for Python compatibility.\n // TODO(cais): Use 'int64' type when available.\n tensor: scalar(this.iterations_, 'int32')\n };\n }\n\n async getWeights(): Promise<NamedTensor[]> {\n throw new Error('getWeights() is not implemented for this optimizer yet.');\n }\n\n async setWeights(weightValues: NamedTensor[]): Promise<void> {\n throw new Error(\n `setWeights() is not implemented for this optimizer class ` +\n `${this.getClassName()}`);\n }\n\n /**\n * Extract the first element of the weight values and set it\n * as the iterations counter variable of this instance of optimizer.\n *\n * @param weightValues\n * @returns Weight values with the first element consumed and excluded.\n */\n protected async extractIterations(weightValues: NamedTensor[]):\n Promise<NamedTensor[]> {\n this.iterations_ = (await weightValues[0].tensor.data())[0];\n return weightValues.slice(1);\n }\n}\n\nObject.defineProperty(Optimizer, Symbol.hasInstance, {\n value: (instance: Optimizer) => {\n return instance.minimize != null && instance.computeGradients != null &&\n instance.applyGradients != null;\n }\n});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/ops';\nimport {square} from '../ops/square';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdadeltaOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adadelta';\n }\n private accumulatedGrads: OptimizerVariable[] = [];\n private accumulatedUpdates: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected rho: number,\n protected epsilon: number = null) {\n super();\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedGrads[i] == null) {\n this.accumulatedGrads[i] = {\n originalName: `${name}/accum_grad`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedUpdates[i] == null) {\n this.accumulatedUpdates[i] = {\n originalName: `${name}/accum_var`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedGrad = this.accumulatedGrads[i].variable;\n const accumulatedUpdate = this.accumulatedUpdates[i].variable;\n\n tidy(() => {\n const newAccumulatedGrad =\n add(mul(accumulatedGrad, this.rho),\n mul(square(gradient), 1 - this.rho));\n\n const updates =\n mul(div(sqrt(add(accumulatedUpdate, this.epsilon)),\n sqrt(add(accumulatedGrad, this.epsilon))),\n gradient);\n\n const newAccumulatedUpdate =\n add(mul(accumulatedUpdate, this.rho),\n mul(square(updates), 1 - this.rho));\n\n accumulatedGrad.assign(newAccumulatedGrad);\n accumulatedUpdate.assign(newAccumulatedUpdate);\n\n const newValue = add(mul(updates, -this.learningRate), value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedUpdates != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n dispose(this.accumulatedUpdates.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedGrads, ...this.accumulatedUpdates];\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const variableCount = weightValues.length / 2;\n const trainable = false;\n this.accumulatedGrads =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedUpdates =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'rho': this.rho,\n 'epsilon': this.epsilon\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate'], config['rho'], config['epsilon']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {fill} from '../ops/fill';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdagradOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adagrad';\n }\n\n private accumulatedGrads: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, private initialAccumulatorValue = 0.1) {\n super();\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n if (this.accumulatedGrads[i] == null) {\n const trainable = false;\n this.accumulatedGrads[i] = {\n originalName: `${name}/accumulator`,\n variable: tidy(\n () => fill(value.shape, this.initialAccumulatorValue)\n .variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedGrad = this.accumulatedGrads[i].variable;\n\n tidy(() => {\n const newAccumulatedGrad = add(accumulatedGrad, square(gradient));\n accumulatedGrad.assign(newAccumulatedGrad);\n\n const newValue = add(\n mul(div(gradient,\n sqrt(add(newAccumulatedGrad, ENGINE.backend.epsilon()))),\n -this.learningRate),\n value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedGrads != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n return [await this.saveIterations()].concat(this.accumulatedGrads.map(\n v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const trainable = false;\n this.accumulatedGrads = weightValues.map(\n v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'initialAccumulatorValue': this.initialAccumulatorValue,\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate'], config['initialAccumulatorValue']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {pow} from '../ops/pow';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adam';\n }\n private accBeta1: Variable;\n private accBeta2: Variable;\n\n private accumulatedFirstMoment: OptimizerVariable[] = [];\n private accumulatedSecondMoment: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected beta1: number,\n protected beta2: number, protected epsilon: number = null) {\n super();\n tidy(() => {\n // accB* will be updated by batch.\n this.accBeta1 = scalar(beta1).variable();\n this.accBeta2 = scalar(beta2).variable();\n });\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const varNames = Array.isArray(variableGradients) ?\n variableGradients.map(v => v.name) :\n Object.keys(variableGradients);\n tidy(() => {\n const oneMinusAccBeta1 = sub(1, this.accBeta1);\n const oneMinusAccBeta2 = sub(1, this.accBeta2);\n\n varNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedFirstMoment[i] == null) {\n this.accumulatedFirstMoment[i] = {\n originalName: `${name}/m`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedSecondMoment[i] == null) {\n this.accumulatedSecondMoment[i] = {\n originalName: `${name}/v`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const firstMoment = this.accumulatedFirstMoment[i].variable;\n const secondMoment = this.accumulatedSecondMoment[i].variable;\n\n const newFirstMoment =\n add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n const newSecondMoment =\n add(mul(secondMoment, this.beta2),\n mul(square(gradient), 1 - this.beta2));\n\n const biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);\n const biasCorrectedSecondMoment =\n div(newSecondMoment, oneMinusAccBeta2);\n\n firstMoment.assign(newFirstMoment);\n secondMoment.assign(newSecondMoment);\n\n const newValue =\n add(mul(div(biasCorrectedFirstMoment,\n add(sqrt(biasCorrectedSecondMoment), this.epsilon)),\n -this.learningRate),\n value);\n value.assign(newValue);\n });\n\n this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n this.accBeta2.assign(mul(this.accBeta2, this.beta2));\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.accBeta1.dispose();\n this.accBeta2.dispose();\n\n if (this.accumulatedFirstMoment != null) {\n dispose(this.accumulatedFirstMoment.map(v => v.variable));\n }\n if (this.accumulatedSecondMoment != null) {\n dispose(this.accumulatedSecondMoment.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n tidy(() => {\n this.accBeta1.assign(pow(this.beta1, this.iterations_ + 1));\n this.accBeta2.assign(pow(this.beta2, this.iterations_ + 1));\n });\n\n const variableCount = weightValues.length / 2;\n const trainable = false;\n this.accumulatedFirstMoment =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedSecondMoment =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'beta1': this.beta1,\n 'beta2': this.beta2,\n 'epsilon': this.epsilon,\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['beta1'], config['beta2'],\n config['epsilon']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {abs} from '../ops/abs';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {maximum} from '../ops/maximum';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamaxOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adamax';\n }\n private accBeta1: Variable;\n private iteration: Variable;\n\n private accumulatedFirstMoment: OptimizerVariable[] = [];\n private accumulatedWeightedInfNorm: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected beta1: number,\n protected beta2: number, protected epsilon: number = null,\n protected decay = 0.0) {\n super();\n\n tidy(() => {\n this.iteration = scalar(0).variable();\n this.accBeta1 = scalar(beta1).variable();\n });\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n tidy(() => {\n const oneMinusAccBeta1 = sub(1, this.accBeta1);\n const lr =\n div(-this.learningRate, add(mul(this.iteration, this.decay), 1));\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedFirstMoment[i] == null) {\n this.accumulatedFirstMoment[i] = {\n originalName: `${name}/m`,\n variable: zerosLike(value).variable(trainable)\n };\n }\n if (this.accumulatedWeightedInfNorm[i] == null) {\n this.accumulatedWeightedInfNorm[i] = {\n originalName: `${name}/v`,\n variable: zerosLike(value).variable(trainable)\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const firstMoment = this.accumulatedFirstMoment[i].variable;\n const weightedInfNorm = this.accumulatedWeightedInfNorm[i].variable;\n\n const newFirstMoment =\n add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n\n const ut0 = mul(weightedInfNorm, this.beta2);\n const ut1 = abs(gradient);\n\n const newWeightedInfNorm = maximum(ut0, ut1);\n\n firstMoment.assign(newFirstMoment);\n weightedInfNorm.assign(newWeightedInfNorm);\n\n const newValue =\n add(mul(div(lr, oneMinusAccBeta1),\n div(newFirstMoment, add(newWeightedInfNorm, this.epsilon))),\n value);\n\n value.assign(newValue);\n });\n\n this.iteration.assign(add(this.iteration, 1));\n this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.accBeta1.dispose();\n this.iteration.dispose();\n\n if (this.accumulatedFirstMoment != null) {\n dispose(this.accumulatedFirstMoment.map(v => v.variable));\n }\n if (this.accumulatedWeightedInfNorm != null) {\n dispose(this.accumulatedWeightedInfNorm.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n throw new Error('getWeights() is not implemented for Adamax yet.');\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n throw new Error('setWeights() is not implemented for Adamax yet.');\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'beta1': this.beta1,\n 'beta2': this.beta2,\n 'epsilon': this.epsilon,\n 'decay': this.decay\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['beta1'], config['beta2'],\n config['epsilon'], config['decay']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {keep, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer} from './optimizer';\n\n/** @doclink Optimizer */\nexport class SGDOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'SGD';\n }\n protected c: Scalar;\n\n constructor(protected learningRate: number) {\n super();\n this.setLearningRate(learningRate);\n }\n\n applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n const varNames = Array.isArray(variableGradients) ?\n variableGradients.map(v => v.name) :\n Object.keys(variableGradients);\n varNames.forEach((name, i) => {\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n const value = ENGINE.registeredVariables[name];\n tidy(() => {\n const newValue = add(mul(this.c, gradient), value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n /**\n * Sets the learning rate of the optimizer.\n */\n setLearningRate(learningRate: number) {\n this.learningRate = learningRate;\n if (this.c != null) {\n this.c.dispose();\n }\n this.c = keep(scalar(-learningRate));\n }\n\n override dispose() {\n this.c.dispose();\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n return [await this.saveIterations()];\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n if (weightValues.length !== 0) {\n throw new Error('SGD optimizer does not have settable weights.');\n }\n }\n\n getConfig(): ConfigDict {\n return {'learningRate': this.learningRate};\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {OptimizerVariable} from './optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\n\n/** @doclink Optimizer */\nexport class MomentumOptimizer extends SGDOptimizer {\n /** @nocollapse */\n // Name matters for Python compatibility.\n static override get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Momentum';\n }\n private m: Scalar;\n private accumulations: OptimizerVariable[] = [];\n\n constructor(\n protected override learningRate: number, private momentum: number,\n private useNesterov = false) {\n super(learningRate);\n this.m = scalar(this.momentum);\n }\n\n override applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n if (this.accumulations[i] == null) {\n const trainable = false;\n this.accumulations[i] = {\n originalName: `${name}/momentum`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const accumulation = this.accumulations[i].variable;\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n tidy(() => {\n let newValue: Tensor;\n const newAccumulation = add(mul(this.m, accumulation), gradient);\n if (this.useNesterov) {\n newValue = add(\n mul(this.c, add(gradient, mul(newAccumulation, this.m))), value);\n } else {\n newValue = add(mul(this.c, newAccumulation), value);\n }\n accumulation.assign(newAccumulation);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.m.dispose();\n if (this.accumulations != null) {\n dispose(this.accumulations.map(v => v.variable));\n }\n }\n\n /**\n * Sets the momentum of the optimizer.\n *\n * @param momentum\n */\n setMomentum(momentum: number) {\n this.momentum = momentum;\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n return [await this.saveIterations()].concat(this.accumulations.map(\n v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const trainable = false;\n this.accumulations = weightValues.map(\n v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n }\n\n override getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'momentum': this.momentum,\n 'useNesterov': this.useNesterov\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['momentum'], config['useNesterov']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class RMSPropOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'RMSProp';\n }\n private centered: boolean;\n\n private accumulatedMeanSquares: OptimizerVariable[] = [];\n private accumulatedMoments: OptimizerVariable[] = [];\n private accumulatedMeanGrads: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected decay = 0.9,\n protected momentum = 0.0, protected epsilon: number = null,\n centered = false) {\n super();\n\n this.centered = centered;\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n if (learningRate == null) {\n throw new Error(`learningRate for RMSPropOptimizer must be defined.`);\n }\n }\n\n applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedMeanSquares[i] == null) {\n this.accumulatedMeanSquares[i] = {\n originalName: `${name}/rms`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedMoments[i] == null) {\n this.accumulatedMoments[i] = {\n originalName: `${name}/momentum`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedMeanGrads[i] == null && this.centered) {\n this.accumulatedMeanGrads[i] = {\n originalName: `${name}/mg`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedMeanSquare = this.accumulatedMeanSquares[i].variable;\n const accumulatedMoments = this.accumulatedMoments[i].variable;\n tidy(() => {\n const newAccumulatedMeanSquare =\n add(mul(accumulatedMeanSquare, this.decay),\n mul(square(gradient), 1 - this.decay));\n\n if (this.centered) {\n const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;\n // Centered gradient\n const newAccumulatedMeanGrad =\n add(mul(accumulatedMeanGrad, this.decay),\n mul(gradient, 1 - this.decay));\n\n const gradContribution =\n div(mul(gradient, this.learningRate),\n sqrt(\n sub(newAccumulatedMeanSquare,\n add(square(newAccumulatedMeanGrad), this.epsilon))));\n const newAccumulatedMoments =\n add(mul(accumulatedMoments, this.momentum), gradContribution);\n\n accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n accumulatedMeanGrad.assign(newAccumulatedMeanGrad);\n accumulatedMoments.assign(newAccumulatedMoments);\n\n const newValue = sub(value, newAccumulatedMoments);\n value.assign(newValue);\n } else {\n // Plain gradient\n const newAccumulatedMeanSquare =\n add(mul(accumulatedMeanSquare, this.decay),\n mul(square(gradient), 1 - this.decay));\n\n const newAccumulatedMoments =\n add(mul(accumulatedMoments, this.momentum),\n div(mul(gradient, this.learningRate),\n sqrt(add(newAccumulatedMeanSquare, this.epsilon))));\n\n accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n accumulatedMoments.assign(newAccumulatedMoments);\n\n const newValue = sub(value, newAccumulatedMoments);\n value.assign(newValue);\n }\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedMeanSquares != null) {\n dispose(this.accumulatedMeanSquares.map(v => v.variable));\n }\n if (this.accumulatedMeanGrads != null && this.centered) {\n dispose(this.accumulatedMeanGrads.map(v => v.variable));\n }\n if (this.accumulatedMoments != null) {\n dispose(this.accumulatedMoments.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise<NamedTensor[]> {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedMeanSquares, ...this.accumulatedMoments];\n if (this.centered) {\n variables.push(...this.accumulatedMeanGrads);\n }\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n weightValues = await this.extractIterations(weightValues);\n const variableCount =\n this.centered ? weightValues.length / 3 : weightValues.length / 2;\n const trainable = false;\n this.accumulatedMeanSquares =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedMoments =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n if (this.centered) {\n this.accumulatedMeanGrads =\n weightValues.slice(variableCount * 2, variableCount * 3)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'decay': this.decay,\n 'momentum': this.momentum,\n 'epsilon': this.epsilon,\n 'centered': this.centered\n };\n }\n\n /** @nocollapse */\n static override fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['decay'], config['momentum'],\n config['epsilon'], config['centered']);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AdadeltaOptimizer} from './adadelta_optimizer';\nimport {AdagradOptimizer} from './adagrad_optimizer';\nimport {AdamOptimizer} from './adam_optimizer';\nimport {AdamaxOptimizer} from './adamax_optimizer';\nimport {MomentumOptimizer} from './momentum_optimizer';\nimport {RMSPropOptimizer} from './rmsprop_optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\nimport {registerClass} from '../serialization';\n\nconst OPTIMIZERS = [\n AdadeltaOptimizer,\n AdagradOptimizer,\n AdamOptimizer,\n AdamaxOptimizer,\n MomentumOptimizer,\n RMSPropOptimizer,\n SGDOptimizer,\n];\n\nexport function registerOptimizers() {\n for (const optimizer of OPTIMIZERS) {\n registerClass(optimizer);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code.\nimport './base_side_effects';\n\n// TODO(mattSoulanille): Move this to base_side_effects.ts\n// It is here for now because custom bundles need to avoid calling it, and they\n// only replace the index.js file, not the base_side_effects file.\nimport {registerOptimizers} from './optimizers/register_optimizers';\nregisterOptimizers();\n\n// All exports from this package should be in base.\nexport * from './base';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nconst contexts: {[key: string]: WebGLRenderingContext} = {};\n\nconst WEBGL_ATTRIBUTES: WebGLContextAttributes = {\n alpha: false,\n antialias: false,\n premultipliedAlpha: false,\n preserveDrawingBuffer: false,\n depth: false,\n stencil: false,\n failIfMajorPerformanceCaveat: true\n};\n\nexport function clearWebGLContext(webGLVersion: number) {\n delete contexts[webGLVersion];\n}\n\nexport function setWebGLContext(\n webGLVersion: number, gl: WebGLRenderingContext) {\n contexts[webGLVersion] = gl;\n}\n\nexport function getWebGLContext(\n webGLVersion: number,\n customCanvas?: HTMLCanvasElement|OffscreenCanvas): WebGLRenderingContext {\n if (!(webGLVersion in contexts) || customCanvas != null) {\n const newCtx = getWebGLRenderingContext(webGLVersion, customCanvas);\n if (newCtx !== null) {\n contexts[webGLVersion] = newCtx;\n } else {\n console.log('Could not get context for WebGL version', webGLVersion);\n return null;\n }\n }\n const gl = contexts[webGLVersion];\n if (gl == null || gl.isContextLost()) {\n delete contexts[webGLVersion];\n return getWebGLContext(webGLVersion);\n }\n\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.STENCIL_TEST);\n gl.disable(gl.BLEND);\n gl.disable(gl.DITHER);\n gl.disable(gl.POLYGON_OFFSET_FILL);\n gl.disable(gl.SAMPLE_COVERAGE);\n gl.enable(gl.SCISSOR_TEST);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n\n return contexts[webGLVersion];\n}\n\nfunction createCanvas(webGLVersion: number) {\n // Use canvas element for Safari, since its offscreen canvas does not support\n // fencing.\n if (!env().getBool('IS_SAFARI') && typeof OffscreenCanvas !== 'undefined' &&\n webGLVersion === 2) {\n return new OffscreenCanvas(300, 150);\n } else if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n } else {\n throw new Error('Cannot create a canvas in this context');\n }\n}\n\nfunction getWebGLRenderingContext(\n webGLVersion: number,\n customCanvas?: HTMLCanvasElement|OffscreenCanvas): WebGLRenderingContext {\n if (webGLVersion !== 1 && webGLVersion !== 2) {\n throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');\n }\n const canvas =\n customCanvas == null ? createCanvas(webGLVersion) : customCanvas;\n\n canvas.addEventListener('webglcontextlost', (ev: Event) => {\n ev.preventDefault();\n delete contexts[webGLVersion];\n }, false);\n\n if (env().getBool('SOFTWARE_WEBGL_ENABLED')) {\n WEBGL_ATTRIBUTES.failIfMajorPerformanceCaveat = false;\n }\n\n if (webGLVersion === 1) {\n return (\n canvas.getContext('webgl', WEBGL_ATTRIBUTES) ||\n (canvas as HTMLCanvasElement)\n .getContext('experimental-webgl', WEBGL_ATTRIBUTES));\n }\n return canvas.getContext('webgl2', WEBGL_ATTRIBUTES) as WebGLRenderingContext;\n}\n","export const DEFAULT_CDN_URL = 'https://websdk-cdn-dev.idmission.com/assets'\n","export type Frame =\n | ImageBitmap\n | HTMLVideoElement\n | HTMLImageElement\n | HTMLCanvasElement\n\nexport function getFrameDimensions(frame: Frame): [number, number] {\n let frameWidth = frame.width,\n frameHeight = frame.height\n\n if (frame instanceof HTMLVideoElement) {\n frameWidth = frame.videoWidth\n frameHeight = frame.videoHeight\n }\n\n return [frameWidth, frameHeight]\n}\n","import styled from 'styled-components'\nimport { Frame, getFrameDimensions } from '../../lib/utils/getFrameDimensions'\n\nexport const InvisibleCanvas = styled.canvas`\n display: none;\n`\n\nexport function drawToCanvas(\n canvas: HTMLCanvasElement | null,\n frame: Frame,\n width?: number,\n height?: number,\n): void {\n if (!canvas) return\n const ctx = canvas.getContext('2d')\n if (!ctx) return\n if (!width || !height) {\n const [frameWidth, frameHeight] = getFrameDimensions(frame)\n width ||= frameWidth\n height ||= frameHeight\n }\n canvas.width = width\n canvas.height = height\n ctx.drawImage(frame, 0, 0, width, height)\n}\n\nexport function clearCanvas(canvas: HTMLCanvasElement | null) {\n if (!canvas) return\n const ctx = canvas.getContext('2d')\n if (!ctx) return\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n}\n","import { Face } from '@tensorflow-models/face-detection'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport { Frame, getFrameDimensions } from './getFrameDimensions'\nimport { clearCanvas } from '../../components/common/InvisibleCanvas'\n\nexport function cropToShoulders(\n rawCanvas: HTMLCanvasElement | null,\n cropCanvas: HTMLCanvasElement | null,\n frame: ImageData,\n face: Face,\n): string {\n if (!rawCanvas || !cropCanvas) return ''\n\n const rawCtx = rawCanvas.getContext('2d')\n const cropCtx = cropCanvas.getContext('2d')\n if (!rawCtx || !cropCtx) throw new Error('could not get 2d context')\n\n rawCanvas.width = frame.width\n rawCanvas.height = frame.height\n rawCtx.putImageData(frame, 0, 0)\n\n const { xMin, width } = face.box\n const frameHeight = frame.height\n const xPadding = frameHeight * 0.6 - width\n const xPos = Math.max(0, xMin - xPadding / 2)\n if (isMobile()) {\n cropCanvas.width = frame.width\n cropCanvas.height = frame.height\n cropCtx.drawImage(rawCanvas, 0, 0, cropCanvas.width, cropCanvas.height)\n } else {\n cropCanvas.width = width + xPadding\n cropCanvas.height = frame.height\n cropCtx.drawImage(\n rawCanvas,\n xPos,\n 0,\n cropCanvas.width,\n cropCanvas.height,\n 0,\n 0,\n cropCanvas.width,\n cropCanvas.height,\n )\n }\n\n const dataURL = cropCanvas.toDataURL('image/jpeg', 0.92)\n\n clearCanvas(rawCanvas)\n clearCanvas(cropCanvas)\n\n return dataURL\n}\n\nexport function cropToBoundingBox(\n frame: Frame,\n bbox: number[],\n): HTMLCanvasElement {\n const canvas = document.createElement('canvas')\n const ctx = canvas.getContext('2d')\n if (!ctx) throw new Error('could not get 2d context')\n\n const [frameWidth, frameHeight] = getFrameDimensions(frame)\n const [xMin, yMin, width, height] = bbox\n canvas.width = width * frameWidth\n canvas.height = height * frameHeight\n ctx.drawImage(\n frame,\n xMin * frameWidth,\n yMin * frameHeight,\n width * frameWidth,\n height * frameHeight,\n 0,\n 0,\n width * frameWidth,\n height * frameHeight,\n )\n return canvas\n}\n","import React, {\n createContext,\n MutableRefObject,\n ReactElement,\n ReactNode,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport * as tf from '@tensorflow/tfjs'\nimport { setWebGLContext } from '@tensorflow/tfjs'\nimport {\n bboxToDetectedObjectUnscaled,\n DetectedObject,\n documentDetectionModel,\n DocumentType,\n loadDocumentDetectionModel,\n RawEdgeDetectionResult,\n unloadDocumentDetectionModel,\n} from '../../lib/models/DocumentDetection'\nimport {\n focusModel,\n FocusPrediction,\n loadFocusModel,\n unloadFocusModel,\n} from '../../lib/models/Focus'\nimport {\n clearWebGLContext,\n getWebGLContext,\n} from '@tensorflow/tfjs-backend-webgl/dist/canvas_util'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { Frame, getFrameDimensions } from '../../lib/utils/getFrameDimensions'\nimport { cropToBoundingBox } from '../../lib/utils/cropping'\nimport {\n clearCanvas,\n drawToCanvas,\n InvisibleCanvas,\n} from '../common/InvisibleCanvas'\n\nexport type IdCapturePrediction = {\n detectedObjects: DetectedObject[]\n detectionTime: number\n detectionScore: number\n detectionThresholdMet: boolean\n detectedDocumentType: DocumentType\n\n passportDetectionScore: number\n passportDetectionThresholdMet: boolean\n\n mrzDetectionScore: number\n mrzDetectionThresholdMet: boolean\n\n pdf417DetectionScore: number\n pdf417DetectionThresholdMet: boolean\n\n bestDocumentOrPassport: DetectedObject | undefined\n bestMrz: DetectedObject | undefined\n bestPdf417: DetectedObject | undefined\n\n focusScore: number\n focusThresholdMet: boolean\n focusPredictionTime: number\n\n frameWidth: number\n frameHeight: number\n\n allZero: boolean\n}\n\nexport type IdCaptureThresholds = {\n document?: number\n passport?: number\n mrz?: number\n pdf417?: number\n focus?: number\n}\n\nconst PRERESIZE = false\n// export const PREDICTION_POSITIONS = { boxes: 1, scores: 4, labels: 2 } // for docdetectuint8\nexport const PREDICTION_POSITIONS = { boxes: 0, scores: 7, labels: 4 } // for documentdetectionquantized\n// export const PREDICTION_POSITIONS = { boxes: 2, scores: 6, labels: 4 } // for documentdetection\n// export const PREDICTION_POSITIONS = { boxes: 5, scores: 4, labels: 1 } // for edgeDetection\n\nexport type IdCaptureModelsState = {\n ready: boolean\n working: MutableRefObject<boolean>\n error: Error | null\n\n thresholds: IdCaptureThresholds\n setThresholds: (value: IdCaptureThresholds) => void\n\n makePrediction: (frame: Frame) => void\n onPredictionMade: (handler: (prediction: IdCapturePrediction) => void) => void\n\n detectionTime: number\n focusPredictionTime: number\n\n getBestFrame: () => Promise<Blob | null>\n resetBestFrame: () => void\n}\n\nexport const IdCaptureModelsContext = createContext<IdCaptureModelsState>({\n ready: false,\n working: { current: false },\n error: null,\n\n thresholds: {},\n setThresholds: () => null,\n\n makePrediction: () => null,\n onPredictionMade: () => null,\n\n detectionTime: 0,\n focusPredictionTime: 0,\n\n getBestFrame: () => Promise.resolve(null),\n resetBestFrame: () => null,\n})\n\nexport type IdCaptureModelsProviderProps = {\n children: ReactNode\n documentDetectionModelUrl?: string | undefined\n focusModelUrl?: string | undefined\n logPredictions?: boolean\n}\n\nconst defaultDocumentDetectionModelUrl = `${DEFAULT_CDN_URL}/models/documentdetection448/model.json`\nconst defaultFocusModelUrl = `${DEFAULT_CDN_URL}/models/focus/model.json`\n\nexport const IdCaptureModelsProvider = ({\n children,\n documentDetectionModelUrl,\n focusModelUrl,\n logPredictions = false,\n}: IdCaptureModelsProviderProps): ReactElement => {\n const [ready, setReady] = useState(false)\n const [documentDetectionThreshold, setDocumentDetectionThreshold] =\n useState(0)\n const [passportDetectionThreshold, setPassportDetectionThreshold] =\n useState(0)\n const [mrzDetectionThreshold, setMrzDetectionThreshold] = useState(0)\n const [pdf417DetectionThreshold, setPdf417DetectionThreshold] = useState(0)\n const [focusThreshold, setFocusThreshold] = useState(0)\n const working = useRef(false)\n const onPredictionHandler =\n useRef<(prediction: IdCapturePrediction) => void>()\n const lastPredictionCanvas = useRef<HTMLCanvasElement | null>(null)\n const [detectionTime, setDetectionTime] = useState<number>(0)\n const [focusPredictionTime, setFocusPredictionTime] = useState<number>(0)\n const [loadingError, setLoadingError] = useState<Error | null>(null)\n\n useEffect(() => {\n setReady(false)\n\n const ddmUrl = documentDetectionModelUrl || defaultDocumentDetectionModelUrl\n const fmUrl = focusModelUrl || defaultFocusModelUrl\n\n async function loadModels() {\n tf.ENV.set('WEBGL_DELETE_TEXTURE_THRESHOLD', 50 * 1024 * 1024)\n await tf.setBackend('webgl')\n await tf.ready()\n await Promise.all([\n loadDocumentDetectionModel(ddmUrl),\n loadFocusModel(fmUrl),\n ])\n }\n\n async function reloadModels() {\n setReady(false)\n unloadDocumentDetectionModel()\n unloadFocusModel()\n clearWebGLContext(2)\n const ctx = document.createElement('canvas').getContext('webgl2')\n if (ctx && ddmUrl && fmUrl) {\n setWebGLContext(2, ctx)\n disposeTfBackend()\n await loadModels()\n setReady(true)\n }\n }\n\n loadModels()\n .then(() => {\n setReady(true)\n })\n .catch((e) => {\n setLoadingError(e as Error)\n })\n\n const webGLCanvas = getWebGLContext(2).canvas\n webGLCanvas.addEventListener('webglcontextlost', reloadModels)\n\n return () => {\n webGLCanvas.removeEventListener?.('webglcontextlost', reloadModels)\n }\n }, [documentDetectionModelUrl, focusModelUrl])\n\n const thresholds = useMemo<IdCaptureThresholds>(\n () => ({\n document: documentDetectionThreshold,\n passport: passportDetectionThreshold,\n mrz: mrzDetectionThreshold,\n pdf417: pdf417DetectionThreshold,\n focus: focusThreshold,\n }),\n [\n documentDetectionThreshold,\n focusThreshold,\n mrzDetectionThreshold,\n passportDetectionThreshold,\n pdf417DetectionThreshold,\n ],\n )\n\n const setThresholds = useCallback((thresholds: IdCaptureThresholds) => {\n if (thresholds.document) setDocumentDetectionThreshold(thresholds.document)\n if (thresholds.passport) setPassportDetectionThreshold(thresholds.passport)\n if (thresholds.mrz) setMrzDetectionThreshold(thresholds.mrz)\n if (thresholds.pdf417) setPdf417DetectionThreshold(thresholds.pdf417)\n if (thresholds.focus) setFocusThreshold(thresholds.focus)\n }, [])\n\n const [timesAllZero, setTimesAllZero] = useState(0)\n const bestPredictionCanvas = useRef<HTMLCanvasElement | null>(null)\n const bestFocusScore = useRef<number>(0)\n const makePrediction = useCallback(\n (frame: Frame) => {\n working.current = true\n ;(async () => {\n if (\n !documentDetectionModel ||\n !focusModel ||\n !lastPredictionCanvas.current\n )\n return\n\n const prediction = await makePredictions(\n frame,\n lastPredictionCanvas.current,\n thresholds,\n logPredictions,\n )\n\n setDetectionTime(prediction.detectionTime)\n setFocusPredictionTime(prediction.focusPredictionTime)\n\n if (bestFocusScore.current <= prediction.focusScore) {\n bestFocusScore.current = prediction.focusScore\n drawToCanvas(bestPredictionCanvas.current, frame)\n }\n\n if (prediction.allZero) setTimesAllZero((n) => n + 1)\n\n onPredictionHandler.current?.(prediction)\n\n working.current = false\n })()\n },\n [logPredictions, thresholds],\n )\n\n useEffect(() => {\n if (timesAllZero >= 2) {\n setLoadingError(new Error('model is returning all zeroes'))\n }\n }, [timesAllZero])\n\n const onPredictionMade = useCallback(\n (handler: (prediction: IdCapturePrediction) => void) => {\n onPredictionHandler.current = handler\n },\n [],\n )\n\n const getBestFrame = useCallback(async () => {\n if (!bestPredictionCanvas.current) return null\n const photoURL = bestPredictionCanvas.current.toDataURL('image/jpeg', 0.98)\n const data = await fetch(photoURL)\n return await data.blob()\n }, [])\n\n const resetBestFrame = useCallback(() => {\n bestFocusScore.current = 0\n clearCanvas(bestPredictionCanvas.current)\n }, [])\n\n const value = useMemo<IdCaptureModelsState>(\n () => ({\n ready,\n working,\n thresholds,\n setThresholds,\n makePrediction,\n onPredictionMade,\n detectionTime,\n focusPredictionTime,\n getBestFrame,\n resetBestFrame,\n error: loadingError,\n }),\n [\n detectionTime,\n focusPredictionTime,\n getBestFrame,\n loadingError,\n makePrediction,\n onPredictionMade,\n ready,\n resetBestFrame,\n setThresholds,\n thresholds,\n ],\n )\n\n return (\n <IdCaptureModelsContext.Provider value={value}>\n {children}\n <InvisibleCanvas ref={lastPredictionCanvas} />\n <InvisibleCanvas ref={bestPredictionCanvas} />\n </IdCaptureModelsContext.Provider>\n )\n}\n\nasync function makePredictions(\n frame: Frame,\n lastPredictionCanvas: HTMLCanvasElement,\n thresholds: IdCaptureThresholds,\n logPredictions: boolean = false,\n): Promise<IdCapturePrediction> {\n const [frameWidth, frameHeight] = getFrameDimensions(frame)\n\n if (PRERESIZE) {\n if (logPredictions) console.time('pre-resize')\n const preResizeCanvas = document.createElement('canvas')\n const [w, h] =\n frameWidth > frameHeight\n ? [frameWidth * (448 / frameHeight), 448]\n : [448, frameHeight * (448 / frameWidth)]\n drawToCanvas(preResizeCanvas, frame, w, h)\n frame = preResizeCanvas\n if (logPredictions) console.timeEnd('pre-resize')\n }\n\n drawToCanvas(lastPredictionCanvas, frame)\n\n const { boxes, scores, labels, time } =\n await makeDocumentDetectionPredictions(frame, logPredictions)\n\n const allZero =\n boxes.length > 0 && !boxes.some((box) => box.some((n) => n > 0))\n\n const detectedObjects = applyNonMaxSuppression(\n boxes.map((box, i) =>\n bboxToDetectedObjectUnscaled(box, scores[i], labels[i]),\n ),\n )\n\n const bestDocument = detectedObjects.find((obj) => obj.label === 'Document')\n const bestPassportPage = detectedObjects.find(\n (obj) => obj.label === 'Passport Page',\n )\n const bestDocumentScore = bestDocument?.score ?? 0\n const passportDetectionScore = bestPassportPage?.score ?? 0\n const passportDetectionThresholdMet =\n passportDetectionScore >= (thresholds.passport ?? 0)\n const bestDocumentOrPassport =\n bestDocumentScore > passportDetectionScore ? bestDocument : bestPassportPage\n const detectionScore = passportDetectionThresholdMet\n ? passportDetectionScore\n : bestDocumentScore\n const detectionThresholdMet = detectionScore >= (thresholds.document ?? 0)\n\n let detectedDocumentType = DocumentType.NONE\n if (passportDetectionThresholdMet) {\n detectedDocumentType = DocumentType.PASSPORT\n } else if (detectionThresholdMet) {\n detectedDocumentType = DocumentType.ID_CARD\n }\n\n const bestMrz = detectedObjects.find((obj) => obj.label === 'MRZ')\n const mrzDetectionScore = bestMrz?.score ?? 0\n const mrzDetectionThresholdMet = mrzDetectionScore >= (thresholds.mrz ?? 0)\n\n const bestPdf417 = detectedObjects.find((obj) => obj.label === 'PDF417')\n const pdf417DetectionScore = bestPdf417?.score ?? 0\n const pdf417DetectionThresholdMet =\n pdf417DetectionScore >= (thresholds.pdf417 ?? 0)\n\n let focusPrediction: FocusPrediction | null = null,\n focusPredictionTime = 0,\n focusScore = 0,\n focusThresholdMet = false\n if (detectionThresholdMet) {\n ;[focusPrediction, focusPredictionTime] = await makeFocusPrediction(\n frame,\n bestDocumentOrPassport?.bbox,\n logPredictions,\n )\n focusScore = focusPrediction?.[1] ?? 0\n focusThresholdMet = focusScore >= (thresholds.focus ?? 0)\n }\n\n return {\n detectedObjects,\n detectionScore,\n detectionTime: time,\n detectionThresholdMet,\n detectedDocumentType,\n passportDetectionScore,\n passportDetectionThresholdMet,\n mrzDetectionScore,\n mrzDetectionThresholdMet,\n pdf417DetectionScore,\n pdf417DetectionThresholdMet,\n bestDocumentOrPassport,\n bestMrz,\n bestPdf417,\n focusScore,\n focusThresholdMet,\n focusPredictionTime,\n frameWidth,\n frameHeight,\n allZero,\n }\n}\n\ntype RawDocumentDetectionPrediction = {\n boxes: number[][]\n scores: number[]\n labels: number[]\n time: number\n}\n\nasync function makeDocumentDetectionPredictions(\n image: Frame,\n logPredictions: boolean = false,\n): Promise<RawDocumentDetectionPrediction> {\n if (!documentDetectionModel) {\n throw new Error('document detection model is not loaded')\n }\n\n const startedAt = new Date()\n\n try {\n const tfImg = tf.browser.fromPixels(image)\n if (logPredictions) console.time('resize')\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n if (logPredictions) console.timeEnd('resize')\n tfImg.dispose()\n if (logPredictions) console.time('convert to int32')\n const tfInt32 = tf.cast(tfResize, 'int32')\n tfResize.dispose()\n const tf4d_ = tf.tensor4d(\n Array.from(await tfInt32.data()),\n [1, 448, 448, 3],\n )\n tfInt32.dispose()\n const tf4d = tf.cast(tf4d_, 'int32')\n if (logPredictions) console.timeEnd('convert to int32')\n tf4d_.dispose()\n if (logPredictions) console.time('predictions')\n const result = await documentDetectionModel.executeAsync(tf4d)\n if (logPredictions) console.timeEnd('predictions')\n tf4d.dispose()\n\n const predictions = result as unknown as RawEdgeDetectionResult\n if (logPredictions) {\n console.log(\n 'predictions made!',\n predictions.map((r) => r.arraySync()),\n )\n }\n\n const [boxes] = (await predictions[\n PREDICTION_POSITIONS.boxes\n ].array()) as number[][][]\n const [scores] = (await predictions[\n PREDICTION_POSITIONS.scores\n ].array()) as number[][]\n let [labels] = (await predictions[\n PREDICTION_POSITIONS.labels\n ].array()) as number[][]\n\n labels = labels.map((l) => Math.round(l))\n\n tf.dispose(result)\n\n const time = new Date().getTime() - startedAt.getTime()\n return { boxes, scores, labels, time }\n } catch (e) {\n console.error('caught error in makeDocumentDetectionPredictions', e)\n return { boxes: [], scores: [], labels: [], time: 0 }\n }\n}\n\nasync function makeFocusPrediction(\n imageData: Frame,\n bbox?: number[],\n logPredictions: boolean = false,\n): Promise<[FocusPrediction, number]> {\n if (!focusModel) {\n throw new Error('focus model is not loaded')\n }\n\n const startedAt = new Date()\n\n try {\n let tfImg: tf.Tensor3D\n if (bbox) {\n tfImg = tf.browser.fromPixels(cropToBoundingBox(imageData, bbox))\n } else {\n tfImg = tf.browser.fromPixels(imageData)\n }\n const tfResize = tf.image.resizeBilinear(tfImg, [448, 448])\n tfImg.dispose()\n const tfInt32 = tf.cast(tfResize, 'int32')\n tfResize.dispose()\n const tf4d_ = tf.tensor4d(\n Array.from(await tfInt32.data()),\n [1, 448, 448, 3],\n )\n tfInt32.dispose()\n const tf4d = tf.cast(tf4d_, 'int32')\n tf4d_.dispose()\n if (logPredictions) console.time('focus prediction')\n const predictions = (await focusModel.predict(tf4d)) as tf.Tensor<tf.Rank>\n tf4d.dispose()\n const [focusPrediction] = (await predictions.array()) as FocusPrediction[]\n if (logPredictions) console.timeEnd('focus prediction')\n tf.dispose(predictions)\n\n const predictionTime = new Date().getTime() - startedAt.getTime()\n\n return [focusPrediction, predictionTime]\n } catch (e) {\n return [[0, 0], 0]\n }\n}\n\nfunction applyNonMaxSuppression(\n detectedObjects: DetectedObject[],\n): DetectedObject[] {\n const maxes: { [label: string]: [number, number] } = {}\n detectedObjects.forEach((obj, i) => {\n if (obj) {\n if (!maxes[obj.label]) maxes[obj.label] = [0, -1]\n if (obj.score > maxes[obj.label][0]) maxes[obj.label] = [obj.score, i]\n }\n })\n return Object.keys(maxes)\n .map((label) => detectedObjects[maxes[label][1]])\n .filter((obj) => !!obj)\n}\n\nfunction disposeTfBackend(): void {\n try {\n tf.backend().dispose()\n } catch (e) {\n console.error('failed to dispose backend', e)\n }\n}\n","import styled from 'styled-components'\nimport React, { ReactElement, useMemo } from 'react'\nimport { DetectedObject } from '../../lib/models/DocumentDetection'\nimport {\n Face,\n FaceKeypoint,\n} from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\n\nexport const DebugStatsPane = styled.span`\n font-size: 16px;\n font-family: monospace;\n position: absolute;\n left: 20px;\n bottom: 20px;\n color: limegreen;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1001;\n`\n\nexport const ObjectDetectionDebugOverlay = styled.div<{ $flipX?: boolean }>`\n position: absolute;\n z-index: 1001;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n overflow: hidden;\n ${({ $flipX }) => ($flipX ? 'transform: scaleX(-1);' : '')}\n`\n\nexport const ObjectDetectionDebugBox = styled.div<{\n $color?: string\n $flipX?: boolean\n}>`\n font: 10px monospace;\n position: absolute;\n border: 3px solid ${({ $color }) => $color ?? 'green'};\n color: ${({ $color }) => $color ?? 'green'};\n ${({ $flipX }) => ($flipX ? 'transform: scaleX(-1);' : '')}\n`\n\nexport const FaceDetectionKeypointMarker = styled.div<{\n $color?: string\n $flipX?: boolean\n}>`\n position: absolute;\n width: 4px;\n height: 4px;\n border: 2px solid ${({ $color }) => $color ?? 'red'};\n font: 10px monospace;\n color: ${({ $color }) => $color ?? 'red'};\n border-radius: 50%;\n ${({ $flipX }) => ($flipX ? 'transform: scaleX(-1);' : '')}\n`\n\nexport type DebugScalingDetails = {\n horizontal: boolean\n pageWidth: number\n pageHeight: number\n videoWidth: number\n videoHeight: number\n scaledWidth: number\n scaledHeight: number\n xOffset: number\n yOffset: number\n}\n\nexport function useDebugScalingDetails({\n enabled = true,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n}: {\n enabled?: boolean\n pageWidth: number\n pageHeight: number\n videoWidth: number\n videoHeight: number\n}): DebugScalingDetails {\n return useMemo(() => {\n let horizontal = false,\n scaledWidth = 0,\n scaledHeight = 0,\n xOffset = 0,\n yOffset = 0\n\n if (enabled) {\n horizontal = pageWidth / pageHeight < videoWidth / videoHeight\n if (horizontal) {\n scaledWidth = videoWidth * (pageHeight / videoHeight)\n xOffset = (scaledWidth - pageWidth) / 2\n } else {\n scaledHeight = videoHeight * (pageWidth / videoWidth)\n yOffset = (scaledHeight - pageHeight) / 2\n }\n }\n\n return {\n horizontal,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n }\n }, [enabled, pageHeight, pageWidth, videoHeight, videoWidth])\n}\n\nexport type DetectedObjectDebugBoxProps = {\n obj: DetectedObject\n scaling: DebugScalingDetails\n flipX?: boolean\n color?: string\n}\n\nexport function IdCaptureDetectedObjectDebugBox({\n obj,\n flipX,\n color = 'green',\n scaling: {\n horizontal,\n pageWidth,\n pageHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n },\n}: DetectedObjectDebugBoxProps): ReactElement {\n let [top, left, width, height] = [\n obj.bbox[1],\n obj.bbox[0],\n obj.bbox[2],\n obj.bbox[3],\n ]\n\n if (horizontal) {\n top *= pageHeight\n left *= scaledWidth - xOffset\n width *= scaledWidth\n height *= pageHeight\n } else {\n top *= scaledHeight - yOffset\n left *= pageWidth\n width *= pageWidth\n height *= scaledHeight\n }\n\n return (\n <ObjectDetectionDebugBox\n $flipX={flipX}\n $color={color}\n style={{ top, left, width, height }}\n >\n {obj.label} ({obj.score.toFixed(3)})\n </ObjectDetectionDebugBox>\n )\n}\n\nexport type SelfieCaptureFaceDebugBoxProps = {\n face: Face\n scaling: DebugScalingDetails\n flipX?: boolean\n color?: string\n}\n\nexport function SelfieCaptureFaceDebugBox({\n face,\n flipX,\n color = 'green',\n scaling,\n}: SelfieCaptureFaceDebugBoxProps): ReactElement {\n const {\n horizontal,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n } = scaling\n\n let top\n let left\n let width\n let height\n\n if (horizontal) {\n top = (face.box.yMin / videoHeight) * pageHeight\n left = (face.box.xMin / videoWidth) * scaledWidth - xOffset\n width = (face.box.width / videoWidth) * scaledWidth\n height = (face.box.height / videoHeight) * pageHeight\n } else {\n top = (face.box.yMin / videoHeight) * scaledHeight - yOffset\n left = (face.box.xMin / videoWidth) * pageWidth\n width = (face.box.width / videoWidth) * pageWidth\n height = (face.box.height / videoHeight) * scaledHeight\n }\n\n return (\n <>\n <ObjectDetectionDebugBox\n $flipX={flipX}\n $color={color}\n style={{ top, left, width, height }}\n />\n\n {face.keypoints.map((point, ii) => (\n <SelfieCaptureFaceKeypoint\n key={ii}\n point={point}\n scaling={scaling}\n flipX={flipX}\n />\n ))}\n </>\n )\n}\n\ntype SelfieCaptureFaceKeypointProps = {\n point: FaceKeypoint\n scaling: DebugScalingDetails\n flipX?: boolean\n color?: string\n}\n\nexport function SelfieCaptureFaceKeypoint({\n point,\n flipX,\n color = 'red',\n scaling: {\n horizontal,\n pageWidth,\n pageHeight,\n videoWidth,\n videoHeight,\n scaledWidth,\n scaledHeight,\n xOffset,\n yOffset,\n },\n}: SelfieCaptureFaceKeypointProps): ReactElement {\n let left, top\n if (horizontal) {\n left = (point.x / videoWidth) * scaledWidth - xOffset\n top = (point.y / videoHeight) * pageHeight\n } else {\n left = (point.x / videoWidth) * pageWidth\n top = (point.y / videoHeight) * scaledHeight - yOffset\n }\n\n top -= 2\n left -= 2\n\n return (\n <FaceDetectionKeypointMarker\n $flipX={flipX}\n $color={color}\n style={{ top, left }}\n />\n )\n}\n","import React from 'react'\nimport styled from 'styled-components'\n\nexport const ExitCaptureStyledButton = styled.button`\n position: absolute;\n top: 12px;\n right: 12px;\n font-size: 20px;\n width: 32px;\n height: 32px;\n font-family: monospace;\n z-index: 1002;\n border: none;\n border-radius: 4px;\n background: #ccc;\n cursor: pointer;\n padding: 8px;\n box-sizing: border-box;\n display: flex;\n\n &:hover {\n background: #ddd;\n }\n\n & > svg {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n`\n\nexport const ExitCaptureButton = ({\n onClick,\n className,\n}: {\n onClick?: () => void\n className?: string\n}) => {\n return (\n <ExitCaptureStyledButton onClick={onClick} className={className}>\n <svg\n version=\"1.1\"\n xmlns=\"http://www.w3.org/2000/svg\"\n x=\"0px\"\n y=\"0px\"\n viewBox=\"19.3 19.3 25.499999999999996 25.499999999999996\"\n enableBackground=\"new 0 0 64 64\"\n width={16}\n height={16}\n >\n <g id=\"close-outline-bot_x5F_s1g1_x5F_s2g2_x5F_s3g1_x5F_s4g1\">\n <line\n fill=\"none\"\n stroke=\"#000000\"\n strokeWidth=\"1\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeMiterlimit=\"10\"\n x1=\"19.75\"\n y1=\"44.25\"\n x2=\"44.25\"\n y2=\"19.75\"\n />\n </g>\n <g id=\"close-outline-top_x5F_s1g1_x5F_s2g2_x5F_s3g1_x5F_s4g1\">\n <line\n fill=\"none\"\n stroke=\"#000000\"\n strokeWidth=\"1\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeMiterlimit=\"10\"\n x1=\"44.25\"\n y1=\"44.25\"\n x2=\"19.75\"\n y2=\"19.75\"\n />\n </g>\n </svg>\n </ExitCaptureStyledButton>\n )\n}\n","import styled from 'styled-components'\n\nexport const Spinner = styled.div<{\n $size?: number\n $thickness?: number\n $color?: string\n}>`\n display: inline-block;\n width: ${({ $size }) => $size ?? 80}px;\n height: ${({ $size }) => $size ?? 80}px;\n margin: auto;\n\n &:after {\n content: ' ';\n display: block;\n width: ${({ $size }) => ($size ?? 80) - 16}px;\n height: ${({ $size }) => ($size ?? 80) - 16}px;\n margin: 8px;\n border-radius: 50%;\n border: ${({ $thickness }) => $thickness ?? 6}px solid\n ${({ $color }) => $color ?? '#888'};\n border-color: ${({ $color }) => $color ?? '#888'} transparent\n ${({ $color }) => $color ?? '#888'} transparent;\n animation: lds-dual-ring 1.2s linear infinite;\n box-sizing: content-box;\n }\n\n @keyframes lds-dual-ring {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n`\n","import { Spinner } from './spinner'\nimport styled from 'styled-components'\nimport React from 'react'\n\nexport type IdCaptureImagePreviewClassNames = {\n container?: string\n text?: string\n imageContainer?: string\n image?: string\n}\n\nexport type IdCaptureImagePreviewProps = {\n classNames?: IdCaptureImagePreviewClassNames\n text?: string\n imageUrl: string\n}\n\nexport const IdCaptureImagePreview = ({\n classNames = {},\n text,\n imageUrl,\n}: IdCaptureImagePreviewProps) => {\n return (\n <ImagePreviewWrapper className={classNames.container}>\n {text && (\n <ImagePreviewText className={classNames.text}>{text}</ImagePreviewText>\n )}\n\n <ImagePreviewImageWrapper className={classNames.imageContainer}>\n <img src={imageUrl} alt=\"\" className={classNames.image} />\n </ImagePreviewImageWrapper>\n </ImagePreviewWrapper>\n )\n}\n\nexport type SelfieProgressPreviewClassNames = {\n container?: string\n text?: string\n spinner?: string\n imageContainer?: string\n image?: string\n}\n\nexport type SelfieProgressPreviewProps = {\n classNames?: SelfieProgressPreviewClassNames\n text: string\n imageUrl: string\n}\n\nexport const SelfieProgressPreview = ({\n classNames = {},\n text,\n imageUrl,\n}: SelfieProgressPreviewProps) => {\n return (\n <ImagePreviewWrapper className={classNames.container}>\n <ImagePreviewText className={classNames.text}>\n <StyledSpinner\n className={classNames.spinner}\n $size={24}\n $color=\"white\"\n $thickness={3}\n />\n {text}\n </ImagePreviewText>\n\n <ImagePreviewImageWrapper className={classNames.imageContainer}>\n <img src={imageUrl} alt=\"\" className={classNames.image} />\n </ImagePreviewImageWrapper>\n </ImagePreviewWrapper>\n )\n}\n\nconst StyledSpinner = styled(Spinner)`\n position: relative;\n top: 4px;\n left: -3px;\n margin: 0 3px 0 -12px;\n`\n\nconst ImagePreviewWrapper = styled.div`\n position: absolute;\n display: flex;\n flex-direction: column;\n height: 33%;\n bottom: 12px;\n right: 12px;\n`\n\nconst ImagePreviewText = styled.div`\n display: block;\n position: absolute;\n top: -32px;\n font: 14px -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,\n Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';\n color: white;\n text-align: center;\n margin: 0 auto;\n width: 100%;\n`\n\nconst ImagePreviewImageWrapper = styled.div`\n position: relative;\n height: calc(100% - 8px);\n padding: 4px;\n border-radius: 4px;\n background: white;\n\n & > img {\n border-radius: 4px;\n width: auto;\n max-height: 100%;\n }\n`\n","export default {}\n","export default {\n 'Use your device camera to capture your ID':\n 'Para capturar la identificación hay que utilizar la cámara del dispositivo.',\n\n 'Use your iPhone as a webcam': 'Usar el iPhone como cámara web',\n 'Models warming up...': 'Cargando modelos...',\n 'Camera initializing...': 'Inicializando la cámara...',\n 'Camera access blocked': 'Acceso bloqueado a la cámara',\n 'Location access blocked': 'Acceso bloqueado a la localización',\n Continue: 'Continuar',\n 'Processing...': 'Procesando...',\n\n 'Your camera permission is disabled':\n 'El permiso de la cámara está desactivado',\n 'This application requires access to your camera to continue. Please accept the permission once prompted by the browser. If the browser does not prompt for camera permissions, you must go to settings and provide camera access to the current browser.':\n 'Esta aplicación requiere el acceso a la cámara para continuar. Hay que aceptar el permiso una vez que se muestre la ventana en el explorador. Si no aparece la ventana para otorgar permisos, entonces hay que dirigirse a Configuración y otorgar el permiso a la cámara en el explorador actual.',\n 'Your location permission is disabled':\n 'El permiso de la localización está desactivado',\n 'This application requires access to your location to continue. Please accept the permission once prompted by the browser. If the browser does not prompt for location permissions, you must go to settings and provide location access to the current browser.':\n 'Esta aplicación requiere el acceso a la localización para continuar. Hay que aceptar el permiso una vez que se muestre la ventana en el explorador. Si no aparece la ventana para otorgar permisos, entonces hay que dirigirse a Configuración y otorgar el permiso a la localización en el explorador actual.',\n Retry: 'Reintentar',\n\n 'Scan the front of ID': 'Escanear el frente de la ID',\n 'Scan the back of ID': 'Escanear el reverso de la ID',\n 'Scan the ID page of passport': 'Escanear la página de datos del pasaporte',\n\n 'ID Card Front': 'Frente de la ID',\n 'ID Card Back': 'Reverso de la ID',\n Passport: 'Pasaporte',\n\n 'Document not detected': 'No se ha detectado el documento',\n 'Document is not centered': 'Documento no centrado',\n 'Document out of focus – try improving the lighting':\n 'Documento no enfocado - hay que tratar de mejorar la iluminación',\n 'Document detected, hold still...':\n 'Se ha detectado el documento, no moverse por favor...',\n\n 'Capturing...': 'Capturando...',\n 'Capture failed!': 'Falló la captura',\n\n 'Please flip your ID card...': 'Por favor voltea la identificación...',\n 'ID card front captured.': 'Se ha capturado el frente de la identificación.',\n\n 'ID Capture Successful': 'Captura Exitosa de ID',\n 'Verify the entire ID was captured clearly with no glare.':\n 'Hay que verificar que toda la ID se vea completa y sin reflejos.',\n\n Submit: 'Enviar',\n 'Submitting...': 'Enviando...',\n\n 'Use your device camera to capture your face':\n 'Hay que utilizar la cámara del dispositivo para capturar el rostro',\n\n 'Remove Sunglasses & Hat': 'Hay que quitarse lentes y/o la gorra',\n 'Avoid Excessive Backlighting': 'Hay que evitar demasiada luz en el fondo',\n\n 'Hold still for a few seconds...':\n 'Hay que permanecer quieto por unos segundos...',\n 'Look straight into the camera...':\n 'Hay que mirar directamente a la cámara...',\n 'Move back...': 'Hay que hacerse hacia atrás..',\n 'Move forward...': 'Hay que hacerse hacia adelante...',\n 'Move to the center...': 'Hay que moverse hacia el centro...',\n 'Please remove your eye coverings (sunglasses, eye patch, etc.)...':\n 'Hay que quitarse lo que cubre los ojos (lentes, parche, etc.)...',\n 'Please remove your head coverings (hat, scarf, etc.)...':\n 'Hay que quitarse lo que cubre la cabeza (gorra, mascada, etc.)...',\n 'Please remove your mask...': 'Hay que quitarse el cubrebocas...',\n 'Live face not detected, please try again':\n 'Rostro vivo no detectado. Por favor hay que intentar de nuevo.',\n Exit: 'Salir',\n 'Face liveness has been verified!':\n 'Se ha verificado la Prueba de Vida en rostro!',\n Done: 'Terminar',\n\n 'Customer has been identified!': '¡Se ha identificado al cliente!',\n 'Customer not found': 'Cliente no encontrado',\n\n 'Additional document capture': 'Captura de otro documento',\n Next: 'Siguiente',\n\n 'Please sign the box below':\n 'Por favor, hay que firmar en el recuadro de abajo',\n Accept: 'Aceptar',\n Clear: 'Borrar',\n\n 'Video signature has been successfully captured!':\n 'La video firma ha sido exitosa.',\n\n 'Network unreachable': 'No hay conexión a internet.',\n \"We're having trouble reaching our services, please check your connection and try again.\": `Estamos teniendo problemas para alcanzar nuestros servicios, por favor verificar la conexión a internet e intentar de nuevo.`,\n \"We're sorry, an unexpected error has occurred.\": `Lo sentimos, se ha producido un error inesperado.`,\n}\n","import { useEffect, useMemo } from 'react'\nimport { initReactI18next, useTranslation } from 'react-i18next'\nimport enTranslation from './en/translation'\nimport esTranslation from './es/translation'\nimport LanguageDetector from 'i18next-browser-languagedetector'\nimport i18n from 'i18next'\n\nexport const ALL_LANGUAGES = ['auto', 'en', 'es'] as const\nexport type LangOptions = typeof ALL_LANGUAGES\nexport type LangOption = LangOptions[number]\n\nexport const resources = {\n en: { translation: enTranslation },\n es: { translation: esTranslation },\n}\n\nexport function initializeI18n() {\n i18n\n .use(LanguageDetector)\n .use(initReactI18next)\n .init({\n resources,\n detection: { caches: [] },\n fallbackLng: 'en',\n debug: false,\n interpolation: { escapeValue: false },\n })\n}\n\nexport const useLanguage = (lang: LangOption): void => {\n const { i18n } = useTranslation()\n useEffect(() => {\n if (lang !== 'auto') {\n i18n.changeLanguage(lang)\n } else {\n i18n.changeLanguage() // call without argument to use detection\n }\n }, [i18n, lang])\n}\n\nexport type CustomerSuppliedTranslations = { [lang: string]: string }\nexport type CustomerSuppliedVerbiage =\n | string\n | CustomerSuppliedTranslations\n | undefined\nexport type RecursiveVerbiageObject =\n | CustomerSuppliedVerbiage\n | { [key: string]: RecursiveVerbiageObject }\n\nfunction evaluateVerbiage(\n t: (key: string) => string,\n currentLanguage: string,\n verbiage: CustomerSuppliedVerbiage,\n fallback: string\n): string {\n if (typeof verbiage === 'string') return verbiage\n\n if (typeof verbiage === 'object') {\n const translations = verbiage as CustomerSuppliedTranslations\n if (translations[currentLanguage]) return translations[currentLanguage]\n\n const nonLocaleLang = currentLanguage.split('-')[0]\n if (translations[nonLocaleLang]) return translations[nonLocaleLang]\n }\n\n return t(fallback)\n}\n\nexport function useVerbiage(\n verbiage: CustomerSuppliedVerbiage,\n fallback: string\n): string {\n const { t, i18n } = useTranslation()\n\n return useMemo(\n () => evaluateVerbiage(t, i18n.language, verbiage, fallback),\n [fallback, i18n.language, t, verbiage]\n )\n}\n\nexport function useTranslations<\n T extends { [key: string]: RecursiveVerbiageObject }\n>(\n verbiage: T | undefined,\n fallbacks: { [K in keyof T]: string }\n): { [K in keyof T]: string } {\n const { t, i18n } = useTranslation()\n\n return useMemo(\n () => ({\n ...verbiage,\n ...Object.keys(fallbacks).reduce(\n (result, key) => ({\n ...result,\n [key as keyof T]: evaluateVerbiage(\n t,\n i18n.language,\n verbiage?.[key] as CustomerSuppliedVerbiage,\n fallbacks[key]\n ),\n }),\n {} as { [K in keyof T]: string }\n ),\n }),\n [fallbacks, i18n.language, t, verbiage]\n )\n}\n","import styled from 'styled-components'\n\nexport type GuidanceMessageVariant = 'default' | 'positive' | 'negative'\n\nexport const GuidanceMessageContainer = styled.div<{ $top?: string }>`\n position: absolute;\n top: calc(${({ $top }) => $top ?? '10vh'});\n font-weight: bold;\n width: 100%;\n display: flex;\n`\n\nexport const GuidanceMessage = styled.div<{\n $background?: string\n $textColor?: string\n $variant?: GuidanceMessageVariant\n}>`\n margin-left: auto;\n margin-right: auto;\n background: ${(props) =>\n props.$background ??\n props.theme?.guidanceMessages?.[props.$variant ?? 'default']\n ?.backgroundColor ??\n '#ccc'};\n color: ${(props) =>\n props.$textColor ??\n props.theme?.guidanceMessages?.[props.$variant ?? 'default']?.textColor ??\n 'black'};\n padding: 10px 12px 8px;\n border-radius: 8px;\n z-index: 10001;\n`\n","import React, {\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport useResizeObserver from 'use-resize-observer'\nimport {\n DocumentCaptureGuideOverlay,\n DocumentCaptureGuideOverlayClassNames,\n} from './DocumentCaptureGuideOverlay'\nimport {\n DetectedObject,\n DocumentType,\n} from '../../lib/models/DocumentDetection'\nimport { PDF417DetectionResult } from '../../lib/barcode/Native'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport {\n scanBarcode,\n supportsNativeBarcodeScanning,\n} from '../../lib/barcode/Scan'\nimport { getBlobDimensions } from '../../lib/utils/getBlobDimensions'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { CaptureAttemptMetadata } from '../../contexts/SubmissionContext'\nimport { PageContainer } from '../common/Page'\nimport {\n IdCaptureModelsContext,\n IdCapturePrediction,\n} from './IdCaptureModelsProvider'\nimport {\n DebugStatsPane,\n IdCaptureDetectedObjectDebugBox,\n ObjectDetectionDebugOverlay,\n useDebugScalingDetails,\n} from '../common/debug'\nimport { ExitCaptureButton } from '../common/ExitCaptureButton'\nimport {\n IdCaptureImagePreview,\n IdCaptureImagePreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport {\n GuidanceMessage,\n GuidanceMessageContainer,\n} from '../common/GuidanceMessage'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { useTheme } from 'styled-components'\n\ntype State = {\n videoWidth: number\n videoHeight: number\n captureStartedAt: Date | null\n\n detectedObjects: DetectedObject[]\n bestDocument: DetectedObject | undefined\n bestMrz: DetectedObject | undefined\n bestPdf417: DetectedObject | undefined\n\n documentType: DocumentType\n requiredDocumentType?: DocumentType\n documentInBounds: boolean\n documentDetectionScore: number\n documentDetectionThresholdMet: boolean\n\n mrzDetectionScore: number\n mrzDetectionThresholdMet: boolean\n\n passportPageDetectionScore: number\n passportPageDetectionThresholdMet: boolean\n\n focusScore: number\n focusThresholdMet: boolean\n\n pdf417DetectionScore: number\n pdf417DetectionThresholdMet: boolean\n\n barcodeScanningEnabled: boolean\n barcodeResult: PDF417DetectionResult | null\n waitingForBarcodeScan: boolean\n shouldScanBarcode: boolean\n autoCaptureBarcodeRequired: boolean | 'mobile'\n barcodeScanFailedAttempts: number\n maxBarcodeScanAttempts: number\n\n isGoodFrame: boolean\n goodFramesCount: number\n goodFramesThreshold: number\n goodFramesThresholdMet: boolean\n\n lastFrameCapturedAt: Date | null\n frameCaptureRate: number\n\n capturing: boolean\n captured: boolean\n captureFailed: boolean\n}\n\nconst initialState: State = {\n videoWidth: 0,\n videoHeight: 0,\n captureStartedAt: null,\n\n detectedObjects: [],\n bestDocument: undefined,\n bestMrz: undefined,\n bestPdf417: undefined,\n\n documentType: DocumentType.NONE,\n documentInBounds: false,\n\n documentDetectionScore: 0,\n documentDetectionThresholdMet: false,\n passportPageDetectionScore: 0,\n passportPageDetectionThresholdMet: false,\n mrzDetectionScore: 0,\n mrzDetectionThresholdMet: false,\n pdf417DetectionScore: 0,\n pdf417DetectionThresholdMet: false,\n focusScore: 0,\n focusThresholdMet: false,\n\n barcodeScanningEnabled: false,\n barcodeResult: null,\n waitingForBarcodeScan: false,\n shouldScanBarcode: false,\n autoCaptureBarcodeRequired: 'mobile',\n barcodeScanFailedAttempts: 0,\n maxBarcodeScanAttempts: 10,\n\n isGoodFrame: false,\n goodFramesCount: 0,\n goodFramesThreshold: 3,\n goodFramesThresholdMet: false,\n\n lastFrameCapturedAt: null,\n frameCaptureRate: 0,\n\n capturing: false,\n captured: false,\n captureFailed: false,\n}\n\ntype Action =\n | {\n type: 'configure'\n payload: {\n requiredDocumentType?: DocumentType\n goodFramesThreshold: number\n autoCaptureBarcodeRequired: boolean | 'mobile'\n barcodeScanningEnabled: boolean\n maxBarcodeScanAttempts: number\n }\n }\n | {\n type: 'objectsDetected'\n payload: { prediction: IdCapturePrediction }\n }\n | {\n type: 'barcodeScanned'\n payload: { result: PDF417DetectionResult }\n }\n | { type: 'barcodeScanFailed' }\n | { type: 'capturing' }\n | { type: 'captured' }\n | { type: 'captureFailed' }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'configure':\n return {\n ...state,\n ...action.payload,\n goodFramesCount: 0,\n captureStartedAt: new Date(),\n capturing: false,\n captured: false,\n captureFailed: false,\n }\n\n case 'objectsDetected':\n const {\n prediction: {\n detectedObjects,\n detectionScore,\n detectionThresholdMet,\n detectedDocumentType,\n passportDetectionScore,\n passportDetectionThresholdMet,\n mrzDetectionScore,\n mrzDetectionThresholdMet,\n pdf417DetectionScore,\n pdf417DetectionThresholdMet,\n bestDocumentOrPassport,\n bestMrz,\n bestPdf417,\n focusScore,\n focusThresholdMet,\n frameWidth,\n frameHeight,\n },\n } = action.payload\n\n const frameCapturedAt = new Date()\n let frameCaptureRate = 0\n let goodFramesThreshold = state.goodFramesThreshold\n if (state.lastFrameCapturedAt) {\n frameCaptureRate =\n 1000.0 /\n (frameCapturedAt.getTime() - state.lastFrameCapturedAt.getTime())\n\n if (frameCaptureRate > 0) {\n goodFramesThreshold = Math.ceil(3 * frameCaptureRate)\n }\n }\n\n let documentInBounds = false\n if (bestDocumentOrPassport) {\n const boundaryPx = 20\n let [boundaryX, boundaryY, boundaryWidth, boundaryHeight] =\n bestDocumentOrPassport.bbox\n boundaryX *= frameWidth\n boundaryWidth *= frameWidth\n boundaryY *= frameHeight\n boundaryHeight *= frameHeight\n\n documentInBounds =\n boundaryY > boundaryPx && // Is it valid top edge of ID detected?\n boundaryY + boundaryHeight + boundaryPx < frameHeight && // Is it valid bottom edge less than max video height\n (boundaryX > boundaryPx ||\n (boundaryX < boundaryPx &&\n boundaryX + boundaryWidth > frameWidth * 0.8)) && // If either the left side visible or if not, right edge of ID should be more than 80% of width.\n boundaryX + boundaryWidth + boundaryPx < frameWidth // Valid right edge if it's less than video width.\n }\n\n const barcodeScanRequired =\n state.autoCaptureBarcodeRequired === true ||\n (state.autoCaptureBarcodeRequired === 'mobile' && isMobile())\n const shouldScanBarcode =\n state.barcodeScanningEnabled &&\n pdf417DetectionThresholdMet &&\n barcodeScanRequired\n const waitingForBarcodeScan = shouldScanBarcode && !state.barcodeResult\n\n const isGoodFrame =\n detectionThresholdMet && documentInBounds && focusThresholdMet\n\n let goodFramesCount = state.goodFramesCount\n if (isGoodFrame) {\n goodFramesCount += 1\n }\n\n return {\n ...state,\n\n videoWidth: frameWidth,\n videoHeight: frameHeight,\n\n detectedObjects,\n bestDocument: bestDocumentOrPassport,\n bestMrz,\n bestPdf417,\n\n documentType: detectedDocumentType,\n documentInBounds,\n documentDetectionScore: detectionScore,\n documentDetectionThresholdMet: detectionThresholdMet,\n\n mrzDetectionScore,\n mrzDetectionThresholdMet,\n\n pdf417DetectionScore,\n pdf417DetectionThresholdMet,\n\n passportPageDetectionScore: passportDetectionScore,\n passportPageDetectionThresholdMet: passportDetectionThresholdMet,\n\n focusScore,\n focusThresholdMet,\n\n shouldScanBarcode,\n waitingForBarcodeScan,\n\n isGoodFrame,\n goodFramesCount,\n goodFramesThreshold,\n goodFramesThresholdMet: goodFramesCount >= goodFramesThreshold,\n\n lastFrameCapturedAt: frameCapturedAt,\n frameCaptureRate,\n }\n\n case 'barcodeScanned':\n return {\n ...state,\n barcodeResult: action.payload.result,\n waitingForBarcodeScan: false,\n autoCaptureBarcodeRequired: false,\n }\n\n case 'barcodeScanFailed': {\n const newState = {\n ...state,\n barcodeScanFailedAttempts: state.barcodeScanFailedAttempts + 1,\n }\n\n if (\n newState.barcodeScanFailedAttempts >= newState.maxBarcodeScanAttempts\n ) {\n newState.autoCaptureBarcodeRequired = false\n newState.shouldScanBarcode = false\n newState.waitingForBarcodeScan = false\n }\n\n return newState\n }\n\n case 'capturing':\n return {\n ...state,\n capturing: true,\n captured: false,\n captureFailed: false,\n }\n\n case 'captured':\n return {\n ...state,\n capturing: false,\n captured: true,\n captureFailed: false,\n }\n\n case 'captureFailed':\n return {\n ...state,\n capturing: false,\n captured: false,\n captureFailed: true,\n }\n\n default:\n return state\n }\n}\n\nexport type IdCaptureAssets = {\n portraitGuidesImageUrl?: string\n landscapeGuidesImageUrl?: string\n}\n\nexport type IdCaptureClassNames = {\n container?: string\n guides?: DocumentCaptureGuideOverlayClassNames\n guidanceMessageContainer?: string\n guidanceMessage?: string\n imagePreview?: IdCaptureImagePreviewClassNames\n exitCaptureBtn?: string\n}\n\nexport type IdCaptureColors = {\n guideBoxUnsatisfiedColor?: string\n guideBoxSatisfiedColor?: string\n guidanceMessagesSatisfiedBackgroundColor?: string\n guidanceMessagesUnsatisfiedBackgroundColor?: string\n guidanceMessagesSatisfiedTextColor?: string\n guidanceMessagesUnsatisfiedTextColor?: string\n}\n\nexport type IdCaptureVerbiage = {\n instructionText?: CustomerSuppliedVerbiage\n processingIdCardText?: CustomerSuppliedVerbiage\n capturingText?: CustomerSuppliedVerbiage\n captureFailedText?: CustomerSuppliedVerbiage\n guidanceSatisfiedText?: CustomerSuppliedVerbiage\n guidanceTooBlurryText?: CustomerSuppliedVerbiage\n guidanceNotCenteredText?: CustomerSuppliedVerbiage\n guidanceNotDetectedText?: CustomerSuppliedVerbiage\n}\n\nexport type IdCaptureProps = {\n requiredDocumentType?: DocumentType\n autoCaptureEnabled?: boolean\n autoCaptureScoreThreshold?: number\n autoCaptureGoodFramesRequired?: number\n autoCaptureBarcodeRequired?: boolean | 'mobile'\n mrzDetectionScoreThreshold?: number\n passportPageDetectionThreshold?: number\n pdf417DetectionThreshold?: number\n\n barcodeScanningEnabled?: boolean\n maxBarcodeScanAttempts?: number\n\n focusScoreThreshold?: number\n\n guidanceMessage?: string\n guidanceSatisfied?: boolean\n\n onPrediction?: (prediction: IdCapturePrediction) => void\n onBarcodeScanned?: (result: PDF417DetectionResult) => void\n onCapture?: (\n frame: string,\n width: number,\n height: number,\n metadata: CaptureAttemptMetadata\n ) => void\n onExit?: () => void\n\n processingScreen?: React.ReactElement\n processingDelay?: number\n\n assets?: IdCaptureAssets\n classNames?: IdCaptureClassNames\n colors?: IdCaptureColors\n verbiage?: IdCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const IdCapture = ({\n requiredDocumentType,\n autoCaptureEnabled = true,\n autoCaptureScoreThreshold = 0.8,\n autoCaptureGoodFramesRequired = 3,\n autoCaptureBarcodeRequired = 'mobile',\n mrzDetectionScoreThreshold = 0.25,\n passportPageDetectionThreshold = 0.6,\n pdf417DetectionThreshold = 0.15,\n focusScoreThreshold = 0.3,\n barcodeScanningEnabled = true,\n maxBarcodeScanAttempts = 10,\n guidanceMessage,\n guidanceSatisfied,\n onPrediction,\n onBarcodeScanned,\n onCapture,\n onExit,\n processingScreen,\n processingDelay = 0,\n assets = {},\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: IdCaptureProps): React.ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const [state, dispatch] = useReducer(reducer, initialState)\n const [imageURL, setImageURL] = useState<string>('')\n const [processingFrame, setProcessingFrame] = useState(false)\n const { cameraRef, cameraReady, takePhoto, videoRef, videoLoaded } =\n useContext(CameraStateContext)\n const captureStartedAt = useRef<Date>()\n const {\n ready: modelsReady,\n working: modelsWorking,\n setThresholds,\n makePrediction,\n onPredictionMade,\n detectionTime,\n focusPredictionTime,\n getBestFrame,\n resetBestFrame,\n } = useContext(IdCaptureModelsContext)\n\n useEffect(() => {\n captureStartedAt.current = new Date()\n }, [])\n\n useEffect(() => {\n dispatch({\n type: 'configure',\n payload: {\n requiredDocumentType,\n goodFramesThreshold: autoCaptureGoodFramesRequired,\n autoCaptureBarcodeRequired,\n barcodeScanningEnabled,\n maxBarcodeScanAttempts,\n },\n })\n\n resetBestFrame()\n setThresholds({\n document: autoCaptureScoreThreshold,\n passport: passportPageDetectionThreshold,\n mrz: mrzDetectionScoreThreshold,\n pdf417: pdf417DetectionThreshold,\n focus: focusScoreThreshold,\n })\n }, [\n requiredDocumentType,\n autoCaptureScoreThreshold,\n focusScoreThreshold,\n mrzDetectionScoreThreshold,\n autoCaptureGoodFramesRequired,\n autoCaptureBarcodeRequired,\n barcodeScanningEnabled,\n maxBarcodeScanAttempts,\n passportPageDetectionThreshold,\n pdf417DetectionThreshold,\n resetBestFrame,\n setThresholds,\n ])\n\n const animationFrame = useRef(0)\n const shouldCaptureFrames = useRef(false)\n\n useEffect(() => {\n shouldCaptureFrames.current =\n videoLoaded &&\n cameraReady &&\n modelsReady &&\n !state.capturing &&\n !state.captured\n }, [cameraReady, state.captured, state.capturing, modelsReady, videoLoaded])\n\n const [lastFrame, setLastFrame] = useState<Blob | null>(null)\n\n useEffect(() => {\n if (!modelsReady || !cameraReady || !videoLoaded) return\n\n animationFrame.current = requestAnimationFrame(async function runFrame() {\n if (shouldCaptureFrames.current && !modelsWorking.current) {\n try {\n if (state.shouldScanBarcode) {\n const frame = await takePhoto()\n if (!frame) {\n animationFrame.current = requestAnimationFrame(runFrame)\n return\n }\n setLastFrame(frame)\n }\n\n if (videoRef.current) makePrediction(videoRef.current)\n } catch (e) {\n console.error('error capturing frame', e)\n }\n }\n\n animationFrame.current = requestAnimationFrame(runFrame)\n })\n\n return () => {\n cancelAnimationFrame(animationFrame.current)\n }\n }, [\n cameraReady,\n makePrediction,\n modelsReady,\n modelsWorking,\n state.shouldScanBarcode,\n takePhoto,\n videoLoaded,\n videoRef,\n ])\n\n useEffect(() => {\n onPredictionMade((prediction) => {\n dispatch({ type: 'objectsDetected', payload: { prediction } })\n onPrediction?.(prediction)\n })\n }, [onPrediction, onPredictionMade])\n\n useEffect(() => {\n ;(async () => {\n if (state.shouldScanBarcode && lastFrame) {\n const result = await scanBarcode(lastFrame, state.bestPdf417?.bbox)\n if (result) {\n dispatch({ type: 'barcodeScanned', payload: { result } })\n onBarcodeScanned?.(result)\n } else {\n dispatch({ type: 'barcodeScanFailed' })\n }\n }\n })()\n }, [\n onBarcodeScanned,\n state.shouldScanBarcode,\n state.bestPdf417?.bbox,\n takePhoto,\n lastFrame,\n ])\n\n const shouldCapture =\n autoCaptureEnabled &&\n state.goodFramesThresholdMet &&\n !state.capturing &&\n !state.captured &&\n !state.waitingForBarcodeScan &&\n timeSince(state.captureStartedAt) >= 3000\n\n useEffect(() => {\n ;(async () => {\n if (!shouldCapture) return\n\n dispatch({ type: 'capturing' })\n\n const photo = await getBestFrame()\n if (!photo) {\n console.log('uh oh, i did not get a photo')\n dispatch({ type: 'captureFailed' })\n return\n }\n setProcessingFrame(true)\n\n const [width, height] = await getBlobDimensions(photo)\n // const canvas = new OffscreenCanvas(width, height)\n const canvas = document.createElement('canvas')\n canvas.width = width\n canvas.height = height\n\n const bitmap = await createImageBitmap(photo)\n\n // resize image to 2k max if barcode is read\n const isGreaterThan2k =\n (width > 1920 && height > 1080) || (width > 1080 && height > 1920)\n if (isGreaterThan2k && !!state.barcodeResult) {\n if (width > height) {\n canvas.width = 1920\n canvas.height = height * (1920 / width)\n } else {\n canvas.height = 1920\n canvas.width = width * (1920 / height)\n }\n const ctx2d = canvas.getContext('2d')\n if (!ctx2d) return\n ctx2d.drawImage(bitmap, 0, 0, canvas.width, canvas.height)\n } else {\n const bmpCtx = canvas.getContext('bitmaprenderer')\n if (!bmpCtx) return\n bmpCtx.transferFromImageBitmap(bitmap)\n }\n\n const imageURL = canvas.toDataURL('image/jpeg', 0.92)\n setImageURL(imageURL)\n\n setTimeout(() => {\n const captureTime =\n new Date().getTime() -\n (captureStartedAt.current ?? new Date()).getTime()\n const metadata: CaptureAttemptMetadata = {\n autoCapture: 'Y',\n captureTime,\n }\n onCapture?.(imageURL, width, height, metadata)\n dispatch({ type: 'captured' })\n setProcessingFrame(false)\n }, processingDelay)\n })()\n }, [\n getBestFrame,\n onCapture,\n processingDelay,\n shouldCapture,\n state.barcodeResult,\n ])\n\n assets.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Portrait-2.svg`\n assets.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n\n const theme = useTheme()\n colors.guideBoxUnsatisfiedColor ||=\n theme.idCapture?.guideBox?.unsatisfiedColor ?? 'white'\n colors.guideBoxSatisfiedColor ||=\n theme.idCapture?.guideBox?.satisfiedColor ?? 'green'\n\n const verbiage = useTranslations(rawVerbiage, {\n instructionText: 'Scan the front of ID',\n processingIdCardText: 'ID card front captured.',\n capturingText: 'Capturing...',\n captureFailedText: 'Capture failed!',\n guidanceSatisfiedText: 'Document detected, hold still...',\n guidanceTooBlurryText: 'Document out of focus – try improving the lighting',\n guidanceNotCenteredText: 'Document is not centered',\n guidanceNotDetectedText: 'Document not detected',\n })\n\n const debugScalingDetails = useDebugScalingDetails({\n enabled: debugMode,\n pageWidth: width,\n pageHeight: height,\n videoWidth: state.videoWidth,\n videoHeight: state.videoHeight,\n })\n\n let satisfied = state.isGoodFrame\n if (typeof guidanceSatisfied === 'boolean') satisfied = guidanceSatisfied\n\n guidanceMessage ||= satisfied\n ? verbiage.guidanceSatisfiedText\n : !state.documentDetectionThresholdMet\n ? verbiage.guidanceNotDetectedText\n : !state.documentInBounds\n ? verbiage.guidanceNotCenteredText\n : !state.focusThresholdMet\n ? verbiage.guidanceTooBlurryText\n : ''\n\n if (processingFrame) {\n return (\n <>\n {processingScreen}\n {imageURL && (\n <IdCaptureImagePreview\n classNames={classNames.imagePreview}\n text={verbiage.processingIdCardText}\n imageUrl={imageURL}\n />\n )}\n </>\n )\n }\n\n if (imageURL !== '') {\n return (\n <img\n src={imageURL}\n alt=\"\"\n style={{ maxWidth: '100%', maxHeight: '100%' }}\n />\n )\n }\n\n return (\n <PageContainer ref={ref} className={`flex ${classNames.container ?? ''}`}>\n <DocumentCaptureGuideOverlay\n classNames={classNames.guides}\n width={width}\n height={height}\n instruction={\n state.captureFailed\n ? verbiage.captureFailedText\n : state.capturing\n ? verbiage?.capturingText\n : verbiage.instructionText\n }\n portraitGuidesImageUrl={assets.portraitGuidesImageUrl}\n landscapeGuidesImageUrl={assets.landscapeGuidesImageUrl}\n isMirrored={!cameraRef.current?.isRearFacing}\n borderColor={\n state.isGoodFrame\n ? colors.guideBoxSatisfiedColor\n : colors.guideBoxUnsatisfiedColor\n }\n />\n\n {guidanceMessage !== '' && (\n <GuidanceMessageContainer\n $top=\"82.5vh\"\n className={classNames.guidanceMessageContainer}\n >\n <GuidanceMessage\n $variant={satisfied ? 'positive' : 'default'}\n className={classNames.guidanceMessage}\n >\n {guidanceMessage}\n </GuidanceMessage>\n </GuidanceMessageContainer>\n )}\n\n {debugMode && state.detectedObjects.length > 0 && (\n <ObjectDetectionDebugOverlay $flipX={!cameraRef.current?.isRearFacing}>\n {state.detectedObjects.map((obj, i) => (\n <IdCaptureDetectedObjectDebugBox\n key={i}\n obj={obj}\n scaling={debugScalingDetails}\n flipX={!cameraRef.current?.isRearFacing}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n )}\n\n {debugMode && (\n <DebugStatsPane>\n {cameraRef.current ? (\n <>\n ✅ Camera: {cameraRef.current.label} ({cameraRef.current.width}x\n {cameraRef.current.height})\n </>\n ) : (\n '❌ Camera not ready'\n )}\n <br />\n {state.frameCaptureRate > 0.75 ? '✅' : '👎'} Frame Rate:{' '}\n {Math.round((state.frameCaptureRate + Number.EPSILON) * 1000) / 1000}{' '}\n fps ({detectionTime}ms doc detect, {focusPredictionTime}ms focus)\n <br />\n {modelsReady ? (\n <>\n {state.documentDetectionThresholdMet ? '✅' : '❌'} Document\n Score: {state.documentDetectionScore} ({state.documentType})\n <br />\n {state.documentInBounds ? '✅' : '❌'} Document In Bounds\n <br />\n {state.focusThresholdMet ? '✅' : '❌'} Focus Score:{' '}\n {state.focusScore}\n <br />\n {state.goodFramesThresholdMet ? '✅' : '❌'} Good Frame Count:{' '}\n {state.goodFramesCount}/{state.goodFramesThreshold}\n {barcodeScanningEnabled && state.autoCaptureBarcodeRequired ? (\n <>\n <br />\n {state.barcodeResult ? '✅' : '❌'} Barcode Scanned (\n {supportsNativeBarcodeScanning() ? 'Native' : 'ZXing'},{' '}\n {state.barcodeScanFailedAttempts}/\n {state.maxBarcodeScanAttempts} failed attempts)\n </>\n ) : null}\n </>\n ) : (\n <>❌ Models not ready</>\n )}\n </DebugStatsPane>\n )}\n\n <ExitCaptureButton\n onClick={onExit}\n className={classNames.exitCaptureBtn}\n />\n </PageContainer>\n )\n}\n\nconst timeSince = (t: Date | null): number => {\n if (!t) return 0\n return Math.abs(new Date().getTime() - t.getTime())\n}\n","import React, { ReactElement, useContext, useEffect, useState } from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n OverlayContainer,\n OverlayImageContainer,\n OverlayInner,\n} from '../common/overlay'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport {\n CameraAccessDeniedOverlay,\n CameraAccessDeniedOverlayAssets,\n CameraAccessDeniedOverlayClassNames,\n CameraAccessDeniedOverlayColors,\n CameraAccessDeniedOverlayVerbiage,\n} from '../camera/CameraAccessDeniedOverlay'\nimport { IdCaptureModelsContext } from './IdCaptureModelsProvider'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport styled from 'styled-components'\n\nconst ContinuityCameraCheckboxContainer = styled.div`\n height: 48px;\n margin-top: -48px;\n margin-bottom: 8px;\n padding-top: 26px;\n`\n\nconst ContinuityCameraCheckbox = styled.input`\n margin-right: 8px;\n`\n\nexport type IdCaptureLoadingOverlayAssets = {\n instructionImageUrl?: string\n cameraAccessDenied?: CameraAccessDeniedOverlayAssets\n}\n\nexport type IdCaptureLoadingOverlayClassNames = {\n container?: string\n inner?: string\n heading?: string\n imageContainer?: string\n image?: string\n continuityCameraCheckboxContainer?: string\n continuityCameraCheckboxLabel?: string\n continuityCameraCheckbox?: string\n continueBtn?: string\n cameraAccessDenied?: CameraAccessDeniedOverlayClassNames\n}\n\nexport type IdCaptureLoadingOverlayColors = {\n continueBtn?: LoaderButtonColors\n cameraAccessDenied?: CameraAccessDeniedOverlayColors\n}\n\nexport type IdCaptureLoadingOverlayVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n useContinuityCameraText?: CustomerSuppliedVerbiage\n modelsWarmingUpText?: CustomerSuppliedVerbiage\n cameraInitializingText?: CustomerSuppliedVerbiage\n continueText?: CustomerSuppliedVerbiage\n cameraAccessDenied?: CameraAccessDeniedOverlayVerbiage\n}\n\nexport type IdCaptureLoadingOverlayProps = {\n onDismissed?: () => void\n\n assets?: IdCaptureLoadingOverlayAssets\n classNames?: IdCaptureLoadingOverlayClassNames\n colors?: IdCaptureLoadingOverlayColors\n verbiage?: IdCaptureLoadingOverlayVerbiage\n}\n\nexport const IdCaptureLoadingOverlay = ({\n onDismissed,\n assets = {},\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n}: IdCaptureLoadingOverlayProps): ReactElement => {\n const { ready: modelsReady } = useContext(IdCaptureModelsContext)\n const {\n cameraReady,\n cameraAccessDenied,\n iphoneContinuityCameraAvailable,\n setIphoneContinuityCameraAllowed,\n } = useContext(CameraStateContext)\n const [dismissed, setDismissed] = useState(false)\n\n assets.instructionImageUrl ||= `${DEFAULT_CDN_URL}/WebSDK-Instruction-DL-Capture-3-Portrait.png`\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: 'Use your device camera to capture your ID',\n useContinuityCameraText: 'Use your iPhone as a webcam',\n modelsWarmingUpText: 'Models warming up...',\n cameraInitializingText: 'Camera initializing...',\n continueText: 'Continue',\n })\n\n useEffect(() => {\n if (modelsReady && cameraReady) return () => null\n\n const t = setTimeout(() => {\n setDismissed(false)\n }, 500)\n\n return () => {\n clearTimeout(t)\n }\n }, [cameraReady, modelsReady])\n\n if (dismissed) return <></>\n if (cameraAccessDenied) {\n return (\n <CameraAccessDeniedOverlay\n assets={assets.cameraAccessDenied}\n classNames={classNames.cameraAccessDenied}\n colors={colors.cameraAccessDenied}\n verbiage={rawVerbiage.cameraAccessDenied}\n />\n )\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <OverlayInner className={classNames.inner}>\n <h3 className={classNames.heading}>{verbiage.headingText}</h3>\n\n <OverlayImageContainer\n className={classNames.imageContainer}\n style={{ pointerEvents: 'none' }}\n >\n <img\n alt={verbiage.headingText}\n src={assets.instructionImageUrl}\n className={classNames.image}\n />\n </OverlayImageContainer>\n\n <ContinuityCameraCheckboxContainer\n className={classNames.continuityCameraCheckboxContainer}\n >\n {iphoneContinuityCameraAvailable && (\n <>\n <ContinuityCameraCheckbox\n className={classNames.continuityCameraCheckbox}\n id=\"use-continuity-camera\"\n type=\"checkbox\"\n defaultChecked={true}\n onChange={(e) => {\n setIphoneContinuityCameraAllowed(e.target.checked)\n }}\n />\n <label\n htmlFor=\"use-continuity-camera\"\n className={classNames.continuityCameraCheckboxLabel}\n >\n {verbiage.useContinuityCameraText}\n </label>\n </>\n )}\n </ContinuityCameraCheckboxContainer>\n\n <LoaderButton\n className={classNames.continueBtn}\n variant=\"positive\"\n disabled={!cameraReady || !modelsReady}\n finished={modelsReady && cameraReady}\n colors={colors.continueBtn}\n onClick={() => {\n setDismissed(true)\n onDismissed?.()\n }}\n >\n {cameraReady && modelsReady\n ? verbiage.continueText\n : modelsReady\n ? verbiage.cameraInitializingText\n : verbiage.modelsWarmingUpText}\n </LoaderButton>\n </OverlayInner>\n </OverlayContainer>\n )\n}\n","import React, { ReactElement, useContext, useEffect, useState } from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport useResizeObserver from 'use-resize-observer'\nimport { GuideOrientationContext } from '../../contexts/GuideOrientationContext'\nimport { isMobile } from '@tensorflow/tfjs-core/dist/device_util'\nimport { PageContainer } from '../common/Page'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\nimport {\n GuideCenterBorder,\n GuideCenterRow,\n GuideImage,\n GuideRegion,\n GuidesContainer,\n GuideText,\n} from './DocumentCaptureGuideOverlay'\nimport styled from 'styled-components'\n\nconst FlippingImage = styled(GuideImage)<{\n $transitionTime?: number\n $transforms?: string\n}>`\n backface-visibility: hidden;\n transform-style: preserve-3d;\n position: relative;\n top: 0;\n left: 0;\n transition: transform ${(props) => props.$transitionTime}s;\n transform: ${(props) => props.$transforms};\n`\n\nconst FlippingImageBack = styled(FlippingImage)`\n position: absolute;\n`\n\nexport type FlipIdPromptAssets = {\n frontPortraitGuidesImageUrl?: string\n frontLandscapeGuidesImageUrl?: string\n backPortraitGuidesImageUrl?: string\n backLandscapeGuidesImageUrl?: string\n}\n\nexport type FlipIdPromptClassNames = {\n container?: string\n inner?: string\n dimmingRegion?: string\n dimmingRegionTop?: string\n dimmingRegionLeft?: string\n dimmingRegionRight?: string\n dimmingRegionBottom?: string\n centerRow?: string\n centerRegion?: string\n image?: string\n guideText?: string\n}\n\nexport type FlipIdPromptVerbiage = {\n instructionText?: CustomerSuppliedVerbiage\n}\n\nexport type FlipIdPromptProps = {\n assets?: FlipIdPromptAssets\n classNames?: FlipIdPromptClassNames\n verbiage?: FlipIdPromptVerbiage\n}\n\nexport const FlipIdPrompt = ({\n assets = {},\n classNames = {},\n verbiage = {},\n}: FlipIdPromptProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const { cameraRef } = useContext(CameraStateContext)\n\n assets.frontPortraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Portrait-2.svg`\n assets.frontLandscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.backPortraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Portrait-2.svg`\n assets.backLandscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n\n const instruction = useVerbiage(\n verbiage.instructionText,\n 'Please flip your ID card...'\n )\n\n const padding = isMobile() ? 0 : 50\n const borderWidth = 4\n const borderColor = 'white'\n const isMirrored = !cameraRef.current?.isRearFacing\n\n const {\n orientation,\n wrapperRef,\n wrapperWidth,\n wrapperHeight,\n imageAspectRatio,\n wrapperAspectRatio,\n onImageLoaded,\n setDimensions,\n } = useContext(GuideOrientationContext)\n\n useEffect(() => {\n setDimensions({ width, height })\n }, [height, setDimensions, width])\n\n const paddingAndBorderPx = padding * 2 + borderWidth * 2\n\n let imageWidth: number | undefined = undefined,\n imageHeight: number | undefined = undefined\n if (imageAspectRatio >= wrapperAspectRatio) {\n imageWidth = wrapperWidth - paddingAndBorderPx\n } else {\n imageHeight = wrapperHeight - paddingAndBorderPx\n }\n\n const [transitionTime, setTransitionTime] = useState(1)\n const [rotationAngle, setRotationAngle] = useState(0)\n const frontTransforms = [`rotateY(${rotationAngle}deg)`]\n if (isMirrored) frontTransforms.push('scaleX(-1)')\n const backTransforms = [`rotateY(${180 - rotationAngle}deg)`]\n if (isMirrored) backTransforms.push('scaleX(-1)')\n\n useEffect(() => {\n const doFlip = () => {\n setTransitionTime(1)\n setRotationAngle(180)\n\n setTimeout(() => {\n setTransitionTime(0)\n setRotationAngle(0)\n }, 1500)\n }\n\n setTimeout(doFlip, 250)\n const interval = setInterval(doFlip, 2500)\n\n return () => {\n clearInterval(interval)\n }\n }, [])\n\n return (\n <PageContainer ref={ref} className={`flex ${classNames.container ?? ''}`}>\n <GuidesContainer ref={wrapperRef} className={classNames.inner}>\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Top')}\n >\n {instruction !== '' && (\n <GuideText className={classNames.guideText}>\n {instruction}\n </GuideText>\n )}\n </GuideRegion>\n\n <GuideCenterRow className={classNames.centerRow}>\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Left')}\n />\n\n <GuideCenterBorder\n $borderWidth={borderWidth}\n $borderColor={borderColor}\n className={classNames.centerRegion}\n >\n <FlippingImage\n src={\n orientation === 'portrait'\n ? assets.frontPortraitGuidesImageUrl\n : assets.frontLandscapeGuidesImageUrl\n }\n alt=\"\"\n className={classNames.image}\n $width={imageWidth}\n $height={imageHeight}\n $transitionTime={transitionTime}\n $transforms={frontTransforms.join(' ')}\n onLoad={onImageLoaded}\n />\n\n <FlippingImageBack\n src={\n orientation === 'portrait'\n ? assets.backPortraitGuidesImageUrl\n : assets.backLandscapeGuidesImageUrl\n }\n alt=\"\"\n className={classNames.image}\n $width={imageWidth}\n $height={imageHeight}\n $transitionTime={transitionTime}\n $transforms={backTransforms.join(' ')}\n />\n </GuideCenterBorder>\n\n <GuideRegion\n $minWidth={padding}\n className={regionClsx(classNames, 'Right')}\n />\n </GuideCenterRow>\n\n <GuideRegion\n $minHeight={padding}\n className={regionClsx(classNames, 'Bottom')}\n >\n {instruction !== '' && (\n <GuideText style={{ opacity: 0 }}>{instruction}</GuideText>\n )}\n </GuideRegion>\n </GuidesContainer>\n </PageContainer>\n )\n}\n\nconst regionClsx = (\n classNames: FlipIdPromptClassNames,\n which: 'Top' | 'Left' | 'Right' | 'Bottom'\n): string =>\n [classNames.dimmingRegion, classNames[`dimmingRegion${which}`]]\n .filter((v) => v)\n .join(' ')\n","import styled from 'styled-components'\n\nexport const ButtonsRow = styled.div`\n display: flex;\n gap: 0 15px;\n justify-content: center;\n`\n","import React, { ReactElement, useCallback, useContext, useEffect } from 'react'\nimport styled from 'styled-components'\nimport { CameraStateContext } from './CameraProvider'\n\nexport const CameraVideoTag = ({\n className,\n}: {\n className?: string\n}): ReactElement => {\n const { videoRef, setVideoLoaded, cameraRef } = useContext(CameraStateContext)\n\n useEffect(() => {\n setVideoLoaded(false)\n }, [setVideoLoaded])\n\n useEffect(() => {\n if (videoRef.current && cameraRef.current?.stream) {\n videoRef.current.srcObject = cameraRef.current.stream\n }\n }, [cameraRef, videoRef])\n\n const onLoadedData = useCallback(() => {\n setVideoLoaded(true)\n }, [setVideoLoaded])\n\n return (\n <FullscreenVideoTag\n className={className}\n autoPlay\n playsInline\n muted\n ref={videoRef}\n onLoadedData={onLoadedData}\n $isRearFacing={cameraRef.current?.isRearFacing}\n />\n )\n}\n\nexport const FullscreenVideoTag = styled.video<{ $isRearFacing?: boolean }>`\n transform: ${(props) => (props.$isRearFacing ? '' : 'scaleX(-1)')};\n min-width: 100%;\n min-height: 100%;\n width: auto;\n height: auto;\n object-fit: cover;\n`\n","import { useEffect, useState } from 'react'\n\nexport function useShowSuccessScreen(\n skipSuccessScreen: boolean | (() => Promise<boolean>),\n successScreenReady: boolean,\n onDoneCallback?: () => void,\n): boolean {\n const [skipSuccessScreenResolvedFalse, setSkipSuccessScreenResolvedFalse] =\n useState(false)\n\n useEffect(() => {\n if (successScreenReady && skipSuccessScreen) {\n if (typeof skipSuccessScreen === 'function') {\n ;(async () => {\n if (await skipSuccessScreen()) {\n onDoneCallback?.()\n } else {\n setSkipSuccessScreenResolvedFalse(true)\n }\n })()\n } else {\n onDoneCallback?.()\n }\n }\n }, [successScreenReady, onDoneCallback, skipSuccessScreen])\n\n return !skipSuccessScreen || skipSuccessScreenResolvedFalse\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport {\n OverlayContainer,\n OverlayImageRow,\n OverlayInner,\n} from '../common/overlay'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport styled from 'styled-components'\nimport { ButtonsRow } from '../common/ButtonsRow'\n\nexport type IdCaptureFallbackClassNames = {\n container?: string\n inner?: string\n heading?: string\n description?: string\n imageContainer?: string\n imageCol?: string\n image?: string\n instruction?: string\n buttonsRow?: string\n captureBtn?: string\n captureMoreBtn?: string\n doneBtn?: string\n}\n\nexport type IdCaptureFallbackColors = {\n captureBtn?: LoaderButtonColors\n captureMoreBtn?: LoaderButtonColors\n doneBtn?: LoaderButtonColors\n}\n\nexport type IdCaptureFallbackVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n descriptionText?: CustomerSuppliedVerbiage\n firstInstructionText?: CustomerSuppliedVerbiage\n secondInstructionText?: CustomerSuppliedVerbiage\n captureBtnText?: CustomerSuppliedVerbiage\n captureMoreBtnText?: CustomerSuppliedVerbiage\n doneBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type IdCaptureFallbackProps = {\n onCapture?: (imageData: string) => void\n onFinished?: (images: string[]) => void\n classNames?: IdCaptureFallbackClassNames\n colors?: IdCaptureFallbackColors\n verbiage?: IdCaptureFallbackVerbiage\n}\n\nexport const IdCaptureFallback = ({\n onCapture,\n onFinished,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n}: IdCaptureFallbackProps): ReactElement => {\n const fileInput = useRef<HTMLInputElement | null>(null)\n const [images, setImages] = useState<string[]>([])\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: `We're having some trouble.`,\n descriptionText:\n 'On-device capture guidance failed, please capture photos of your ID card or passport manually.',\n firstInstructionText:\n 'Please capture the front of your ID card, or the ID page of your passport.',\n secondInstructionText:\n 'Please capture the back of your ID card, or click Done if submitting a passport.',\n captureBtnText: 'Capture',\n captureMoreBtnText: 'Capture back of ID Card',\n doneBtnText: 'Done',\n })\n\n function onFileSelected(e: React.ChangeEvent<HTMLInputElement>) {\n const file = e.target.files?.[0]\n if (!file) return\n\n const reader = new FileReader()\n reader.addEventListener('load', (e) => {\n const imageData = e.target?.result as string\n setImages((images) => [...images, imageData])\n onCapture?.(imageData)\n })\n reader.readAsDataURL(file)\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <StyledOverlayInner className={classNames.inner}>\n <Heading className={classNames.heading}>{verbiage.headingText}</Heading>\n <Description className={classNames.description}>\n {verbiage.descriptionText}\n </Description>\n\n {images.length > 0 && (\n <OverlayImageRow className={classNames.imageContainer}>\n {images.map((image, i) => (\n <ImageCol key={i} className={classNames.imageCol}>\n <img src={image} alt=\"\" className={classNames.image} />\n </ImageCol>\n ))}\n </OverlayImageRow>\n )}\n\n {images.length < 2 && (\n <Instruction className={classNames.instruction}>\n {images.length === 0\n ? verbiage.firstInstructionText\n : verbiage.secondInstructionText}\n </Instruction>\n )}\n\n <input\n ref={fileInput}\n type=\"file\"\n accept=\"image/*\"\n onChange={onFileSelected}\n hidden\n />\n\n <StyledButtonsRow className={classNames.buttonsRow}>\n {images.length < 2 && (\n <LoaderButton\n variant={images.length > 0 ? 'secondary' : 'positive'}\n className={\n images.length > 0\n ? classNames.captureMoreBtn\n : classNames.captureBtn\n }\n colors={\n images.length > 0 ? colors.captureMoreBtn : colors.captureBtn\n }\n finished\n onClick={() => {\n fileInput.current?.click()\n }}\n >\n {images.length > 0\n ? verbiage.captureMoreBtnText\n : verbiage.captureBtnText}\n </LoaderButton>\n )}\n\n {images.length > 0 && (\n <LoaderButton\n variant=\"positive\"\n className={classNames.doneBtn}\n colors={colors.doneBtn}\n finished\n onClick={() => {\n onFinished?.(images)\n }}\n >\n {verbiage.doneBtnText}\n </LoaderButton>\n )}\n </StyledButtonsRow>\n </StyledOverlayInner>\n </OverlayContainer>\n )\n}\n\nconst StyledOverlayInner = styled(OverlayInner)`\n justify-content: center;\n`\n\nconst Heading = styled.h3`\n margin-bottom: 8px;\n`\n\nconst Description = styled.p`\n margin-bottom: 8px;\n`\n\nconst Instruction = styled.p`\n font-weight: bold;\n`\n\nconst ImageCol = styled.div`\n display: flex;\n justify-content: center;\n flex-grow: 1;\n flex-basis: 0;\n`\n\nconst StyledButtonsRow = styled(ButtonsRow)`\n margin-top: 32px;\n`\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport { DocumentType } from '../../lib/models/DocumentDetection'\nimport {\n IdCapture,\n IdCaptureAssets,\n IdCaptureClassNames,\n IdCaptureColors,\n IdCaptureVerbiage,\n} from './IdCapture'\nimport { PDF417DetectionResult } from '../../lib/barcode/Native'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n IdCaptureLoadingOverlay,\n IdCaptureLoadingOverlayAssets,\n IdCaptureLoadingOverlayClassNames,\n IdCaptureLoadingOverlayColors,\n IdCaptureLoadingOverlayVerbiage,\n} from './IdCaptureLoadingOverlay'\nimport {\n FlipIdPrompt,\n FlipIdPromptAssets,\n FlipIdPromptClassNames,\n FlipIdPromptVerbiage,\n} from './FlipIdPrompt'\nimport { dataUrlToBase64Sync } from '../../lib/utils/dataUrlToBase64'\nimport {\n CaptureAttemptMetadata,\n SubmissionStatus,\n} from '../../contexts/SubmissionContext'\nimport {\n CapturedDocument,\n CapturedDocuments,\n} from '../additional_document_capture/CapturedDocuments'\nimport {\n IdCaptureSuccess,\n IdCaptureSuccessClassNames,\n IdCaptureSuccessColors,\n IdCaptureSuccessVerbiage,\n} from './IdCaptureSuccess'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport { PageContainer } from '../common/Page'\nimport {\n IdCaptureModelsContext,\n IdCapturePrediction,\n} from './IdCaptureModelsProvider'\nimport { useShowSuccessScreen } from '../common/useShowSuccessScreen'\nimport { useTranslations } from '../../lib/locales'\nimport {\n IdCaptureFallback,\n IdCaptureFallbackClassNames,\n IdCaptureFallbackColors,\n IdCaptureFallbackVerbiage,\n} from '../fallback_flows/IdCapture'\nimport { SubmissionContext } from '../submission/SubmissionProvider'\n\nenum CaptureState {\n CAPTURING = 'CAPTURING',\n COMPLETE = 'COMPLETE',\n}\n\ntype State = {\n captureState: CaptureState\n capturedDocuments: CapturedDocuments\n requestedDocumentType: DocumentType\n currentDocumentType: DocumentType\n differentDocumentTypeDetections: number\n barcodeResult: PDF417DetectionResult | null\n}\n\nconst initialState: State = {\n captureState: CaptureState.CAPTURING,\n capturedDocuments: {},\n requestedDocumentType: DocumentType.ID_CARD_FRONT,\n currentDocumentType: DocumentType.NONE,\n differentDocumentTypeDetections: 0,\n barcodeResult: null,\n}\n\ntype Action =\n | { type: 'predictionMade'; payload: { prediction: IdCapturePrediction } }\n | { type: 'barcodeScanned'; payload: { result: PDF417DetectionResult } }\n | { type: 'imageCaptured'; payload: CapturedDocument }\n | { type: 'imageCapturedManually'; payload: { imageData: string } }\n | { type: 'reset' }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'predictionMade': {\n const { prediction } = action.payload\n const newState = {\n ...state,\n currentDocumentType: prediction.detectedDocumentType,\n }\n\n if (newState.currentDocumentType === state.requestedDocumentType) {\n newState.differentDocumentTypeDetections = 0\n }\n\n if (\n prediction.detectedDocumentType === 'PASSPORT' &&\n state.requestedDocumentType !== 'PASSPORT'\n ) {\n newState.requestedDocumentType = DocumentType.PASSPORT\n }\n\n if (\n state.requestedDocumentType === 'PASSPORT' &&\n prediction.passportDetectionScore < 0.3\n ) {\n newState.requestedDocumentType = DocumentType.ID_CARD_FRONT\n }\n\n return newState\n }\n\n case 'barcodeScanned':\n return { ...state, barcodeResult: action.payload.result }\n\n case 'imageCaptured': {\n const newState = {\n ...state,\n capturedDocuments: {\n ...state.capturedDocuments,\n [state.requestedDocumentType]: action.payload,\n },\n }\n\n if (\n state.requestedDocumentType === 'ID_CARD_FRONT' &&\n !state.capturedDocuments['ID_CARD_BACK']\n ) {\n newState.requestedDocumentType = DocumentType.ID_CARD_BACK\n } else if (\n state.requestedDocumentType === 'ID_CARD_BACK' &&\n !state.capturedDocuments['ID_CARD_FRONT']\n ) {\n newState.requestedDocumentType = DocumentType.ID_CARD_FRONT\n } else {\n newState.captureState = CaptureState.COMPLETE\n }\n\n return newState\n }\n\n case 'imageCapturedManually': {\n const newState = { ...state }\n const capturedDocument = { ...action.payload, width: 0, height: 0 }\n\n if (Object.keys(state.capturedDocuments).length === 0) {\n newState.capturedDocuments[DocumentType.PASSPORT] = capturedDocument\n } else {\n newState.capturedDocuments = {}\n newState.capturedDocuments[DocumentType.ID_CARD_FRONT] =\n state.capturedDocuments[DocumentType.PASSPORT]\n newState.capturedDocuments[DocumentType.ID_CARD_BACK] = capturedDocument\n }\n\n return newState\n }\n\n case 'reset':\n return { ...initialState }\n }\n}\n\nexport type IdCaptureWizardAssets = {\n documentDetectionModelUrl?: string\n focusModelUrl?: string\n loadingOverlay?: IdCaptureLoadingOverlayAssets\n idCardFront?: IdCaptureAssets\n idCardBack?: IdCaptureAssets\n passport?: IdCaptureAssets\n flipIdPrompt?: FlipIdPromptAssets\n}\n\nexport type IdCaptureWizardClassNames = {\n container?: string\n cameraFeed?: string\n loadingOverlay?: IdCaptureLoadingOverlayClassNames\n capture?: IdCaptureClassNames\n flipIdPrompt?: FlipIdPromptClassNames\n success?: IdCaptureSuccessClassNames\n fallback?: IdCaptureFallbackClassNames\n}\n\nexport type IdCaptureWizardColors = IdCaptureColors & {\n loadingOverlay?: IdCaptureLoadingOverlayColors\n success?: IdCaptureSuccessColors\n fallback?: IdCaptureFallbackColors\n}\n\nexport type IdCaptureWizardVerbiage = {\n loadingOverlay?: IdCaptureLoadingOverlayVerbiage\n idCardFront?: IdCaptureVerbiage\n idCardBack?: IdCaptureVerbiage\n passport?: IdCaptureVerbiage\n flipIdPrompt?: FlipIdPromptVerbiage\n success?: IdCaptureSuccessVerbiage\n fallback?: IdCaptureFallbackVerbiage\n}\n\nexport type IdCaptureSubmission = {\n idFrontImage: string | null\n idBackImage: string | null\n passportImage: string | null\n}\n\nexport type IdCaptureWizardProps = {\n onSuccess?: (submission: IdCaptureSubmission) => void\n onExitCapture?: () => void\n\n autoCaptureEnabled?: boolean\n autoCaptureGoodFramesRequired?: number\n autoCaptureBarcodeRequired?: 'mobile' | boolean\n barcodeScanningEnabled?: boolean\n idCardAutoCaptureScoreThreshold?: number\n passportAutoCaptureScoreThreshold?: number\n mrzDetectionScoreThreshold?: number\n idCardFocusScoreThreshold?: number\n passportFocusScoreThreshold?: number\n skipSuccessScreen?: boolean | (() => Promise<boolean>)\n releaseCameraAccessOnExit?: boolean\n\n assets?: IdCaptureWizardAssets\n classNames?: IdCaptureWizardClassNames\n colors?: IdCaptureWizardColors\n verbiage?: IdCaptureWizardVerbiage\n debugMode?: boolean\n}\n\nexport const IdCaptureWizard = ({\n onSuccess,\n onExitCapture,\n\n autoCaptureEnabled = true,\n autoCaptureGoodFramesRequired = 3,\n autoCaptureBarcodeRequired = 'mobile',\n barcodeScanningEnabled = false,\n idCardAutoCaptureScoreThreshold = 0.8,\n passportAutoCaptureScoreThreshold = 0.75,\n mrzDetectionScoreThreshold = 0.25,\n idCardFocusScoreThreshold = 0.3,\n passportFocusScoreThreshold = 0.3,\n skipSuccessScreen = false,\n releaseCameraAccessOnExit = true,\n\n assets = {},\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: IdCaptureWizardProps): ReactElement => {\n const [state, dispatch] = useReducer(reducer, initialState)\n const { releaseCameraAccess } = useContext(CameraStateContext)\n const [overlayDismissed, setOverlayDismissed] = useState(false)\n const {\n submissionStatus,\n setIdFrontImage,\n setIdBackImage,\n setPassportImage,\n logIdFrontCaptureAttempt,\n logIdBackCaptureAttempt,\n } = useContext(SubmissionContext)\n const { error: modelsError } = useContext(IdCaptureModelsContext)\n const operationStartedAt = useRef<Date>()\n\n useEffect(() => {\n operationStartedAt.current = new Date()\n }, [state.capturedDocuments.length])\n\n const logCaptureMetadata = useCallback(\n (metadata: CaptureAttemptMetadata) => {\n metadata.operationTime =\n new Date().getTime() -\n (operationStartedAt.current ?? new Date()).getTime()\n\n state.requestedDocumentType === 'ID_CARD_BACK'\n ? logIdBackCaptureAttempt(metadata)\n : logIdFrontCaptureAttempt(metadata)\n },\n [\n logIdBackCaptureAttempt,\n logIdFrontCaptureAttempt,\n state.requestedDocumentType,\n ]\n )\n\n const onPrediction = useCallback((prediction: IdCapturePrediction) => {\n dispatch({ type: 'predictionMade', payload: { prediction } })\n }, [])\n\n const onBarcodeScanned = useCallback((result: PDF417DetectionResult) => {\n dispatch({ type: 'barcodeScanned', payload: { result } })\n }, [])\n\n const onCapture = useCallback(\n (\n imageData: string,\n width: number,\n height: number,\n metadata: CaptureAttemptMetadata\n ) => {\n logCaptureMetadata(metadata)\n dispatch({ type: 'imageCaptured', payload: { imageData, width, height } })\n },\n [logCaptureMetadata]\n )\n\n const onSubmitClick = useCallback(() => {\n const idFrontDocument = state.capturedDocuments['ID_CARD_FRONT']\n const idBackDocument = state.capturedDocuments['ID_CARD_BACK']\n const passportDocument = state.capturedDocuments['PASSPORT']\n\n const idFrontImage =\n idFrontDocument && dataUrlToBase64Sync(idFrontDocument.imageData)\n const idBackImage =\n idBackDocument && dataUrlToBase64Sync(idBackDocument.imageData)\n const passportImage =\n passportDocument && dataUrlToBase64Sync(passportDocument.imageData)\n\n setIdFrontImage(idFrontImage)\n setIdBackImage(idBackImage)\n setPassportImage(passportImage)\n\n releaseCameraAccessOnExit && releaseCameraAccess()\n setTimeout(() => {\n onSuccess?.({ idFrontImage, idBackImage, passportImage })\n }, 0)\n }, [\n onSuccess,\n releaseCameraAccess,\n releaseCameraAccessOnExit,\n setIdBackImage,\n setIdFrontImage,\n setPassportImage,\n state.capturedDocuments,\n ])\n\n const showSuccessScreen = useShowSuccessScreen(\n skipSuccessScreen,\n state.captureState === CaptureState.COMPLETE,\n onSubmitClick\n )\n\n const onRetryClick = useCallback(() => {\n dispatch({ type: 'reset' })\n }, [])\n\n const [attempt, setAttempt] = useState(0)\n const onExit = useCallback(() => {\n setOverlayDismissed(false)\n setAttempt((n) => n + 1)\n dispatch({ type: 'reset' })\n onExitCapture?.()\n }, [onExitCapture])\n\n useEffect(() => {\n if (submissionStatus !== SubmissionStatus.READY) {\n releaseCameraAccessOnExit && releaseCameraAccess()\n }\n }, [releaseCameraAccess, releaseCameraAccessOnExit, submissionStatus])\n\n assets.idCardFront ||= {}\n assets.idCardFront.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Portrait-2.svg`\n assets.idCardFront.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.idCardBack ||= {}\n assets.idCardBack.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Portrait-2.svg`\n assets.idCardBack.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n assets.passport ||= {}\n assets.passport.portraitGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-Passport-Front-SVG-Portrait-2.svg`\n assets.passport.landscapeGuidesImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-Passport-Front-SVG-Landscape-2.svg`\n assets.flipIdPrompt ||= {}\n assets.flipIdPrompt.frontPortraitGuidesImageUrl ||=\n assets.idCardFront.portraitGuidesImageUrl\n assets.flipIdPrompt.frontLandscapeGuidesImageUrl ||=\n assets.idCardFront.landscapeGuidesImageUrl\n assets.flipIdPrompt.backPortraitGuidesImageUrl ||=\n assets.idCardBack.portraitGuidesImageUrl\n assets.flipIdPrompt.backLandscapeGuidesImageUrl ||=\n assets.idCardBack.landscapeGuidesImageUrl\n\n const idCardFrontVerbiage = useTranslations(verbiage.idCardFront, {\n instructionText: 'Scan the front of ID',\n processingIdCardText: 'ID card front captured.',\n })\n const idCardBackVerbiage = useTranslations(verbiage.idCardBack, {\n instructionText: 'Scan the back of ID',\n })\n const passportVerbiage = useTranslations(verbiage.idCardBack, {\n instructionText: 'Scan the ID page of passport',\n })\n\n if (modelsError) {\n return (\n <IdCaptureFallback\n onFinished={onSubmitClick}\n onCapture={(imageData) => {\n dispatch({ type: 'imageCapturedManually', payload: { imageData } })\n }}\n classNames={classNames.fallback}\n colors={colors.fallback}\n verbiage={verbiage.fallback}\n />\n )\n }\n\n return (\n <PageContainer className={`flex ${classNames?.container ?? ''}`}>\n {state.captureState !== CaptureState.COMPLETE && (\n <CameraVideoTag className={classNames?.cameraFeed} />\n )}\n\n {overlayDismissed &&\n (() => {\n const docCount = Object.keys(state.capturedDocuments).length\n switch (state.requestedDocumentType) {\n case DocumentType.ID_CARD_FRONT:\n return (\n <IdCapture\n key={`capture${docCount}`}\n requiredDocumentType={state.requestedDocumentType}\n autoCaptureEnabled={autoCaptureEnabled}\n autoCaptureScoreThreshold={idCardAutoCaptureScoreThreshold}\n autoCaptureGoodFramesRequired={autoCaptureGoodFramesRequired}\n autoCaptureBarcodeRequired={autoCaptureBarcodeRequired}\n barcodeScanningEnabled={false}\n mrzDetectionScoreThreshold={mrzDetectionScoreThreshold}\n focusScoreThreshold={idCardFocusScoreThreshold}\n onPrediction={onPrediction}\n onCapture={onCapture}\n onExit={onExit}\n processingDelay={3500}\n assets={assets.idCardFront}\n classNames={classNames?.capture}\n colors={colors}\n verbiage={idCardFrontVerbiage}\n debugMode={debugMode}\n processingScreen={\n <FlipIdPrompt\n assets={assets.flipIdPrompt}\n classNames={classNames.flipIdPrompt}\n verbiage={verbiage.flipIdPrompt}\n />\n }\n />\n )\n\n case DocumentType.ID_CARD_BACK:\n return (\n <IdCapture\n key={`capture${docCount}`}\n requiredDocumentType={state.requestedDocumentType}\n autoCaptureEnabled={autoCaptureEnabled}\n autoCaptureScoreThreshold={idCardAutoCaptureScoreThreshold}\n autoCaptureGoodFramesRequired={autoCaptureGoodFramesRequired}\n autoCaptureBarcodeRequired={autoCaptureBarcodeRequired}\n barcodeScanningEnabled={barcodeScanningEnabled}\n mrzDetectionScoreThreshold={mrzDetectionScoreThreshold}\n focusScoreThreshold={idCardFocusScoreThreshold}\n onPrediction={onPrediction}\n onBarcodeScanned={onBarcodeScanned}\n onCapture={onCapture}\n onExit={onExit}\n assets={assets.idCardBack}\n classNames={classNames?.capture}\n colors={colors}\n verbiage={idCardBackVerbiage}\n debugMode={debugMode}\n />\n )\n\n case DocumentType.PASSPORT:\n return (\n <IdCapture\n key={`capture${docCount}`}\n requiredDocumentType={state.requestedDocumentType}\n autoCaptureEnabled={autoCaptureEnabled}\n autoCaptureScoreThreshold={passportAutoCaptureScoreThreshold}\n mrzDetectionScoreThreshold={mrzDetectionScoreThreshold}\n autoCaptureGoodFramesRequired={autoCaptureGoodFramesRequired}\n autoCaptureBarcodeRequired={autoCaptureBarcodeRequired}\n barcodeScanningEnabled={false}\n focusScoreThreshold={passportFocusScoreThreshold}\n onPrediction={onPrediction}\n onBarcodeScanned={onBarcodeScanned}\n onCapture={onCapture}\n onExit={onExit}\n assets={assets.passport}\n classNames={classNames?.capture}\n colors={colors}\n verbiage={passportVerbiage}\n debugMode={debugMode}\n />\n )\n\n default:\n return null\n }\n })()}\n\n {!overlayDismissed && (\n <IdCaptureLoadingOverlay\n key={attempt}\n assets={assets.loadingOverlay}\n classNames={classNames.loadingOverlay}\n colors={colors.loadingOverlay}\n verbiage={verbiage.loadingOverlay}\n onDismissed={() => {\n setOverlayDismissed(true)\n }}\n />\n )}\n\n {state.captureState === CaptureState.COMPLETE && showSuccessScreen && (\n <IdCaptureSuccess\n capturedDocuments={state.capturedDocuments}\n barcodeResult={state.barcodeResult}\n classNames={classNames.success}\n onSubmitClick={onSubmitClick}\n onRetryClick={onRetryClick}\n colors={colors.success}\n verbiage={verbiage.success}\n />\n )}\n </PageContainer>\n )\n}\n","import * as React from 'react'\nimport {\n createContext,\n MutableRefObject,\n ReactElement,\n ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n FaceDetector,\n FilesetResolver,\n FaceDetectorResult,\n} from '@mediapipe/tasks-vision'\n\nconst NUM_KEYPOINTS = 6\nconst GREEN = '#32EEDB'\nconst RED = '#FF2C35'\n// const FACE_DETECTOR_VERSION = mpFaceDetection.VERSION ?? '0.4.1646425229'\n// const FACE_DETECTOR_VERSION = '0.4.1646425229'\n\nexport type FaceKeypoint = { x: number; y: number; name: string }\nexport type Face = {\n keypoints: FaceKeypoint[]\n box: {\n xMin: number\n xMax: number\n yMin: number\n yMax: number\n width: number\n height: number\n }\n}\n\nfunction drawPath(\n ctx: CanvasRenderingContext2D,\n points: number[][],\n closePath: boolean,\n) {\n const region = new Path2D()\n region.moveTo(points[0][0], points[0][1])\n for (let i = 1; i < points.length; i++) {\n const point = points[i]\n region.lineTo(point[0], point[1])\n }\n\n if (closePath) {\n region.closePath()\n }\n ctx.stroke(region)\n}\n\n/**\n * Draw the keypoints on the video.\n * @param ctx 2D rendering context.\n * @param faces A list of faces to render.\n * @param boundingBox Whether or not to display the bounding box.\n * @param showKeypoints Whether or not to display the keypoints.\n */\nfunction drawResults(\n ctx: CanvasRenderingContext2D,\n faces: Face[],\n boundingBox: boolean,\n showKeypoints: boolean,\n) {\n faces.forEach((face) => {\n const keypoints = face.keypoints.map((keypoint) => [keypoint.x, keypoint.y])\n\n if (boundingBox) {\n ctx.strokeStyle = RED\n ctx.lineWidth = 1\n\n const box = face.box\n drawPath(\n ctx,\n [\n [box.xMin, box.yMin],\n [box.xMax, box.yMin],\n [box.xMax, box.yMax],\n [box.xMin, box.yMax],\n ],\n true,\n )\n }\n\n if (showKeypoints) {\n ctx.fillStyle = GREEN\n\n for (let i = 0; i < NUM_KEYPOINTS; i++) {\n const x = keypoints[i][0]\n const y = keypoints[i][1]\n\n ctx.beginPath()\n ctx.arc(x, y, 3 /* radius */, 0, 2 * Math.PI)\n ctx.fill()\n }\n }\n })\n}\n\nlet detector: FaceDetector\n\nexport async function loadHighPerformanceFaceDetector(): Promise<FaceDetector> {\n if (detector) return detector\n\n const vision = await FilesetResolver.forVisionTasks(\n 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.7/wasm',\n )\n\n detector = await FaceDetector.createFromOptions(vision, {\n baseOptions: {\n modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite`,\n delegate: 'GPU',\n },\n runningMode: 'VIDEO',\n })\n\n return detector\n}\n\ntype PredictionHandler = (prediction: Face[]) => void\ntype HighPerformanceSelfieGuidanceModelsState = {\n start: () => void\n stop: () => void\n onPredictionMade: (handler: PredictionHandler) => void\n canvasRef: MutableRefObject<HTMLCanvasElement | null>\n ready: boolean\n error: Error | null\n}\n\nexport const HighPerformanceSelfieGuidanceModelsContext =\n createContext<HighPerformanceSelfieGuidanceModelsState>({\n start: () => null,\n stop: () => null,\n onPredictionMade: () => null,\n canvasRef: { current: null },\n ready: false,\n error: null,\n })\n\nexport const HighPerformanceSelfieGuidanceModelsProvider = ({\n autoStart = true,\n children,\n throttleMs,\n}: {\n autoStart?: boolean\n children: ReactNode\n throttleMs?: number\n}): ReactElement => {\n const { videoRef, videoLoaded, cameraReady } = useContext(CameraStateContext)\n const canvasRef = useRef<HTMLCanvasElement>(null)\n const onPredictionHandler = useRef<PredictionHandler>()\n const [ready, setReady] = useState(false)\n const [running, setRunning] = useState(false)\n const detectorRef = useRef<FaceDetector | null>(null)\n const rafId = useRef(0)\n const loopId = useRef(0)\n const [error, setError] = useState<Error | null>(null)\n\n useEffect(() => {\n ;(async () => {\n setReady(false)\n try {\n detectorRef.current = await loadHighPerformanceFaceDetector()\n } catch (e) {\n setError(e as Error)\n }\n setReady(true)\n })()\n }, [])\n\n useEffect(() => {\n if (!videoLoaded || !cameraReady || !running || !ready) return\n let timer: NodeJS.Timeout\n loopId.current += 1\n const currentLoopId = loopId.current\n\n ;(async () => {\n if (!videoRef.current || !detectorRef.current) return\n\n const ctx = canvasRef.current?.getContext('2d')\n if (canvasRef.current) {\n canvasRef.current.width = videoRef.current?.videoWidth\n canvasRef.current.height = videoRef.current?.videoHeight\n ctx?.translate(videoRef.current.videoWidth, 0)\n ctx?.scale(-1, 1)\n }\n\n await (async function renderPrediction() {\n if (\n !detectorRef.current ||\n !videoRef.current ||\n currentLoopId !== loopId.current\n )\n return\n\n if (videoRef.current.readyState < 2) {\n await new Promise((resolve) => {\n if (videoRef.current)\n videoRef.current.onloadeddata = () => {\n resolve([])\n }\n })\n }\n\n const vw = videoRef.current.videoWidth\n const vh = videoRef.current.videoHeight\n ctx?.drawImage(videoRef.current, 0, 0, vw, vh)\n\n let prediction: FaceDetectorResult | null\n // Detectors can throw errors, for example when using custom URLs that\n // contain a model that doesn't provide the expected output.\n try {\n prediction = await detectorRef.current.detectForVideo(\n videoRef.current,\n performance.now(),\n )\n if (prediction) {\n const faces = prediction.detections.map<Face>((d) => ({\n keypoints: d.keypoints.map((k) => ({\n ...k,\n x: k.x * vw,\n y: k.y * vh,\n name: k.label ?? '',\n })),\n box: {\n xMin: d.boundingBox?.originX ?? 0,\n xMax:\n (d.boundingBox?.originX ?? 0) + (d.boundingBox?.width ?? 0),\n yMin: d.boundingBox?.originY ?? 0,\n yMax:\n (d.boundingBox?.originY ?? 0) + (d.boundingBox?.height ?? 0),\n width: d.boundingBox?.width ?? 0,\n height: d.boundingBox?.height ?? 0,\n },\n }))\n onPredictionHandler.current?.(faces)\n ctx && drawResults(ctx, faces, true, true)\n }\n } catch (error) {\n console.error('caught face detection error', error)\n // detector.dispose()\n }\n\n if (throttleMs) {\n timer = setTimeout(() => {\n rafId.current = requestAnimationFrame(renderPrediction)\n }, throttleMs)\n } else {\n rafId.current = requestAnimationFrame(renderPrediction)\n }\n })()\n })()\n\n return () => {\n rafId.current && cancelAnimationFrame(rafId.current)\n timer && clearTimeout(timer)\n }\n }, [cameraReady, ready, running, throttleMs, videoLoaded, videoRef])\n\n const start = useCallback(() => {\n setRunning(true)\n }, [])\n\n const stop = useCallback(() => {\n setRunning(false)\n }, [])\n\n useEffect(() => {\n if (autoStart) start()\n return () => {\n stop()\n }\n }, [autoStart, start, stop])\n\n const onPredictionMade = useCallback((handler: PredictionHandler) => {\n onPredictionHandler.current = handler\n }, [])\n\n const value = useMemo<HighPerformanceSelfieGuidanceModelsState>(\n () => ({ start, stop, ready, canvasRef, onPredictionMade, error }),\n [error, onPredictionMade, ready, start, stop],\n )\n\n return (\n <HighPerformanceSelfieGuidanceModelsContext.Provider value={value}>\n {children}\n </HighPerformanceSelfieGuidanceModelsContext.Provider>\n )\n}\n","import { useEffect, useState } from 'react'\n\nexport const useTimeout = (\n durationMs?: number,\n onTimeout?: () => void,\n timeoutAverted?: boolean,\n shouldWaitLonger?: boolean,\n shouldStart: boolean = true,\n) => {\n const [timedOut, setTimedOut] = useState(false)\n const [timeoutStartedAt, setTimeoutStartedAt] = useState<Date | null>()\n\n useEffect(() => {\n if (!durationMs || !shouldStart) return\n\n setTimeoutStartedAt(new Date())\n const timer = setTimeout(() => {\n setTimedOut(true)\n }, durationMs)\n\n return () => {\n if (timer) clearTimeout(timer)\n }\n }, [durationMs, shouldStart])\n\n useEffect(() => {\n if (!timedOut || timeoutAverted) return\n if (!shouldWaitLonger) {\n onTimeout?.()\n return\n }\n\n const t = setTimeout(() => {\n onTimeout?.()\n }, 120000)\n\n return () => {\n clearTimeout(t)\n }\n }, [onTimeout, shouldWaitLonger, timedOut, timeoutAverted])\n\n return { timedOut, timeoutStartedAt }\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport {\n OverlayContainer,\n OverlayImageContainer,\n OverlayInner,\n} from '../common/overlay'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport styled from 'styled-components'\nimport { ButtonsRow } from '../common/ButtonsRow'\n\nexport type SelfieCaptureFallbackClassNames = {\n container?: string\n inner?: string\n heading?: string\n description?: string\n imageContainer?: string\n image?: string\n buttonsRow?: string\n captureBtn?: string\n doneBtn?: string\n}\n\nexport type SelfieCaptureFallbackColors = {\n captureBtn?: LoaderButtonColors\n doneBtn?: LoaderButtonColors\n}\n\nexport type SelfieCaptureFallbackVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n descriptionText?: CustomerSuppliedVerbiage\n captureBtnText?: CustomerSuppliedVerbiage\n doneBtnText?: CustomerSuppliedVerbiage\n doneBtnLoadingText?: CustomerSuppliedVerbiage\n}\n\nexport type SelfieCaptureFallbackProps = {\n onFinished?: (imageData: string) => void\n onCapture?: (imageData: string) => void\n classNames?: SelfieCaptureFallbackClassNames\n colors?: SelfieCaptureFallbackColors\n verbiage?: SelfieCaptureFallbackVerbiage\n}\n\nexport const SelfieCaptureFallback = ({\n onFinished,\n onCapture,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n}: SelfieCaptureFallbackProps): ReactElement => {\n const [image, setImage] = useState<string | null>(null)\n const fileInput = useRef<HTMLInputElement | null>(null)\n const [loading, setLoading] = useState(false)\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: `We're having some trouble.`,\n descriptionText:\n 'On-device capture guidance failed, please capture a selfie manually.',\n captureBtnText: 'Capture',\n doneBtnText: 'Done',\n doneBtnLoadingText: 'Verifying...',\n })\n\n function onFileSelected(e: React.ChangeEvent<HTMLInputElement>) {\n const file = e.target.files?.[0]\n if (!file) return\n\n const reader = new FileReader()\n reader.addEventListener('load', (e) => {\n const imageData = e.target?.result as string\n setImage(imageData)\n onCapture?.(imageData)\n })\n reader.readAsDataURL(file)\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <StyledOverlayInner className={classNames.inner}>\n <Heading className={classNames.heading}>{verbiage.headingText}</Heading>\n\n <Description className={classNames.description}>\n {verbiage.descriptionText}\n </Description>\n\n {image && (\n <ImageContainer className={classNames.imageContainer}>\n <img src={image} alt=\"\" className={classNames.image} />\n </ImageContainer>\n )}\n\n <input\n ref={fileInput}\n type=\"file\"\n accept=\"image/*\"\n onChange={onFileSelected}\n hidden\n />\n\n <StyledButtonsRow className={classNames.buttonsRow}>\n {!image && (\n <LoaderButton\n variant=\"positive\"\n className={classNames.captureBtn}\n colors={colors.captureBtn}\n finished\n onClick={() => {\n fileInput.current?.click()\n }}\n >\n {verbiage.captureBtnText}\n </LoaderButton>\n )}\n\n {image && (\n <LoaderButton\n variant=\"positive\"\n key={loading ? 'loading-btn' : 'ready-btn'}\n className={classNames.doneBtn}\n colors={colors.doneBtn}\n finished={!loading}\n onClick={() => {\n setLoading(true)\n onFinished?.(image)\n }}\n >\n {loading ? verbiage.doneBtnLoadingText : verbiage.doneBtnText}\n </LoaderButton>\n )}\n </StyledButtonsRow>\n </StyledOverlayInner>\n </OverlayContainer>\n )\n}\n\nconst StyledOverlayInner = styled(OverlayInner)`\n justify-content: center;\n`\n\nconst Heading = styled.h3`\n margin-bottom: 8px;\n`\n\nconst Description = styled.p`\n margin-bottom: 8px;\n`\n\nconst ImageContainer = styled(OverlayImageContainer)`\n margin-top: 32px;\n`\n\nconst StyledButtonsRow = styled(ButtonsRow)`\n margin-top: 32px;\n`\n","import React, {\n ReactElement,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport useResizeObserver from 'use-resize-observer'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport {\n FaceCaptureGuideOverlay,\n FaceCaptureGuideOverlayClassNames,\n} from '../face_liveness/FaceCaptureGuideOverlay'\nimport {\n Face,\n HighPerformanceSelfieGuidanceModelsContext,\n} from './HighPerformanceSelfieGuidanceModelsProvider'\nimport { PageContainer } from '../common/Page'\nimport {\n DebugStatsPane,\n ObjectDetectionDebugOverlay,\n SelfieCaptureFaceDebugBox,\n useDebugScalingDetails,\n} from '../common/debug'\nimport { ExitCaptureButton } from '../common/ExitCaptureButton'\nimport {\n GuidanceMessage,\n GuidanceMessageContainer,\n} from '../common/GuidanceMessage'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport {\n clearCanvas,\n drawToCanvas,\n InvisibleCanvas,\n} from '../common/InvisibleCanvas'\nimport {\n SelfieCaptureFallback,\n SelfieCaptureFallbackClassNames,\n} from '../fallback_flows/SelfieCapture'\n\ntype State = {\n videoWidth: number\n videoHeight: number\n\n capturing: boolean\n captured: boolean\n captureFailed: boolean\n\n frame: ImageBitmap | null\n faces: Face[]\n faceNotCentered: boolean\n faceLookingAway: boolean\n faceTooClose: boolean\n faceTooFar: boolean\n faceReady: boolean\n faceReadyAt: Date | null\n\n // TODO: remove good frames threshold\n goodFramesCount: number\n goodFramesThreshold: number\n goodFramesThresholdMet: boolean\n}\n\nconst initialState: State = {\n videoWidth: 0,\n videoHeight: 0,\n\n capturing: false,\n captured: false,\n captureFailed: false,\n\n frame: null,\n faces: [],\n faceNotCentered: false,\n faceLookingAway: false,\n faceTooClose: false,\n faceTooFar: false,\n faceReady: false,\n faceReadyAt: null,\n\n goodFramesCount: 0,\n goodFramesThreshold: 1,\n goodFramesThresholdMet: false,\n}\n\ntype Action =\n | { type: 'configure'; payload: { videoWidth: number; videoHeight: number } }\n | { type: 'capturing' }\n | { type: 'captured' }\n | { type: 'captureFailed' }\n | { type: 'facesDetected'; payload: { frame?: ImageBitmap; faces: Face[] } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'configure':\n return {\n ...state,\n videoWidth: action.payload.videoWidth,\n videoHeight: action.payload.videoHeight,\n }\n\n case 'capturing':\n return {\n ...state,\n capturing: true,\n captured: false,\n captureFailed: false,\n }\n\n case 'captured':\n return {\n ...state,\n capturing: false,\n captured: true,\n captureFailed: false,\n }\n\n case 'captureFailed':\n return {\n ...state,\n capturing: false,\n captured: false,\n captureFailed: true,\n }\n\n case 'facesDetected': {\n const { faces } = action.payload\n const face = faces[0]\n\n let faceNotCentered = true,\n faceLookingAway = false,\n faceTooClose = false,\n faceTooFar = false,\n faceReadyAt = state.faceReadyAt,\n goodFramesCount = state.goodFramesCount\n\n if (face) {\n // calculate centroids\n const vCX = state.videoWidth / 2\n const vCY = state.videoHeight / 2\n const fCX = (face.box.xMin + face.box.xMax) / 2\n const fCY = (face.box.yMin + face.box.yMax) / 2\n\n // calculate thresholds\n const vTX = state.videoWidth * 0.125\n const vTY = state.videoHeight * 0.125\n const fTW = face.box.width * 0.2\n const fTH = face.box.height * 0.2\n\n const nose = face.keypoints[2] //.find((k) => k.name === 'noseTip')\n if (nose) {\n faceNotCentered =\n Math.abs(vCX - fCX) > vTX || Math.abs(vCY + 50 - fCY) > vTY\n faceLookingAway =\n Math.abs(fCX - nose.x) > fTW || Math.abs(fCY - nose.y) > fTH\n }\n\n const isMobile = state.videoWidth < state.videoHeight\n\n const tooCloseMultiple = isMobile ? 2 : 4.5\n const tooFarMultiple = isMobile ? 6 : 7\n faceTooClose = face.box.width > state.videoWidth / tooCloseMultiple\n faceTooFar = face.box.width < state.videoWidth / tooFarMultiple\n }\n\n const faceReady =\n !faceNotCentered && !faceLookingAway && !faceTooClose && !faceTooFar\n\n if (!faceReady) {\n faceReadyAt = null\n goodFramesCount = 0\n } else if (!state.faceReady) {\n faceReadyAt = new Date()\n }\n\n return {\n ...state,\n faces,\n faceNotCentered,\n faceLookingAway,\n faceTooClose,\n faceTooFar,\n faceReady,\n faceReadyAt,\n goodFramesCount,\n }\n }\n }\n}\n\nexport type SelfieCaptureClassNames = {\n container?: string\n cameraFeed?: string\n guides?: FaceCaptureGuideOverlayClassNames\n guidanceMessageContainer?: string\n guidanceMessage?: string\n exitCaptureBtn?: string\n fallback?: SelfieCaptureFallbackClassNames\n}\n\nexport type SelfieCaptureColors = {\n guidesUnsatisfiedColor?: string\n guidesSatisfiedColor?: string\n guidanceMessagesSatisfiedBackgroundColor?: string\n guidanceMessagesUnsatisfiedBackgroundColor?: string\n guidanceMessagesSatisfiedTextColor?: string\n guidanceMessagesUnsatisfiedTextColor?: string\n}\n\nexport type SelfieCaptureVerbiage = {\n guidanceHoldStillText?: CustomerSuppliedVerbiage\n guidanceLookStraightText?: CustomerSuppliedVerbiage\n guidanceMoveBackText?: CustomerSuppliedVerbiage\n guidanceMoveForwardText?: CustomerSuppliedVerbiage\n guidanceMoveToCenterText?: CustomerSuppliedVerbiage\n}\n\nexport type SelfieCaptureProps = {\n onGuidanceSatisfied?: () => void\n onGuidanceNotSatisfied?: () => void\n onSelfieCaptured?: (frame: ImageData, face: Face) => void\n onTimeout?: () => void\n onExit?: () => void\n timeoutDurationMs?: number\n guidanceMessage?: string\n guidanceSatisfied?: boolean\n classNames?: SelfieCaptureClassNames\n colors?: SelfieCaptureColors\n verbiage?: SelfieCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const SelfieCapture = ({\n onGuidanceSatisfied,\n onGuidanceNotSatisfied,\n onSelfieCaptured,\n onTimeout,\n onExit,\n timeoutDurationMs = 15000,\n guidanceMessage,\n guidanceSatisfied,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: SelfieCaptureProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const [state, dispatch] = useReducer(reducer, initialState)\n const lastPredictionCanvas = useRef<HTMLCanvasElement | null>(null)\n const { cameraRef, cameraReady, videoRef } = useContext(CameraStateContext)\n const { onPredictionMade, error: guidanceError } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n\n useEffect(() => {\n if (cameraReady && videoRef.current && videoRef.current.videoWidth !== 0) {\n dispatch({\n type: 'configure',\n payload: {\n videoWidth: videoRef.current.videoWidth,\n videoHeight: videoRef.current.videoHeight,\n },\n })\n }\n }, [cameraReady, videoRef])\n\n useEffect(() => {\n onPredictionMade((prediction) => {\n dispatch({\n type: 'facesDetected',\n payload: { faces: prediction },\n })\n })\n }, [onPredictionMade])\n\n const [captureReady, setCaptureReady] = useState(false)\n useEffect(() => {\n let timer: NodeJS.Timer\n\n if (state.faceReady) {\n onGuidanceSatisfied?.()\n timer = setTimeout(() => {\n setCaptureReady(true)\n }, 1000)\n } else {\n onGuidanceNotSatisfied?.()\n }\n\n return () => {\n if (timer) clearTimeout(timer)\n }\n }, [onGuidanceNotSatisfied, onGuidanceSatisfied, state.faceReady])\n\n useEffect(() => {\n ;(async () => {\n if (\n captureReady &&\n videoRef.current &&\n lastPredictionCanvas.current &&\n state.faces.length > 0\n ) {\n drawToCanvas(lastPredictionCanvas.current, videoRef.current)\n const ctx = lastPredictionCanvas.current.getContext('2d')\n if (!ctx) return\n const imageData = ctx.getImageData(\n 0,\n 0,\n videoRef.current.videoWidth,\n videoRef.current.videoHeight\n )\n\n onSelfieCaptured?.(imageData, state.faces[0])\n clearCanvas(lastPredictionCanvas.current)\n }\n })()\n }, [captureReady, onSelfieCaptured, state.faces, videoRef])\n\n const { timedOut, timeoutStartedAt } = useTimeout(\n timeoutDurationMs,\n onTimeout\n )\n\n const debugScalingDetails = useDebugScalingDetails({\n enabled: debugMode,\n pageWidth: width,\n pageHeight: height,\n videoWidth: state.videoWidth,\n videoHeight: state.videoHeight,\n })\n\n colors.guidesUnsatisfiedColor ||= 'white'\n colors.guidesSatisfiedColor ||= 'green'\n\n const verbiage = useTranslations(rawVerbiage, {\n guidanceHoldStillText: 'Hold still for a few seconds...',\n guidanceLookStraightText: 'Look straight into the camera...',\n guidanceMoveBackText: 'Move back...',\n guidanceMoveForwardText: 'Move forward...',\n guidanceMoveToCenterText: 'Move to the center...',\n })\n\n let satisfied = state.faceReady\n if (typeof guidanceSatisfied === 'boolean') satisfied = guidanceSatisfied\n\n guidanceMessage ||= satisfied\n ? verbiage.guidanceHoldStillText\n : state.faceLookingAway\n ? verbiage.guidanceLookStraightText\n : state.faceTooClose\n ? verbiage.guidanceMoveBackText\n : state.faceTooFar\n ? verbiage.guidanceMoveForwardText\n : state.faceNotCentered\n ? verbiage.guidanceMoveToCenterText\n : ''\n\n if (guidanceError) {\n return <SelfieCaptureFallback classNames={classNames.fallback} />\n }\n\n return (\n <PageContainer ref={ref} className={`flex ${classNames.container ?? ''}`}>\n <InvisibleCanvas ref={lastPredictionCanvas} />\n <CameraVideoTag className={classNames.cameraFeed} />\n\n <FaceCaptureGuideOverlay\n classNames={classNames.guides}\n variant={satisfied ? 'satisfied' : 'unsatisfied'}\n />\n\n {guidanceMessage !== '' && (\n <GuidanceMessageContainer\n className={classNames.guidanceMessageContainer}\n >\n <GuidanceMessage\n $variant={satisfied ? 'positive' : 'negative'}\n className={classNames.guidanceMessage}\n >\n {guidanceMessage}\n </GuidanceMessage>\n </GuidanceMessageContainer>\n )}\n\n {debugMode && state.faces.length > 0 && (\n <ObjectDetectionDebugOverlay $flipX={!cameraRef.current?.isRearFacing}>\n {state.faces.map((face, i) => (\n <SelfieCaptureFaceDebugBox\n key={i}\n face={face}\n scaling={debugScalingDetails}\n flipX={!cameraRef.current?.isRearFacing}\n color={satisfied ? 'green' : 'red'}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n )}\n\n {debugMode && (\n <DebugStatsPane>\n {cameraRef.current ? (\n <>\n ✅ Camera: {cameraRef.current.label} ({cameraRef.current.width}x\n {cameraRef.current.height})\n </>\n ) : (\n '❌ Camera not ready'\n )}\n <br />\n {!state.faceNotCentered ? '✅' : '❌'} Face Centered\n <br />\n {!state.faceTooClose && !state.faceTooFar ? '✅' : '❌'} Face{' '}\n {state.faceTooClose\n ? 'Too Close'\n : state.faceTooFar\n ? 'Too Far'\n : 'Distance Correct'}\n <br />\n {!state.faceLookingAway ? '✅' : '❌'} Face Looking Forward\n <br />\n {state.goodFramesThresholdMet ? '✅' : '❌'} {state.goodFramesCount}{' '}\n Good Frames\n <br />\n {!timedOut ? '✅' : '❌'} Time Remaining:{' '}\n {Math.max(\n 0,\n timeoutDurationMs -\n (new Date().getTime() -\n (timeoutStartedAt ?? new Date()).getTime())\n )}\n ms\n </DebugStatsPane>\n )}\n\n <ExitCaptureButton\n onClick={onExit}\n className={classNames.exitCaptureBtn}\n />\n </PageContainer>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport { Face } from '@tensorflow-models/face-detection'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { LiveCheckResponse } from '../../contexts/SubmissionContext'\nimport {\n SelfieCapture,\n SelfieCaptureClassNames,\n SelfieCaptureColors,\n SelfieCaptureVerbiage,\n} from '../selfie_capture/SelfieCapture'\nimport { cropToShoulders } from '../../lib/utils/cropping'\nimport {\n SelfieProgressPreview,\n SelfieProgressPreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport { InvisibleCanvas } from '../common/InvisibleCanvas'\nimport { SelfieCaptureFallback } from '../fallback_flows/SelfieCapture'\nimport { HighPerformanceSelfieGuidanceModelsContext } from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport { SubmissionContext } from '../submission/SubmissionProvider'\n\ntype LivenessCheckState =\n | 'CAPTURING'\n | 'CAPTURED'\n | 'IN_PROGRESS'\n | 'PASSED'\n | 'FAILED'\n | 'ERROR'\n\ntype State = {\n frame: ImageData | null\n face: Face | null\n requestState: LivenessCheckState\n requestError: Error | null\n imageUrl: string | null\n faceLive: boolean\n eyeCoveringDetected: boolean\n maskDetected: boolean\n headCoveringDetected: boolean\n phoneDetected: boolean\n timesLivenessCheckFailed: number\n}\n\nconst initialState: State = {\n frame: null,\n face: null,\n requestState: 'CAPTURING',\n requestError: null,\n imageUrl: null,\n faceLive: false,\n eyeCoveringDetected: false,\n maskDetected: false,\n headCoveringDetected: false,\n phoneDetected: false,\n timesLivenessCheckFailed: 0,\n}\n\ntype Action =\n | { type: 'livenessReady'; payload: { frame: ImageData; face: Face } }\n | { type: 'livenessChecking' }\n | {\n type: 'livenessChecked'\n payload: {\n frame?: ImageData\n face?: Face\n imageUrl: string\n response: LiveCheckResponse\n }\n }\n | { type: 'livenessCheckFailed'; payload: { error: Error } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'livenessReady': {\n const allowedStates = ['CAPTURING', 'FAILED', 'ERROR']\n if (allowedStates.includes(state.requestState)) {\n return {\n ...state,\n requestState: 'CAPTURED',\n frame: action.payload.frame,\n face: action.payload.face,\n }\n } else {\n return state\n }\n }\n\n case 'livenessChecking':\n return { ...state, requestState: 'IN_PROGRESS' }\n\n case 'livenessChecked': {\n const {\n status: { statusCode, statusMessage, errorData },\n resultData,\n } = action.payload.response\n\n if (statusCode !== '000') {\n return {\n ...state,\n requestState: 'ERROR',\n requestError: new Error(`${statusMessage}: ${errorData}`),\n }\n }\n\n const faceLive = resultData.verificationResult === 'Live Face Detected'\n const eyeCoveringDetected = resultData.eyeCovering === 'true'\n const maskDetected = resultData.faceMask === 'true'\n const headCoveringDetected = resultData.headCovering === 'true'\n const phoneDetected = resultData.cellPhone === 'true'\n\n const livenessCheckPassed =\n faceLive &&\n !eyeCoveringDetected &&\n !maskDetected &&\n !headCoveringDetected\n const requestState = livenessCheckPassed ? 'PASSED' : 'FAILED'\n\n let timesLivenessCheckFailed = state.timesLivenessCheckFailed\n if (livenessCheckPassed) {\n timesLivenessCheckFailed = 0\n } else {\n timesLivenessCheckFailed += 1\n }\n\n return {\n ...state,\n frame: action.payload.frame ?? null,\n face: action.payload.face ?? null,\n imageUrl: action.payload.imageUrl,\n requestState,\n faceLive,\n eyeCoveringDetected,\n maskDetected,\n headCoveringDetected,\n phoneDetected,\n timesLivenessCheckFailed,\n }\n }\n\n case 'livenessCheckFailed':\n return {\n ...state,\n requestState: 'ERROR',\n requestError: action.payload.error,\n }\n\n default:\n return state\n }\n}\n\nexport type FaceLivenessCaptureClassNames = SelfieCaptureClassNames & {\n imagePreview?: SelfieProgressPreviewClassNames\n}\n\nexport type FaceLivenessCaptureColors = SelfieCaptureColors\n\nexport type FaceLivenessCaptureVerbiage = SelfieCaptureVerbiage & {\n guidanceRemoveEyeCoveringsText?: CustomerSuppliedVerbiage\n guidanceRemoveHeadCoveringsText?: CustomerSuppliedVerbiage\n guidanceRemoveMaskText?: CustomerSuppliedVerbiage\n progressPreviewText?: CustomerSuppliedVerbiage\n}\n\nexport type FaceLivenessCaptureProps = {\n onCapture?: () => void\n onSuccess?: (faceCropImageUrl: string) => void\n onTimeout?: () => void\n onExit?: () => void\n timeoutDurationMs?: number\n classNames?: FaceLivenessCaptureClassNames\n colors?: FaceLivenessCaptureColors\n verbiage?: FaceLivenessCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const FaceLivenessCapture = ({\n onCapture,\n onSuccess,\n onTimeout,\n onExit,\n timeoutDurationMs = 15000,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode,\n}: FaceLivenessCaptureProps): ReactElement => {\n const { checkLiveness, submissionError } = useContext(SubmissionContext)\n const { error: modelsError } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n const [state, dispatch] = useReducer(reducer, initialState)\n const [imageUrl, setImageUrl] = useState<string | null>(null)\n const rawCanvas = useRef<HTMLCanvasElement | null>(null)\n const cropCanvas = useRef<HTMLCanvasElement | null>(null)\n\n const onSelfieCaptured = useCallback(\n (frame: ImageData, face: Face) => {\n onCapture?.()\n dispatch({ type: 'livenessReady', payload: { frame, face } })\n },\n [onCapture]\n )\n\n const { frame, face } = state\n const isReady = state.requestState === 'CAPTURED'\n const isPassed = state.requestState === 'PASSED'\n useEffect(() => {\n if (!frame || !face || !isReady || submissionError) return\n dispatch({ type: 'livenessChecking' })\n ;(async () => {\n try {\n const imageUrl = cropToShoulders(\n rawCanvas.current,\n cropCanvas.current,\n frame,\n face\n )\n setImageUrl(imageUrl)\n\n const response = await checkLiveness(await dataUrlToBase64(imageUrl))\n\n dispatch({\n type: 'livenessChecked',\n payload: { frame, face, imageUrl, response },\n })\n } catch (e) {\n dispatch({\n type: 'livenessCheckFailed',\n payload: { error: e as Error },\n })\n }\n })()\n }, [checkLiveness, face, frame, isReady, submissionError])\n\n const onFallbackImageCaptured = useCallback(\n async (imageUrl: string) => {\n dispatch({ type: 'livenessChecking' })\n\n try {\n const response = await checkLiveness(await dataUrlToBase64(imageUrl))\n dispatch({\n type: 'livenessChecked',\n payload: { imageUrl, response },\n })\n } catch (e) {\n dispatch({\n type: 'livenessCheckFailed',\n payload: { error: e as Error },\n })\n }\n },\n [checkLiveness]\n )\n\n useEffect(() => {\n if (isPassed && state.imageUrl) onSuccess?.(state.imageUrl)\n }, [onSuccess, state.imageUrl, isPassed])\n\n useEffect(() => {\n const allowedFailures = modelsError ? 1 : 2\n if (state.timesLivenessCheckFailed >= allowedFailures) {\n onTimeout?.()\n }\n }, [modelsError, onTimeout, state.timesLivenessCheckFailed])\n\n useTimeout(\n timeoutDurationMs,\n onTimeout,\n state.requestState === 'PASSED' || !!modelsError,\n state.requestState === 'IN_PROGRESS'\n )\n\n const verbiage = useTranslations(rawVerbiage, {\n guidanceRemoveEyeCoveringsText:\n 'Please remove your eye coverings (sunglasses, eye patch, etc.)...',\n guidanceRemoveHeadCoveringsText:\n 'Please remove your head coverings (hat, scarf, etc.)...',\n guidanceRemoveMaskText: 'Please remove your mask...',\n progressPreviewText: 'Processing...',\n })\n\n const guidanceMessage = state.eyeCoveringDetected\n ? verbiage.guidanceRemoveEyeCoveringsText\n : state.headCoveringDetected\n ? verbiage.guidanceRemoveHeadCoveringsText\n : state.maskDetected\n ? verbiage.guidanceRemoveMaskText\n : undefined\n\n if (modelsError) {\n return <SelfieCaptureFallback onFinished={onFallbackImageCaptured} />\n }\n\n return (\n <>\n <InvisibleCanvas ref={rawCanvas} />\n <InvisibleCanvas ref={cropCanvas} />\n\n <SelfieCapture\n onSelfieCaptured={onSelfieCaptured}\n onExit={onExit}\n timeoutDurationMs={timeoutDurationMs}\n guidanceMessage={guidanceMessage}\n guidanceSatisfied={guidanceMessage ? false : undefined}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n\n {imageUrl && (\n <SelfieProgressPreview\n classNames={classNames.imagePreview}\n imageUrl={imageUrl}\n text={verbiage.progressPreviewText ?? ''}\n />\n )}\n </>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport {\n FaceLivenessCapture,\n FaceLivenessCaptureClassNames,\n FaceLivenessCaptureColors,\n FaceLivenessCaptureVerbiage,\n} from './FaceLivenessCapture'\nimport {\n SelfieCaptureLoadingOverlay,\n SelfieCaptureLoadingOverlayAssets,\n SelfieCaptureLoadingOverlayClassNames,\n SelfieCaptureLoadingOverlayColors,\n SelfieCaptureLoadingOverlayVerbiage,\n} from '../selfie_capture/SelfieCaptureLoadingOverlay'\nimport {\n FaceLivenessSuccess,\n FaceLivenessSuccessClassNames,\n FaceLivenessSuccessColors,\n FaceLivenessSuccessVerbiage,\n} from './FaceLivenessSuccess'\nimport {\n FaceLivenessFailure,\n FaceLivenessFailureAssets,\n FaceLivenessFailureClassNames,\n FaceLivenessFailureColors,\n FaceLivenessFailureVerbiage,\n} from './FaceLivenessFailure'\nimport {\n LivenessCheckRequest,\n SubmissionResponse,\n} from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { useShowSuccessScreen } from '../common/useShowSuccessScreen'\nimport { SubmissionContext } from '../submission/SubmissionProvider'\n\ntype CaptureState = 'LOADING' | 'CAPTURING' | 'SUCCESS' | 'FAILED'\n\nexport type FaceLivenessAssets = {\n loadingOverlay?: SelfieCaptureLoadingOverlayAssets\n failure?: FaceLivenessFailureAssets\n}\n\nexport type FaceLivenessClassNames = {\n loadingOverlay?: SelfieCaptureLoadingOverlayClassNames\n capture?: FaceLivenessCaptureClassNames\n success?: FaceLivenessSuccessClassNames\n failure?: FaceLivenessFailureClassNames\n}\n\nexport type FaceLivenessColors = FaceLivenessCaptureColors & {\n loadingOverlay?: SelfieCaptureLoadingOverlayColors\n success?: FaceLivenessSuccessColors\n failure?: FaceLivenessFailureColors\n}\n\nexport type FaceLivenessVerbiage = FaceLivenessCaptureVerbiage & {\n loadingOverlay?: SelfieCaptureLoadingOverlayVerbiage\n success?: FaceLivenessSuccessVerbiage\n failure?: FaceLivenessFailureVerbiage\n}\n\nexport type FaceLivenessWizardProps = {\n onSuccess?: (resp: SubmissionResponse, req: LivenessCheckRequest) => void\n onComplete?: (\n resp: SubmissionResponse | null,\n req: LivenessCheckRequest | null\n ) => void\n onTimeout?: (\n resp: SubmissionResponse | null,\n req: LivenessCheckRequest | null\n ) => void\n onExitCapture?: () => void\n onExitAfterFailure?: (\n resp: SubmissionResponse | null,\n req: LivenessCheckRequest | null\n ) => void\n\n timeoutDurationMs?: number\n maxRetries?: number\n skipSuccessScreen?: boolean | (() => Promise<boolean>)\n releaseCameraAccessOnExit?: boolean\n\n assets?: FaceLivenessAssets\n classNames?: FaceLivenessClassNames\n colors?: FaceLivenessColors\n verbiage?: FaceLivenessVerbiage\n debugMode?: boolean\n}\n\nexport const FaceLivenessWizard = ({\n onComplete,\n onSuccess,\n onTimeout,\n onExitCapture,\n onExitAfterFailure,\n timeoutDurationMs = 15000,\n maxRetries = 2,\n skipSuccessScreen = false,\n releaseCameraAccessOnExit = true,\n assets = {},\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: FaceLivenessWizardProps): ReactElement => {\n const {\n submissionResponse,\n livenessCheckRequest,\n setSelfieImage,\n logSelfieCaptureAttempt,\n } = useContext(SubmissionContext)\n const { releaseCameraAccess } = useContext(CameraStateContext)\n const [faceCropImageUrl, setFaceCropImageUrl] = useState('')\n const [retryCount, setRetryCount] = useState(0)\n const [captureState, setCaptureState] = useState<CaptureState>('LOADING')\n const captureStartedAt = useRef<Date>()\n const captureEndedAt = useRef<Date>()\n const operationStartedAt = useRef<Date>()\n\n useEffect(() => {\n operationStartedAt.current = new Date()\n }, [])\n\n useEffect(() => {\n if (captureState === 'CAPTURING') {\n captureStartedAt.current = new Date()\n }\n }, [captureState])\n\n const onCapture = useCallback(() => {\n captureEndedAt.current = new Date()\n }, [])\n\n const logCaptureMetadata = useCallback(() => {\n logSelfieCaptureAttempt({\n autoCapture: 'Y',\n captureTime:\n (captureEndedAt.current ?? new Date()).getTime() -\n (captureStartedAt.current ?? new Date()).getTime(),\n operationTime:\n new Date().getTime() -\n (operationStartedAt.current ?? new Date()).getTime(),\n })\n\n operationStartedAt.current = new Date()\n }, [logSelfieCaptureAttempt])\n\n const onSuccessCallback = useCallback(\n async (faceCropImageUrl: string) => {\n if (!livenessCheckRequest || !submissionResponse) return\n setCaptureState('SUCCESS')\n setFaceCropImageUrl(faceCropImageUrl)\n setSelfieImage(await dataUrlToBase64(faceCropImageUrl))\n onSuccess?.(submissionResponse, livenessCheckRequest)\n },\n [onSuccess, setSelfieImage, livenessCheckRequest, submissionResponse]\n )\n\n const onTimeoutCallback = useCallback(() => {\n setCaptureState('FAILED')\n onTimeout?.(submissionResponse, livenessCheckRequest)\n }, [onTimeout, livenessCheckRequest, submissionResponse])\n\n const [attempt, setAttempt] = useState(0)\n const onExitCallback = useCallback(() => {\n setAttempt((n) => n + 1)\n setCaptureState('LOADING')\n onExitCapture?.()\n }, [onExitCapture])\n\n const onDoneCallback = useCallback(() => {\n logCaptureMetadata()\n releaseCameraAccessOnExit && releaseCameraAccess()\n setTimeout(() => {\n onComplete?.(submissionResponse, livenessCheckRequest)\n }, 0)\n }, [\n logCaptureMetadata,\n onComplete,\n releaseCameraAccess,\n releaseCameraAccessOnExit,\n livenessCheckRequest,\n submissionResponse,\n ])\n\n const showSuccessScreen = useShowSuccessScreen(\n skipSuccessScreen,\n captureState === 'SUCCESS',\n onDoneCallback\n )\n\n return (\n <>\n {captureState !== 'LOADING' &&\n (() => {\n switch (captureState) {\n case 'CAPTURING':\n return (\n <FaceLivenessCapture\n key={`capture${attempt}`}\n onCapture={onCapture}\n onSuccess={onSuccessCallback}\n onTimeout={onTimeoutCallback}\n onExit={onExitCallback}\n timeoutDurationMs={timeoutDurationMs}\n classNames={classNames.capture}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n )\n\n case 'SUCCESS':\n if (!showSuccessScreen) return null\n return (\n <FaceLivenessSuccess\n key=\"success\"\n imageUrl={faceCropImageUrl}\n classNames={classNames.success}\n colors={colors.success}\n verbiage={verbiage.success}\n onDoneClick={onDoneCallback}\n onRetryClick={() => {\n logCaptureMetadata()\n setCaptureState('CAPTURING')\n }}\n />\n )\n\n case 'FAILED':\n return (\n <FaceLivenessFailure\n key=\"failure\"\n assets={assets.failure}\n classNames={classNames.failure}\n colors={colors.failure}\n verbiage={verbiage.failure}\n canRetry={maxRetries > -1 && retryCount < maxRetries}\n onRetryClick={() => {\n logCaptureMetadata()\n setRetryCount((c) => c + 1)\n setCaptureState('CAPTURING')\n }}\n onExitClick={() => {\n releaseCameraAccessOnExit && releaseCameraAccess()\n setTimeout(() => {\n onExitAfterFailure?.(\n submissionResponse,\n livenessCheckRequest\n )\n }, 0)\n }}\n />\n )\n\n default:\n return null\n }\n })()}\n\n <SelfieCaptureLoadingOverlay\n key={attempt}\n assets={assets.loadingOverlay}\n classNames={classNames.loadingOverlay}\n colors={colors.loadingOverlay}\n verbiage={verbiage.loadingOverlay}\n onDismissed={() => {\n setCaptureState('CAPTURING')\n }}\n />\n </>\n )\n}\n","import React, { ReactElement, ReactNode, useCallback, useState } from 'react'\nimport {\n GuideOrientationContext,\n GuideOrientationState,\n} from '../contexts/GuideOrientationContext'\nimport useResizeObserver from 'use-resize-observer'\n\nexport const GuideOrientationProvider = ({\n children,\n}: {\n children: ReactNode\n}): ReactElement => {\n const [_, setDimensions] = useState({ width: 1, height: 1 })\n const [imageAspectRatio, setImageAspectRatio] = useState(1)\n const {\n ref: wrapperRef,\n width: wrapperWidth = 1,\n height: wrapperHeight = 1,\n } = useResizeObserver<HTMLDivElement>()\n\n const wrapperAspectRatio = wrapperWidth / wrapperHeight\n\n const onImageLoaded = useCallback((e: React.SyntheticEvent) => {\n const img = e.target as HTMLImageElement\n setImageAspectRatio(img.naturalWidth / img.naturalHeight)\n }, [])\n\n const orientation = 'landscape' //width > height ? 'landscape' : 'portrait'\n const value: GuideOrientationState = {\n orientation,\n wrapperWidth,\n wrapperHeight,\n wrapperAspectRatio,\n imageAspectRatio,\n setDimensions,\n wrapperRef,\n onImageLoaded,\n }\n\n return (\n <GuideOrientationContext.Provider value={value}>\n {children}\n </GuideOrientationContext.Provider>\n )\n}\n","import React, { ReactElement, useContext, useMemo, useState } from 'react'\nimport { SubmissionContext } from './SubmissionProvider'\n\nexport const SubmissionSuccess = (): ReactElement => {\n const { submissionRequest, submissionResponse } =\n useContext(SubmissionContext)\n const [showRequestBody, setShowRequestBody] = useState(false)\n const [truncateImages, setTruncateImages] = useState(true)\n\n const requestBodyDisplay = useMemo(() => {\n const body = JSON.parse(JSON.stringify(submissionRequest))\n if (truncateImages) {\n if (body?.customerData?.idData?.idImageFront)\n body.customerData.idData.idImageFront = truncate(\n body.customerData.idData.idImageFront,\n 200\n )\n if (body?.customerData?.idData?.idImageBack)\n body.customerData.idData.idImageBack = truncate(\n body.customerData.idData.idImageBack,\n 200\n )\n if (body?.customerData?.biometricData?.selfie)\n body.customerData.biometricData.selfie = truncate(\n body.customerData.biometricData.selfie,\n 200\n )\n }\n return JSON.stringify(body, null, 2)\n }, [submissionRequest, truncateImages])\n\n return (\n <>\n <h3>Submission completed!</h3>\n\n <button\n onClick={() => {\n setShowRequestBody(!showRequestBody)\n }}\n >\n {showRequestBody ? 'Hide' : 'Show'} request body\n </button>\n\n {showRequestBody && (\n <>\n <button\n style={{ marginLeft: 8 }}\n onClick={() => {\n setTruncateImages(!truncateImages)\n }}\n >\n {truncateImages ? 'Display full images' : 'Truncate images'}\n </button>\n\n <h5>Request Body</h5>\n <pre>{requestBodyDisplay}</pre>\n </>\n )}\n\n <h5>Response Body</h5>\n <pre>{JSON.stringify(submissionResponse, null, 2)}</pre>\n </>\n )\n}\n\nfunction truncate(str: string, max_chars: number): string {\n let truncated = str.split('').splice(0, max_chars).join('')\n if (truncated.length < str.length) truncated += '...'\n return truncated\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport {\n contentDispositionFromDataUrl,\n dataUrlToBase64Sync,\n} from '../../lib/utils/dataUrlToBase64'\nimport { OverlayContainer, OverlayInner } from '../common/overlay'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport styled from 'styled-components'\nimport { LoaderButton } from '../common/LoaderButton'\nimport { ButtonsRow } from '../common/ButtonsRow'\n\nexport type AdditionalDocument = {\n name: string\n description?: string\n skip?: () => Promise<boolean>\n}\n\nexport type UploadedDocument = {\n documentName: string\n additionalDocument: string | Record<string, string>\n}\n\nexport type AdditionalDocumentCaptureClassNames = {\n container?: string\n inner?: string\n heading?: string\n description?: string\n buttonsRow?: string\n captureBtn?: string\n nextBtn?: string\n}\n\nexport type AdditionalDocumentCaptureVerbiage = {\n headingText?: CustomerSuppliedVerbiage\n captureBtnText?: CustomerSuppliedVerbiage\n nextBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type AdditionalDocumentCaptureProps = {\n document: AdditionalDocument\n onComplete?: (uploadedDocument: UploadedDocument) => void\n classNames?: AdditionalDocumentCaptureClassNames\n verbiage?: AdditionalDocumentCaptureVerbiage\n}\n\nexport const AdditionalDocumentCapture = ({\n document,\n onComplete,\n classNames = {},\n verbiage: rawVerbiage = {},\n}: AdditionalDocumentCaptureProps): ReactElement => {\n const fileInput = useRef<HTMLInputElement | null>(null)\n const [file, setFile] = useState<File | null>(null)\n\n const verbiage = useTranslations(rawVerbiage, {\n headingText: 'Additional document capture',\n captureBtnText: 'Capture',\n nextBtnText: 'Next',\n })\n\n function onFileSelected(e: React.ChangeEvent<HTMLInputElement>) {\n const file = e.target.files?.[0]\n if (file) setFile(file)\n }\n\n function onNextClicked() {\n if (!file) return\n\n const fileReader = new FileReader()\n fileReader.onloadend = () => {\n if (!fileReader.result) return\n const fileContent = fileReader.result.toString()\n onComplete?.({\n documentName: document.name,\n additionalDocument: {\n name: file.name,\n fileContent: dataUrlToBase64Sync(fileContent),\n type: contentDispositionFromDataUrl(fileContent),\n fileUploadType: 'Y',\n isImageControlData: 'N',\n fieldId: '',\n },\n })\n }\n fileReader.readAsDataURL(file)\n }\n\n return (\n <OverlayContainer className={classNames.container}>\n <Inner className={classNames.inner}>\n <Heading className={classNames.heading}>\n {verbiage.headingText}: {document.name}\n </Heading>\n\n {document.description && (\n <Description className={classNames.description}>\n {document.description}\n </Description>\n )}\n\n <input\n ref={fileInput}\n type=\"file\"\n accept=\"image/*,.pdf\"\n onChange={onFileSelected}\n hidden\n />\n\n <StyledButtonsRow className={classNames.buttonsRow}>\n {file ? (\n <LoaderButton\n variant=\"positive\"\n className={classNames.nextBtn}\n disabled={!file}\n finished\n onClick={onNextClicked}\n >\n {verbiage.nextBtnText}\n </LoaderButton>\n ) : (\n <LoaderButton\n variant=\"primary\"\n className={classNames.captureBtn}\n finished\n onClick={() => {\n fileInput.current?.click()\n }}\n >\n {verbiage.captureBtnText}\n </LoaderButton>\n )}\n </StyledButtonsRow>\n </Inner>\n </OverlayContainer>\n )\n}\n\nconst Inner = styled(OverlayInner)`\n justify-content: center;\n`\n\nconst Heading = styled.h3`\n margin-bottom: 8px;\n`\n\nconst Description = styled.p`\n margin-bottom: 8px;\n`\n\nconst StyledButtonsRow = styled(ButtonsRow)`\n margin-top: 32px;\n`\n","import React, { ReactElement, useEffect, useState } from 'react'\nimport {\n AdditionalDocument,\n AdditionalDocumentCapture,\n AdditionalDocumentCaptureClassNames,\n AdditionalDocumentCaptureVerbiage,\n UploadedDocument,\n} from './AdditionalDocumentCapture'\n\nexport type AdditionalDocumentCaptureWizardClassNames =\n AdditionalDocumentCaptureClassNames\n\nexport type AdditionalDocumentCaptureWizardVerbiage =\n AdditionalDocumentCaptureVerbiage\n\nexport type AdditionalDocumentCaptureWizardProps = {\n documents: AdditionalDocument[]\n onComplete?: (uploadedDocuments: UploadedDocument[]) => void\n classNames?: AdditionalDocumentCaptureWizardClassNames\n verbiage?: AdditionalDocumentCaptureWizardVerbiage\n}\n\nexport const AdditionalDocumentCaptureWizard = ({\n documents,\n onComplete,\n classNames = {},\n verbiage = {},\n}: AdditionalDocumentCaptureWizardProps): ReactElement => {\n const [uploadedDocuments, setUploadedDocuments] = useState<\n (UploadedDocument | null)[]\n >([])\n const documentIndex = uploadedDocuments.length\n const currentDocument = documents[documentIndex]\n const isComplete = documentIndex >= documents.length\n\n useEffect(() => {\n if (!currentDocument?.skip) return\n ;(async () => {\n if (await currentDocument.skip?.()) {\n setUploadedDocuments((f) => [...f, null])\n }\n })()\n }, [currentDocument])\n\n useEffect(() => {\n if (isComplete) {\n onComplete?.(uploadedDocuments.filter((d) => !!d) as UploadedDocument[])\n }\n }, [isComplete, onComplete, uploadedDocuments])\n\n if (isComplete) return <>Thanks, your documents have been received.</>\n\n return (\n <AdditionalDocumentCapture\n key={documentIndex}\n document={currentDocument}\n classNames={classNames}\n verbiage={verbiage}\n onComplete={(data) => {\n setUploadedDocuments((f) => [...f, data])\n }}\n />\n )\n}\n","import ReactSignatureCanvas from 'react-signature-canvas'\nimport { dataUrlToBase64Sync } from '../../lib/utils/dataUrlToBase64'\n\nexport type SignatureData = {\n clickX_simple: number[][]\n clickY_simple: number[][]\n time_simple: string[][]\n pressure: string\n fileContent: string\n}\n\nexport function signatureDataToIdmissionFormat(\n signatureCanvas: ReactSignatureCanvas\n): SignatureData {\n const dataURL = signatureCanvas.toDataURL() ?? null\n\n const signatureData: SignatureData = {\n clickX_simple: [],\n clickY_simple: [],\n time_simple: [],\n pressure: '',\n fileContent: dataURL ? dataUrlToBase64Sync(dataURL) : '',\n }\n\n signatureCanvas.toData().forEach((stroke) => {\n const xs: number[] = []\n const ys: number[] = []\n const times: string[] = []\n stroke.forEach((d) => {\n xs.push(d.x)\n ys.push(d.y)\n times.push(new Date(d.time).toString())\n })\n signatureData.clickX_simple.push(xs)\n signatureData.clickY_simple.push(ys)\n signatureData.time_simple.push(times)\n })\n\n return signatureData\n}\n","import styled from 'styled-components'\nimport { ButtonsRow } from './ButtonsRow'\n\nexport const SignaturePaperBacking = styled.div`\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n ${(props) =>\n props.theme.signatureCapture?.background\n ? `background: ${props.theme.signatureCapture?.background};`\n : ``}\n ${(props) =>\n props.theme.signatureCapture?.backgroundSize\n ? `background-size: ${props.theme.signatureCapture?.backgroundSize};`\n : ``}\n ${(props) =>\n props.theme.signatureCapture?.backgroundPosition\n ? `background-position: ${props.theme.signatureCapture?.backgroundPosition};`\n : ``}\n`\n\nexport const SignatureCanvasContainer = styled.div`\n position: absolute;\n top: 25%;\n left: 15%;\n width: 70%;\n height: 50%;\n\n @media (max-width: 800px) {\n top: 15%;\n left: 2%;\n width: 96%;\n height: 70%;\n }\n`\n\nexport const SignaturePad = styled.div`\n position: relative;\n background: ${(props) =>\n props.theme.signatureCapture?.canvas?.background ??\n 'rgba(255, 255, 255, 0.5)'};\n border: ${(props) =>\n props.theme.signatureCapture?.canvas?.border ?? `1px solid #dedede`};\n border-radius: ${(props) =>\n props.theme.signatureCapture?.canvas?.borderRadius ?? '16px'};\n flex-grow: 1;\n z-index: 100;\n height: 100%;\n`\n\nexport const SignatureButtonsContainer = styled(ButtonsRow)`\n flex-grow: 0;\n padding-top: 12px;\n display: flex;\n z-index: 1000;\n position: relative;\n`\n","import { useCallback, useRef, useState } from 'react'\nimport { Camera } from './Camera'\n\nexport const useVideoRecorder = (camera: Camera | null) => {\n const mediaRecorder = useRef<MediaRecorder | null>(null)\n const videoChunks = useRef<BlobPart[]>([])\n const [videoUrl, setVideoUrl] = useState<string | null>(null)\n const [isRecording, setIsRecording] = useState(false)\n\n const stream = camera?.stream\n const startRecording = useCallback(() => {\n if (!stream) return\n\n videoChunks.current = []\n setIsRecording(true)\n\n mediaRecorder.current = new MediaRecorder(stream)\n\n mediaRecorder.current.ondataavailable = (e) => {\n videoChunks.current.push(e.data)\n }\n\n mediaRecorder.current.onstop = () => {\n const blobFile = new Blob(videoChunks.current, { type: 'video/mp4' })\n videoChunks.current = []\n setVideoUrl(URL.createObjectURL(blobFile))\n setIsRecording(false)\n camera?.release()\n }\n\n mediaRecorder.current.start()\n }, [camera, stream])\n\n const stopRecording = useCallback(() => {\n mediaRecorder.current?.stop()\n }, [])\n\n return { isRecording, startRecording, stopRecording, videoUrl }\n}\n","import React, { useContext, useEffect, useRef, useState } from 'react'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { useVideoRecorder } from '../../lib/camera/useVideoRecorder'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport {\n SignatureData,\n signatureDataToIdmissionFormat,\n} from '../signature_capture/data'\nimport SignatureCanvas from 'react-signature-canvas'\nimport useResizeObserver from 'use-resize-observer'\nimport { HighPerformanceSelfieGuidanceModelsContext } from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport { PageContainer } from '../common/Page'\nimport {\n SignatureButtonsContainer,\n SignatureCanvasContainer,\n SignaturePad,\n} from '../common/signature'\nimport {\n GuidanceMessage,\n GuidanceMessageContainer,\n} from '../common/GuidanceMessage'\nimport { DebugStatsPane } from '../common/debug'\nimport { ExitCaptureButton } from '../common/ExitCaptureButton'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\nimport { LoaderButton } from '../common/LoaderButton'\nimport styled from 'styled-components'\n\nexport type VideoSignatureCaptureClassNames = {\n container?: string\n cameraFeed?: string\n guidanceMessageContainer?: string\n guidanceMessage?: string\n canvasContainer?: string\n canvasInner?: string\n canvas?: string\n buttonsRow?: string\n acceptBtn?: string\n clearBtn?: string\n exitCaptureBtn?: string\n}\n\nexport type VideoSignatureCaptureColors = {\n guidanceMessageBackgroundColor?: string\n guidanceMessageTextColor?: string\n}\n\nexport type VideoSignatureCaptureVerbiage = {\n guidanceMessageText?: CustomerSuppliedVerbiage\n acceptBtnText?: CustomerSuppliedVerbiage\n clearBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type VideoSignatureCaptureProps = {\n onVideoCaptured?: (\n videoData: Blob,\n signatureData: SignatureData,\n signatureImageData: string\n ) => void\n onFaceNotDetected?: () => void\n onExit?: () => void\n classNames?: VideoSignatureCaptureClassNames\n colors?: VideoSignatureCaptureColors\n verbiage?: VideoSignatureCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const VideoSignatureCapture = ({\n onVideoCaptured,\n onFaceNotDetected,\n onExit,\n classNames = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: VideoSignatureCaptureProps): React.ReactElement => {\n const { cameraRef, videoRef } = useContext(CameraStateContext)\n const { ref, width, height } = useResizeObserver()\n const signaturePad = useRef<SignatureCanvas | null>(null)\n const signatureRecorder = useRef<MediaRecorder | null>(null)\n const recordedChunks = useRef<BlobPart[]>([])\n const [signatureVideoUrl, setSignatureVideoUrl] = useState<string | null>(\n null\n )\n const { onPredictionMade } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n\n const { isRecording, startRecording, stopRecording, videoUrl } =\n useVideoRecorder(cameraRef.current)\n const [signatureData, setSignatureData] = useState<SignatureData | null>(null)\n const [signatureDataUrl, setSignatureDataUrl] = useState<string | null>(null)\n const [signatureVideoData, setSignatureVideoData] = useState<Blob | null>(\n null\n )\n\n colors.guidanceMessageBackgroundColor ||= '#ccc'\n colors.guidanceMessageTextColor ||= 'black'\n\n const verbiage = useTranslations(rawVerbiage, {\n guidanceMessageText: 'Please sign the box below',\n acceptBtnText: 'Accept',\n clearBtnText: 'Clear',\n })\n\n const outputCanvas = useRef<HTMLCanvasElement | null>(null)\n\n useEffect(() => {\n // delay 100ms to make sure outputCanvas has rendered.\n setTimeout(() => {\n if (!isRecording && !videoUrl && !!outputCanvas.current) {\n startRecording()\n\n const stream = outputCanvas.current.captureStream(25 /* fps */)\n signatureRecorder.current = new MediaRecorder(stream, {\n // mimeType: 'video/mp4; codecs=\"avc1.424028, mp4a.40.2\"',\n })\n\n signatureRecorder.current.start()\n\n signatureRecorder.current.ondataavailable = function (event) {\n recordedChunks.current.push(event.data)\n if (signatureRecorder.current?.state === 'recording') {\n signatureRecorder.current.stop()\n }\n }\n\n signatureRecorder.current.onstop = function () {\n const blob = new Blob(recordedChunks.current, { type: 'video/mp4' })\n setSignatureVideoData(blob)\n const url = URL.createObjectURL(blob)\n setSignatureVideoUrl(url)\n }\n }\n }, 100)\n }, [isRecording, startRecording, videoUrl])\n\n useEffect(() => {\n if (signatureVideoData && signatureData && signatureDataUrl) {\n onVideoCaptured?.(signatureVideoData, signatureData, signatureDataUrl)\n }\n }, [onVideoCaptured, signatureData, signatureDataUrl, signatureVideoData])\n\n const animationFrame = useRef(0)\n useEffect(() => {\n if (\n !signaturePad.current ||\n !videoRef.current ||\n !outputCanvas.current ||\n !cameraRef.current ||\n !isRecording\n )\n return\n\n let [w, h] = [cameraRef.current.width, cameraRef.current.height]\n const isPortrait = window.innerWidth < window.innerHeight\n const cameraIsLandscape = w > h\n if (isPortrait && cameraIsLandscape) [w, h] = [h, w]\n outputCanvas.current.width = w\n outputCanvas.current.height = h\n\n const ctx = outputCanvas.current.getContext('2d')\n if (!ctx) return\n\n animationFrame.current = requestAnimationFrame(async function runFrame() {\n if (!signaturePad.current || !videoRef.current || !outputCanvas.current) {\n cancelAnimationFrame(animationFrame.current)\n return\n }\n\n const rect: [number, number, number, number] = [\n w * (isPortrait ? 0.02 : 0.15),\n h * (isPortrait ? 0.15 : 0.25),\n w * (isPortrait ? 0.96 : 0.7),\n h * (isPortrait ? 0.7 : 0.5),\n ]\n\n ctx.drawImage(videoRef.current, 0, 0, w, h)\n\n ctx.beginPath()\n ctx.fillStyle = 'rgba(255,255,255,0.5)'\n ctx.roundRect(...rect, 16)\n ctx.fill()\n\n ctx.drawImage(signaturePad.current.getCanvas(), ...rect)\n\n animationFrame.current = requestAnimationFrame(runFrame)\n })\n\n return () => {\n cancelAnimationFrame(animationFrame.current)\n }\n }, [cameraRef, isRecording, onFaceNotDetected, videoRef])\n\n const [numFramesWithoutFaces, setNumFramesWithoutFaces] = useState(0)\n useEffect(() => {\n onPredictionMade((faces) => {\n setNumFramesWithoutFaces((n) => (faces.length === 0 ? n + 1 : 0))\n })\n }, [onPredictionMade])\n\n useEffect(() => {\n if (numFramesWithoutFaces >= 2) {\n onFaceNotDetected?.()\n }\n }, [numFramesWithoutFaces, onFaceNotDetected])\n\n if (!isRecording && videoUrl) {\n return (\n <>\n {signatureVideoUrl && (\n <video src={signatureVideoUrl} controls={true} width=\"100%\" />\n )}\n {signatureDataUrl && <img src={signatureDataUrl} alt=\"signature\" />}\n {signatureData && (\n <textarea\n readOnly\n style={{ width: '100%', height: 500 }}\n value={JSON.stringify(signatureData, null, 2)}\n />\n )}\n </>\n )\n }\n\n function onAcceptClicked() {\n if (!signaturePad.current) return\n\n const signatureData = signatureDataToIdmissionFormat(signaturePad.current)\n setSignatureData(signatureData)\n setSignatureDataUrl(signaturePad.current.toDataURL())\n stopRecording()\n signatureRecorder.current?.stop()\n }\n\n return (\n <PageContainer className={`flex ${classNames.container ?? ''}`}>\n <CameraVideoTag className={classNames.cameraFeed} />\n\n {verbiage.guidanceMessageText && (\n <GuidanceMessageContainer\n $top=\"5vh\"\n className={classNames.guidanceMessageContainer}\n >\n <GuidanceMessage\n className={classNames.guidanceMessage}\n $background={colors.guidanceMessageBackgroundColor}\n $textColor={colors.guidanceMessageTextColor}\n >\n {verbiage.guidanceMessageText}\n </GuidanceMessage>\n </GuidanceMessageContainer>\n )}\n\n <SignatureCanvasContainer className={classNames.canvasContainer}>\n <SignaturePad ref={ref} className={classNames.canvasInner}>\n <SignatureCanvas\n ref={signaturePad}\n canvasProps={{ width, height, className: classNames.canvas }}\n />\n </SignaturePad>\n\n <SignatureButtonsContainer className={classNames.buttonsRow}>\n <LoaderButton\n variant=\"secondary\"\n className={classNames.clearBtn}\n onClick={signaturePad.current?.clear}\n finished\n >\n {verbiage.clearBtnText}\n </LoaderButton>\n\n <AcceptBtn\n variant=\"positive\"\n className={classNames.acceptBtn}\n style={{ marginLeft: 'auto' }}\n onClick={onAcceptClicked}\n finished\n >\n {verbiage.acceptBtnText}\n </AcceptBtn>\n </SignatureButtonsContainer>\n </SignatureCanvasContainer>\n\n {debugMode && (\n <DebugStatsPane>\n Video: {cameraRef.current?.width}x{cameraRef.current?.height}\n </DebugStatsPane>\n )}\n\n <ExitCaptureButton\n onClick={onExit}\n className={classNames.exitCaptureBtn}\n />\n\n <div style={{ display: 'none' }}>\n <canvas ref={outputCanvas} />\n </div>\n </PageContainer>\n )\n}\n\nconst AcceptBtn = styled(LoaderButton)`\n margin-left: auto;\n`\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport {\n VideoSignatureCapture,\n VideoSignatureCaptureClassNames,\n VideoSignatureCaptureColors,\n VideoSignatureCaptureVerbiage,\n} from './VideoSignatureCapture'\nimport {\n FaceLivenessCapture,\n FaceLivenessCaptureClassNames,\n} from '../face_liveness/FaceLivenessCapture'\nimport { HighPerformanceSelfieGuidanceModelsProvider } from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { SignatureData } from '../signature_capture/data'\nimport {\n VideoSignatureSuccess,\n VideoSignatureSuccessClassNames,\n VideoSignatureSuccessColors,\n VideoSignatureSuccessVerbiage,\n} from './VideoSignatureSuccess'\nimport {\n FaceLivenessColors,\n FaceLivenessVerbiage,\n} from '../face_liveness/FaceLivenessWizard'\nimport {\n SelfieCaptureLoadingOverlay,\n SelfieCaptureLoadingOverlayAssets,\n SelfieCaptureLoadingOverlayClassNames,\n SelfieCaptureLoadingOverlayVerbiage,\n} from '../selfie_capture/SelfieCaptureLoadingOverlay'\nimport { useShowSuccessScreen } from '../common/useShowSuccessScreen'\nimport { SubmissionContext } from '../submission/SubmissionProvider'\n\ntype CaptureState =\n | 'LOADING'\n | 'CHECKING_LIVENESS'\n | 'CAPTURING_SIGNATURE'\n | 'SUCCESS'\n | 'FAILED'\n\nexport type VideoSignatureAssets = {\n loadingOverlay?: SelfieCaptureLoadingOverlayAssets\n}\n\nexport type VideoSignatureClassNames = VideoSignatureCaptureClassNames & {\n loadingOverlay?: SelfieCaptureLoadingOverlayClassNames\n faceLiveness?: FaceLivenessCaptureClassNames\n success?: VideoSignatureSuccessClassNames\n}\n\nexport type VideoSignatureColors = VideoSignatureCaptureColors & {\n faceLiveness?: FaceLivenessColors\n success?: VideoSignatureSuccessColors\n}\n\nexport type VideoSignatureVerbiage = VideoSignatureCaptureVerbiage & {\n loadingOverlay?: SelfieCaptureLoadingOverlayVerbiage\n faceLiveness?: FaceLivenessVerbiage\n success?: VideoSignatureSuccessVerbiage\n}\n\nexport type VideoSignatureWizardProps = {\n onComplete?: () => void\n onVideoCaptured?: (\n videoData: Blob,\n signatureData: SignatureData,\n signatureImageData: string\n ) => void\n onRetryClicked?: () => void\n onExitCapture?: () => void\n skipSuccessScreen?: boolean | (() => Promise<boolean>)\n\n assets?: VideoSignatureAssets\n classNames?: VideoSignatureClassNames\n colors?: VideoSignatureColors\n verbiage?: VideoSignatureVerbiage\n debugMode?: boolean\n}\n\nexport const VideoSignatureWizard = ({\n onComplete,\n onVideoCaptured,\n onRetryClicked,\n onExitCapture,\n skipSuccessScreen = false,\n assets = {},\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: VideoSignatureWizardProps): ReactElement => {\n const {\n selfieImage,\n signatureVideoUrl,\n setSelfieImage,\n setSignatureData,\n setSignatureVideoUrl,\n logSelfieCaptureAttempt,\n } = useContext(SubmissionContext)\n const [captureState, setCaptureState] = useState<CaptureState>('LOADING')\n const operationStartedAt = useRef<Date>()\n const captureStartedAt = useRef<Date>()\n const captureEndedAt = useRef<Date>()\n\n useEffect(() => {\n operationStartedAt.current = new Date()\n }, [])\n\n useEffect(() => {\n if (captureState === 'CHECKING_LIVENESS') {\n captureStartedAt.current = new Date()\n }\n }, [captureState])\n\n const logCaptureMetadata = useCallback(() => {\n logSelfieCaptureAttempt({\n autoCapture: 'Y',\n captureTime:\n (captureEndedAt.current ?? new Date()).getTime() -\n (captureStartedAt.current ?? new Date()).getTime(),\n operationTime:\n new Date().getTime() -\n (operationStartedAt.current ?? new Date()).getTime(),\n })\n\n operationStartedAt.current = new Date()\n }, [logSelfieCaptureAttempt])\n\n const onLoadingOverlayDismissed = useCallback(() => {\n setCaptureState('CHECKING_LIVENESS')\n }, [])\n\n const onFaceCaptureSuccess = useCallback(\n async (faceCropImageUrl: string) => {\n setCaptureState('CAPTURING_SIGNATURE')\n logCaptureMetadata()\n if (!selfieImage) {\n setSelfieImage(await dataUrlToBase64(faceCropImageUrl))\n }\n },\n [logCaptureMetadata, selfieImage, setSelfieImage]\n )\n\n const onSignatureCaptureCompleted = useCallback(\n (\n videoData: Blob,\n signatureData: SignatureData,\n signatureImageData: string\n ) => {\n setSignatureData(signatureData)\n setSignatureVideoUrl(URL.createObjectURL(videoData))\n setCaptureState('SUCCESS')\n onVideoCaptured?.(videoData, signatureData, signatureImageData)\n },\n [onVideoCaptured, setSignatureData, setSignatureVideoUrl]\n )\n\n const onSignatureCaptureFacesNotDetected = useCallback(() => {\n setCaptureState('CHECKING_LIVENESS')\n }, [])\n\n const [attempt, setAttempt] = useState(0)\n const onExit = useCallback(() => {\n setAttempt((n) => n + 1)\n setCaptureState('LOADING')\n onExitCapture?.()\n }, [onExitCapture])\n const onRetry = useCallback(() => {\n onRetryClicked?.()\n onExit()\n }, [onExit, onRetryClicked])\n\n const showSuccessScreen = useShowSuccessScreen(\n skipSuccessScreen,\n captureState === 'SUCCESS',\n onComplete\n )\n\n return (\n <HighPerformanceSelfieGuidanceModelsProvider\n throttleMs={captureState === 'CAPTURING_SIGNATURE' ? 250 : 0}\n >\n {captureState !== 'LOADING' &&\n (() => {\n switch (captureState) {\n case 'CHECKING_LIVENESS':\n return (\n <FaceLivenessCapture\n onSuccess={onFaceCaptureSuccess}\n onExit={onExit}\n classNames={classNames.faceLiveness}\n colors={colors.faceLiveness}\n verbiage={verbiage.faceLiveness}\n debugMode={debugMode}\n />\n )\n\n case 'CAPTURING_SIGNATURE':\n return (\n <VideoSignatureCapture\n onVideoCaptured={onSignatureCaptureCompleted}\n onFaceNotDetected={onSignatureCaptureFacesNotDetected}\n onExit={onExit}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n )\n\n case 'SUCCESS':\n if (!showSuccessScreen) return\n return (\n <VideoSignatureSuccess\n videoUrl={signatureVideoUrl ?? ''}\n onDoneClick={onComplete}\n onRetryClick={onRetry}\n classNames={classNames.success}\n colors={colors.success}\n verbiage={verbiage.success}\n />\n )\n\n default:\n return null\n }\n })()}\n\n <SelfieCaptureLoadingOverlay\n key={attempt}\n assets={assets.loadingOverlay}\n classNames={classNames.loadingOverlay}\n verbiage={verbiage.loadingOverlay}\n onDismissed={onLoadingOverlayDismissed}\n />\n </HighPerformanceSelfieGuidanceModelsProvider>\n )\n}\n","import React, {\n CSSProperties,\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport useResizeObserver from 'use-resize-observer'\nimport { CameraStateContext } from '../camera/CameraProvider'\n\nexport type IdVideoCaptureFlipIdPromptAssets = {\n frontImageUrl?: string\n backImageUrl?: string\n}\nexport type IdVideoCaptureFlipIdPromptVerbiage = {\n instructionText?: CustomerSuppliedVerbiage\n}\n\nexport type IdVideoCaptureFlipIdPromptProps = {\n imageWidth?: number\n imageHeight?: number\n style?: CSSProperties\n assets?: IdVideoCaptureFlipIdPromptAssets\n verbiage?: IdVideoCaptureFlipIdPromptVerbiage\n}\n\nexport const IdVideoCaptureFlipIdPrompt = ({\n imageWidth,\n imageHeight,\n style = {},\n assets = {},\n verbiage = {},\n}: IdVideoCaptureFlipIdPromptProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const { cameraRef } = useContext(CameraStateContext)\n\n assets.frontImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.backImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n\n const instructionText = useVerbiage(\n verbiage.instructionText,\n 'Please flip your ID card...',\n )\n\n const padding = 0\n const borderWidth = 4\n const borderColor = 'white'\n const isMirrored = !cameraRef.current?.isRearFacing\n\n // const [imageLoaded, setImageLoaded] = useState(false)\n const onImageLoaded = useCallback(() => {\n // setImageLoaded(true)\n }, [])\n\n let imageStyle: React.CSSProperties = {\n height: height - padding * 2 - borderWidth * 2,\n }\n // if (imageAspectRatio >= wrapperAspectRatio) {\n imageStyle = {\n width: width - padding * 2 - borderWidth * 2,\n }\n // }\n\n const [transitionTime, setTransitionTime] = useState(1)\n const [rotationAngle, setRotationAngle] = useState(0)\n const frontTransforms = [`rotateY(${rotationAngle}deg)`]\n if (isMirrored) frontTransforms.push('scaleX(-1)')\n const backTransforms = [`rotateY(${180 - rotationAngle}deg)`]\n if (isMirrored) backTransforms.push('scaleX(-1)')\n\n useEffect(() => {\n const doFlip = () => {\n setTransitionTime(1)\n setRotationAngle(180)\n\n setTimeout(() => {\n setTransitionTime(0)\n setRotationAngle(0)\n }, 1500)\n }\n\n setTimeout(doFlip, 250)\n const interval = setInterval(doFlip, 2500)\n\n return () => {\n clearInterval(interval)\n }\n }, [])\n\n return (\n <div ref={ref} style={{ ...style, position: 'relative' }}>\n <div\n style={{\n display: 'flex',\n flexFlow: 'column nowrap',\n height: '100%',\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n }}\n >\n {instructionText}\n </span>\n </div>\n\n <div\n style={{\n position: 'relative',\n display: 'flex',\n flexFlow: 'row nowrap',\n alignItems: 'center',\n justifyItems: 'center',\n maxWidth: `calc(100%)`,\n maxHeight: `calc(100% - ${padding * 2}px - ${borderWidth * 2}px)`,\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n minWidth: padding,\n flexGrow: 1,\n }}\n />\n <div\n style={{\n maxWidth: `calc(100% - ${padding * 2}px - ${borderWidth * 2}px)`,\n maxHeight: height - padding * 2 - borderWidth * 2,\n }}\n >\n <div\n style={{\n position: 'relative',\n border: `${borderWidth}px solid ${borderColor}`,\n }}\n >\n <img\n src={assets.frontImageUrl}\n alt=\"\"\n width={imageWidth}\n height={imageHeight}\n onLoad={onImageLoaded}\n style={{\n backfaceVisibility: 'hidden',\n transition: `transform ${transitionTime}s`,\n transform: frontTransforms.join(' '),\n transformStyle: 'preserve-3d',\n position: 'relative',\n top: 0,\n left: 0,\n display: 'block',\n ...imageStyle,\n }}\n />\n\n <img\n src={assets.backImageUrl}\n alt=\"\"\n style={{\n backfaceVisibility: 'hidden',\n transition: `transform ${transitionTime}s`,\n transform: backTransforms.join(' '),\n transformStyle: 'preserve-3d',\n position: 'absolute',\n top: 0,\n left: 0,\n display: 'block',\n ...imageStyle,\n }}\n />\n </div>\n </div>\n <div\n style={{\n width: '100%',\n height: '100%',\n minWidth: padding,\n flexGrow: 1,\n }}\n />\n </div>\n\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n opacity: 0,\n }}\n >\n {instructionText}\n </span>\n </div>\n </div>\n </div>\n )\n}\n","import React, { ReactElement, useRef, useState } from 'react'\nimport { DEFAULT_CDN_URL } from '../common/cdn'\nimport { IdVideoCaptureFlipIdPrompt } from './IdVideoCaptureFlipIdPrompt'\nimport { CustomerSuppliedVerbiage, useTranslations } from '../../lib/locales'\n\nexport type Action = 'SHOW_ID_FRONT' | 'FLIP_ID' | 'SHOW_ID_BACK' | 'READ_TEXT'\n\nexport type IdVideoCaptureGuidesAssets = {\n frontImageUrl?: string\n backImageUrl?: string\n}\n\nexport type IdVideoCaptureGuidesVerbiage = {\n idFrontInstructionText?: CustomerSuppliedVerbiage\n idBackInstructionText?: CustomerSuppliedVerbiage\n flipIdInstructionText?: CustomerSuppliedVerbiage\n}\n\nexport type IdVideoCaptureGuidesProps = {\n borderWidth?: number\n borderColor?: string\n requestedAction?: Action\n assets?: IdVideoCaptureGuidesAssets\n verbiage?: IdVideoCaptureGuidesVerbiage\n}\n\nexport const IdVideoCaptureGuides = ({\n requestedAction = 'SHOW_ID_FRONT',\n borderWidth = 3,\n borderColor = 'white',\n assets = {},\n verbiage: rawVerbiage = {},\n}: IdVideoCaptureGuidesProps): ReactElement => {\n const imageRef = useRef<HTMLImageElement | null>(null)\n const [imageWidth, setImageWidth] = useState(0)\n const [imageHeight, setImageHeight] = useState(0)\n assets.frontImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Front-SVG-Landscape-2.svg`\n assets.backImageUrl ||= `${DEFAULT_CDN_URL}/Shieldout-IDCard-Back-SVG-Landscape-2.svg`\n\n const verbiage = useTranslations(rawVerbiage, {\n idFrontInstructionText: 'Display the front of your ID card...',\n idBackInstructionText: 'Display the back of your ID card...',\n })\n\n const instructionText =\n requestedAction === 'SHOW_ID_FRONT'\n ? verbiage.idFrontInstructionText\n : verbiage.idBackInstructionText\n\n const idGuideWidth = window.innerWidth > window.innerHeight ? '30%' : '75%'\n\n return (\n <>\n <div\n style={{\n position: 'absolute',\n zIndex: 1000,\n width: '100%',\n height: '100%',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n <div\n style={{\n borderWidth,\n borderColor,\n borderStyle: 'solid',\n borderRadius: '50%',\n aspectRatio: '1 / 1.618',\n height: '100%',\n margin: '4% auto auto',\n }}\n />\n\n {requestedAction === 'FLIP_ID' ? (\n <IdVideoCaptureFlipIdPrompt\n assets={assets}\n verbiage={{ instructionText: verbiage.flipIdInstructionText }}\n imageWidth={imageWidth}\n imageHeight={imageHeight}\n style={{ width: idGuideWidth, margin: '2% auto 2%' }}\n />\n ) : (\n <div\n style={{\n width: idGuideWidth,\n margin: '2% auto 2%',\n display: 'flex',\n flexFlow: 'column nowrap',\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n }}\n >\n {instructionText}\n </span>\n </div>\n\n <div style={{ border: `4px solid ${borderColor}` }}>\n <img\n ref={imageRef}\n src={\n requestedAction === 'SHOW_ID_BACK'\n ? assets.backImageUrl\n : assets.frontImageUrl\n }\n alt=\"\"\n style={{ width: '100%' }}\n onLoad={() => {\n if (!imageWidth) setImageWidth(imageRef.current?.width ?? 0)\n if (!imageHeight)\n setImageHeight(imageRef.current?.height ?? 0)\n }}\n />\n </div>\n\n <div\n style={{\n width: '100%',\n height: '100%',\n flexGrow: 1,\n textAlign: 'center',\n color: 'white',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'end',\n }}\n >\n <span\n style={{\n alignContent: 'center',\n marginTop: 12,\n marginBottom: 12,\n opacity: 0,\n }}\n >\n {instructionText}\n </span>\n </div>\n </div>\n )}\n </div>\n </>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { CameraVideoTag } from '../camera/CameraVideoTag'\nimport { PageContainer } from '../common/Page'\nimport {\n Face,\n HighPerformanceSelfieGuidanceModelsContext,\n} from '../selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport {\n DebugStatsPane,\n IdCaptureDetectedObjectDebugBox,\n ObjectDetectionDebugOverlay,\n SelfieCaptureFaceDebugBox,\n useDebugScalingDetails,\n} from '../common/debug'\nimport { CameraStateContext } from '../camera/CameraProvider'\nimport { DetectedObject } from '../../lib/models/DocumentDetection'\nimport useResizeObserver from 'use-resize-observer'\nimport { IdCaptureModelsContext } from '../id_capture/IdCaptureModelsProvider'\nimport {\n IdVideoCaptureGuides,\n IdVideoCaptureGuidesAssets,\n IdVideoCaptureGuidesVerbiage,\n} from './IdVideoCaptureGuides'\nimport { useVideoRecorder } from '../../lib/camera/useVideoRecorder'\nimport {\n CustomerSuppliedVerbiage,\n useTranslations,\n useVerbiage,\n} from '../../lib/locales'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { LoaderButton, LoaderButtonColors } from '../common/LoaderButton'\nimport {\n clearCanvas,\n drawToCanvas,\n InvisibleCanvas,\n} from '../common/InvisibleCanvas'\n\nexport type Action = 'SHOW_ID_FRONT' | 'FLIP_ID' | 'SHOW_ID_BACK' | 'READ_TEXT'\n\nexport type IdVideoCaptureAssets = {\n guides?: IdVideoCaptureGuidesAssets\n}\n\nexport type IdVideoCaptureClassNames = {}\n\nexport type IdVideoCaptureColors = {\n guidesSatisfiedColor?: string\n guidesUnsatisfiedColor?: string\n readTextDoneBtn?: LoaderButtonColors\n}\n\nexport type IdVideoCaptureVerbiage = {\n guides?: IdVideoCaptureGuidesVerbiage\n readTextHeading?: CustomerSuppliedVerbiage\n readTextDoneBtnText?: CustomerSuppliedVerbiage\n}\n\nexport type IdVideoCaptureProps = {\n onComplete?: (videoUrl: string) => void\n onIdFrontImageCaptured?: (imageUrl: string) => void\n onIdBackImageCaptured?: (imageUrl: string) => void\n onFaceNotDetected?: () => void\n\n idCardFrontDetectionThreshold?: number\n idCardFrontFocusThreshold?: number\n goodIdCardFrontFramesThreshold?: number\n showIdCardBackDurationMs?: number\n skipShowIdCardBack?: boolean | (() => Promise<boolean>)\n readTextPrompt?: CustomerSuppliedVerbiage\n readTextTimeoutDurationMs?: number\n\n assets?: IdVideoCaptureAssets\n colors?: IdVideoCaptureColors\n verbiage?: IdVideoCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const IdVideoCapture = ({\n onComplete,\n onIdFrontImageCaptured,\n onIdBackImageCaptured,\n onFaceNotDetected,\n\n idCardFrontDetectionThreshold = 0.48,\n idCardFrontFocusThreshold = 0.15,\n goodIdCardFrontFramesThreshold = 3,\n showIdCardBackDurationMs = 5000,\n skipShowIdCardBack = false,\n readTextPrompt,\n readTextTimeoutDurationMs = 15000,\n\n assets = {},\n colors = {},\n verbiage: rawVerbiage = {},\n debugMode = false,\n}: IdVideoCaptureProps): ReactElement => {\n const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>()\n const { cameraRef, videoRef, videoLoaded, cameraReady } =\n useContext(CameraStateContext)\n const [detectedObjects, setDetectedObjects] = useState<DetectedObject[]>([])\n const [faces, setFaces] = useState<Face[]>([])\n const {\n ready: idModelsReady,\n working: idModelsWorking,\n makePrediction: makeIdPrediction,\n onPredictionMade: onIdPredictionMade,\n setThresholds,\n } = useContext(IdCaptureModelsContext)\n const { onPredictionMade: onSelfiePredictionMade } = useContext(\n HighPerformanceSelfieGuidanceModelsContext\n )\n const { isRecording, startRecording, stopRecording, videoUrl } =\n useVideoRecorder(cameraRef.current)\n\n useEffect(() => {\n if (!isRecording && !videoUrl) startRecording()\n if (videoUrl) onComplete?.(videoUrl)\n }, [isRecording, onComplete, startRecording, videoUrl])\n\n const animationFrame = useRef(0)\n const shouldCaptureFrames = useRef(false)\n\n useEffect(() => {\n shouldCaptureFrames.current = videoLoaded && cameraReady && idModelsReady\n }, [cameraReady, idModelsReady, videoLoaded])\n\n const [requestedAction, setRequestedAction] =\n useState<Action>('SHOW_ID_FRONT')\n\n useEffect(() => {\n if (requestedAction !== 'SHOW_ID_FRONT') return\n if (!idModelsReady || !cameraReady || !videoLoaded) return\n\n animationFrame.current = requestAnimationFrame(async function runFrame() {\n if (shouldCaptureFrames.current && !idModelsWorking.current) {\n if (videoRef.current) makeIdPrediction(videoRef.current)\n }\n\n animationFrame.current = requestAnimationFrame(runFrame)\n })\n\n return () => {\n cancelAnimationFrame(animationFrame.current)\n }\n }, [\n cameraReady,\n idModelsReady,\n idModelsWorking,\n makeIdPrediction,\n requestedAction,\n videoLoaded,\n videoRef,\n ])\n\n useEffect(() => {\n setThresholds({\n document: idCardFrontDetectionThreshold,\n passport: 1,\n focus: idCardFrontFocusThreshold,\n })\n }, [idCardFrontDetectionThreshold, idCardFrontFocusThreshold, setThresholds])\n\n const [goodIdCardFrontFramesCount, setGoodFramesCount] = useState(0)\n const goodFramesThresholdMet =\n goodIdCardFrontFramesCount >= goodIdCardFrontFramesThreshold\n useEffect(() => {\n onIdPredictionMade((prediction) => {\n setDetectedObjects(prediction.detectedObjects)\n if (prediction.detectionThresholdMet && prediction.focusThresholdMet) {\n setGoodFramesCount((n) => n + 1)\n } else {\n setGoodFramesCount(0)\n }\n })\n }, [idCardFrontDetectionThreshold, onIdPredictionMade])\n\n const captureCanvas = useRef<HTMLCanvasElement | null>(null)\n const captureFrame = useCallback(() => {\n if (!captureCanvas.current || !videoRef.current) return\n drawToCanvas(captureCanvas.current, videoRef.current)\n const imageUrl = captureCanvas.current.toDataURL('image/jpeg', 0.98)\n clearCanvas(captureCanvas.current)\n return imageUrl\n }, [videoRef])\n\n const onIdBackCaptureComplete = useCallback(() => {\n if (readTextPrompt) {\n setRequestedAction('READ_TEXT')\n } else {\n stopRecording()\n }\n }, [readTextPrompt, stopRecording])\n\n useEffect(() => {\n ;(async () => {\n if (goodFramesThresholdMet && requestedAction == 'SHOW_ID_FRONT') {\n if (onIdFrontImageCaptured) {\n console.log('capturing front frame!')\n const frame = captureFrame()\n console.log(frame)\n frame && onIdFrontImageCaptured(frame)\n }\n\n if (skipShowIdCardBack) {\n if (skipShowIdCardBack === true) {\n return onIdBackCaptureComplete()\n } else if (await skipShowIdCardBack()) {\n return onIdBackCaptureComplete()\n }\n }\n\n setRequestedAction('FLIP_ID')\n setTimeout(() => {\n setRequestedAction('SHOW_ID_BACK')\n setTimeout(() => {\n if (onIdBackImageCaptured) {\n console.log('capturing rear frame!')\n const frame = captureFrame()\n console.log(frame)\n frame && onIdBackImageCaptured(frame)\n }\n }, showIdCardBackDurationMs - 1000)\n }, 3500)\n }\n })()\n }, [\n captureFrame,\n goodFramesThresholdMet,\n onIdBackCaptureComplete,\n onIdBackImageCaptured,\n onIdFrontImageCaptured,\n requestedAction,\n showIdCardBackDurationMs,\n skipShowIdCardBack,\n ])\n\n useTimeout(\n showIdCardBackDurationMs,\n onIdBackCaptureComplete,\n requestedAction !== 'SHOW_ID_BACK',\n false,\n requestedAction === 'SHOW_ID_BACK'\n )\n\n const onReadTextTimeout = useCallback(() => {\n stopRecording()\n }, [stopRecording])\n\n const { timeoutStartedAt } = useTimeout(\n readTextTimeoutDurationMs,\n onReadTextTimeout,\n requestedAction !== 'READ_TEXT',\n false,\n requestedAction === 'READ_TEXT'\n )\n\n const [numFramesWithoutFaces, setNumFramesWithoutFaces] = useState(0)\n useEffect(() => {\n onSelfiePredictionMade((faces) => {\n setFaces(faces)\n setNumFramesWithoutFaces((n) => (faces.length === 0 ? n + 1 : 0))\n })\n }, [onSelfiePredictionMade])\n\n useEffect(() => {\n if (numFramesWithoutFaces >= 2) {\n onFaceNotDetected?.()\n }\n }, [numFramesWithoutFaces, onFaceNotDetected])\n\n colors.guidesSatisfiedColor ||= 'green'\n colors.guidesUnsatisfiedColor ||= 'white'\n\n const verbiage = useTranslations(rawVerbiage, {\n readTextHeading: 'Please read the following text aloud',\n readTextDoneBtnText: 'Done',\n })\n\n readTextPrompt = useVerbiage(readTextPrompt, '')\n\n const debugScalingDetails = useDebugScalingDetails({\n enabled: debugMode,\n pageWidth: width,\n pageHeight: height,\n videoWidth: videoRef.current?.videoWidth ?? 0,\n videoHeight: videoRef.current?.videoHeight ?? 0,\n })\n\n const timeRemaining = msToTime(\n Math.max(\n 0,\n readTextTimeoutDurationMs -\n (new Date().getTime() - (timeoutStartedAt ?? new Date()).getTime())\n )\n )\n\n const satisfied =\n requestedAction === 'SHOW_ID_BACK' || goodIdCardFrontFramesCount > 0\n\n return (\n <PageContainer ref={ref} className=\"flex\">\n <CameraVideoTag />\n <InvisibleCanvas ref={captureCanvas} />\n\n {requestedAction === 'READ_TEXT' ? (\n <div\n style={{\n position: 'absolute',\n width: '100%',\n height: '100%',\n top: 0,\n left: 0,\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n <div\n style={{\n margin: 'auto auto 32px',\n background: 'rgba(255,255,255,0.5)',\n borderRadius: 8,\n padding: 20,\n fontWeight: 'bold',\n }}\n >\n {verbiage.readTextHeading}\n </div>\n\n <div\n style={{\n margin: '0 auto',\n textAlign: 'center',\n background: 'rgba(255,255,255,0.5)',\n borderRadius: 8,\n padding: 50,\n fontSize: 24,\n maxWidth: window.innerWidth > window.innerHeight ? '40%' : '90%',\n }}\n >\n {readTextPrompt}\n </div>\n\n <div style={{ display: 'flex', margin: '32px auto auto', gap: 20 }}>\n <div\n style={{\n background: 'rgba(255,255,255,0.5)',\n borderRadius: 4,\n padding: 20,\n }}\n >\n {timeRemaining}\n </div>\n\n <LoaderButton\n variant=\"positive\"\n onClick={stopRecording}\n colors={colors.readTextDoneBtn}\n finished\n >\n {verbiage.readTextDoneBtnText}\n </LoaderButton>\n </div>\n </div>\n ) : (\n <>\n <IdVideoCaptureGuides\n assets={assets.guides}\n verbiage={rawVerbiage.guides}\n requestedAction={requestedAction}\n borderColor={\n satisfied\n ? colors.guidesSatisfiedColor\n : colors.guidesUnsatisfiedColor\n }\n />\n\n {debugMode && requestedAction === 'SHOW_ID_FRONT' && (\n <>\n <ObjectDetectionDebugOverlay\n $flipX={!cameraRef.current?.isRearFacing}\n >\n {detectedObjects.map((obj, i) => (\n <IdCaptureDetectedObjectDebugBox\n key={i}\n obj={obj}\n scaling={debugScalingDetails}\n color=\"blue\"\n flipX={!cameraRef.current?.isRearFacing}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n\n <ObjectDetectionDebugOverlay\n $flipX={!cameraRef.current?.isRearFacing}\n >\n {faces.map((face, i) => (\n <SelfieCaptureFaceDebugBox\n key={i}\n face={face}\n scaling={debugScalingDetails}\n flipX={!cameraRef.current?.isRearFacing}\n />\n ))}\n </ObjectDetectionDebugOverlay>\n </>\n )}\n </>\n )}\n\n {debugMode && (\n <DebugStatsPane>\n {cameraRef.current ? (\n <>\n ✅ Camera: {cameraRef.current.label} ({cameraRef.current.width}x\n {cameraRef.current.height})\n </>\n ) : (\n '❌ Camera not ready'\n )}\n <br />\n {isRecording ? '✅ Recording' : '❌ Not recording'}\n <br />\n {goodFramesThresholdMet ? '✅' : '❌'} Good Frame Count:{' '}\n {goodIdCardFrontFramesCount}/{goodIdCardFrontFramesThreshold}\n </DebugStatsPane>\n )}\n </PageContainer>\n )\n}\n\nfunction msToTime(s: number): string {\n const ms = s % 1000\n s = (s - ms) / 1000\n let secs = s % 60\n s = (s - secs) / 60\n const mins = s % 60\n secs += 1\n\n return mins + ':' + ('00' + secs).slice(-2)\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react'\nimport {\n IdCaptureSubmission,\n IdCaptureWizard,\n IdCaptureWizardProps,\n} from './id_capture/IdCaptureWizard'\nimport {\n FaceLivenessWizard,\n FaceLivenessWizardProps,\n} from './face_liveness/FaceLivenessWizard'\nimport { IdCaptureModelsProvider } from './id_capture/IdCaptureModelsProvider'\nimport { CameraProvider } from './camera/CameraProvider'\nimport { GuideOrientationProvider } from './GuideOrientationProvider'\nimport {\n SubmissionContext,\n SubmissionProvider,\n} from './submission/SubmissionProvider'\nimport {\n LivenessCheckRequest,\n SubmissionAction,\n SubmissionEnvironment,\n SubmissionResponse,\n SubmissionStatus,\n} from '../contexts/SubmissionContext'\nimport { SubmissionSuccess } from './submission/SubmissionSuccess'\nimport { Spinner } from './common/spinner'\nimport {\n AdditionalDocumentCaptureWizard,\n AdditionalDocumentCaptureWizardProps,\n} from './additional_document_capture/AdditionalDocumentCaptureWizard'\nimport {\n SignatureCapture,\n SignatureCaptureProps,\n} from './signature_capture/SignatureCapture'\nimport { HighPerformanceSelfieGuidanceModelsProvider } from './selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\nimport {\n VideoSignatureWizard,\n VideoSignatureWizardProps,\n} from './video_signature_capture/VideoSignatureWizard'\nimport { SignatureData } from './signature_capture/data'\nimport { UploadedDocument } from './additional_document_capture/AdditionalDocumentCapture'\nimport { PageContainer } from './common/Page'\nimport {\n VideoIdWizard,\n VideoIdWizardProps,\n} from './video_id/IdVideoCaptureWizard'\n\nexport type CompositeWizardCheck =\n | 'IdCapture'\n | 'FaceLiveness'\n | 'SignatureCapture'\n | 'VideoSignatureCapture'\n | 'AdditionalDocumentCapture'\n | 'VideoIdCapture'\n\nexport type CompositeWizardComponentProps = {\n checks: CompositeWizardCheck[]\n\n idCaptureProps?: IdCaptureWizardProps\n faceLivenessProps?: FaceLivenessWizardProps\n additionalDocumentCaptureProps?: AdditionalDocumentCaptureWizardProps\n signatureCaptureProps?: SignatureCaptureProps\n videoSignatureCaptureProps?: VideoSignatureWizardProps\n videoIdCaptureProps?: VideoIdWizardProps\n captureSignature?: boolean | (() => Promise<boolean>)\n captureSignatureVideo?: boolean | (() => Promise<boolean>)\n\n debugMode?: boolean\n}\n\nexport type CompositeWizardProps = CompositeWizardComponentProps & {\n submissionToken: string\n submissionAction?: SubmissionAction\n submissionEnvironment?: SubmissionEnvironment\n submissionUrl?: string\n onComplete?: (submissionResponse: SubmissionResponse) => void\n}\n\nexport const CompositeWizard = (props: CompositeWizardProps): ReactElement => (\n <SubmissionProvider\n token={props.submissionToken}\n action={props.submissionAction ?? SubmissionAction.VALIDATE}\n environment={props.submissionEnvironment ?? 'prod'}\n url={props.submissionUrl}\n onResponseReceived={props.onComplete}\n >\n <CompositeWizardComponent {...props} />\n </SubmissionProvider>\n)\n\nexport const CompositeWizardComponent = ({\n checks: userChecks,\n idCaptureProps = {},\n faceLivenessProps = {},\n additionalDocumentCaptureProps,\n signatureCaptureProps = {},\n videoSignatureCaptureProps = {},\n videoIdCaptureProps = {},\n captureSignature = false,\n captureSignatureVideo = false,\n debugMode = false,\n}: CompositeWizardComponentProps): ReactElement => {\n const { submit, submissionStatus, setSignatureData, setAdditionalDocuments } =\n useContext(SubmissionContext)\n const [checkIndex, setCheckIndex] = useState(0)\n const checks = useMemo(() => {\n const checks = [...userChecks]\n if (captureSignature && captureSignatureVideo) {\n throw new Error(\n 'captureSignature and captureSignatureVideo cannot be used together'\n )\n }\n if (captureSignature) {\n checks.push('SignatureCapture')\n }\n if (captureSignatureVideo) {\n checks.push('VideoSignatureCapture')\n // remove face liveness because video signature already has it.\n if (checks.includes('FaceLiveness'))\n checks.splice(checks.indexOf('FaceLiveness'), 1)\n }\n if (additionalDocumentCaptureProps?.documents?.length ?? 0 > 0) {\n checks.push('AdditionalDocumentCapture')\n }\n return checks\n }, [\n additionalDocumentCaptureProps?.documents?.length,\n captureSignature,\n captureSignatureVideo,\n userChecks,\n ])\n const currentCheck = checks[checkIndex]\n const isComplete = checkIndex >= checks.length\n\n useEffect(() => {\n if (\n currentCheck === 'SignatureCapture' &&\n typeof captureSignature === 'function'\n ) {\n captureSignature().then((shouldProceed) => {\n if (!shouldProceed) {\n setCheckIndex((i) => i + 1)\n }\n })\n } else if (\n currentCheck === 'VideoSignatureCapture' &&\n typeof captureSignatureVideo === 'function'\n ) {\n captureSignatureVideo().then((shouldProceed) => {\n if (!shouldProceed) {\n setCheckIndex((i) => i + 1)\n }\n })\n }\n }, [captureSignature, captureSignatureVideo, currentCheck])\n\n useEffect(() => {\n if (isComplete) submit()\n }, [isComplete, submit])\n\n const onIdCaptureSuccessProp = idCaptureProps.onSuccess\n const onIdCaptureSuccess = useCallback(\n (submission: IdCaptureSubmission) => {\n onIdCaptureSuccessProp?.(submission)\n setCheckIndex((i) => i + 1)\n },\n [onIdCaptureSuccessProp]\n )\n\n const onVideoIdCaptureCompleteProp = videoIdCaptureProps.onComplete\n const onVideoIdCaptureComplete = useCallback(() => {\n onVideoIdCaptureCompleteProp?.()\n setCheckIndex((i) => i + 1)\n }, [onVideoIdCaptureCompleteProp])\n\n const onFaceLivenessCompleteProp = faceLivenessProps.onComplete\n const onFaceLivenessComplete = useCallback(\n (resp: SubmissionResponse | null, req: LivenessCheckRequest | null) => {\n onFaceLivenessCompleteProp?.(resp, req)\n setCheckIndex((i) => i + 1)\n },\n [onFaceLivenessCompleteProp]\n )\n\n const onSignatureCaptureSuccess = useCallback(\n (signatureData: SignatureData) => {\n setSignatureData(signatureData)\n setCheckIndex((i) => i + 1)\n },\n [setSignatureData]\n )\n\n const onVideoSignatureCompleteProp = videoSignatureCaptureProps.onComplete\n const onVideoSignatureComplete = useCallback(() => {\n onVideoSignatureCompleteProp?.()\n setCheckIndex((i) => i + 1)\n }, [onVideoSignatureCompleteProp])\n const [videoSignatureAttempts, setVideoSignatureAttempts] = useState(0)\n const onVideoSignatureRetryProp = videoSignatureCaptureProps.onRetryClicked\n const onVideoSignatureRetry = useCallback(() => {\n onVideoSignatureRetryProp?.()\n setVideoSignatureAttempts((n) => n + 1)\n }, [onVideoSignatureRetryProp])\n\n const onAdditionalDocumentCaptureCompleteProp =\n additionalDocumentCaptureProps?.onComplete\n const onAdditionalDocumentCaptureComplete = useCallback(\n (uploadedDocuments: UploadedDocument[]) => {\n setAdditionalDocuments(uploadedDocuments)\n onAdditionalDocumentCaptureCompleteProp?.(uploadedDocuments)\n setCheckIndex((i) => i + 1)\n },\n [onAdditionalDocumentCaptureCompleteProp, setAdditionalDocuments]\n )\n\n const documents = useMemo(\n () => additionalDocumentCaptureProps?.documents ?? [],\n [additionalDocumentCaptureProps?.documents]\n )\n\n if (isComplete) {\n switch (submissionStatus) {\n case SubmissionStatus.SUBMITTING:\n return (\n <PageContainer className=\"flex\">\n <Spinner />\n </PageContainer>\n )\n\n case SubmissionStatus.SUBMITTED:\n return <SubmissionSuccess />\n\n case SubmissionStatus.FAILED:\n return <>Submission failed!</>\n\n default:\n return <>Complete!!</>\n }\n }\n\n switch (checks[checkIndex]) {\n case 'IdCapture':\n return (\n <IdCaptureModelsProvider\n documentDetectionModelUrl={\n idCaptureProps.assets?.documentDetectionModelUrl ?? ''\n }\n focusModelUrl={idCaptureProps.assets?.focusModelUrl ?? ''}\n logPredictions={debugMode}\n >\n <CameraProvider key=\"IdCaptureCamera\">\n <GuideOrientationProvider>\n <IdCaptureWizard\n {...idCaptureProps}\n onSuccess={onIdCaptureSuccess}\n />\n </GuideOrientationProvider>\n </CameraProvider>\n </IdCaptureModelsProvider>\n )\n\n case 'VideoIdCapture':\n return (\n <VideoIdWizard\n {...videoIdCaptureProps}\n onComplete={onVideoIdCaptureComplete}\n />\n )\n\n case 'FaceLiveness':\n return (\n <CameraProvider\n key=\"FaceLivenessCamera\"\n preferFrontFacingCamera={true}\n preferContinuityCamera={false}\n >\n <HighPerformanceSelfieGuidanceModelsProvider>\n <FaceLivenessWizard\n {...faceLivenessProps}\n onComplete={onFaceLivenessComplete}\n />\n </HighPerformanceSelfieGuidanceModelsProvider>\n </CameraProvider>\n )\n\n case 'SignatureCapture':\n return (\n <SignatureCapture\n {...signatureCaptureProps}\n onAccept={onSignatureCaptureSuccess}\n />\n )\n\n case 'VideoSignatureCapture':\n return (\n <CameraProvider\n key={`SignatureKycCamera-${videoSignatureAttempts}`}\n preferContinuityCamera={false}\n preferFrontFacingCamera={true}\n >\n <VideoSignatureWizard\n {...videoSignatureCaptureProps}\n onComplete={onVideoSignatureComplete}\n onRetryClicked={onVideoSignatureRetry}\n />\n </CameraProvider>\n )\n\n case 'AdditionalDocumentCapture':\n return (\n <AdditionalDocumentCaptureWizard\n {...additionalDocumentCaptureProps}\n documents={documents}\n onComplete={onAdditionalDocumentCaptureComplete}\n />\n )\n\n default:\n return <></>\n }\n}\n","import React, { ReactNode, useEffect } from \"react\";\nimport { DefaultTheme, ThemeProvider as ScThemeProvider } from \"styled-components\";\nimport { Color } from \"./color\";\n\nexport interface Theme {\n isFullscreen?: boolean\n fontFamily?: string\n background?: string\n padding?: string\n textAlign?: string\n textColor?: string\n\n colors?: {\n primary?: Color\n secondary?: Color\n positive?: Color\n negative?: Color\n warning?: Color\n }\n\n buttons?: {\n style?: 'bootstrap' | 'none'\n primary?: {\n backgroundColor?: string\n textColor?: string\n }\n secondary?: {\n backgroundColor?: string\n textColor?: string\n }\n positive?: {\n backgroundColor?: string\n textColor?: string\n }\n negative?: {\n backgroundColor?: string\n textColor?: string\n }\n warning?: {\n backgroundColor?: string\n textColor?: string\n }\n loading?: {\n backgroundColor?: string\n textColor?: string\n }\n }\n\n guidanceMessages?: {\n default?: {\n backgroundColor?: string\n textColor?: string\n }\n positive?: {\n backgroundColor?: string\n textColor?: string\n }\n negative?: {\n backgroundColor?: string\n textColor?: string\n }\n }\n\n idCapture?: {\n guideOverlay?: {\n backgroundColor?: string\n textColor?: string\n }\n guideBox?: {\n unsatisfiedColor?: string\n satisfiedColor?: string\n borderWidth?: number\n }\n }\n\n selfieCapture?: {\n guides?: {\n unsatisfiedColor?: string\n satisfiedColor?: string\n }\n }\n\n signatureCapture?: {\n background?: string\n backgroundSize?: string\n backgroundPosition?: string\n\n canvas?: {\n background?: string\n border?: string\n borderRadius?: string\n }\n }\n}\n\nconst noneTheme = {} satisfies Theme;\nconst defaultTheme = {\n fontFamily: `Inter, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif`,\n isFullscreen: true,\n background: \"white\",\n textColor: \"black\",\n textAlign: \"center\",\n padding: \"25px\",\n\n colors: {\n primary: {\n \"50\": \"#eef8ff\",\n \"100\": \"#d8eeff\",\n \"200\": \"#b9e0ff\",\n \"300\": \"#89cfff\",\n \"400\": \"#52b4ff\",\n \"500\": \"#2a91ff\",\n \"600\": \"#0d6efd\", // default\n \"700\": \"#0c5ae9\",\n \"800\": \"#1149bc\",\n \"900\": \"#144194\",\n \"950\": \"#11295a\"\n },\n secondary: {\n \"50\": \"#f6f6f6\",\n \"100\": \"#e7e7e7\",\n \"200\": \"#d1d1d1\",\n \"300\": \"#b0b0b0\",\n \"400\": \"#888888\",\n \"500\": \"#666666\", // default\n \"600\": \"#5d5d5d\",\n \"700\": \"#4f4f4f\",\n \"800\": \"#454545\",\n \"900\": \"#3d3d3d\",\n \"950\": \"#262626\"\n },\n positive: {\n \"50\": \"#f1fcf9\",\n \"100\": \"#cef9eb\",\n \"200\": \"#9df2d8\",\n \"300\": \"#65e3c2\",\n \"400\": \"#35cca9\",\n \"500\": \"#1cb090\",\n \"600\": \"#16a085\", // default\n \"700\": \"#147160\",\n \"800\": \"#155a4f\",\n \"900\": \"#164b42\",\n \"950\": \"#062d28\"\n },\n negative: {\n \"50\": \"#fff1f2\",\n \"100\": \"#ffe4e6\",\n \"200\": \"#fecdd3\",\n \"300\": \"#fda4af\",\n \"400\": \"#fb7185\",\n \"500\": \"#f43f5e\", // default\n \"600\": \"#e11d48\",\n \"700\": \"#be123c\",\n \"800\": \"#9f1239\",\n \"900\": \"#881337\",\n \"950\": \"#4c0519\"\n },\n warning: {\n \"50\": \"#fdf5ef\",\n \"100\": \"#fbe7d9\",\n \"200\": \"#f6cdb2\",\n \"300\": \"#f0ab81\",\n \"400\": \"#ea8557\", // default\n \"500\": \"#e35e2c\",\n \"600\": \"#d54621\",\n \"700\": \"#b1341d\",\n \"800\": \"#8d2b1f\",\n \"900\": \"#72261c\",\n \"950\": \"#3d100d\"\n }\n },\n\n buttons: {\n style: 'bootstrap',\n\n primary: {\n backgroundColor: \"var(--idm-color-primary-600)\",\n textColor: \"white\"\n },\n secondary: {\n backgroundColor: \"var(--idm-color-secondary-500)\",\n textColor: \"white\"\n },\n positive: {\n backgroundColor: \"var(--idm-color-positive-600)\",\n textColor: \"white\"\n },\n negative: {\n backgroundColor: \"var(--idm-color-negative-400)\",\n textColor: \"white\"\n },\n warning: {\n backgroundColor: \"var(--idm-color-warning-400)\",\n textColor: \"white\"\n },\n loading: {\n backgroundColor: \"gray\",\n textColor: \"white\"\n }\n },\n\n guidanceMessages: {\n default: {\n backgroundColor: 'var(--idm-color-secondary-200)',\n textColor: 'black',\n },\n positive: {\n backgroundColor: 'var(--idm-color-positive-700)',\n textColor: 'white',\n },\n negative: {\n backgroundColor: 'var(--idm-color-negative-600)',\n textColor: 'white',\n },\n },\n\n idCapture: {\n guideOverlay: {\n backgroundColor: 'rgba(0,0,0,0.5)',\n textColor: 'white',\n },\n guideBox: {\n unsatisfiedColor: \"white\",\n satisfiedColor: \"var(--idm-color-positive-500)\",\n borderWidth: 4,\n },\n },\n\n selfieCapture: {\n guides: {\n unsatisfiedColor: \"white\",\n satisfiedColor: \"var(--idm-color-positive-500)\",\n }\n },\n\n signatureCapture: {\n background: 'radial-gradient(#444cf7 0.5px, transparent 0.5px), radial-gradient(#444cf7 0.5px, #e5e5f7 0.5px)',\n backgroundSize: '20px 20px',\n backgroundPosition: '0 0, 10px 10px',\n },\n} satisfies Theme;\n\nexport const themes = {\n default: defaultTheme,\n none: noneTheme\n};\n\nexport type ThemeInput = keyof typeof themes | Theme\n\nexport const resolveTheme = (input: ThemeInput): DefaultTheme => {\n if (typeof input === \"string\") {\n if (input in themes) return themes[input];\n return themes.none;\n }\n\n return input;\n};\n\nexport const ThemeProvider = ({\n children,\n theme: themeInput,\n}: {\n children: ReactNode\n theme: ThemeInput\n}) => {\n const theme = resolveTheme(themeInput);\n const colors = theme.colors;\n\n useEffect(() => {\n for (const name in colors) {\n const variants = colors[name as keyof typeof colors];\n for (const num in variants) {\n const color = variants[num as keyof typeof variants];\n document.documentElement.style.setProperty(`--idm-color-${name}-${num}`, color)\n }\n }\n }, [colors]);\n\n return <ScThemeProvider theme={theme}>{children}</ScThemeProvider>;\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport {\n SubmissionRequest,\n SubmissionResponse,\n} from '../../contexts/SubmissionContext'\nimport {\n SelfieCapture,\n SelfieCaptureClassNames,\n SelfieCaptureColors,\n SelfieCaptureVerbiage,\n} from '../selfie_capture/SelfieCapture'\nimport { Face } from '@tensorflow-models/face-detection'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { cropToShoulders } from '../../lib/utils/cropping'\nimport {\n SelfieProgressPreview,\n SelfieProgressPreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { InvisibleCanvas } from '../common/InvisibleCanvas'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\nimport { SubmissionContext } from '../submission/SubmissionProvider'\n\nconst ALLOWED_RETRIES = 0\n\ntype IdentificationState =\n | 'CAPTURING'\n | 'CAPTURED'\n | 'VERIFYING'\n | 'VERIFIED'\n | 'REJECTED'\n | 'ERROR'\n\ntype State = {\n frame: ImageData | null\n face: Face | null\n imageUrl: string | null\n requestState: IdentificationState\n requestError: Error | null\n unverifiedTimes: number\n}\n\nconst initialState: State = {\n frame: null,\n face: null,\n imageUrl: null,\n requestState: 'CAPTURING',\n requestError: null,\n unverifiedTimes: 0,\n}\n\ntype Action =\n | {\n type: 'verificationReady'\n payload: { frame: ImageData; face: Face }\n }\n | { type: 'verifying'; payload: { imageUrl: string } }\n | {\n type: 'verificationCompleted'\n payload: { response: SubmissionResponse }\n }\n | { type: 'verificationFailed'; payload: { error: Error } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'verificationReady': {\n const allowedStates = ['CAPTURING', 'ERROR']\n if (allowedStates.includes(state.requestState)) {\n return {\n ...state,\n requestState: 'CAPTURED',\n frame: action.payload.frame,\n face: action.payload.face,\n }\n } else {\n return state\n }\n }\n\n case 'verifying':\n return {\n ...state,\n requestState: 'VERIFYING',\n imageUrl: action.payload.imageUrl,\n }\n\n case 'verificationCompleted': {\n const {\n status: { statusCode, statusMessage, errorData },\n resultData,\n } = action.payload.response\n\n if (statusCode !== '000') {\n return {\n ...state,\n requestState: 'ERROR',\n requestError: new Error(`${statusMessage}: ${errorData}`),\n }\n }\n\n let { requestState, unverifiedTimes } = state\n const customerMatched = resultData.verificationResultCode === '00'\n if (customerMatched) {\n requestState = 'VERIFIED'\n } else {\n if (unverifiedTimes < ALLOWED_RETRIES) {\n requestState = 'CAPTURING'\n unverifiedTimes += 1\n } else {\n requestState = 'REJECTED'\n }\n }\n\n return { ...state, requestState, unverifiedTimes }\n }\n\n case 'verificationFailed':\n return {\n ...state,\n requestState: 'ERROR',\n requestError: action.payload.error,\n }\n\n default:\n return state\n }\n}\n\nexport type CustomerVerificationCaptureClassNames = SelfieCaptureClassNames & {\n imagePreview?: SelfieProgressPreviewClassNames\n}\n\nexport type CustomerVerificationCaptureColors = SelfieCaptureColors\n\nexport type CustomerVerificationCaptureVerbiage = SelfieCaptureVerbiage & {\n progressPreviewText?: CustomerSuppliedVerbiage\n}\n\nexport type CustomerVerificationCaptureProps = {\n onCustomerMatched?: (resp: SubmissionResponse, req: SubmissionRequest) => void\n onCustomerNotMatched?: (\n resp: SubmissionResponse,\n req: SubmissionRequest\n ) => void\n onCaptureGuidanceTimeout?: () => void\n onExit?: () => void\n captureGuidanceTimeoutDurationMs?: number\n classNames?: CustomerVerificationCaptureClassNames\n colors?: CustomerVerificationCaptureColors\n verbiage?: CustomerVerificationCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const CustomerVerificationCapture = ({\n onCustomerMatched,\n onCustomerNotMatched,\n onCaptureGuidanceTimeout,\n onExit,\n captureGuidanceTimeoutDurationMs,\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: CustomerVerificationCaptureProps): ReactElement => {\n const [state, dispatch] = useReducer(reducer, initialState)\n const { frame, face } = state\n const {\n submit,\n submissionRequest,\n submissionResponse,\n submissionError,\n selfieImage,\n setSelfieImage,\n } = useContext(SubmissionContext)\n const [imageUrl, setImageUrl] = useState<string | null>(null)\n const rawCanvas = useRef<HTMLCanvasElement | null>(null)\n const cropCanvas = useRef<HTMLCanvasElement | null>(null)\n\n const onSelfieCaptured = useCallback((frame: ImageData, face: Face) => {\n dispatch({ type: 'verificationReady', payload: { frame, face } })\n }, [])\n\n const isReady = state.requestState === 'CAPTURED'\n useEffect(() => {\n if (!frame || !face || submissionError) return\n\n const imageUrl = cropToShoulders(\n rawCanvas.current,\n cropCanvas.current,\n frame,\n face\n )\n setImageUrl(imageUrl)\n\n dataUrlToBase64(imageUrl).then((img) => {\n setSelfieImage(img)\n })\n }, [face, frame, setSelfieImage, submissionError])\n\n useEffect(() => {\n if (!isReady || !selfieImage || submissionError) return\n ;(async () => {\n try {\n dispatch({ type: 'verifying', payload: { imageUrl: selfieImage } })\n const submissionResponse = await submit()\n if (!submissionResponse) throw new Error('submission failed!')\n\n dispatch({\n type: 'verificationCompleted',\n payload: { response: submissionResponse },\n })\n } catch (e) {\n dispatch({\n type: 'verificationFailed',\n payload: { error: e as Error },\n })\n }\n })()\n }, [\n isReady,\n onCustomerMatched,\n onCustomerNotMatched,\n selfieImage,\n state.requestState,\n submissionError,\n submit,\n ])\n\n useEffect(() => {\n if (!submissionRequest || !submissionResponse) return\n if (state.requestState === 'VERIFIED') {\n onCustomerMatched?.(submissionResponse, submissionRequest)\n } else if (state.requestState === 'REJECTED') {\n onCustomerNotMatched?.(submissionResponse, submissionRequest)\n }\n }, [\n onCustomerMatched,\n onCustomerNotMatched,\n state.requestState,\n submissionRequest,\n submissionResponse,\n ])\n\n useTimeout(\n captureGuidanceTimeoutDurationMs,\n onCaptureGuidanceTimeout,\n ['VERIFIED', 'REJECTED'].includes(state.requestState),\n state.requestState === 'VERIFYING'\n )\n\n const progressPreviewText = useVerbiage(\n verbiage.progressPreviewText,\n 'Processing...'\n )\n\n return (\n <>\n <InvisibleCanvas ref={rawCanvas} />\n <InvisibleCanvas ref={cropCanvas} />\n\n <SelfieCapture\n onSelfieCaptured={onSelfieCaptured}\n onExit={onExit}\n timeoutDurationMs={captureGuidanceTimeoutDurationMs}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n\n {imageUrl && (\n <SelfieProgressPreview\n imageUrl={imageUrl}\n text={progressPreviewText}\n classNames={classNames.imagePreview}\n />\n )}\n </>\n )\n}\n","import React, {\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react'\nimport {\n SelfieCapture,\n SelfieCaptureClassNames,\n SelfieCaptureColors,\n SelfieCaptureVerbiage,\n} from '../selfie_capture/SelfieCapture'\nimport { Face } from '@tensorflow-models/face-detection'\nimport {\n SubmissionRequest,\n SubmissionResponse,\n} from '../../contexts/SubmissionContext'\nimport { dataUrlToBase64 } from '../../lib/utils/dataUrlToBase64'\nimport { cropToShoulders } from '../../lib/utils/cropping'\nimport {\n SelfieProgressPreview,\n SelfieProgressPreviewClassNames,\n} from '../common/SelfieProgressPreview'\nimport { useTimeout } from '../../lib/utils/useTimeout'\nimport { InvisibleCanvas } from '../common/InvisibleCanvas'\nimport { CustomerSuppliedVerbiage, useVerbiage } from '../../lib/locales'\nimport { SubmissionContext } from '../submission/SubmissionProvider'\n\nconst ALLOWED_RETRIES = 0\n\ntype IdentificationState =\n | 'CAPTURING'\n | 'CAPTURED'\n | 'IDENTIFYING'\n | 'FOUND'\n | 'NOT_FOUND'\n | 'ERROR'\n\ntype State = {\n frame: ImageData | null\n face: Face | null\n imageUrl: string | null\n requestState: IdentificationState\n requestError: Error | null\n notFoundTimes: number\n}\n\nconst initialState: State = {\n frame: null,\n face: null,\n imageUrl: null,\n requestState: 'CAPTURING',\n requestError: null,\n notFoundTimes: 0,\n}\n\ntype Action =\n | {\n type: 'identificationReady'\n payload: { frame: ImageData; face: Face }\n }\n | { type: 'identifying'; payload: { imageUrl: string } }\n | {\n type: 'identificationCompleted'\n payload: { response: SubmissionResponse }\n }\n | { type: 'identificationFailed'; payload: { error: Error } }\n\nconst reducer = (state: State, action: Action): State => {\n switch (action.type) {\n case 'identificationReady': {\n const allowedStates = ['CAPTURING', 'ERROR']\n if (allowedStates.includes(state.requestState)) {\n return {\n ...state,\n requestState: 'CAPTURED',\n frame: action.payload.frame,\n face: action.payload.face,\n }\n } else {\n return state\n }\n }\n\n case 'identifying':\n return {\n ...state,\n requestState: 'IDENTIFYING',\n imageUrl: action.payload.imageUrl,\n }\n\n case 'identificationCompleted': {\n const {\n status: { statusCode, statusMessage, errorData },\n resultData,\n } = action.payload.response\n\n if (statusCode !== '000') {\n return {\n ...state,\n requestState: 'ERROR',\n requestError: new Error(`${statusMessage}: ${errorData}`),\n }\n }\n\n let { requestState, notFoundTimes } = state\n const customerMatched = resultData.verificationResultCode === '46'\n if (customerMatched) {\n requestState = 'FOUND'\n } else if (notFoundTimes < ALLOWED_RETRIES) {\n requestState = 'CAPTURING'\n notFoundTimes += 1\n } else {\n requestState = 'NOT_FOUND'\n }\n\n return { ...state, requestState, notFoundTimes }\n }\n\n case 'identificationFailed':\n return {\n ...state,\n requestState: 'ERROR',\n requestError: action.payload.error,\n }\n\n default:\n return state\n }\n}\n\nexport type CustomerIdentificationCaptureClassNames =\n SelfieCaptureClassNames & {\n imagePreview?: SelfieProgressPreviewClassNames\n }\n\nexport type CustomerIdentificationCaptureColors = SelfieCaptureColors\n\nexport type CustomerIdentificationCaptureVerbiage = SelfieCaptureVerbiage & {\n progressPreviewText?: CustomerSuppliedVerbiage\n}\n\nexport type CustomerIdentificationCaptureProps = {\n onCustomerMatched?: (resp: SubmissionResponse, req: SubmissionRequest) => void\n onCustomerNotMatched?: (\n resp: SubmissionResponse,\n req: SubmissionRequest\n ) => void\n onCaptureGuidanceTimeout?: () => void\n onExit?: () => void\n captureGuidanceTimeoutDurationMs?: number\n classNames?: CustomerIdentificationCaptureClassNames\n colors?: CustomerIdentificationCaptureColors\n verbiage?: CustomerIdentificationCaptureVerbiage\n debugMode?: boolean\n}\n\nexport const CustomerIdentificationCapture = ({\n onCustomerMatched,\n onCustomerNotMatched,\n onCaptureGuidanceTimeout,\n onExit,\n captureGuidanceTimeoutDurationMs,\n classNames = {},\n colors = {},\n verbiage = {},\n debugMode = false,\n}: CustomerIdentificationCaptureProps): ReactElement => {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {\n submit,\n submissionRequest,\n submissionResponse,\n submissionError,\n selfieImage,\n setSelfieImage,\n } = useContext(SubmissionContext)\n const [imageUrl, setImageUrl] = useState<string | null>(null)\n const rawCanvas = useRef<HTMLCanvasElement | null>(null)\n const cropCanvas = useRef<HTMLCanvasElement | null>(null)\n\n const onSelfieCaptured = useCallback((frame: ImageData, face: Face) => {\n dispatch({ type: 'identificationReady', payload: { frame, face } })\n }, [])\n\n const { frame, face } = state\n const isReady = state.requestState === 'CAPTURED'\n useEffect(() => {\n if (!frame || !face || submissionError) return\n\n const imageUrl = cropToShoulders(\n rawCanvas.current,\n cropCanvas.current,\n frame,\n face\n )\n setImageUrl(imageUrl)\n\n dataUrlToBase64(imageUrl).then((img) => {\n setSelfieImage(img)\n })\n }, [face, frame, setSelfieImage, submissionError])\n\n useEffect(() => {\n if (!isReady || !selfieImage || submissionError) return\n ;(async () => {\n try {\n dispatch({ type: 'identifying', payload: { imageUrl: selfieImage } })\n const submissionResponse = await submit()\n if (!submissionResponse) throw new Error('submission failed!')\n\n dispatch({\n type: 'identificationCompleted',\n payload: { response: submissionResponse },\n })\n } catch (e) {\n dispatch({\n type: 'identificationFailed',\n payload: { error: e as Error },\n })\n }\n })()\n }, [\n isReady,\n onCustomerMatched,\n onCustomerNotMatched,\n selfieImage,\n state.requestState,\n submissionError,\n submit,\n ])\n\n useEffect(() => {\n if (!submissionRequest || !submissionResponse) return\n if (state.requestState === 'FOUND') {\n onCustomerMatched?.(submissionResponse, submissionRequest)\n } else if (state.requestState === 'NOT_FOUND') {\n onCustomerNotMatched?.(submissionResponse, submissionRequest)\n }\n }, [\n onCustomerMatched,\n onCustomerNotMatched,\n state.requestState,\n submissionRequest,\n submissionResponse,\n ])\n\n useTimeout(\n captureGuidanceTimeoutDurationMs,\n onCaptureGuidanceTimeout,\n ['FOUND', 'NOT_FOUND'].includes(state.requestState),\n state.requestState === 'IDENTIFYING'\n )\n\n const progressPreviewText = useVerbiage(\n verbiage.progressPreviewText,\n 'Processing...'\n )\n\n return (\n <>\n <InvisibleCanvas ref={rawCanvas} />\n <InvisibleCanvas ref={cropCanvas} />\n\n <SelfieCapture\n onSelfieCaptured={onSelfieCaptured}\n onExit={onExit}\n timeoutDurationMs={captureGuidanceTimeoutDurationMs}\n classNames={classNames}\n colors={colors}\n verbiage={verbiage}\n debugMode={debugMode}\n />\n\n {imageUrl && (\n <SelfieProgressPreview\n text={progressPreviewText}\n imageUrl={imageUrl}\n classNames={classNames.imagePreview}\n />\n )}\n </>\n )\n}\n","import { loadDocumentDetectionModel } from './DocumentDetection'\nimport { loadFocusModel } from './Focus'\nimport { DEFAULT_CDN_URL } from '../../components/common/cdn'\nimport { loadHighPerformanceFaceDetector } from '../../components/selfie_capture/HighPerformanceSelfieGuidanceModelsProvider'\n\nexport const preloadModels = async ({\n documentDetectionModel = true,\n focusModel = true,\n faceDetectionModel = true,\n}: {\n documentDetectionModel?: string | boolean\n focusModel?: string | boolean\n faceDetectionModel?: boolean\n}): Promise<void> => {\n if (documentDetectionModel) {\n if (documentDetectionModel === true)\n documentDetectionModel = `${DEFAULT_CDN_URL}/models/documentdetection448/model.json`\n await loadDocumentDetectionModel(documentDetectionModel)\n }\n\n if (focusModel) {\n if (focusModel === true)\n focusModel = `${DEFAULT_CDN_URL}/models/focus/model.json`\n await loadFocusModel(focusModel)\n }\n\n if (faceDetectionModel) {\n await loadHighPerformanceFaceDetector()\n }\n}\n","import React, { FC, PropsWithChildren, ReactNode } from 'react'\nimport * as ReactDOM from 'react-dom/client'\nimport {\n IdValidation,\n IdValidationProps,\n} from './components/customer_flows/IdValidation'\nimport {\n FaceValidation,\n FaceValidationProps,\n} from './components/customer_flows/FaceValidation'\nimport {\n IdAndFaceValidation,\n IdAndFaceValidationProps,\n} from './components/customer_flows/IdAndFaceValidation'\nimport {\n CustomerEnrollmentProps,\n CustomerIdAndBiometricsEnrollment,\n} from './components/customer_flows/CustomerIdAndBiometricsEnrollment'\nimport {\n CustomerVerification,\n CustomerVerificationProps,\n} from './components/customer_flows/CustomerVerification'\nimport {\n CustomerIdentification,\n CustomerIdentificationProps,\n} from './components/customer_flows/CustomerIdentification'\nimport {\n SignatureKYC,\n SignatureKYCProps,\n} from './components/customer_flows/SignatureKYC'\nimport {\n VideoIdValidation,\n VideoIdValidationProps,\n} from './components/customer_flows/VideoIdValidation'\nimport { preloadModels } from './lib/models/preloadModels'\nimport { initializeI18n } from './lib/locales'\nimport { CustomerBiometricsEnrollment } from './components/customer_flows/CustomerBiometricsEnrollment'\nimport { OverlayContainer } from './components/common/overlay'\nimport { webSdkVersion } from './version'\nimport { themes } from './themes'\n\ninitializeI18n()\n\ntype TargetElement = Element | DocumentFragment | string | undefined\n\nfunction renderElement(\n component: ReactNode,\n targetElement?: TargetElement\n): Element | DocumentFragment {\n if (typeof targetElement === 'string') {\n const result = document.querySelector(targetElement)\n if (!result) throw new Error(`targetElement ${targetElement} not found`)\n targetElement = result\n } else if (!targetElement) {\n targetElement = document.createElement('div')\n document.body.append(targetElement)\n }\n\n const root = ReactDOM.createRoot(targetElement)\n root.render(<OverlayContainer>{component}</OverlayContainer>)\n\n if ('remove' in targetElement) {\n const originalRemove = targetElement.remove\n targetElement.remove = () => {\n try {\n root.unmount()\n originalRemove()\n } catch (e) {}\n }\n }\n\n return targetElement\n}\n\nfunction renderComponent<T extends PropsWithChildren>(\n Component: FC<T>,\n targetElement: TargetElement | T,\n options?: T\n): Element | DocumentFragment {\n if (!options) {\n options = targetElement as T\n targetElement = undefined\n }\n\n return renderElement(\n <Component {...options} />,\n targetElement as TargetElement\n )\n}\n\nexport const renderIdValidation = (\n optionsOrTargetElement: TargetElement | IdValidationProps,\n options?: IdValidationProps\n) => renderComponent(IdValidation, optionsOrTargetElement, options)\n\nexport const renderFaceValidation = (\n optionsOrTargetElement: TargetElement | FaceValidationProps,\n options?: FaceValidationProps\n) => renderComponent(FaceValidation, optionsOrTargetElement, options)\n\nexport const renderIdAndFaceValidation = (\n optionsOrTargetElement: TargetElement | IdAndFaceValidationProps,\n options?: IdAndFaceValidationProps\n) => renderComponent(IdAndFaceValidation, optionsOrTargetElement, options)\n\nexport const renderCustomerIdAndBiometricsEnrollment = (\n optionsOrTargetElement: TargetElement | CustomerEnrollmentProps,\n options?: CustomerEnrollmentProps\n) =>\n renderComponent(\n CustomerIdAndBiometricsEnrollment,\n optionsOrTargetElement,\n options\n )\n\nexport const renderCustomerBiometricsEnrollment = (\n optionsOrTargetElement: TargetElement | CustomerEnrollmentProps,\n options?: CustomerEnrollmentProps\n) =>\n renderComponent(CustomerBiometricsEnrollment, optionsOrTargetElement, options)\n\nexport const renderCustomerVerification = (\n optionsOrTargetElement: TargetElement | CustomerVerificationProps,\n options?: CustomerVerificationProps\n) => renderComponent(CustomerVerification, optionsOrTargetElement, options)\n\nexport const renderCustomerIdentification = (\n optionsOrTargetElement: TargetElement | CustomerIdentificationProps,\n options?: CustomerIdentificationProps\n) => renderComponent(CustomerIdentification, optionsOrTargetElement, options)\n\nexport const renderSignatureKYC = (\n optionsOrTargetElement: TargetElement | SignatureKYCProps,\n options?: SignatureKYCProps\n) => renderComponent(SignatureKYC, optionsOrTargetElement, options)\n\nexport const renderVideoIdValidation = (\n optionsOrTargetElement: TargetElement | VideoIdValidationProps,\n options?: VideoIdValidationProps\n) => renderComponent(VideoIdValidation, optionsOrTargetElement, options)\n\nexport type IDmissionSDK = {\n renderIdValidation: typeof renderIdValidation\n renderFaceValidation: typeof renderFaceValidation\n renderIdAndFaceValidation: typeof renderIdAndFaceValidation\n renderCustomerIdAndBiometricsEnrollment: typeof renderCustomerIdAndBiometricsEnrollment\n renderCustomerBiometricsEnrollment: typeof renderCustomerBiometricsEnrollment\n renderCustomerVerification: typeof renderCustomerVerification\n renderCustomerIdentification: typeof renderCustomerIdentification\n renderSignatureKYC: typeof renderSignatureKYC\n renderVideoIdValidation: typeof renderVideoIdValidation\n\n preloadModels: typeof preloadModels\n themes: typeof themes\n version: string\n ready: boolean\n}\n\ndeclare global {\n // eslint-disable-next-line no-var\n var IDmissionSDK: IDmissionSDK\n}\n\nglobalThis.IDmissionSDK = {\n renderIdValidation,\n renderFaceValidation,\n renderIdAndFaceValidation,\n renderCustomerIdAndBiometricsEnrollment,\n renderCustomerBiometricsEnrollment,\n renderCustomerVerification,\n renderCustomerIdentification,\n renderSignatureKYC,\n renderVideoIdValidation,\n preloadModels,\n themes,\n version: webSdkVersion,\n ready: true,\n}\n\nexport {\n preloadModels,\n themes,\n IdValidation,\n FaceValidation,\n IdAndFaceValidation,\n CustomerIdAndBiometricsEnrollment,\n CustomerBiometricsEnrollment,\n CustomerVerification,\n CustomerIdentification,\n SignatureKYC,\n VideoIdValidation,\n}\n"],"names":["React","useState","useCallback","styled","useRef","ENV","base.checkConversionForErrors","base.isPromise","util.now","util.rightPad","util.arraysEqual","util.sizeFromShape","util.assert","util.getArrayFromDType","opHandler","util.decodeString","log.warn","util.isString","util.encodeString","util.bytesPerElement","util.makeZerosTypedArray","add","util.isFunction","device_util.isBrowser","util.isTypedArray","maybeStripScheme","util.assertNonNegativeIntegerDimensions","util.isValidDtype","__awaiter","templateObject_1","__makeTemplateObject","__assign","useContext","useMemo"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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