Here's a single HTML file template that loads the ONNX model from Hugging Face and generates images using the Latent Consistency Model pipeline. Note that this is a simplified implementation requiring additional dependencies and optimizations for production use.
<!DOCTYPE html>
<html>
<head>
<title>LCM Dreamshaper ONNX</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.15.0/dist/ort.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@xifrat/tokenizers-js@0.1.0/bundled/bpe.min.js"></script>
<style>
body { font-family: Arial; padding: 20px; }
canvas { max-width: 100%; border: 1px solid #ccc; }
#progress { margin: 10px 0; width: 100%; background: #f0f0f0; height: 20px; }
#progress-bar { background: #4caf50; height: 100%; width: 0%; }
</style>
</head>
<body>
<h1>LCM Dreamshaper Image Generator</h1>
<input type="text" id="prompt" placeholder="Enter your prompt..." style="width: 80%;">
<button onclick="generateImage()">Generate</button>
<div id="progress"><div id="progress-bar"></div></div>
<canvas id="output"></canvas>
<script>
const provider = 'webgl'; // or 'wasm' for better compatibility
const modelPath = 'https://huggingface.co/TheyCallMeHex/LCM-Dreamshaper-V7-ONNX/resolve/main/';
// Initialize models
let textEncoder, unet, vaeDecoder;
let tokenizer;
async function loadModels() {
// Load tokenizer
const vocab = await fetch(modelPath + 'tokenizer/vocab.json').then(r => r.json());
const merges = await fetch(modelPath + 'tokenizer/merges.txt').then(r => r.text());
tokenizer = new BPE.Tokenizer(vocab, merges);
// Load ONNX models
textEncoder = await ort.InferenceSession.create(modelPath + 'text_encoder/model.onnx', { executionProviders: [provider] });
unet = await ort.InferenceSession.create(modelPath + 'unet/model.onnx', { executionProviders: [provider] });
vaeDecoder = await ort.InferenceSession.create(modelPath + 'vae_decoder/model.onnx', { executionProviders: [provider] });
console.log('All models loaded successfully');
}
async function generateImage() {
const prompt = document.getElementById('prompt').value;
if (!prompt) return alert('Please enter a prompt');
// Tokenize prompt
const tokens = tokenizer.encode(prompt).concat(49407); // Add end token
const tokenTensor = new ort.Tensor('int64', new BigInt64Array(tokens), [1, tokens.length]);
// Get text embeddings
const textEmbeds = await textEncoder.run({ input_ids: tokenTensor });
const pooledEmbeds = textEmbeds.last_hidden_state; // Adjust based on model output
// Initialize latents
let latents = createRandomTensor([1, 4, 64, 64]); // LCM specific latent size
// LCM sampling parameters
const timesteps = 4; // LCM typically uses few steps
const guidanceScale = 7.5;
// Diffusion loop (simplified)
for (let i = 0; i < timesteps; i++) {
// Classifier-free guidance
const noisyLatents = latents; // Add noise based on current timestep
const stepTensor = new ort.Tensor('int64', [i], [1]);
// UNet prediction
const noisePred = await unet.run({
sample: noisyLatents,
timestep: stepTensor,
encoder_hidden_states: pooledEmbeds
});
// Update latents (simplified LCM step)
latents = latents; // Implement actual step from LCM paper
// Update progress
document.getElementById('progress-bar').style.width = `${(i+1)/timesteps*100}%`;
}
// Decode latents to image
const imageTensor = await vaeDecoder.run({ sample: latents });
const image = tensorToImage(imageTensor.sample); // Implement tensor conversion
// Display result
const canvas = document.getElementById('output');
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
}
function createRandomTensor(shape) {
// Create random normal tensor
const size = shape.reduce((a,b) => a*b, 1);
const data = new Float32Array(size);
for (let i = 0; i < size; i++) {
data[i] = gaussianRandom(); // Standard normal distribution
}
return new ort.Tensor('float32', data, shape);
}
function gaussianRandom() {
// Box-Muller transform
let u = 0, v = 0;
while (u === 0) u = Math.random();
while (v === 0) v = Math.random();
return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}
function tensorToImage(tensor) {
// Convert tensor to image (implement based on actual tensor format)
const canvas = document.createElement('canvas');
// Implement tensor normalization and RGB conversion
return canvas;
}
// Load models on page load
window.onload = loadModels;
</script>
</body>
</html>
Important Notes:
-
Dependencies: This code requires:
- ONNX Runtime Web (loaded via CDN)
- BPE Tokenizer library (simplified version)
-
Limitations:
- Actual implementation requires proper tensor handling
- Scheduler logic needs to match LCM implementation
- VAE decoding requires proper normalization
- WebGL provider may not work on all devices
-
Performance:
- Large models may cause memory issues
- WebGL acceleration improves speed
- May need optimization for mobile devices
-
Security:
- Ensure proper CORS headers from Hugging Face
- Consider using a proxy for production
To make this fully functional, you would need to:
- Implement the complete LCM scheduler logic
- Handle proper tensor normalization and scaling
- Implement tensor-to-image conversion
- Add error handling and loading states
- Optimize for performance and memory usage
For production use, consider implementing a backend service that handles the heavy computation and serving the results to the frontend.