@huggingface/tasks 0.16.7 → 0.17.0

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.
Files changed (36) hide show
  1. package/dist/commonjs/index.d.ts +1 -3
  2. package/dist/commonjs/index.d.ts.map +1 -1
  3. package/dist/commonjs/index.js +5 -15
  4. package/dist/commonjs/snippets/index.d.ts +2 -5
  5. package/dist/commonjs/snippets/index.d.ts.map +1 -1
  6. package/dist/commonjs/snippets/index.js +2 -21
  7. package/dist/esm/index.d.ts +1 -3
  8. package/dist/esm/index.d.ts.map +1 -1
  9. package/dist/esm/index.js +1 -2
  10. package/dist/esm/snippets/index.d.ts +2 -5
  11. package/dist/esm/snippets/index.d.ts.map +1 -1
  12. package/dist/esm/snippets/index.js +2 -5
  13. package/package.json +1 -1
  14. package/src/index.ts +7 -3
  15. package/src/snippets/index.ts +2 -6
  16. package/dist/commonjs/snippets/curl.d.ts +0 -17
  17. package/dist/commonjs/snippets/curl.d.ts.map +0 -1
  18. package/dist/commonjs/snippets/curl.js +0 -129
  19. package/dist/commonjs/snippets/js.d.ts +0 -21
  20. package/dist/commonjs/snippets/js.d.ts.map +0 -1
  21. package/dist/commonjs/snippets/js.js +0 -413
  22. package/dist/commonjs/snippets/python.d.ts +0 -23
  23. package/dist/commonjs/snippets/python.d.ts.map +0 -1
  24. package/dist/commonjs/snippets/python.js +0 -435
  25. package/dist/esm/snippets/curl.d.ts +0 -17
  26. package/dist/esm/snippets/curl.d.ts.map +0 -1
  27. package/dist/esm/snippets/curl.js +0 -121
  28. package/dist/esm/snippets/js.d.ts +0 -21
  29. package/dist/esm/snippets/js.d.ts.map +0 -1
  30. package/dist/esm/snippets/js.js +0 -401
  31. package/dist/esm/snippets/python.d.ts +0 -23
  32. package/dist/esm/snippets/python.d.ts.map +0 -1
  33. package/dist/esm/snippets/python.js +0 -421
  34. package/src/snippets/curl.ts +0 -173
  35. package/src/snippets/js.ts +0 -471
  36. package/src/snippets/python.ts +0 -483
@@ -1,421 +0,0 @@
1
- import { openAIbaseUrl } from "../inference-providers.js";
2
- import { stringifyGenerationConfig, stringifyMessages } from "./common.js";
3
- import { getModelInputSnippet } from "./inputs.js";
4
- const HFH_INFERENCE_CLIENT_METHODS = {
5
- "audio-classification": "audio_classification",
6
- "audio-to-audio": "audio_to_audio",
7
- "automatic-speech-recognition": "automatic_speech_recognition",
8
- "text-to-speech": "text_to_speech",
9
- "image-classification": "image_classification",
10
- "image-segmentation": "image_segmentation",
11
- "image-to-image": "image_to_image",
12
- "image-to-text": "image_to_text",
13
- "object-detection": "object_detection",
14
- "text-to-image": "text_to_image",
15
- "text-to-video": "text_to_video",
16
- "zero-shot-image-classification": "zero_shot_image_classification",
17
- "document-question-answering": "document_question_answering",
18
- "visual-question-answering": "visual_question_answering",
19
- "feature-extraction": "feature_extraction",
20
- "fill-mask": "fill_mask",
21
- "question-answering": "question_answering",
22
- "sentence-similarity": "sentence_similarity",
23
- summarization: "summarization",
24
- "table-question-answering": "table_question_answering",
25
- "text-classification": "text_classification",
26
- "text-generation": "text_generation",
27
- "token-classification": "token_classification",
28
- translation: "translation",
29
- "zero-shot-classification": "zero_shot_classification",
30
- "tabular-classification": "tabular_classification",
31
- "tabular-regression": "tabular_regression",
32
- };
33
- const snippetImportInferenceClient = (accessToken, provider) => `\
34
- from huggingface_hub import InferenceClient
35
-
36
- client = InferenceClient(
37
- provider="${provider}",
38
- api_key="${accessToken || "{API_TOKEN}"}"
39
- )`;
40
- export const snippetConversational = (model, accessToken, provider, providerModelId, opts) => {
41
- const streaming = opts?.streaming ?? true;
42
- const exampleMessages = getModelInputSnippet(model);
43
- const messages = opts?.messages ?? exampleMessages;
44
- const messagesStr = stringifyMessages(messages, { attributeKeyQuotes: true });
45
- const config = {
46
- ...(opts?.temperature ? { temperature: opts.temperature } : undefined),
47
- max_tokens: opts?.max_tokens ?? 500,
48
- ...(opts?.top_p ? { top_p: opts.top_p } : undefined),
49
- };
50
- const configStr = stringifyGenerationConfig(config, {
51
- indent: "\n\t",
52
- attributeValueConnector: "=",
53
- });
54
- if (streaming) {
55
- return [
56
- {
57
- client: "huggingface_hub",
58
- content: `\
59
- ${snippetImportInferenceClient(accessToken, provider)}
60
-
61
- messages = ${messagesStr}
62
-
63
- stream = client.chat.completions.create(
64
- model="${model.id}",
65
- messages=messages,
66
- ${configStr}
67
- stream=True
68
- )
69
-
70
- for chunk in stream:
71
- print(chunk.choices[0].delta.content, end="")`,
72
- },
73
- {
74
- client: "openai",
75
- content: `\
76
- from openai import OpenAI
77
-
78
- client = OpenAI(
79
- base_url="${openAIbaseUrl(provider)}",
80
- api_key="${accessToken || "{API_TOKEN}"}"
81
- )
82
-
83
- messages = ${messagesStr}
84
-
85
- stream = client.chat.completions.create(
86
- model="${providerModelId ?? model.id}",
87
- messages=messages,
88
- ${configStr}
89
- stream=True
90
- )
91
-
92
- for chunk in stream:
93
- print(chunk.choices[0].delta.content, end="")`,
94
- },
95
- ];
96
- }
97
- else {
98
- return [
99
- {
100
- client: "huggingface_hub",
101
- content: `\
102
- ${snippetImportInferenceClient(accessToken, provider)}
103
-
104
- messages = ${messagesStr}
105
-
106
- completion = client.chat.completions.create(
107
- model="${model.id}",
108
- messages=messages,
109
- ${configStr}
110
- )
111
-
112
- print(completion.choices[0].message)`,
113
- },
114
- {
115
- client: "openai",
116
- content: `\
117
- from openai import OpenAI
118
-
119
- client = OpenAI(
120
- base_url="${openAIbaseUrl(provider)}",
121
- api_key="${accessToken || "{API_TOKEN}"}"
122
- )
123
-
124
- messages = ${messagesStr}
125
-
126
- completion = client.chat.completions.create(
127
- model="${providerModelId ?? model.id}",
128
- messages=messages,
129
- ${configStr}
130
- )
131
-
132
- print(completion.choices[0].message)`,
133
- },
134
- ];
135
- }
136
- };
137
- export const snippetZeroShotClassification = (model) => {
138
- return [
139
- {
140
- client: "requests",
141
- content: `\
142
- def query(payload):
143
- response = requests.post(API_URL, headers=headers, json=payload)
144
- return response.json()
145
-
146
- output = query({
147
- "inputs": ${getModelInputSnippet(model)},
148
- "parameters": {"candidate_labels": ["refund", "legal", "faq"]},
149
- })`,
150
- },
151
- ];
152
- };
153
- export const snippetZeroShotImageClassification = (model) => {
154
- return [
155
- {
156
- client: "requests",
157
- content: `\
158
- def query(data):
159
- with open(data["image_path"], "rb") as f:
160
- img = f.read()
161
- payload={
162
- "parameters": data["parameters"],
163
- "inputs": base64.b64encode(img).decode("utf-8")
164
- }
165
- response = requests.post(API_URL, headers=headers, json=payload)
166
- return response.json()
167
-
168
- output = query({
169
- "image_path": ${getModelInputSnippet(model)},
170
- "parameters": {"candidate_labels": ["cat", "dog", "llama"]},
171
- })`,
172
- },
173
- ];
174
- };
175
- export const snippetBasic = (model, accessToken, provider) => {
176
- return [
177
- ...(model.pipeline_tag && model.pipeline_tag in HFH_INFERENCE_CLIENT_METHODS
178
- ? [
179
- {
180
- client: "huggingface_hub",
181
- content: `\
182
- ${snippetImportInferenceClient(accessToken, provider)}
183
-
184
- result = client.${HFH_INFERENCE_CLIENT_METHODS[model.pipeline_tag]}(
185
- model="${model.id}",
186
- inputs=${getModelInputSnippet(model)},
187
- provider="${provider}",
188
- )
189
-
190
- print(result)
191
- `,
192
- },
193
- ]
194
- : []),
195
- {
196
- client: "requests",
197
- content: `\
198
- def query(payload):
199
- response = requests.post(API_URL, headers=headers, json=payload)
200
- return response.json()
201
-
202
- output = query({
203
- "inputs": ${getModelInputSnippet(model)},
204
- })`,
205
- },
206
- ];
207
- };
208
- export const snippetFile = (model) => {
209
- return [
210
- {
211
- client: "requests",
212
- content: `\
213
- def query(filename):
214
- with open(filename, "rb") as f:
215
- data = f.read()
216
- response = requests.post(API_URL, headers=headers, data=data)
217
- return response.json()
218
-
219
- output = query(${getModelInputSnippet(model)})`,
220
- },
221
- ];
222
- };
223
- export const snippetTextToImage = (model, accessToken, provider, providerModelId) => {
224
- return [
225
- {
226
- client: "huggingface_hub",
227
- content: `\
228
- ${snippetImportInferenceClient(accessToken, provider)}
229
-
230
- # output is a PIL.Image object
231
- image = client.text_to_image(
232
- ${getModelInputSnippet(model)},
233
- model="${model.id}"
234
- )`,
235
- },
236
- ...(provider === "fal-ai"
237
- ? [
238
- {
239
- client: "fal-client",
240
- content: `\
241
- import fal_client
242
-
243
- result = fal_client.subscribe(
244
- "${providerModelId ?? model.id}",
245
- arguments={
246
- "prompt": ${getModelInputSnippet(model)},
247
- },
248
- )
249
- print(result)
250
- `,
251
- },
252
- ]
253
- : []),
254
- ...(provider === "hf-inference"
255
- ? [
256
- {
257
- client: "requests",
258
- content: `\
259
- def query(payload):
260
- response = requests.post(API_URL, headers=headers, json=payload)
261
- return response.content
262
-
263
- image_bytes = query({
264
- "inputs": ${getModelInputSnippet(model)},
265
- })
266
-
267
- # You can access the image with PIL.Image for example
268
- import io
269
- from PIL import Image
270
- image = Image.open(io.BytesIO(image_bytes))`,
271
- },
272
- ]
273
- : []),
274
- ];
275
- };
276
- export const snippetTextToVideo = (model, accessToken, provider) => {
277
- return ["fal-ai", "replicate"].includes(provider)
278
- ? [
279
- {
280
- client: "huggingface_hub",
281
- content: `\
282
- ${snippetImportInferenceClient(accessToken, provider)}
283
-
284
- video = client.text_to_video(
285
- ${getModelInputSnippet(model)},
286
- model="${model.id}"
287
- )`,
288
- },
289
- ]
290
- : [];
291
- };
292
- export const snippetTabular = (model) => {
293
- return [
294
- {
295
- client: "requests",
296
- content: `\
297
- def query(payload):
298
- response = requests.post(API_URL, headers=headers, json=payload)
299
- return response.content
300
-
301
- response = query({
302
- "inputs": {"data": ${getModelInputSnippet(model)}},
303
- })`,
304
- },
305
- ];
306
- };
307
- export const snippetTextToAudio = (model) => {
308
- // Transformers TTS pipeline and api-inference-community (AIC) pipeline outputs are diverged
309
- // with the latest update to inference-api (IA).
310
- // Transformers IA returns a byte object (wav file), whereas AIC returns wav and sampling_rate.
311
- if (model.library_name === "transformers") {
312
- return [
313
- {
314
- client: "requests",
315
- content: `\
316
- def query(payload):
317
- response = requests.post(API_URL, headers=headers, json=payload)
318
- return response.content
319
-
320
- audio_bytes = query({
321
- "inputs": ${getModelInputSnippet(model)},
322
- })
323
- # You can access the audio with IPython.display for example
324
- from IPython.display import Audio
325
- Audio(audio_bytes)`,
326
- },
327
- ];
328
- }
329
- else {
330
- return [
331
- {
332
- client: "requests",
333
- content: `\
334
- def query(payload):
335
- response = requests.post(API_URL, headers=headers, json=payload)
336
- return response.json()
337
-
338
- audio, sampling_rate = query({
339
- "inputs": ${getModelInputSnippet(model)},
340
- })
341
- # You can access the audio with IPython.display for example
342
- from IPython.display import Audio
343
- Audio(audio, rate=sampling_rate)`,
344
- },
345
- ];
346
- }
347
- };
348
- export const snippetDocumentQuestionAnswering = (model) => {
349
- return [
350
- {
351
- client: "requests",
352
- content: `\
353
- def query(payload):
354
- with open(payload["image"], "rb") as f:
355
- img = f.read()
356
- payload["image"] = base64.b64encode(img).decode("utf-8")
357
- response = requests.post(API_URL, headers=headers, json=payload)
358
- return response.json()
359
-
360
- output = query({
361
- "inputs": ${getModelInputSnippet(model)},
362
- })`,
363
- },
364
- ];
365
- };
366
- export const pythonSnippets = {
367
- // Same order as in tasks/src/pipelines.ts
368
- "text-classification": snippetBasic,
369
- "token-classification": snippetBasic,
370
- "table-question-answering": snippetBasic,
371
- "question-answering": snippetBasic,
372
- "zero-shot-classification": snippetZeroShotClassification,
373
- translation: snippetBasic,
374
- summarization: snippetBasic,
375
- "feature-extraction": snippetBasic,
376
- "text-generation": snippetBasic,
377
- "text2text-generation": snippetBasic,
378
- "image-text-to-text": snippetConversational,
379
- "fill-mask": snippetBasic,
380
- "sentence-similarity": snippetBasic,
381
- "automatic-speech-recognition": snippetFile,
382
- "text-to-image": snippetTextToImage,
383
- "text-to-video": snippetTextToVideo,
384
- "text-to-speech": snippetTextToAudio,
385
- "text-to-audio": snippetTextToAudio,
386
- "audio-to-audio": snippetFile,
387
- "audio-classification": snippetFile,
388
- "image-classification": snippetFile,
389
- "tabular-regression": snippetTabular,
390
- "tabular-classification": snippetTabular,
391
- "object-detection": snippetFile,
392
- "image-segmentation": snippetFile,
393
- "document-question-answering": snippetDocumentQuestionAnswering,
394
- "image-to-text": snippetFile,
395
- "zero-shot-image-classification": snippetZeroShotImageClassification,
396
- };
397
- export function getPythonInferenceSnippet(model, accessToken, provider, providerModelId, opts) {
398
- if (model.tags.includes("conversational")) {
399
- // Conversational model detected, so we display a code snippet that features the Messages API
400
- return snippetConversational(model, accessToken, provider, providerModelId, opts);
401
- }
402
- else {
403
- const snippets = model.pipeline_tag && model.pipeline_tag in pythonSnippets
404
- ? pythonSnippets[model.pipeline_tag]?.(model, accessToken, provider, providerModelId) ?? []
405
- : [];
406
- return snippets.map((snippet) => {
407
- return {
408
- ...snippet,
409
- content: snippet.client === "requests"
410
- ? `\
411
- import requests
412
-
413
- API_URL = "${openAIbaseUrl(provider)}"
414
- headers = {"Authorization": ${accessToken ? `"Bearer ${accessToken}"` : `f"Bearer {API_TOKEN}"`}}
415
-
416
- ${snippet.content}`
417
- : snippet.content,
418
- };
419
- });
420
- }
421
- }
@@ -1,173 +0,0 @@
1
- import { HF_HUB_INFERENCE_PROXY_TEMPLATE, type SnippetInferenceProvider } from "../inference-providers.js";
2
- import type { PipelineType } from "../pipelines.js";
3
- import type { ChatCompletionInputMessage, GenerationParameters } from "../tasks/index.js";
4
- import { stringifyGenerationConfig, stringifyMessages } from "./common.js";
5
- import { getModelInputSnippet } from "./inputs.js";
6
- import type { InferenceSnippet, ModelDataMinimal } from "./types.js";
7
-
8
- export const snippetBasic = (
9
- model: ModelDataMinimal,
10
- accessToken: string,
11
- provider: SnippetInferenceProvider
12
- ): InferenceSnippet[] => {
13
- if (provider !== "hf-inference") {
14
- return [];
15
- }
16
- return [
17
- {
18
- client: "curl",
19
- content: `\
20
- curl https://router.huggingface.co/hf-inference/models/${model.id} \\
21
- -X POST \\
22
- -d '{"inputs": ${getModelInputSnippet(model, true)}}' \\
23
- -H 'Content-Type: application/json' \\
24
- -H 'Authorization: Bearer ${accessToken || `{API_TOKEN}`}'`,
25
- },
26
- ];
27
- };
28
-
29
- export const snippetTextGeneration = (
30
- model: ModelDataMinimal,
31
- accessToken: string,
32
- provider: SnippetInferenceProvider,
33
- providerModelId?: string,
34
- opts?: {
35
- streaming?: boolean;
36
- messages?: ChatCompletionInputMessage[];
37
- temperature?: GenerationParameters["temperature"];
38
- max_tokens?: GenerationParameters["max_tokens"];
39
- top_p?: GenerationParameters["top_p"];
40
- }
41
- ): InferenceSnippet[] => {
42
- if (model.tags.includes("conversational")) {
43
- const baseUrl =
44
- provider === "hf-inference"
45
- ? `https://router.huggingface.co/hf-inference/models/${model.id}/v1/chat/completions`
46
- : HF_HUB_INFERENCE_PROXY_TEMPLATE.replace("{{PROVIDER}}", provider) + "/v1/chat/completions";
47
- const modelId = providerModelId ?? model.id;
48
-
49
- // Conversational model detected, so we display a code snippet that features the Messages API
50
- const streaming = opts?.streaming ?? true;
51
- const exampleMessages = getModelInputSnippet(model) as ChatCompletionInputMessage[];
52
- const messages = opts?.messages ?? exampleMessages;
53
-
54
- const config = {
55
- ...(opts?.temperature ? { temperature: opts.temperature } : undefined),
56
- max_tokens: opts?.max_tokens ?? 500,
57
- ...(opts?.top_p ? { top_p: opts.top_p } : undefined),
58
- };
59
- return [
60
- {
61
- client: "curl",
62
- content: `curl '${baseUrl}' \\
63
- -H 'Authorization: Bearer ${accessToken || `{API_TOKEN}`}' \\
64
- -H 'Content-Type: application/json' \\
65
- --data '{
66
- "model": "${modelId}",
67
- "messages": ${stringifyMessages(messages, {
68
- indent: "\t",
69
- attributeKeyQuotes: true,
70
- customContentEscaper: (str) => str.replace(/'/g, "'\\''"),
71
- })},
72
- ${stringifyGenerationConfig(config, {
73
- indent: "\n ",
74
- attributeKeyQuotes: true,
75
- attributeValueConnector: ": ",
76
- })}
77
- "stream": ${!!streaming}
78
- }'`,
79
- },
80
- ];
81
- } else {
82
- return snippetBasic(model, accessToken, provider);
83
- }
84
- };
85
-
86
- export const snippetZeroShotClassification = (
87
- model: ModelDataMinimal,
88
- accessToken: string,
89
- provider: SnippetInferenceProvider
90
- ): InferenceSnippet[] => {
91
- if (provider !== "hf-inference") {
92
- return [];
93
- }
94
- return [
95
- {
96
- client: "curl",
97
- content: `curl https://router.huggingface.co/hf-inference/models/${model.id} \\
98
- -X POST \\
99
- -d '{"inputs": ${getModelInputSnippet(model, true)}, "parameters": {"candidate_labels": ["refund", "legal", "faq"]}}' \\
100
- -H 'Content-Type: application/json' \\
101
- -H 'Authorization: Bearer ${accessToken || `{API_TOKEN}`}'`,
102
- },
103
- ];
104
- };
105
-
106
- export const snippetFile = (
107
- model: ModelDataMinimal,
108
- accessToken: string,
109
- provider: SnippetInferenceProvider
110
- ): InferenceSnippet[] => {
111
- if (provider !== "hf-inference") {
112
- return [];
113
- }
114
- return [
115
- {
116
- client: "curl",
117
- content: `curl https://router.huggingface.co/hf-inference/models/${model.id} \\
118
- -X POST \\
119
- --data-binary '@${getModelInputSnippet(model, true, true)}' \\
120
- -H 'Authorization: Bearer ${accessToken || `{API_TOKEN}`}'`,
121
- },
122
- ];
123
- };
124
-
125
- export const curlSnippets: Partial<
126
- Record<
127
- PipelineType,
128
- (
129
- model: ModelDataMinimal,
130
- accessToken: string,
131
- provider: SnippetInferenceProvider,
132
- providerModelId?: string,
133
- opts?: Record<string, unknown>
134
- ) => InferenceSnippet[]
135
- >
136
- > = {
137
- // Same order as in tasks/src/pipelines.ts
138
- "text-classification": snippetBasic,
139
- "token-classification": snippetBasic,
140
- "table-question-answering": snippetBasic,
141
- "question-answering": snippetBasic,
142
- "zero-shot-classification": snippetZeroShotClassification,
143
- translation: snippetBasic,
144
- summarization: snippetBasic,
145
- "feature-extraction": snippetBasic,
146
- "text-generation": snippetTextGeneration,
147
- "image-text-to-text": snippetTextGeneration,
148
- "text2text-generation": snippetBasic,
149
- "fill-mask": snippetBasic,
150
- "sentence-similarity": snippetBasic,
151
- "automatic-speech-recognition": snippetFile,
152
- "text-to-image": snippetBasic,
153
- "text-to-speech": snippetBasic,
154
- "text-to-audio": snippetBasic,
155
- "audio-to-audio": snippetFile,
156
- "audio-classification": snippetFile,
157
- "image-classification": snippetFile,
158
- "image-to-text": snippetFile,
159
- "object-detection": snippetFile,
160
- "image-segmentation": snippetFile,
161
- };
162
-
163
- export function getCurlInferenceSnippet(
164
- model: ModelDataMinimal,
165
- accessToken: string,
166
- provider: SnippetInferenceProvider,
167
- providerModelId?: string,
168
- opts?: Record<string, unknown>
169
- ): InferenceSnippet[] {
170
- return model.pipeline_tag && model.pipeline_tag in curlSnippets
171
- ? curlSnippets[model.pipeline_tag]?.(model, accessToken, provider, providerModelId, opts) ?? []
172
- : [];
173
- }