import {z} from 'zod' export type KerasModelVariantEnum = 'int8' | 'float32' | 'akida'; export type CreateApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleIdArgs = {projectId: number, sampleId: number, blockId: number, variant?: KerasModelVariantEnum | undefined, truncateStructuredLabels?: boolean | undefined}; export type CreateApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleIdOptions = {baseUrl?: string | undefined, ApiKeyAuthentication?: string | undefined, fetch?: typeof fetch | undefined}; export const learnBlockType = z.enum(["anomaly", "anomaly-gmm", "keras", "keras-transfer-image", "keras-transfer-kws", "keras-object-detection", "keras-regression", "keras-akida", "keras-akida-transfer-image", "keras-akida-object-detection", "keras-visual-anomaly", "keras-freeform", "keras-self-contained-freeform", "keras-anomaly", "vlm"]); export const impulseSpecificGpuTrainingProcessor = z.enum(["cpu", "gpu"]); export const impulseLearnBlock = z.object({id: z.number().int().gte(1), type: learnBlockType, name: z.string(), dsp: z.array(z.number().int()), title: z.string(), createdBy: z.string().optional(), createdAt: z.string().optional(), trainingProcessor: impulseSpecificGpuTrainingProcessor.optional()}); export const boundingBoxWithScore = z.object({label: z.string(), x: z.number(), y: z.number(), width: z.number(), height: z.number(), score: z.number()}); export const anomalyResult = z.object({boxes: z.array(boundingBoxWithScore).optional(), scores: z.array(z.array(z.number())).optional(), meanScore: z.number().optional(), maxScore: z.number().optional()}); export const structuredClassifyResult = z.object({boxes: z.array(z.array(z.number())), labels: z.array(z.string()).optional(), scores: z.array(z.number()), mAP: z.number(), f1: z.number(), precision: z.number(), recall: z.number(), debugInfoJson: z.string().optional()}); export const classifySampleResponseClassificationDetails = z.object({boxes: z.array(z.array(z.number())).optional(), labels: z.array(z.number()).optional(), scores: z.array(z.number()).optional(), mAP: z.number().optional(), f1: z.number().optional()}); export const objectDetectionLastLayer = z.enum(["mobilenet-ssd", "fomo", "yolov2-akida", "yolov5", "yolov5v5-drpai", "yolox", "yolov7", "yolo-pro", "tao-retinanet", "tao-ssd", "tao-yolov3", "tao-yolov4", "yolov11", "yolov11-abs", "paddleocr-detector", "qc-face-det-lite", "qc-yolox"]); export const sampleLabelMapLabels = z.object({type: z.literal("key-values"), labels: z.record(z.string(), z.string())}); export const structuredLabel = z.object({startIndex: z.number().int(), endIndex: z.number().int(), label: z.string(), labelMap: sampleLabelMapLabels.optional()}); export const blockThreshold = z.object({key: z.string(), description: z.string(), helpText: z.string(), suggestedValue: z.number().optional(), suggestedValueText: z.string().optional(), value: z.union([z.number(), z.string()]), dropdownOptions: z.array(z.object({description: z.string(), value: z.string()})).optional()}); export const classifySampleResponseClassification = z.object({learnBlock: impulseLearnBlock, result: z.array(z.record(z.string(), z.number())), anomalyResult: z.array(anomalyResult).optional(), structuredResult: z.array(structuredClassifyResult).optional(), minimumConfidenceRating: z.number(), details: z.array(classifySampleResponseClassificationDetails).optional(), objectDetectionLastLayer: objectDetectionLastLayer.optional(), expectedLabels: z.array(structuredLabel), expectedAnomalyOutcome: z.array(structuredLabel).optional(), thresholds: z.array(blockThreshold), isMultiLabel: z.boolean().optional(), intervalMs: z.number(), frequencyHz: z.number(), labelMapResult: z.array(z.record(z.string(), z.string())).optional(), labelMapScores: z.array(z.record(z.string(), z.record(z.string(), z.number()))).optional(), resultCount: z.number().int()}); export const rawDataCategory = z.enum(["training", "testing", "validation", "post-processing"]); export const sensor = z.object({index: z.number().int(), name: z.string(), units: z.string()}); export const boundingBox = z.object({label: z.string(), x: z.number().int(), y: z.number().int(), width: z.number().int(), height: z.number().int()}); export const projectLabelingMethod = z.enum(["single_label", "object_detection", "label_map"]); export const lastUpdatedByUser = z.object({type: z.literal("user"), id: z.number().int()}); export const lastUpdatedByProjectApiKey = z.object({type: z.literal("projectApiKey"), id: z.number().int()}); export const lastUpdatedByOAuthClient = z.object({type: z.literal("oauthClient"), oauthClientId: z.string(), userId: z.number().int().optional()}); export const lastUpdatedByDatasetVersionRestore = z.object({type: z.literal("datasetVersionRestore"), datasetVersionId: z.number().int(), groupKey: z.string(), actor: z.union([z.object({type: z.literal("user"), id: z.number().int()}), z.object({type: z.literal("projectApiKey"), id: z.number().int()}), z.object({type: z.literal("oauthClient"), oauthClientId: z.string(), userId: z.number().int().optional()})]).optional()}); export const sampleDatastream = z.object({index: z.number().int(), chartType: z.enum(["chart", "image", "video", "table"]), intervalMs: z.number(), frequencyHz: z.number(), sensors: z.array(sensor), valuesCount: z.number().int(), imageDimensions: z.object({width: z.number().int(), height: z.number().int()}).optional(), totalLengthMs: z.number()}); export const sample = z.object({id: z.number().int(), filename: z.string(), signatureValidate: z.boolean(), signatureMethod: z.string().optional(), signatureKey: z.string().optional(), created: z.string(), lastModified: z.string(), category: rawDataCategory, coldstorageFilename: z.string(), label: z.string(), intervalMs: z.number(), frequency: z.number(), originalIntervalMs: z.number(), originalFrequency: z.number(), deviceName: z.string().optional(), deviceType: z.string(), sensors: z.array(sensor), valuesCount: z.number().int(), totalLengthMs: z.number().optional(), added: z.string(), boundingBoxes: z.array(boundingBox), boundingBoxesType: z.enum(["object_detection", "constrained_object_detection"]), chartType: z.enum(["chart", "image", "video", "table"]), thumbnailVideo: z.string().optional(), thumbnailVideoFull: z.string().optional(), isDisabled: z.boolean(), isProcessing: z.boolean(), processingJobId: z.number().int().optional(), processingError: z.boolean(), processingErrorString: z.string().optional(), isCropped: z.boolean(), metadata: z.record(z.string(), z.string()).optional(), projectId: z.number().int(), projectOwnerName: z.string().optional(), projectName: z.string().optional(), projectLabelingMethod: projectLabelingMethod.optional(), sha256Hash: z.string(), structuredLabels: z.array(structuredLabel).optional(), structuredLabelsList: z.array(z.string()).optional(), createdBySyntheticDataJobId: z.number().int().optional(), imageDimensions: z.object({width: z.number().int(), height: z.number().int()}).optional(), videoUrl: z.string().optional(), videoUrlFull: z.string().optional(), labelMap: sampleLabelMapLabels.optional(), lastUpdatedBy: z.discriminatedUnion("type", [lastUpdatedByUser, lastUpdatedByProjectApiKey, lastUpdatedByOAuthClient, lastUpdatedByDatasetVersionRestore]).optional(), datastreams: z.array(sampleDatastream)}); export const rawSamplePayload = z.object({device_name: z.string().optional(), device_type: z.string(), sensors: z.array(sensor), values: z.array(z.array(z.number())), cropStart: z.number().int().optional(), cropEnd: z.number().int().optional(), intervalMs: z.number(), frequencyHz: z.number()}); export const rawSampleDataWithDataStreamPayloads = z.object({sample: sample, payload: rawSamplePayload, totalPayloadLength: z.number().int(), datastreamPayloads: z.array(z.object({index: z.number().int(), payload: rawSamplePayload, totalPayloadLength: z.number().int()}))}); export const classifySampleResponse = z.object({success: z.boolean(), error: z.string().optional(), classifications: z.array(classifySampleResponseClassification), sample: rawSampleDataWithDataStreamPayloads, windowSizeMs: z.number().int(), windowIncreaseMs: z.number().int(), alreadyInDatabase: z.boolean(), warning: z.string().optional()}); export const startJobResponse = z.object({success: z.boolean(), error: z.string().optional(), id: z.number().int()}); export const createApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleIdResponse = z.union([classifySampleResponse, startJobResponse]); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Classify sample by learn block * * POST /api/{projectId}/classify/anomaly-gmm/v2/{blockId}/{sampleId} * * Also accepts auth: JWTAuthentication, JWTHttpHeaderAuthentication, OAuth2 */ export const createApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleId = async (args: CreateApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleIdArgs, options?: CreateApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleIdOptions) => { const {baseUrl = "https://studio.edgeimpulse.com/v1", fetch: fetchFn = fetch, ApiKeyAuthentication} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.variant != null) query.append("variant", String(args.variant)) if (args.truncateStructuredLabels != null) query.append("truncateStructuredLabels", String(args.truncateStructuredLabels)) if (ApiKeyAuthentication !== undefined) headers.set("x-api-key", ApiKeyAuthentication) const url = `${baseUrl.replace(/\/+$/, '')}/api/${encodeURIComponent(String(args.projectId))}/classify/anomaly-gmm/v2/${encodeURIComponent(String(args.blockId))}/${encodeURIComponent(String(args.sampleId))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiApiProjectIdClassifyAnomalyGmmV2BlockIdSampleIdResponse, await res.json()) };