-
Notifications
You must be signed in to change notification settings - Fork 391
[JS] Implement Text2ImagePipeline #3740
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Retribution98
wants to merge
3
commits into
openvinotoolkit:master
Choose a base branch
from
Retribution98:text2image
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,84 @@ | ||
| # Text to Image JavaScript Generation Pipeline | ||
|
|
||
| This example showcases inference of text-to-image diffusion models like Stable Diffusion 1.5, 2.1, FLUX, and LCM. The application doesn't have many configuration options to encourage the reader to explore and modify the source code. For example, change the device for inference to GPU. The sample features `Text2ImagePipeline` from `openvino-genai-node` and uses a text prompt as input source. | ||
|
|
||
| Sample files: | ||
| - [`text2image.js`](./text2image.js) demonstrates basic usage of the text-to-image pipeline with a step callback and saves the result as a BMP file using `bmp-js` | ||
|
|
||
| Users can change the sample code and play with the following generation parameters: | ||
|
|
||
| - Change width or height of generated image | ||
| - Generate multiple images per prompt (`num_images_per_prompt`) | ||
| - Adjust a number of inference steps (`num_inference_steps`) | ||
| - Play with [guidance scale](https://huggingface.co/spaces/stabilityai/stable-diffusion/discussions/9) (read [more details](https://arxiv.org/abs/2207.12598)) | ||
| - (SD 1.x, 2.x; SD3, SDXL) Add negative prompt when guidance scale > 1 | ||
| - (SDXL, SD3, FLUX) Specify other positive prompts like `prompt_2` | ||
| - Add a per-step callback to monitor progress or stop generation early | ||
|
|
||
| ## Download and convert the model | ||
|
|
||
| The `--upgrade-strategy eager` option is needed to ensure `optimum-intel` is upgraded to the latest version. | ||
|
|
||
| It's not required to install [../../export-requirements.txt](../../export-requirements.txt) for deployment if the model has already been exported. | ||
|
|
||
| ```sh | ||
| pip install --upgrade-strategy eager -r ../../export-requirements.txt | ||
| ``` | ||
|
|
||
| Then, run the export with Optimum CLI: | ||
|
|
||
| ```sh | ||
| optimum-cli export openvino --model dreamlike-art/dreamlike-anime-1.0 --task stable-diffusion --weight-format fp16 dreamlike_anime_1_0_ov/FP16 | ||
| ``` | ||
|
|
||
| ## Run | ||
|
|
||
| From the `samples/js` directory, install dependencies (if not already done): | ||
|
|
||
| ```bash | ||
| npm install | ||
| ``` | ||
|
|
||
| If you use the master branch, you may need to [build openvino-genai-node from source](../../../src/js/README.md#build-bindings) first. | ||
|
|
||
| Run the sample: | ||
|
|
||
| ```bash | ||
| node image_generation/text2image.js dreamlike_anime_1_0_ov/FP16 "cyberpunk cityscape like Tokyo New York with tall buildings at dusk golden hour cinematic lighting" | ||
| ``` | ||
|
|
||
| The result is saved as `image.bmp` in the current directory. | ||
|
|
||
| ### Optional: change device | ||
|
|
||
| The device is hardcoded to `CPU` in the sample. To use `GPU`, edit `text2image.js` and change: | ||
|
|
||
| ```js | ||
| const device = "CPU"; // GPU can be used as well | ||
| ``` | ||
|
|
||
| ### Examples | ||
|
|
||
| Prompt: `cyberpunk cityscape like Tokyo New York with tall buildings at dusk golden hour cinematic lighting` | ||
|
|
||
|  | ||
|
|
||
| Refer to the [Supported Models](https://openvinotoolkit.github.io/openvino.genai/docs/supported-models/#image-generation-models) for the list of supported models. | ||
|
|
||
| ## Run with a step callback | ||
|
|
||
| The sample registers a callback that prints progress to stdout on each denoising step. The callback can also stop generation early by returning `true`: | ||
|
|
||
| ```js | ||
| function callback(step, numSteps) { | ||
| process.stdout.write(`Step ${step + 1}/${numSteps}\r`); | ||
| return false; // return true to stop early | ||
| } | ||
|
|
||
| const imageTensor = await pipeline.generate(prompt, { | ||
| width: 512, | ||
| height: 512, | ||
| num_inference_steps: 20, | ||
| callback, | ||
| }); | ||
| ``` |
This file contains hidden or 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,80 @@ | ||
| // Copyright (C) 2023-2026 Intel Corporation | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { writeFile } from "node:fs/promises"; | ||
| import { basename } from "node:path"; | ||
| import bmp from "bmp-js"; | ||
| import yargs from "yargs/yargs"; | ||
| import { hideBin } from "yargs/helpers"; | ||
| import { Text2ImagePipeline } from "openvino-genai-node"; | ||
|
|
||
| function toABGR(tensor) { | ||
| const [_, height, width, channels] = tensor.getShape(); | ||
| if (channels !== 3) { | ||
| throw new Error(`Expected RGB image tensor, got ${channels} channels.`); | ||
| } | ||
|
|
||
| const rgb = tensor.data instanceof Uint8Array ? tensor.data : Uint8Array.from(tensor.data); | ||
| const rgba = Buffer.allocUnsafe(width * height * 4); | ||
|
|
||
| for (let src = 0, dst = 0; src < rgb.length; src += 3, dst += 4) { | ||
| rgba[dst] = 255; // A | ||
| rgba[dst + 1] = rgb[src + 2]; // B | ||
| rgba[dst + 2] = rgb[src + 1]; // G | ||
| rgba[dst + 3] = rgb[src]; // R | ||
| } | ||
|
|
||
| return { height, width, rgba }; | ||
| } | ||
|
|
||
| async function main() { | ||
| const argv = await yargs(hideBin(process.argv)) | ||
| .scriptName(basename(process.argv[1])) | ||
| .command( | ||
| "$0 <model_dir> <prompt>", | ||
| "Run Text2Image pipeline and save generated image as BMP file", | ||
| (yargsBuilder) => | ||
| yargsBuilder | ||
| .positional("model_dir", { | ||
| type: "string", | ||
| describe: "Path to the converted image generation model directory", | ||
| demandOption: true, | ||
| }) | ||
| .positional("prompt", { | ||
| type: "string", | ||
| describe: "Prompt to generate images from", | ||
| demandOption: true, | ||
| }) | ||
| ) | ||
| .strict() | ||
| .help() | ||
| .parse(); | ||
|
|
||
| const device = "CPU"; // GPU can be used as well | ||
| const pipeline = await Text2ImagePipeline(argv.model_dir, device); | ||
|
|
||
| function callback(step, numSteps) { | ||
| process.stdout.write(`Step ${step + 1}/${numSteps}\r`); | ||
| return false; | ||
| } | ||
|
|
||
| const imageTensor = await pipeline.generate( | ||
| argv.prompt, | ||
| { | ||
| width: 512, | ||
| height: 512, | ||
| num_inference_steps: 20, | ||
| num_images_per_prompt: 1, | ||
| callback, | ||
| }, | ||
| ); | ||
|
|
||
| const { height, width, rgba } = toABGR(imageTensor); | ||
| const bmpData = bmp.encode({ width, height, data: rgba }); | ||
| await writeFile("image.bmp", bmpData.data); | ||
| } | ||
|
|
||
| main().catch((error) => { | ||
| console.error(error); | ||
| process.exitCode = 1; | ||
| }); | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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
This file contains hidden or 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
26 changes: 26 additions & 0 deletions
26
site/docs/use-cases/image-generation/_sections/_run_model/_text2image_js.mdx
This file contains hidden or 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,26 @@ | ||
| import CodeBlock from '@theme/CodeBlock'; | ||
|
|
||
| <CodeBlock language="javascript" showLineNumbers> | ||
| {`import { writeFile } from 'node:fs/promises'; | ||
| import bmp from 'bmp-js'; | ||
| import { Text2ImagePipeline } from 'openvino-genai-node'; | ||
|
|
||
| const pipeline = await Text2ImagePipeline(modelPath, '${props.device || 'CPU'}'); | ||
| const image = await pipeline.generate(prompt); | ||
|
|
||
| // Save the first generated image as BMP | ||
| const [height, width] = [image.getShape()[1], image.getShape()[2]]; | ||
| const rgb = Uint8Array.from(image.data); | ||
| const abgr = Buffer.allocUnsafe(width * height * 4); | ||
|
|
||
| for (let src = 0, dst = 0; src < rgb.length; src += 3, dst += 4) { | ||
| abgr[dst] = 255; // A | ||
| abgr[dst + 1] = rgb[src + 2]; // B | ||
| abgr[dst + 2] = rgb[src + 1]; // G | ||
| abgr[dst + 3] = rgb[src]; // R | ||
| } | ||
|
|
||
| const bmpData = bmp.encode({ width, height, data: abgr }); | ||
| await writeFile('image.bmp', bmpData.data); | ||
| `} | ||
| </CodeBlock> |
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.