-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Write a test to use pipeline with a zero-shot-image-classification model
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import type { PyodideInterface } from "pyodide"; | ||
import { beforeEach, describe, it, expect } from "vitest"; | ||
import { setupPyodideForTest } from "./utils"; | ||
|
||
describe("transformers.pipeline", () => { | ||
let pyodide: PyodideInterface; | ||
|
||
beforeEach(async () => { | ||
pyodide = await setupPyodideForTest(); | ||
}); | ||
|
||
it("works with zero-shot-image-classification model", async () => { | ||
await fetch("https://huggingface.co/spaces/gradio/image_mod/resolve/main/images/lion.jpg") | ||
.then((response) => response.blob()) | ||
.then((blob) => blob.arrayBuffer()) | ||
.then((arrayBuffer) => { | ||
const fileData = new Uint8Array(arrayBuffer); | ||
const filePath = "/tmp/cheetah.jpg"; | ||
pyodide.FS.writeFile(filePath, fileData); | ||
}); | ||
|
||
await pyodide.runPythonAsync(` | ||
from transformers_js import import_transformers_js, as_url | ||
transformers = await import_transformers_js() | ||
pipeline = transformers.pipeline | ||
pipe = await pipeline('zero-shot-image-classification') | ||
image = "/tmp/cheetah.jpg" | ||
data = await pipe(as_url(image), ["tower", "lion", "flower"]) | ||
result = {item['label']: round(item['score'], 2) for item in data} | ||
`); | ||
const resultMap = await pyodide.globals.get("result").toJs(); // Python's dict to JS's Map | ||
const resultObj = Object.fromEntries(resultMap); | ||
expect(Object.keys(resultObj)).toEqual(["tower", "lion", "flower"]); | ||
|
||
const topLabel = Object.keys(resultObj).reduce((a, b) => resultObj[a] > resultObj[b] ? a : b); | ||
expect(topLabel).toEqual("lion"); | ||
}); | ||
}); |