scrimba
Helen Chong's JavaScriptmas 2023 Solutions
Helen Chong's JavaScriptmas 2023 Day 9 solution
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Helen Chong's JavaScriptmas 2023 Day 9 solution
AboutCommentsNotes
Helen Chong's JavaScriptmas 2023 Day 9 solution
Expand for more info
index.js
run
preview
console
/** uncomment one of these **/
// import OpenAI from "openai"
import { HfInference } from '@huggingface/inference'

const dialogModal = document.getElementById('dialog-modal')
const imageContainer = document.getElementById('image-container')

/** show dialog on load **/
dialogModal.show()

/**
* 🎄 Challenge:
* 1. When a user hits submit, dialogModal
* should be hidden.
* 2. Use the inputted text to generate an image
* for the e-card using an AI model.
* ⚠️ Make sure the image is square.
* 3. Render the image to imageContainer.
*
* 🎁 hint.md for help!
**/

const hf = new HfInference(process.env.HUGGINGFACE_TOKEN)
const form = document.querySelector('form')
const userInput = document.getElementById('user-input')
let prompt = userInput.value

async function getImage() {
const response = await hf.textToImage({
model: "stabilityai/stable-diffusion-2",
inputs: prompt,
parameters: {
negative_prompt: "blurry",
},
})

async function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
})
}

const imageUrl = await blobToBase64(response)
return imageUrl
}

// console.log(await getImage())

form.addEventListener('submit', async (event) => {
event.preventDefault()
dialogModal.close()
const imageUrl = await getImage()
imageContainer.innerHTML = `
<img src="${imageUrl}">
`
})
Console
/index.html?
LIVE