|
| 1 | +import * as Flex from '.'; |
| 2 | +const BFL_API = 'https://api.bfl.ml'; |
| 3 | +const FLEX_PRO = `${BFL_API}/v1/flux-pro-1.1`; |
| 4 | +const FLEX_PRO_ULTRA = `${BFL_API}/v1/flux-pro-1.1-ultra`; |
| 5 | +const GET_RESULT = `${BFL_API}/v1/get_result?id=`; |
| 6 | + |
| 7 | +export async function generateImage(prompt: string): Promise<Flex.Response> { |
| 8 | + const promptReq: Flex.ProPrompt = { |
| 9 | + prompt: prompt, |
| 10 | + width: 1024, |
| 11 | + height: 768, |
| 12 | + prompt_upsampling: false, |
| 13 | + seed: null, |
| 14 | + safety_tolerance: 6, |
| 15 | + output_format: 'jpeg', |
| 16 | + }; |
| 17 | + const options = { |
| 18 | + method: 'POST', |
| 19 | + body: JSON.stringify(promptReq), |
| 20 | + headers: new Headers({ |
| 21 | + 'Content-Type': 'application/json', |
| 22 | + 'X-Key': `${process.env.BFL_KEY}`, |
| 23 | + }), |
| 24 | + }; |
| 25 | + const response: Flex.Response = await fetch(new URL(FLEX_PRO), options).then( |
| 26 | + data => data.json() |
| 27 | + ); |
| 28 | + |
| 29 | + console.log('response:\n', response); |
| 30 | + |
| 31 | + let imgResponse = null; |
| 32 | + while (imgResponse === null) { |
| 33 | + await sleep(500); |
| 34 | + imgResponse = await getImageFromAPI(response.id); |
| 35 | + console.log('imgResponse:\n', imgResponse); |
| 36 | + } |
| 37 | + |
| 38 | + return imgResponse; |
| 39 | +} |
| 40 | + |
| 41 | +async function getImageFromAPI( |
| 42 | + id: string |
| 43 | +): Promise<Flex.GetResponse | Flex.Error | null> { |
| 44 | + const res: Flex.GetResponse = await fetch(`${GET_RESULT}${id}`).then(data => |
| 45 | + data.json() |
| 46 | + ); |
| 47 | + console.log('res:', res); |
| 48 | + if (res.status === 'Ready') return res; |
| 49 | + |
| 50 | + return null; |
| 51 | +} |
| 52 | + |
| 53 | +async function sleep(msec: number) { |
| 54 | + return new Promise(resolve => setTimeout(resolve, msec)); |
| 55 | +} |
0 commit comments