File size: 1,877 Bytes
bce29b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { ZeroShotImageClassificationInput, ZeroShotImageClassificationOutput } from "@huggingface/tasks";
import { resolveProvider } from "../../lib/getInferenceProviderMapping.js";
import { getProviderHelper } from "../../lib/getProviderHelper.js";
import type { BaseArgs, Options, RequestArgs } from "../../types.js";
import { base64FromBytes } from "../../utils/base64FromBytes.js";
import { innerRequest } from "../../utils/request.js";

/**
 * @deprecated
 */
interface LegacyZeroShotImageClassificationInput {
	inputs: { image: Blob | ArrayBuffer };
}

export type ZeroShotImageClassificationArgs = BaseArgs &
	(ZeroShotImageClassificationInput | LegacyZeroShotImageClassificationInput);

async function preparePayload(args: ZeroShotImageClassificationArgs): Promise<RequestArgs> {
	if (args.inputs instanceof Blob) {
		return {
			...args,
			inputs: {
				image: base64FromBytes(new Uint8Array(await args.inputs.arrayBuffer())),
			},
		};
	} else {
		return {
			...args,
			inputs: {
				image: base64FromBytes(
					new Uint8Array(
						args.inputs.image instanceof ArrayBuffer ? args.inputs.image : await args.inputs.image.arrayBuffer()
					)
				),
			},
		};
	}
}

/**
 * Classify an image to specified classes.
 * Recommended model: openai/clip-vit-large-patch14-336
 */
export async function zeroShotImageClassification(
	args: ZeroShotImageClassificationArgs,
	options?: Options
): Promise<ZeroShotImageClassificationOutput> {
	const provider = await resolveProvider(args.provider, args.model, args.endpointUrl);
	const providerHelper = getProviderHelper(provider, "zero-shot-image-classification");
	const payload = await preparePayload(args);
	const { data: res } = await innerRequest<ZeroShotImageClassificationOutput>(payload, providerHelper, {
		...options,
		task: "zero-shot-image-classification",
	});
	return providerHelper.getResponse(res);
}