Skip to content

स्ट्रीमिंग ​

बड़ी प्लेट के स्कैन में एक मिनट लग सकता है। रिक्वेस्ट में "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 और items, जिनमें name और portion होते हैं। यह पहली झलक है: अंतिम नतीजा आइटम का नाम बदल सकता है, जोड़ सकता है या हटा सकता है।
scan.completedपूरा होने परपूरा नतीजा, वही JSON जो स्ट्रीम के बिना मिलता है।
errorscan.completed की जगह{"status": 422 or 500, "error": {"code", "message"}}, जैसे no_food_detected।
: pingहर 15 सेकंड मेंएक कमेंट लाइन जो कनेक्शन खुला रखती है। इसे अनदेखा करें।

फिर भी सादे JSON में क्या आता है ​

स्कैन शुरू होने से पहले पकड़ी गई एरर स्ट्रीम की जगह अपने स्टेटस कोड के साथ सामान्य JSON एरर के रूप में आती हैं: गलत key, गलत बॉडी, रेट लिमिट या क्रेडिट कम होना। इवेंट पढ़ना शुरू करने से पहले रिस्पॉन्स का स्टेटस और 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"])

स्ट्रीम टूट जाए तो क्या होता है? ​

स्कैन हमारी तरफ चलता रहता है और आपसे दूसरी बार पैसे नहीं लिए जाते। scan.started की id रख लें, थोड़ा रुकें, फिर तैयार नतीजा लेने के लिए GET /v1/scans/{id} कॉल करें।

स्ट्रीमिंग कब इस्तेमाल करें? ​

जब कोई व्यक्ति स्क्रीन पर नतीजे का इंतज़ार कर रहा हो तब स्ट्रीमिंग इस्तेमाल करें, और बैकग्राउंड जॉब के लिए सादी कॉल।

  • जब कोई व्यक्ति स्क्रीन पर इंतज़ार कर रहा हो तब इसे इस्तेमाल करें। पहचाने गए आइटम उन्हें देखने को कुछ देते हैं, और कोई गलत आइटम वे जल्दी पकड़ सकते हैं।
  • बैकग्राउंड जॉब के लिए इसे छोड़ दें। 100 सेकंड के टाइमआउट वाली सादी कॉल ज़्यादा आसान है।

संबंधित पेज: रिक्वेस्ट के हर फील्ड के लिए स्कैन बनाएं, scan.completed के फील्ड के लिए नतीजा, क्रेडिट की लागत के लिए न्यूट्रिशन API की कीमतें और न्यूट्रिशन API ओवरव्यू।