ストリーミング
量の多い皿は、スキャンに1分近くかかることがあります。リクエストに "stream": true を追加すると、同じ呼び出しがすぐに text/event-stream で応答を始めます。写真に写っているアイテムは約10〜15秒後に届き、完全な結果は準備ができた時点で続けて届きます。数値を読み込んでいる間に、アイテムをユーザーに見せられます。
bash
curl -N https://platform-api.nutriscan.app/v1/scans \
-H "Authorization: Bearer $NUTRISCAN_KEY" \
-H "Content-Type: application/json" \
-d '{ "type": "meal", "image_url": "https://example.com/lunch.jpg", "stream": true }'ストリームは次のようになります。
text
event: scan.started
data: {"id":"scn_8Kd2…","status":"processing"}
event: items.detected
data: {"id":"scn_8Kd2…","dish_name":"Tofu salad bowl","items":[{"name":"Tofu","portion":"100 g"}, …]}
: ping
event: scan.completed
data: { …the same JSON as a normal response… }イベント
| イベント | タイミング | データ |
|---|---|---|
scan.started | すぐに | スキャンの id です。保存しておいてください。接続が切れてもスキャンは最後まで完了し、GET /v1/scans/{id} で取得できます。 |
items.detected | 約10〜15秒後 | dish_name と、name と portion を持つ items です。最初の見立てにあたり、最終結果ではアイテムの名前の変更、追加、削除が起こることがあります。 |
scan.completed | 完了時 | 完全な結果です。ストリーミングなしの場合と同じJSONです。 |
error | scan.completed の代わりに | {"status": 422 or 500, "error": {"code", "message"}} です。たとえば no_food_detected があります。 |
: ping | 15秒ごと | 接続を保つためのコメント行です。無視してください。 |
通常のJSONで返るもの
スキャンが始まる前に見つかったエラーは、ストリームではなく、ステータスコード付きの通常のJSONエラーとして返ります。キーの誤り、ボディの誤り、レート制限、クレジット不足などが該当します。イベントを読み始める前に、レスポンスのステータスと Content-Type を確認してください。
ストリーミングのスキャンは最長で140秒かかることがあり、使うクレジットは通常の呼び出しと同じです。
コードでストリームを読む
ブラウザの EventSource は GET にしか対応していないため、レスポンスのボディを自分で読みます。次の例はサーバー上で動かします。
js
const resp = await fetch("https://platform-api.nutriscan.app/v1/scans", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.NUTRISCAN_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ type: "meal", image_url: "https://example.com/lunch.jpg", stream: true }),
signal: AbortSignal.timeout(150_000), // a streamed scan can run up to 140 seconds
});
if (!resp.headers.get("content-type")?.startsWith("text/event-stream")) {
throw new Error((await resp.json()).error.code); // rejected before the scan started
}
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of resp.body) {
buffer += decoder.decode(chunk, { stream: true });
let end;
while ((end = buffer.indexOf("\n\n")) !== -1) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = block.match(/^event: (.+)$/m)?.[1];
const data = block.match(/^data: (.+)$/m)?.[1];
if (!event || !data) continue; // ": ping" comments land here
const payload = JSON.parse(data);
if (event === "items.detected") console.log("Items:", payload.items.map((i) => i.name));
if (event === "scan.completed") console.log("Done:", payload.meal.totals.calories, "kcal");
if (event === "error") console.error(payload.status, payload.error.code);
}
}python
import json, os, requests
resp = requests.post(
"https://platform-api.nutriscan.app/v1/scans",
headers={"Authorization": f"Bearer {os.environ['NUTRISCAN_KEY']}"},
json={"type": "meal", "image_url": "https://example.com/lunch.jpg", "stream": True},
stream=True,
timeout=150, # a streamed scan can run up to 140 seconds
)
if not resp.headers.get("content-type", "").startswith("text/event-stream"):
raise RuntimeError(resp.json()["error"]["code"]) # rejected before the scan started
event = None
for line in resp.iter_lines(decode_unicode=True):
if line.startswith("event: "):
event = line[7:]
elif line.startswith("data: ") and event:
payload = json.loads(line[6:])
if event == "items.detected":
print("Items:", [i["name"] for i in payload["items"]])
elif event == "scan.completed":
print("Done:", payload["meal"]["totals"]["calories"], "kcal")
elif event == "error":
print("Error:", payload["status"], payload["error"]["code"])ストリームが切れたらどうなりますか?
スキャンはNutriScan側で動き続け、2回目の課金はありません。scan.started で受け取った id を保存しておき、少し待ってから GET /v1/scans/{id} を呼ぶと、完了した結果を取得できます。
ストリーミングはどんなときに使いますか?
人が画面の前で結果を待つときはストリーミング、バックグラウンドのジョブには通常の呼び出しを使います。
- 人が画面で待っているときに使ってください。検出されたアイテムが表示されるので待ち時間に見るものができ、間違ったアイテムにも早く気づけます。
- バックグラウンドのジョブでは使わないでください。タイムアウトを100秒にした通常の呼び出しのほうが簡単です。
関連ページ:リクエストの全フィールドはスキャンの作成、scan.completed のフィールドは結果、クレジットの消費は栄養APIの料金、全体像は栄養APIの概要をご覧ください。