Okay, this is a complex task to put into a single HTML file, as it requires:
Loading several large ONNX model files from the specified Hugging Face repository.
Running the ONNX models (Text Encoder, UNet, VAE Decoder) in the browser.
Implementing the diffusion pipeline logic (tokenizer, scheduler, denoising loop).
Doing this manually with just ONNX Runtime Web would involve writing a significant amount of JavaScript code to replicate the diffusion pipeline steps.
Fortunately, the @xenova/transformers library (built on ONNX Runtime Web) provides high-level DiffusionPipeline classes that can handle much of this complexity for you, loading models directly from Hugging Face Hub.
Here's a single HTML file that uses @xenova/transformers to load the model and generate an image. Please note:
This will download several large files (~2GB total) the first time it runs.
Generation speed depends heavily on the user's device and network speed.
LCM models use very few steps (typically 4-8) and often guidance scale 0 for speed.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LCM Dreamshaper V7 ONNX - In Browser</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
background-color: #f0f0f0;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 600px;
text-align: center;
}
h1 {
color: #333;
margin-bottom: 20px;
}
input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1em;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s ease;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
button:hover:not(:disabled) {
background-color: #0056b3;
}
#status {
margin-top: 15px;
font-size: 0.9em;
color: #555;
min-height: 1.2em; /* Reserve space */
}
#imageOutput {
margin-top: 20px;
border: 1px solid #eee;
max-width: 100%; /* Ensure it fits in the container */
height: auto;
display: block; /* Prevent extra space below image */
margin-left: auto;
margin-right: auto;
}
canvas {
margin-top: 20px;
border: 1px solid #eee;
display: block; /* Prevent extra space below */
margin-left: auto;
margin-right: auto;
}
</style>
<!-- Import ONNX Runtime Web -->
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
<!-- Import Xenova/transformers -->
<script src="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.15.1"></script>
</head>
<body>
<div class="container">
<h1>LCM Dreamshaper V7 ONNX</h1>
<input type="text" id="promptInput" placeholder="Enter your prompt here...">
<button id="generateButton">Generate Image</button>
<div id="status">Loading model...</div>
<canvas id="imageCanvas" width="512" height="512"></canvas>
</div>
<script type="module">
import { DiffusionPipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.15.1';
// Model ID on Hugging Face Hub
const modelId = 'TheyCallMeHex/LCM-Dreamshaper-V7-ONNX';
// DOM elements
const promptInput = document.getElementById('promptInput');
const generateButton = document.getElementById('generateButton');
const statusDiv = document.getElementById('status');
const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let pipeline = null;
// Function to update status text
function updateStatus(message) {
statusDiv.innerText = message;
}
// Function to load the pipeline
async function loadPipeline() {
updateStatus('Loading model components...');
generateButton.disabled = true; // Disable button while loading
try {
// Set ONNX Runtime execution provider (optional, default is WebGL if available)
// ort.env.wasm.execMode = 'parallel'; // Example: Use parallel execution
// ort.env.wasm.numThreads = 2; // Example: Set thread count
pipeline = await DiffusionPipeline.from_pretrained(modelId, {
// This callback updates the status during loading
progress_callback: (data) => {
let message = `Loading ${data.file}... `;
if (data.progress !== undefined) {
message += `${Math.round(data.progress * 100)}%`;
}
updateStatus(message);
},
// Ensure ONNX Runtime is configured correctly
ort_options: {
executionProviders: ['wasm'] // Explicitly use WASM provider
// executionProviders: ['webgl', 'wasm'] // Prioritize WebGL if available
}
});
updateStatus('Model loaded. Enter prompt and click Generate.');
generateButton.disabled = false; // Enable button
} catch (error) {
console.error("Failed to load the pipeline:", error);
updateStatus('Error loading model. Check console.');
}
}
// Function to generate the image
async function generateImage() {
const prompt = promptInput.value.trim();
if (!prompt) {
updateStatus('Please enter a prompt.');
return;
}
if (!pipeline) {
updateStatus('Model is not loaded yet. Please wait.');
return;
}
generateButton.disabled = true;
updateStatus('Generating image...');
try {
// Generate the image using the pipeline
// LCM models typically use low steps and guidance scale 0
const output = await pipeline(prompt, {
num_inference_steps: 4, // Recommended steps for LCM
guidance_scale: 0, // Recommended guidance for LCM
// This callback updates the status during generation
callback_steps: 1, // Report progress every step
callback: (step, timestep, latents) => {
updateStatus(`Generating image... Step ${step}/${4}`); // Update step progress
},
// You can add negative prompt here if needed
// negative_prompt: "bad anatomy, blurry, low resolution",
});
// The output is a canvas element provided by the pipeline
const outputCanvas = output.images[0]; // Get the first image (which is a canvas)
// Draw the output canvas onto our display canvas
ctx.clearRect(0, 0, imageCanvas.width, imageCanvas.height);
ctx.drawImage(outputCanvas, 0, 0, imageCanvas.width, imageCanvas.height);
updateStatus('Done!');
} catch (error) {
console.error("Failed to generate image:", error);
updateStatus('Error generating image. Check console.');
} finally {
generateButton.disabled = false;
}
}
// Event listener for the button
generateButton.addEventListener('click', generateImage);
// Initial model loading when the page loads
loadPipeline();
</script>
</body>
</html>
How to Use:
Save the code above as an HTML file (e.g., lcm_dreamshaper.html).
Open the HTML file in a modern web browser (like Chrome, Firefox, Edge, Safari).
The page will immediately start loading the model components from Hugging Face Hub. This will take some time depending on your internet speed. The status message will show the loading progress.
Once the status shows "Model loaded...", enter your text prompt in the input box.
Click the "Generate Image" button.
The status will change to "Generating image...".
After a short time (typically a few seconds on decent hardware), the generated image will appear on the canvas.
This approach leverages the power of @xenova/transformers to handle the complexities of the pipeline, allowing you to achieve the goal in a relatively simple single HTML file.