AWS SDK AI Examples: Rekognition Image Labels आणि Bedrock Text Generation (Python, PHP, Node.js)
AWS कडे तयार AI आहे जे इतर API सारखं call करता येतं. Python, PHP आणि Node.js मधून Rekognition ने photos मधले labels व text ओळखू, uploads moderate करू, आणि Amazon Bedrock Converse API ने text generate करू, streaming सह. Example: Milan मधली Giulia आणि कोचीची Meera यांचं second-hand marketplace.
या chapter मध्ये तुम्ही काय शिकाल
- Image मधले labels
- Text वाचा व content moderate
- Bedrock Converse call
- Model output stream
- Cost व safety
1. मोठं चित्र: shop assistant
हे का लागतं?
Seller bicycle चा photo upload करतो. एक assistant पाहून सांगतो "bicycle, wheel, outdoor". दुसरा छान listing लिहितो: "थोडी वापरलेली city bike, €180". Rekognition पहिला, Bedrock दुसरा.
हे काय आहे?
Rekognition Image (bytes किंवा S3Object) घेतो आणि Confidence सह labels देतो. Bedrock Converse modelId व messages घेतो आणि reply व token usage देतो. आधी Bedrock console मध्ये model access चालू करा.
कसं करायचं (step by step)
2. Labels detect करा
हे का लागतं?
Buyers "bicycle" किंवा "sofa" शोधू शकतील म्हणून Giulia ला प्रत्येक photo tag हवा.
हे काय आहे?
MaxLabels व MinConfidence सह DetectLabels. S3 मधल्या photos साठी S3Object (same region).
कसं करायचं (step by step)
- Python.
import boto3
rk = boto3.client("rekognition", region_name="eu-west-1")
r = rk.detect_labels(Image={"S3Object": {"Bucket": "market-photos-mi", "Name": "bike-221.jpg"}},
MaxLabels=5, MinConfidence=80)
for l in r["Labels"]: print(l["Name"], round(l["Confidence"]))
अपेक्षित output:
Bicycle 99
Wheel 98
Vehicle 97
Outdoors 88
City 82
- Node.js: local bytes मधून.
import { readFileSync } from "node:fs";
import { RekognitionClient, DetectLabelsCommand } from "@aws-sdk/client-rekognition";
const rk = new RekognitionClient({ region: "ap-south-1" });
const r = await rk.send(new DetectLabelsCommand({ Image: { Bytes: readFileSync("sofa-88.jpg") }, MaxLabels: 3 }));
console.log(r.Labels.map(l => l.Name).join(", "));
अपेक्षित output:
Couch, Furniture, Living Room
- PHP.
<?php
require "vendor/autoload.php";
$rk = new Aws\Rekognition\RekognitionClient(["region" => "eu-west-1"]);
$r = $rk->detectLabels(["Image" => ["Bytes" => file_get_contents("lamp.jpg")], "MaxLabels" => 2]);
echo implode(", ", array_column($r["Labels"], "Name")), PHP_EOL;
अपेक्षित output:
Lamp, Lampshade
- CLI ने verify.
aws rekognition detect-labels --image "S3Object={Bucket=market-photos-mi,Name=bike-221.jpg}" --max-labels 1 --region eu-west-1 --query "Labels[0].Name" --output text
अपेक्षित output:
Bicycle
3. Text वाचा आणि moderate
हे का लागतं?
Meera unsafe photos block करते आणि कोचीच्या मसाल्याच्या डब्याच्या photo मधला price tag वाचते: ₹350.
हे काय आहे?
DetectText LINE व WORD items देतो. DetectModerationLabels "Violence" सारख्या categories देतो; रिकामी list म्हणजे safe.
कसं करायचं (step by step)
- Python: text lines.
r = rk.detect_text(Image={"Bytes": open("tin.jpg", "rb").read()})
print([t["DetectedText"] for t in r["TextDetections"] if t["Type"] == "LINE"])
अपेक्षित output:
['KERALA PEPPER', 'MRP ₹350', '200 g']
- Node.js: moderation.
import { DetectModerationLabelsCommand } from "@aws-sdk/client-rekognition";
const r = await rk.send(new DetectModerationLabelsCommand({ Image: { Bytes: readFileSync("sofa-88.jpg") }, MinConfidence: 60 }));
console.log(r.ModerationLabels.length === 0 ? "safe" : r.ModerationLabels.map(m => m.Name));
अपेक्षित output:
safe
- PHP: upload handler मध्ये reject.
<?php
$m = $rk->detectModerationLabels(["Image" => ["Bytes" => file_get_contents($_FILES["p"]["tmp_name"])], "MinConfidence" => 70]);
if (count($m["ModerationLabels"])) { http_response_code(422); exit("Photo not allowed"); }
echo "accepted", PHP_EOL;
अपेक्षित output:
accepted
- Verify: test image.
aws rekognition detect-text --image-bytes fileb://tin.jpg --region ap-south-1 --query "TextDetections[?Type=='LINE'] | [1].DetectedText" --output text
अपेक्षित output:
MRP ₹350
4. Bedrock ने text generate
हे का लागतं?
Labels व price वरून English किंवा Italian मध्ये छोटी, प्रामाणिक listing.
हे काय आहे?
Converse प्रत्येक model साठी तोच request shape: messages, system, inferenceConfig. तुमच्या account मध्ये enabled model ID किंवा inference profile वापरा.
कसं करायचं (step by step)
- Python.
br = boto3.client("bedrock-runtime", region_name="eu-west-1")
r = br.converse(modelId="amazon.nova-lite-v1:0",
system=[{"text": "You write short marketplace listings. Max 25 words. No made-up facts."}],
messages=[{"role": "user", "content": [{"text": "Labels: Bicycle, City. Price €180. Condition: lightly used. Italian."}]}],
inferenceConfig={"maxTokens": 120, "temperature": 0.4})
print(r["output"]["message"]["content"][0]["text"]); print(r["usage"])
अपेक्षित output:
Bici da città poco usata, pronta per Milano. €180.
{'inputTokens': 41, 'outputTokens': 17, 'totalTokens': 58}
- Node.js.
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const br = new BedrockRuntimeClient({ region: "ap-south-1" });
const r = await br.send(new ConverseCommand({ modelId: "apac.amazon.nova-lite-v1:0",
messages: [{ role: "user", content: [{ text: "Write a 20-word listing: Couch, 3-seater, ₹9,500, Kochi pickup." }] }],
inferenceConfig: { maxTokens: 100 } }));
console.log(r.output.message.content[0].text);
अपेक्षित output:
Comfortable 3-seater couch in great shape. ₹9,500. Pickup in Kochi.
- PHP.
<?php
$br = new Aws\BedrockRuntime\BedrockRuntimeClient(["region" => "eu-west-1"]);
$r = $br->converse(["modelId" => "amazon.nova-lite-v1:0",
"messages" => [["role" => "user", "content" => [["text" => "One-line listing: Lamp, brass, £25, London."]]]],
"inferenceConfig" => ["maxTokens" => 60]]);
echo $r["output"]["message"]["content"][0]["text"], PHP_EOL;
अपेक्षित output:
Vintage brass lamp, warm light, £25 — collect in London.
- Verify: model access चालू.
aws bedrock list-foundation-models --region eu-west-1 --by-provider amazon --query "modelSummaries[?modelId=='amazon.nova-lite-v1:0'].modelId" --output text
अपेक्षित output:
amazon.nova-lite-v1:0
5. उत्तर stream करा
हे का लागतं?
Chat helper मध्ये Dubai च्या buyers ना 5 seconds थांबण्याऐवजी शब्द लगेच दिसायला हवेत.
हे काय आहे?
ConverseStream event stream देतो: contentBlockDelta events मध्ये text चे तुकडे; metadata मध्ये usage.
कसं करायचं (step by step)
- Python.
r = br.converse_stream(modelId="amazon.nova-lite-v1:0",
messages=[{"role": "user", "content": [{"text": "Is a used bike for AED 700 a fair price? 2 lines."}]}])
for ev in r["stream"]:
if "contentBlockDelta" in ev: print(ev["contentBlockDelta"]["delta"]["text"], end="", flush=True)
print()
अपेक्षित output:
For a lightly used city bike, AED 700 is fair.
Check brakes and gears before paying.
- Node.js.
import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
const r = await br.send(new ConverseStreamCommand({ modelId: "apac.amazon.nova-lite-v1:0",
messages: [{ role: "user", content: [{ text: "Give 3 tips to sell a sofa fast." }] }] }));
for await (const ev of r.stream) if (ev.contentBlockDelta) process.stdout.write(ev.contentBlockDelta.delta.text);
अपेक्षित output:
1. Clear photos in daylight. 2. Fair price. 3. Offer pickup times.
- PHP.
<?php
$r = $br->converseStream(["modelId" => "amazon.nova-lite-v1:0",
"messages" => [["role" => "user", "content" => [["text" => "Say hello in Italian and Malayalam."]]]]]);
foreach ($r["stream"] as $ev) if (isset($ev["contentBlockDelta"])) echo $ev["contentBlockDelta"]["delta"]["text"];
echo PHP_EOL;
अपेक्षित output:
Ciao! നമസ്കാരം!
- Verify: token usage metric.
aws cloudwatch get-metric-statistics --namespace AWS/Bedrock --metric-name OutputTokenCount --dimensions Name=ModelId,Value=amazon.nova-lite-v1:0 --statistics Sum --period 3600 --start-time $(date -u -d "-1 hour" +%FT%TZ) --end-time $(date -u +%FT%TZ) --region eu-west-1 --query "Datapoints[0].Sum"
अपेक्षित output:
112.0
6. हाच call Java, Go, .NET आणि CLI मध्ये
हे का लागतं?
Teams अनेकदा भाषा मिसळतात. Python, PHP आणि Node.js मध्ये call समजला की बाकीचे SDKs म्हणजे तोच API, फक्त syntax वेगळा.
हे काय आहे?
सगळे Converse API call करतात. Terminal मधून पटकन test करायला CLI ओळ वापरा.
कसं करायचं (step by step)
| Stack | Code |
|---|---|
| AWS CLI | aws bedrock-runtime converse --model-id amazon.nova-lite-v1:0 --messages '[{"role":"user","content":[{"text":"Hi"}]}]' |
| Java v2 | var r = br.converse(b -> b.modelId("amazon.nova-lite-v1:0").messages(Message.builder().role(ConversationRole.USER).content(ContentBlock.fromText("Hi")).build())); |
| Go v2 | out, _ := client.Converse(ctx, &bedrockruntime.ConverseInput{ModelId: aws.String("amazon.nova-lite-v1:0"), Messages: msgs}) |
| .NET | var r = await br.ConverseAsync(new ConverseRequest { ModelId = "amazon.nova-lite-v1:0", Messages = msgs }); |
7. काहीही खर्च चालू राहू नये म्हणून cleanup
हे का लागतं?
चालू ठेवलेले lab resources पैसे खातात आणि security risk बनतात.
हे काय आहे?
उलट्या क्रमाने delete करा: आधी children, मग parents.
कसं करायचं (step by step)
- On-demand calls साठी delete करायला काही नाही; test photos काढा.
aws s3 rm s3://market-photos-mi/bike-221.jpg
अपेक्षित output:
(no output means success)
Ravindra Bagale's Tip
नेहमी maxTokens ठेवा आणि usage log करा; loop मधला बिनमर्यादा prompt पटकन खरे पैसे खातो.
8. मुलाखत प्रश्न आणि उत्तरं
प्र. Rekognition input?
Bytes (5 MB) किंवा S3Object.
प्र. Models कोणता client call करतो?
bedrock-runtime.
प्र. Converse का?
सर्व models साठी एक format.
प्र. Stream कसं?
ConverseStream.
प्र. रिकामी ModerationLabels?
Unsafe काही नाही.
घरी करून बघा
- Chain करा: Python S3 photo चे labels वाचून Bedrock कडून मराठी listing मागेल.
- totalTokens > 2,000 झाल्यावर थांबणारा Node.js guard लिहा.
थोडक्यात सांगायचं तर
- Confidence सह DetectLabels.
- DetectText / Moderation.
- Converse = एक format.
- Chat साठी ConverseStream.
- Tokens limit, usage log.
सराव Tasks
Bengaluru HealthTech हा बेंगळुरू मधला हेल्थ टेक व्यवसाय आहे. Arjun Rao त्यांचं IT व cloud काम पाहतात. त्यांचे पैसे INR मध्ये मोजले जातात आणि AWS resources ap-south-1 Region मध्ये चालतात. खालच्या tasks मध्ये तुम्ही या lesson मध्ये शिकलेलं वापरून त्यांची खरी कामं करता. सगळी नावं, account IDs, IP addresses व numbers सरावासाठी काल्पनिक आहेत.
0 / 10
सोपं Bedrock models दाखवा
का: तुमच्या Region मध्ये कोणते foundation models आहेत ते पाहा.
काय करायचं: Amazon Bedrock मधले foundation models दाखवा.
- Task वाचा आणि ते कोणत्या AWS service बद्दल आहे ते ठरवा.
- aws लिहा, मग service चं नाव, मग operation (action शब्द).
- प्रत्येक आवश्यक flag (--name) व त्यापुढे task मधली value लिहा.
- Flags कोणत्याही क्रमाने चालतात. Check answer दाबा.
सोपं SageMaker endpoints दाखवा
का: Endpoints ना दर तासाला खर्च येतो; विसरलेले शोधा.
काय करायचं: SageMaker endpoints दाखवा.
- Task वाचा आणि ते कोणत्या AWS service बद्दल आहे ते ठरवा.
- aws लिहा, मग service चं नाव, मग operation (action शब्द).
- प्रत्येक आवश्यक flag (--name) व त्यापुढे task मधली value लिहा.
- Flags कोणत्याही क्रमाने चालतात. Check answer दाबा.
सोपं /16 मध्ये किती addresses?
का: VPC size ठरवायला ही संख्या लागते.
काय करायचं: Bengaluru HealthTech चा VPC 10.130.0.0/16. एकूण किती IP addresses?
- Task मधले numbers लिहून घ्या.
- कागदावर step by step काढा.
- Box मध्ये फक्त final उत्तर लिहा.
- Check answer दाबा.
सोपं SSH चा port
का: Security group rules ला योग्य port हवा.
काय करायचं: SSH साठी security group ने कोणता TCP port उघडावा?
- Task मधले numbers लिहून घ्या.
- कागदावर step by step काढा.
- Box मध्ये फक्त final उत्तर लिहा.
- Check answer दाबा.
सोपं तुम्ही कुठे आहात ते पाहा
का: काही copy किंवा delete करण्याआधी तुम्ही कोणत्या folder मध्ये आहात हे माहीत हवं.
काय करायचं: Arjun Rao Bengaluru HealthTech च्या server वर login झाले आहेत, पण terminal कोणत्या folder मध्ये आहे ते माहीत नाही. सध्याच्या folder चा path दाखवा.
- हे काम करणारा Linux command शोधा.
- Task ला लागणारे options (उदा. -r, -h) जोडा.
- File नावं, folders किंवा users योग्य क्रमाने लिहा.
- System files/users बदलत असाल तर sudo वापरा. Check answer दाबा.
सोपं एका bucket ला read-only access
का: Least privilege: कामाला लागणारे actions व bucket च द्या.
काय करायचं: User ला फक्त blrhealthtech-data bucket मधले objects वाचू (s3:GetObject) देणारी identity policy लिहा.
- { "Version": "2012-10-17", "Statement": [ ... ] } ने सुरू करा.
- प्रत्येक statement मध्ये Effect, Action व Resource लिहा.
- Task ला लागेल तेवढंच द्या (least privilege).
- Double quotes व commas नीट वापरा. Check answer दाबा.
मध्यम Image मधले labels ओळखा
का: Rekognition photo मधल्या वस्तू ओळखतो.
काय करायचं: s3://blrhealthtech-media/shop/p1.jpg (Bucket=blrhealthtech-media, Name=shop/p1.jpg) मधले labels ओळखा, कमाल 10.
- Task वाचा आणि ते कोणत्या AWS service बद्दल आहे ते ठरवा.
- aws लिहा, मग service चं नाव, मग operation (action शब्द).
- प्रत्येक आवश्यक flag (--name) व त्यापुढे task मधली value लिहा.
- Flags कोणत्याही क्रमाने चालतात. Check answer दाबा.
मध्यम एक Bedrock model allow
का: Apps ना approved model पुरतं मर्यादित ठेवा.
काय करायचं: फक्त arn:aws:bedrock:ap-south-1::foundation-model/amazon.nova-lite-v1:0 वर bedrock:InvokeModel allow करा.
- { "Version": "2012-10-17", "Statement": [ ... ] } ने सुरू करा.
- प्रत्येक statement मध्ये Effect, Action व Resource लिहा.
- Task ला लागेल तेवढंच द्या (least privilege).
- Double quotes व commas नीट वापरा. Check answer दाबा.
मध्यम AWS /24 subnet मधले usable IPs
का: AWS प्रत्येक subnet मध्ये 5 addresses राखून ठेवतो.
काय करायचं: AWS वर 10.130.1.0/24 subnet मध्ये Bengaluru HealthTech servers साठी किती addresses वापरू शकतो?
- Task मधले numbers लिहून घ्या.
- कागदावर step by step काढा.
- Box मध्ये फक्त final उत्तर लिहा.
- Check answer दाबा.
अवघड Model ला प्रश्न विचारा
का: Converse अनेक models साठी एकच API shape.
काय करायचं: msgs.json मधल्या messages सह amazon.nova-lite-v1:0 model वर converse call करा.
- Task वाचा आणि ते कोणत्या AWS service बद्दल आहे ते ठरवा.
- aws लिहा, मग service चं नाव, मग operation (action शब्द).
- प्रत्येक आवश्यक flag (--name) व त्यापुढे task मधली value लिहा.
- Flags कोणत्याही क्रमाने चालतात. Check answer दाबा.
उजळणी, तुलना आणि मुलाखत cards
हा lesson काही मिनिटांत revise करा. Cards phone वर save करा किंवा PNG download करा. प्रत्येक card वरचा QR हा lesson उघडतो.




अजून cards: Ravi Sir's Cards.