Thuta Learning
API Tutorial
AdvancedWeb Developmentအလယ်အလတ်

Stability AI (Images)

API Tutorialသင်ခန်းစာ 2435 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Bearer key ပါတဲ့ POST /v2beta/stable-image/generate/core အတွက် multipart/form-data request တည်ဆောက်နိုင်ဖို့
  • Raw byte အတွက် Accept: image/* နဲ့ base64 အတွက် Accept: application/json ကို ရွေးပြီး reply တစ်ခုစီကို decode လုပ်နိုင်ဖို့
  • Byte တွေကို signature နဲ့ စစ်ဆေး၊ finish-reason ကိုဖတ်ပြီး file ကို လုံခြုံစွာ သိမ်းနိုင်ဖို့
  • Docs ပါ JSON error body နဲ့ 400၊ 403 content moderation၊ 413၊ 422၊ 429 နဲ့ 5xx တွေကို ကိုင်တွယ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Text API တွေက စကားလုံးတွေကို JSON ထဲ ထည့်ပြီး ပြန်ပေးပါတယ်။ ပုံ API ကတော့ ပုံတစ်ပုံ ပြန်ပေးပြီး ပုံဆိုတာ byte တွေပါ။ Stability AI ရဲ့ Stable Image Core endpoint က prompt ကိုယူပြီး ပုံပြန်ပို့တာမို့ အရင် lesson တွေမှာ ကျင့်ထားတဲ့ အလေ့အကျင့်နှစ်ခု ပြောင်းပါတယ်။ Request က JSON body အစား browser က file upload အတွက် ပို့လေ့ရှိတဲ့ multipart/form-data လို့ခေါ်တဲ့ form ပုံစံ ဖြစ်ပါတယ်။ ပြီးတော့ header တစ်ခုက reply ကို ပုံကိုယ်တိုင်လား၊ စာသားအဖြစ်ထုပ်ထားတဲ့ ပုံလား ဆုံးဖြတ်ပါတယ်။

ဓာတ်ပုံဆိုင်မှာ ပုံနှိပ်ခိုင်းတာကို စဉ်းစားကြည့်ပါ။ အော်ဒါ form ဖြည့်ပါတယ်၊ ဒါက multipart request ပါ။ ပြီးတော့ ပုံနှိပ်ထားတာကို စာအိတ်နဲ့ လိုချင်လား၊ binary ပါ၊ ဒါမှမဟုတ် email နဲ့ scan ကူးထားတာ လိုချင်လား၊ JSON ထဲက base64 ပါ၊ ပြောပါတယ်။

Problem → Why → Solution

ပြဿနာ: binary reply တွေက JSON အကျင့်ကို ဖျက်ဆီးတယ်

အောက်ကို curl command က ပထမအကြိမ်မှာတင် အလုပ်လုပ်ပြီး အဲဒါပဲ ထောင်ချောက်ပါ။ Code ထဲမှာ တစ်ယောက်က အောင်မြင်တဲ့ response ပေါ် res.json() ခေါ်ပြီး body က PNG byte တွေမို့ SyntaxError ရပါတယ်။ တခြားတစ်ယောက်က script ထဲမှာ curl ရဲ့ --output flag ကို ဆက်ထားလို့ key မှားတဲ့အခါ JSON error စာသားက out.png ထဲ သိမ်းသွားပြီး ပုံ မဖွင့်နိုင်တော့ပါဘူး။

တတိယလူက .png နာမည်ကို ယုံပြီး ပြန်လာတာ ဘာမဆို သိမ်းတာ ဒါမှမဟုတ် ပြန်ပေးတာ လုပ်ပါတယ်။ File နာမည်က တံဆိပ်ပါ၊ သက်သေ မဟုတ်ပါဘူး။ ထုတ်ပေးတဲ့ media ကို တခြား မယုံကြည်ရသေးတဲ့ upload လိုပဲ ဆက်ဆံသင့်ပါတယ်။

first-try.sh
# works once; on a 4xx/5xx the error JSON is written into out.png as well
curl -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
  -H "Authorization: Bearer $STABILITY_API_KEY" \
  -H "Accept: image/*" \
  -F "prompt=Myanmar landscape at sunrise" \
  --output out.png

တစ်ပြိုင်တည်း ကျတဲ့ ယူဆချက်သုံးခု

JSON အကျင့်တွေက body တိုင်းက စာသားလို့၊ status code တိုင်းမှာ content type တူတယ်လို့၊ နာမည်က file ဘာလဲ ပြောတယ်လို့ ယူဆပါတယ်။ ပုံ endpoint က သုံးခုလုံးကို ချိုးပါတယ်။ အောင်မြင်တာက binary၊ error တွေက JSON၊ ပြီးတော့ ပထမ byte တွေကပဲ file အစစ်ကို ပြောပါတယ်။ ပြင်နည်းက status ကို အရင်စစ်၊ Accept header က ကတိပေးတဲ့ပုံစံအတိုင်း body ကိုဖတ်၊ ဘာမှမသိမ်းခင် signature ကို စစ်တာပါ။

Core concept: form ဝင်၊ byte ဒါမှမဟုတ် base64 ထွက်

အောက်ပါ အချက်တွေက Stability AI ရဲ့ API reference ကနေ ယူထားတာပါ။ Endpoint နဲ့ parameter တွေက v2beta path အောက်မှာ ရှိနေဆဲမို့ တည်ဆောက်တဲ့အခါ docs ကို ဖွင့်ထားပါ။

၁။ Endpoint၊ base URL နဲ့ key

https://api.stability.ai/v2beta/stable-image/generate/core ကို Authorization: Bearer $STABILITY_API_KEY header နဲ့ POST လုပ်ပါ။ Key မပါ ဒါမှမဟုတ် မှားရင် 401 ပြန်ပါတယ်။ အောင်မြင်တဲ့ request တစ်ခုချင်းစီက credit သုံးပြီး ပမာဏက service ပေါ်မူတည်ပါတယ်၊ တစ်ခုချင်းစီရဲ့ ကုန်ကျစရိတ်ကို Pricing page မှာ စာရင်းပြထားပါတယ်။

၂။ multipart/form-data body

Generation endpoint တွေက သူတို့ရဲ့ text parameter တွေကို form field အဖြစ် လက်ခံပါတယ်။ Stable Image Core မှာ prompt တစ်ခုပဲ မဖြစ်မနေလိုပါတယ်။ Optional field တွေမှာ aspect_ratio၊ negative_prompt၊ seed၊ style_preset နဲ့ output_format ပါပြီး output_format က png၊ jpeg ဒါမှမဟုတ် webp ဖြစ်နိုင်ကာ default က png ပါ။ curl မှာ -F name=value လို့ရေးပြီး JavaScript မှာတော့ FormData object တည်ဆောက်ကာ fetch ကို boundary ပါတဲ့ Content-Type ထည့်ခိုင်းပါ။

၃။ Accept က reply format ကို ရွေးတယ်

output_format ပေးထားတဲ့ ပုံစံနဲ့ ပုံ byte တွေ ရဖို့ Accept: image/* ကို ပို့ပါ။ image field ထဲမှာ base64 အဖြစ် encode လုပ်ထားတဲ့ ပုံနဲ့ seed၊ finish_reason ပါတဲ့ JSON ရဖို့ Accept: application/json ကို ပို့ပါ။ Base64 က byte သုံးခုတိုင်းကို စာလုံးလေးလုံးဖြစ်စေလို့ JSON လမ်းကြောင်းက data ကို သုံးပုံတစ်ပုံလောက် ပိုရွှေ့ပါတယ်။

၄။ finish-reason: အောင်မြင် ဒါမှမဟုတ် filter ခံရ

Binary reply တွေမှာ seed နဲ့ finish-reason ကို response header အဖြစ်၊ JSON reply တွေမှာ seed နဲ့ finish_reason ကို field အဖြစ် ပါပါတယ်။ SUCCESS က ပုံမှန်ပုံပါ။ CONTENT_FILTERED ဆိုတာ generate လုပ်လို့ရပေမယ့် output က content moderation policy ကို ချိုးဖောက်ပြီး blur လုပ်ထားတာမို့ ပုံကို မပြခင် မသိမ်းခင် စစ်ပါ။

၅။ Error တွေက name နဲ့ စာရင်းပါတဲ့ JSON ပါ

Failure က id၊ စက်ဖတ်လို့ရတဲ့ name နဲ့ လူဖတ်လို့ရတဲ့ string တွေပါတဲ့ errors စာရင်း ပါတဲ့ JSON ပြန်ပါတယ်။ ဥပမာ name bad_request နဲ့ errors ["prompt: is required"] ပါ။ ပုံ byte တောင်းထားရင်တောင် error က JSON ဖြစ်လို့ body ကို ပုံအဖြစ် မသဘောထားခင် res.ok ကို စစ်ပါ။

Statusအဓိပ္ပာယ်လုပ်ရမယ့်အရာ
400Parameter မမှန်errors ကိုဖတ်ပြီး form ကိုပြင်
403Moderation က flag လုပ်Prompt တူတူကို retry မလုပ်ပါနဲ့
413Request body ကြီးလွန်းပိုသေးတဲ့ input ပို့
422Process မလုပ်နိုင်Input ပုံကို စစ်
429Rate limit ကျော်Backoff လုပ်ပြီး retry
500Server ဘက်ပြဿနာRetry ပြီး support ကို ဆက်သွယ်
Mental model: အော်ဒါ form၊ ပြီးရင် ပါဆယ်ကို စစ်
  1. Form field တွေက ပုံကို ဖော်ပြ
  2. Accept က byte ဒါမှမဟုတ် base64 ကို ရွေး
  3. Status ကိုစစ်ပြီး byte ကို စစ်
  4. လုံခြုံတဲ့နေရာ သိမ်းပြီးမှ သုံး

အောင်မြင်တဲ့ HTTP status က call အလုပ်လုပ်တယ်လို့ပဲ ပြောပါတယ်။ Byte တွေက ကိုယ်မျှော်တာဖြစ်ကြောင်း မပြောပါဘူး၊ အဲဒါကို signature နဲ့ finish reason ကပဲ ပြောနိုင်ပါတယ်။

အခြေခံ ပုံစံ

bash
curl -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
  -H "Authorization: Bearer $STABILITY_API_KEY" \
  -H "Accept: image/*" \
  -F "prompt=<prompt>" \
  -F "output_format=<png|jpeg|webp>" \
  --output <file-name>

-F တစ်ခုစီက form field တစ်ခုဖြစ်ပြီး --output က reply ကို သိမ်းပါတယ်။ Angle bracket ပါတဲ့ အပိုင်းတွေက placeholder ပါ။ ပုံဥပမာပါ၊ လက်ရှိ docs ကို စစ်ပြီး ကိုယ့် key ကို environment variable ထဲ ထားပါ။

Binary နဲ့ JSON reply တွေ၊ ပြီးရင် byte တွေကို စစ်ခြင်း

Mock server က multipart form ကို parse လုပ်ပြီး docs ပါ shape တွေနဲ့ ဖြေပါတယ်။ seed နဲ့ finish-reason header ပါတဲ့ raw PNG byte၊ ဒါမှမဟုတ် base64 ပုံပါတဲ့ JSON၊ ပြီးတော့ id၊ name၊ errors စာရင်းပါတဲ့ JSON error တွေပါ။ Client က form တူတူကို Accept တန်ဖိုးတစ်ခုစီနဲ့ နှစ်ကြိမ်ပို့၊ reply တစ်ခုစီရဲ့ ပထမ byte တွေကိုစစ်၊ file ကို temporary directory ထဲရေးပြီး အဆုံးမှာ directory ကို ဖျက်ပါတယ်။

stability-client.mjs
import http from "node:http";
import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const KEY = "sk-demo-stability-key";
// A real 1x1 PNG, so the byte checks below have something genuine to inspect.
const PNG_BASE64 =
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAC" +
  "hwGA60e6kgAAAABJRU5ErkJggg==";
const PNG = Buffer.from(PNG_BASE64, "base64");

// Mock server: same SHAPE as POST /v2beta/stable-image/generate/core.
const server = http.createServer((req, res) => {
  const chunks = [];
  req.on("data", (chunk) => chunks.push(chunk));
  req.on("end", async () => {
    const fail = (status, name, errors) => {
      res.writeHead(status, { "content-type": "application/json" });
      res.end(JSON.stringify({ id: "demo", name, errors }));
    };
    if (req.headers.authorization !== "Bearer " + KEY) {
      return fail(401, "unauthorized", ["invalid or missing API key"]);
    }
    const contentType = req.headers["content-type"] ?? "";
    const form = await new Response(Buffer.concat(chunks), {
      headers: { "content-type": contentType },
    }).formData();
    const prompt = form.get("prompt");
    if (!prompt) return fail(400, "bad_request", ["prompt: is required"]);
    if (prompt === "forbidden") {
      return fail(403, "content_moderation", ["flagged by content moderation"]);
    }
    const finish = prompt === "borderline" ? "CONTENT_FILTERED" : "SUCCESS";
    if ((req.headers.accept ?? "").includes("application/json")) {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(
        JSON.stringify({ image: PNG.toString("base64"), seed: 7, finish_reason: finish }),
      );
    }
    res.writeHead(200, {
      "content-type": "image/png",
      seed: "7",
      "finish-reason": finish,
    });
    res.end(PNG);
  });
});

// Client: multipart request, Accept header chooses binary or base64 JSON.
async function generate(base, fields, accept) {
  const form = new FormData();
  for (const [name, value] of Object.entries(fields)) form.append(name, value);
  const res = await fetch(base + "/v2beta/stable-image/generate/core", {
    method: "POST",
    headers: { authorization: "Bearer " + KEY, accept },
    body: form, // fetch adds the multipart boundary itself
  });
  if (!res.ok) {
    const err = await res.json();
    throw new Error(res.status + " " + err.name + ": " + err.errors.join(", "));
  }
  if (accept === "application/json") {
    const data = await res.json();
    return { bytes: Buffer.from(data.image, "base64"), finish: data.finish_reason };
  }
  const bytes = Buffer.from(await res.arrayBuffer());
  return { bytes, finish: res.headers.get("finish-reason") };
}

// Never trust a file extension or a content-type: look at the first bytes.
function sniff(bytes) {
  if (bytes.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47]))) return "png";
  if (bytes.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return "jpeg";
  const riff = bytes.subarray(0, 4).toString() === "RIFF";
  if (riff && bytes.subarray(8, 12).toString() === "WEBP") return "webp";
  return null;
}

await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;
const dir = await mkdtemp(join(tmpdir(), "stability-demo-"));

const fields = { prompt: "Myanmar landscape at sunrise", aspect_ratio: "16:9" };
for (const accept of ["image/*", "application/json"]) {
  const { bytes, finish } = await generate(base, fields, accept);
  const kind = sniff(bytes);
  if (!kind) throw new Error("the reply is not an image");
  const file = join(dir, "out." + kind);
  await writeFile(file, bytes);
  const size = (await stat(file)).size;
  console.log(accept, "->", kind, size, "bytes, finish:", finish);
}

const filtered = await generate(base, { prompt: "borderline" }, "image/*");
console.log("filtered image finish:", filtered.finish, "(blurred, do not publish)");

for (const body of [{ aspect_ratio: "1:1" }, { prompt: "forbidden" }]) {
  try {
    await generate(base, body, "image/*");
  } catch (err) {
    console.log("error:", err.message);
  }
}
await rm(dir, { recursive: true });
server.close();

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. A form, not JSONfor (const [name, value] of Object.entries(fields)) form.append(name, value);

    Field တစ်ခုချင်းစီက multipart body ရဲ့ အပိုင်းတစ်ခု ဖြစ်လာပါတယ်။ aspect_ratio လို field တစ်ခုထည့်ချင်ရင် fields object ထဲ key တစ်ခု ထပ်ထည့်ရုံပါပဲ။

  2. No hand-written Content-Typebody: form, // fetch adds the multipart boundary itself

    fetch က FormData body ကိုမြင်ပြီး boundary မှန်မှန်ပါတဲ့ Content-Type ကို ရေးပေးပါတယ်။ အဲဒီ header ကို ကိုယ်တိုင်သတ်မှတ်ရင် server က အပိုင်းတွေကို ခွဲလို့မရတော့ပါဘူး။

  3. Status before bodyif (!res.ok) {

    400 နဲ့ 403 reply တွေက request က ပုံ byte တောင်းထားပေမယ့် JSON ဖြစ်လို့ arrayBuffer() ကို မခေါ်ခင် error branch ကို အရင် run ပါတယ်။

  4. Binary: arrayBufferconst bytes = Buffer.from(await res.arrayBuffer());

    Binary data ကို arrayBuffer() နဲ့ဖတ်ပါတယ်၊ text() ဒါမှမဟုတ် json() နဲ့ မဖတ်ပါဘူး၊ အဲဒါတွေက ပျက်စီးစေ ဒါမှမဟုတ် ပယ်ချမှာပါ။ Finish reason ကို finish-reason header ကနေ ရပါတယ်။

  5. JSON: decode base64return { bytes: Buffer.from(data.image, "base64"), finish: data.finish_reason };

    image field က base64 စာသားကို ကိုင်ထားပါတယ်။ Decode လုပ်ရင် binary လမ်းကြောင်းနဲ့ 70 byte တူတူ ရပြီး Accept တန်ဖိုးနှစ်ခုလုံးအတွက် output က အတည်ပြုပါတယ်။

  6. Sniff the signatureif (bytes.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47]))) return "png";

    PNG က byte 89 50 4E 47 နဲ့ အမြဲစပါတယ်။ သိမ်းတဲ့ file နာမည်က request ဒါမှမဟုတ် reply header က စာသားမဟုတ်ဘဲ detect လုပ်ထားတဲ့ အမျိုးအစားကို သုံးပါတယ်။

You should see
image/* -> png 70 bytes, finish: SUCCESS
application/json -> png 70 bytes, finish: SUCCESS
filtered image finish: CONTENT_FILTERED (blurred, do not publish)
error: 400 bad_request: prompt: is required
error: 403 content_moderation: flagged by content moderation

curl နဲ့ call တူတူ

Command နှစ်ခုစလုံး ပုံဥပမာပါ။ လက်ရှိ docs ကို စစ်ပြီး ကိုယ့် key ကို STABILITY_API_KEY ထဲ သုံးပါ။ -f flag က error body ကို ပုံအဖြစ် မသိမ်းဘဲ curl ကို error နဲ့ ထွက်စေပြီး -sS က progress meter ကိုဖျောက်ပေမယ့် error message တွေ ထားပါတယ်။ ဒုတိယ command က JSON တောင်းပြီး image field ကို jq နဲ့ base64 သုံးပြီး decode လုပ်ပါတယ်။

bash
# Illustrative - check the current docs, and use your own key in STABILITY_API_KEY.
# -f: exit with an error instead of saving the API error body as sunrise.png.
curl -sS -f -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
  -H "Authorization: Bearer $STABILITY_API_KEY" \
  -H "Accept: image/*" \
  -F "prompt=Myanmar landscape at sunrise" \
  -F "aspect_ratio=16:9" \
  -F "output_format=png" \
  --output sunrise.png
bash
# Illustrative: ask for JSON instead, then decode the base64 field yourself.
curl -sS -f -X POST "https://api.stability.ai/v2beta/stable-image/generate/core" \
  -H "Authorization: Bearer $STABILITY_API_KEY" \
  -H "Accept: application/json" \
  -F "prompt=Myanmar landscape at sunrise" \
  -o response.json
jq -r '.finish_reason' response.json
jq -r '.image' response.json | base64 --decode > sunrise.png

ထုတ်ထားတဲ့ file တွေကို လုံခြုံစွာ သိမ်းခြင်း

ထုတ်ပေးတဲ့ media က network service တစ်ခုက ရတဲ့ byte တွေမို့ user upload နဲ့ တူတဲ့ ဂရုစိုက်မှု ပေးပါ။

  • File နာမည်ကို prompt စာသားနဲ့ မဟုတ်ဘဲ ကိုယ်ထုတ်တဲ့ id နဲ့ detect လုပ်ထားတဲ့ အမျိုးအစားကနေ ကိုယ်တိုင်တည်ဆောက်ပါ။
  • လက်ခံမယ့် အရွယ်အစားကို ကန့်သတ်ပြီး file တွေကို web server ထုတ်ပြန်တဲ့ directory ပြင်ပမှာ သိမ်းပါ။
  • File ကို ပြန်ပေးတဲ့အခါ detect လုပ်ထားတဲ့ content type နဲ့ X-Content-Type-Options: nosniff ကို ပို့ပါ။
  • Seed နဲ့ finish reason ကို record နဲ့အတူ ထားပါ၊ ဒါမှ ရလဒ်ကို ပြန်ထုတ်လို့ရပြီး filter ခံရတာကို ဖျောက်လို့ရပါမယ်။

Credit၊ limit နဲ့ moderation

အောင်မြင်တဲ့ request တိုင်းက credit သုံးတာမို့ bug ပါတဲ့ loop တစ်ခုက ငွေတောင်းခံလွှာ ဖြစ်သွားပါတယ်။ API က မည်သည့် စက္ကန့် 10 ကာလမှာမဆို request 150 အထိ ခွင့်ပြုပြီး ကျော်ရင် 429 ပြန်ကာ စက္ကန့် 60 ကြာ ကိုယ့် request တွေကို ပိတ်ပါတယ်၊ ဒါကြောင့် 429 ကို တုံ့ပြန်တာထက် ကိုယ့် back end ထဲက မျှဝေသုံး limiter က ပိုလုံခြုံပါတယ်။ Moderation ကနေ 403 ဒါမှမဟုတ် CONTENT_FILTERED reply ဆိုတာ prompt ဒါမှမဟုတ် ရလဒ်က policy ကိုချိုးတာမို့ prompt တူတူကို ထပ်လုပ်လည်း မပြောင်းပါဘူး။ အဲဒီအခါ ကိုယ့် product က ဘာပြမလဲ၊ ထုတ်ထားတဲ့ပုံတွေအတွက် copyright နဲ့ privacy policy က ဘာပြောလဲ ကြိုဆုံးဖြတ်ထားပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project မှာ ဘယ်လိုသုံးမလဲ

Staff တွေက banner ပုံတွေထုတ်တဲ့ marketing tool တစ်ခုကို မြင်ကြည့်ပါ။ Browser က Stability key ကို ဘယ်တော့မှ မမြင်ရပါဘူး။ ကိုယ့် endpoint ကို ခေါ်ပြီး endpoint က sign in ဝင်ထားတဲ့ user နဲ့ user တစ်ယောက်ချင်းစီရဲ့ နေ့စဉ် quota ကို စစ်ပြီးမှ Stability ကို ခေါ်ပါတယ်။ Endpoint က Accept: image/* ပို့၊ status ကိုစစ်၊ signature နဲ့ finish reason ကိုစစ်ပြီး file ကို သူထုတ်တဲ့ နာမည်နဲ့ seed နဲ့ prompt အတူ object storage ထဲ သိမ်းပါတယ်။

403 ဒါမှမဟုတ် CONTENT_FILTERED ရလဒ်ဆိုရင် ပျက်နေတဲ့ပုံအစား ရှင်းလင်းတဲ့ message ကို user ကိုပြပါတယ်။ 429 ကို နှောင့်နှေးချိန်နဲ့ queue ပေါ်ပြန်တင်ပါတယ်။ Test တွေက binary success၊ JSON error၊ moderation rejection၊ 429၊ ကြီးလွန်းတဲ့ body နဲ့ content type မှားတဲ့ reply ကို ပြန်ပေးတဲ့ mock endpoint ကိုသုံးလို့ တကယ့် user က လမ်းကြောင်းတစ်ခုကို မလှုပ်ရှားခင်မှာ လမ်းကြောင်းတိုင်း run ပြီးသား ဖြစ်ပါတယ်။

အမှားများ

မကြာခဏ လုပ်မိတတ်တဲ့ အမှားတွေ

Broken-image bug အားလုံးလိုလိုကို အမှားလေးခုက ဖြစ်စေပါတယ်။

Binary success ပေါ် res.json() ခေါ်ခြင်း

Accept: image/* နဲ့ဆို အောင်မြင်တဲ့ body က ပုံ byte တွေမို့ res.json() က ပစ်ပါတယ်။ arrayBuffer() နဲ့ဖတ်ပါ၊ ဒါမှမဟုတ် application/json တောင်းပြီး image field ကို ကိုယ်တိုင် decode လုပ်ပါ။

Reply အားလုံးကို ပုံ file ထဲ သိမ်းခြင်း

curl --output ရိုးရိုးက ရောက်လာတာ ဘာမဆို၊ JSON error body အပါအဝင် ရေးပါတယ်။ Script တွေမှာ -f ကိုသုံးပြီး code မှာ file ကို မထိခင် res.ok နဲ့ ခွဲပါ။

File နာမည် ဒါမှမဟုတ် content type ကို ယုံခြင်း

နှစ်ခုစလုံးက မှားနိုင်တဲ့ တံဆိပ်တွေပါ။ File ရဲ့ ပထမ byte တွေကိုစစ်၊ အရွယ်အစားကို ကန့်သတ်ပြီး သိမ်းတဲ့ file ကို ကိုယ်တိုင် နာမည်ပေးပါ။

Multipart request မှာ Content-Type ကို ကိုယ်တိုင် သတ်မှတ်ခြင်း

boundary မပါဘဲ Content-Type: multipart/form-data လို့ ရေးရင် server က ကိုယ့် field တွေကို မဖတ်နိုင်ဘဲ 400 ရပါတယ်။ FormData body ကိုပေးပြီး header ကို fetch ကို သတ်မှတ်ခိုင်းပါ။

Best Practices

ထိန်းသိမ်းသင့်တဲ့ အလေ့အကျင့်တွေ

  • Call တိုင်းရဲ့ status၊ finish reason နဲ့ seed ကို log မှတ်ပါ၊ key ကိုတော့ ဘယ်တော့မှ မမှတ်ပါနဲ့။
  • သိမ်းဆည်းတဲ့ pipeline တွေအတွက် binary reply ကို၊ ပုံက တခြား JSON document ထဲမှာ သွားရတဲ့အခါ JSON reply ကို ဦးစားပေးပါ။
  • Generation ကို မျှဝေသုံး rate limiter ပါတဲ့ queue နောက်မှာထားပါ၊ ဒါမှ burst တစ်ခုက 429 block ကို မရောက်ပါလိမ့်မယ်။

Mini challenge

Reply checker တည်ဆောက်ပါ

ပုံ reply တွေအတွက် checkReply(res) ကိုရေးပါ။ Content-type အလိုက် body ကို base64 JSON အဖြစ် ဒါမှမဟုတ် raw byte အဖြစ်ဖတ်၊ CONTENT_FILTERED finish reason ကို ပယ်၊ 100 byte ထက်ကြီးတဲ့ body ကို ပယ်၊ PNG၊ JPEG ဒါမှမဟုတ် WebP ကို signature နဲ့ detect လုပ်ပြီး png (70 bytes) လို စာသားပြန်ပေးပါ။ ရိုးသားတဲ့ binary path၊ JSON path၊ filtered path၊ လိမ်တဲ့ path နဲ့ huge path ပါတဲ့ port 0 ပေါ်က mock server နဲ့ သက်သေပြပါ။

  • Content-type မှာ json ပါရင် image field ကို base64 ကနေ decode လုပ်ပါ
  • Header ဖြစ်ဖြစ် JSON field ဖြစ်ဖြစ် CONTENT_FILTERED ကို ပယ်ပါ
  • ပထမ byte တွေကနေ format ကို detect လုပ်ပြီး ပုံမဟုတ်တာ ဘာမဆို ပယ်ပါ
  • Byte ကန့်သတ်ချက်ကျော်တဲ့ body တွေကို ဂဏန်းနှစ်ခုလုံးပြတဲ့ message နဲ့ ပယ်ပါ
check-reply.mjs
import http from "node:http";

const MAX_BYTES = 100;

function detect(bytes) {
  // TODO 1: look at the first bytes and return "png" (89 50 4E 47), "jpeg" (FF D8 FF)
  //   or "webp" ("RIFF" at 0-3 and "WEBP" at 8-11); return null for anything else
  return null;
}

async function checkReply(res) {
  // TODO 2: if the content-type contains "json", read { image, finish_reason } and
  //   decode image from base64; otherwise read the body bytes and the
  //   finish-reason response header
  // TODO 3: throw "CONTENT_FILTERED" when the finish reason says so
  // TODO 4: throw "<n> bytes is over the 100 byte limit" for a body over MAX_BYTES
  // TODO 5: throw "not a PNG, JPEG or WebP image" when detect() finds nothing
  // TODO 6: return a text such as "png (70 bytes)"
  return "";
}

// TODO 7: start a mock server on port 0 with five paths: /binary (a real PNG),
//   /json (the same PNG as base64), /filtered (a PNG with the CONTENT_FILTERED
//   header), /liar (HTML sent as image/png) and /huge (a PNG followed by 200 zero bytes)
//   A 1x1 PNG in base64, to be joined into one string:
//   iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAC
//   hwGA60e6kgAAAABJRU5ErkJggg==

// TODO 8: request every path, print "<path> -> accepted <result>" or
//   "<path> -> refused: <message>", then close the server

ရလဒ်: စာကြောင်းငါးကြောင်း ထွက်ပါမယ်။ /binary နဲ့ /json က png (70 bytes) အဖြစ် လက်ခံ၊ /filtered ကို CONTENT_FILTERED နဲ့ ပယ်၊ /liar ကို ပုံမဟုတ်လို့ ပယ်၊ /huge ကို 100 byte ကန့်သတ်ချက်ကျော်တဲ့ 270 byte ဖြစ်လို့ ပယ်ပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

Finish reason ကို size နဲ့ signature မစစ်ခင် အရင်ဖတ်ပါ။ Buffer.toString("latin1", 0, 4) က RIFF marker ကိုပေးပြီး Array.prototype.every က signature array ကို ပထမ byte တွေနဲ့ နှိုင်းယှဉ်ပေးပါတယ်။

အဖြေ ကြည့်ရန်
check-reply.mjs
import http from "node:http";

const PNG = Buffer.from(
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAC" +
    "hwGA60e6kgAAAABJRU5ErkJggg==",
  "base64",
);
const MAX_BYTES = 100;

// The first bytes of a file say what it really is, whatever the name or header claims.
const MAGIC = { png: [0x89, 0x50, 0x4e, 0x47], jpeg: [0xff, 0xd8, 0xff] };
function detect(bytes) {
  for (const [kind, magic] of Object.entries(MAGIC)) {
    if (magic.every((value, i) => bytes[i] === value)) return kind;
  }
  const head = bytes.toString("latin1", 0, 4);
  if (head === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP") return "webp";
  return null;
}

async function checkReply(res) {
  const isJson = (res.headers.get("content-type") ?? "").includes("json");
  const body = isJson ? await res.json() : null;
  const raw = body ? body.image : await res.arrayBuffer();
  const bytes = body ? Buffer.from(raw, "base64") : Buffer.from(raw);
  const finish = body ? body.finish_reason : res.headers.get("finish-reason");
  if (finish === "CONTENT_FILTERED") throw new Error("CONTENT_FILTERED");
  if (bytes.length > MAX_BYTES) {
    throw new Error(bytes.length + " bytes is over the " + MAX_BYTES + " byte limit");
  }
  const kind = detect(bytes);
  if (!kind) throw new Error("not a PNG, JPEG or WebP image");
  return kind + " (" + bytes.length + " bytes)";
}

// Mock server: five replies, some of them dishonest.
const server = http.createServer((req, res) => {
  const send = (type, body, extra = {}) => {
    res.writeHead(200, { "content-type": type, ...extra });
    res.end(body);
  };
  if (req.url === "/binary") return send("image/png", PNG);
  if (req.url === "/json") {
    const image = PNG.toString("base64");
    return send("application/json", JSON.stringify({ image, finish_reason: "SUCCESS" }));
  }
  if (req.url === "/filtered") {
    return send("image/png", PNG, { "finish-reason": "CONTENT_FILTERED" });
  }
  if (req.url === "/liar") return send("image/png", "<html>sorry</html>");
  send("image/png", Buffer.concat([PNG, Buffer.alloc(200)]));
});
await new Promise((resolve) => server.listen(0, resolve));

const base = "http://127.0.0.1:" + server.address().port;
for (const path of ["/binary", "/json", "/filtered", "/liar", "/huge"]) {
  try {
    console.log(path, "-> accepted", await checkReply(await fetch(base + path)));
  } catch (err) {
    console.log(path, "-> refused:", err.message);
  }
}
server.close();

Quick Quiz 1 / 3

Accept: image/* ပို့ပြီး call အောင်မြင်ပါတယ်။ await res.json() က ဘာဖြစ်မလဲ။

Quick Quiz 2 / 3

Reply က HTTP 200 ဖြစ်ပြီး finish-reason header က CONTENT_FILTERED လို့ ပြောပါတယ်။ ဘာကိုဆိုလိုတာလဲ။

Quick Quiz 3 / 3

.png file နာမည်ကို မယုံဘဲ reply ရဲ့ ပထမ byte တွေကို ဘာကြောင့် စစ်သလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Request က Bearer key နဲ့ prompt တစ်ခုတည်း မဖြစ်မနေလိုတဲ့ multipart/form-data body ပါတဲ့ POST /v2beta/stable-image/generate/core ပါ။
  • Accept: image/* က raw byte၊ Accept: application/json က image field ထဲက base64 ကိုပြန်ပေးပြီး တစ်ခုစီကို နည်းလမ်းမှန်နဲ့ ဖတ်ပါ။
  • Store ဒါမှမဟုတ် ပြမခင် res.ok ကို အရင်၊ ပြီးရင် finish-reason၊ ပြီးရင် file ရဲ့ ပထမ byte တွေကို စစ်ပါ။
  • Error တွေက id၊ name၊ errors ပါတဲ့ JSON ပါ။ 429 က စက္ကန့် 10 အတွင်း request 150 ကျော်တာနဲ့ စက္ကန့် 60 block ဆိုတဲ့ အဓိပ္ပာယ်ပါ။

Stability AI — API Reference — Stability AI

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Stability AI (Images) | Thuta Learning