Upload folder using huggingface_hub
Browse filesFiles changed (37)
- .gitattributes+12
- app.pyAdded+128
- catalogue/catalogue.jsonAdded+162
- catalogue/images/britannia_5050_150g.jpgAdded
- catalogue/images/britannia_bourbon_150g.jpgAdded
- catalogue/images/britannia_good_day_butter_150g.jpgAdded
- catalogue/images/britannia_good_day_cashew_150g.jpgAdded
- catalogue/images/britannia_jimjam_150g.jpgAdded
- catalogue/images/britannia_marie_gold_250g.jpgAdded
- catalogue/images/britannia_milk_bikis_200g.jpgAdded
- catalogue/images/britannia_tiger_glucose_250g.jpgAdded
- catalogue/images/mcvities_digestive_250g.jpgAdded
- catalogue/images/oreo_chocolate_120g.jpgAdded
- catalogue/images/oreo_vanilla_120g.jpgAdded
- catalogue/images/parle_g_250g.jpgAdded
- catalogue/images/parle_hide_seek_100g.jpgAdded
- catalogue/images/parle_krackjack_200g.jpgAdded
- catalogue/images/parle_monaco_200g.jpgAdded
- catalogue/images/priyagold_butter_bite_200g.jpgAdded
- catalogue/images/sunfeast_dark_fantasy_150g.jpgAdded
- catalogue/images/sunfeast_marie_light_200g.jpgAdded
- catalogue/images/sunfeast_mom_magic_200g.jpgAdded
- catalogue/images/unibic_choco_chip_150g.jpgAdded
- catalogue/planogram.jsonAdded+11
- requirements.txtAdded+9
- shelf_images/shelf_01.jpgAdded
- shelf_images/shelf_03.jpgAdded
- src/__init__.pyAdded
- src/compliance.pyAdded+140
- src/cropper.pyAdded+64
- src/detector.pyAdded+131
- src/embedder.pyAdded+124
- src/matcher.pyAdded+102
- src/pipeline.pyAdded+73
- src/position.pyAdded+85
- src/visualizer.pyAdded+100
- src/vlm_fallback.pyAdded+99
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404142434445464732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textcatalogue/images/britannia_bourbon_150g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/britannia_good_day_cashew_150g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/mcvities_digestive_250g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/oreo_vanilla_120g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/parle_g_250g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/parle_hide_seek_100g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/parle_krackjack_200g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/sunfeast_dark_fantasy_150g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/sunfeast_marie_light_200g.jpg filter=lfs diff=lfs merge=lfs -textcatalogue/images/unibic_choco_chip_150g.jpg filter=lfs diff=lfs merge=lfs -textshelf_images/shelf_01.jpg filter=lfs diff=lfs merge=lfs -textshelf_images/shelf_03.jpg filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""ShelfEye Gradio Demo — AI-Powered Retail Shelf Intelligence."""
import sysimport jsonimport tempfilefrom pathlib import Path
sys.path.insert(0, str(Path(__file__).parent / "src"))
import gradio as grimport numpy as np
from detector import detect_productsfrom cropper import crop_detectionsfrom embedder import embed_catalogue, embed_cropsfrom matcher import match_detectionsfrom position import assign_positionsfrom compliance import check_compliancefrom visualizer import draw_detections
def analyze_shelf(image_path: str, use_vlm: bool, clip_threshold: float): if image_path is None: return None, "Upload a shelf image to begin."
dets = detect_products(image_path) dets = crop_detections(image_path, dets) dets = match_detections(dets, clip_threshold=clip_threshold, use_vlm=use_vlm) dets = assign_positions(dets)
annotated = draw_detections(image_path, dets) annotated_rgb = annotated[:, :, ::-1]
# Build pipeline result for compliance products = [] for d in dets: products.append({ "sku_id": d.get("sku_id"), "product_name": d.get("product_name", "unknown"), "confidence": round(d.get("similarity", d.get("confidence", 0)), 4), "bbox": [int(c) for c in d["bbox"]], "row": d["row"], "column": d["column"], "matched": d.get("matched", False), "match_method": d.get("match_method", "none"), })
matched_count = sum(1 for p in products if p["matched"]) result = { "image": Path(image_path).name, "total_products": len(products), "matched": matched_count, "unmatched": len(products) - matched_count, "products": products, }
# Compliance check planogram_path = Path("catalogue/planogram.json") if planogram_path.exists(): compliance = check_compliance(result, str(planogram_path)) else: compliance = {"note": "No planogram found. Skipping compliance check."}
result_json = json.dumps(result, indent=2) compliance_json = json.dumps(compliance, indent=2)
summary = ( f"**Detected:** {len(products)} products\n\n" f"**Matched:** {matched_count} ({matched_count/len(products)*100:.0f}%)\n\n" f"**Unmatched:** {len(products) - matched_count}\n\n" )
if "compliance_score" in compliance: summary += ( f"**Compliance Score:** {compliance['compliance_score']}%\n\n" f"**Out of Stock:** {compliance['summary']['out_of_stock']}\n\n" f"**Wrong Position:** {compliance['summary']['wrong_position']}\n\n" f"**Unexpected:** {compliance['summary']['unexpected']}" )
return annotated_rgb, summary, result_json, compliance_json
with open("catalogue/catalogue.json") as f: catalogue = json.load(f)catalogue_info = "\n".join(f"- {p['product_name']} ({p['brand']})" for p in catalogue)
with gr.Blocks(title="ShelfEye — AI Shelf Intelligence", theme=gr.themes.Soft()) as demo: gr.Markdown( "# ShelfEye — AI-Powered Retail Shelf Intelligence\n" "Upload a retail shelf image to detect products, match them against a catalogue, " "and check planogram compliance.\n\n" "**Pipeline:** Grounding DINO (detection) → CLIP (matching) → Qwen2.5-VL (fallback) → Compliance Engine" )
with gr.Row(): with gr.Column(scale=1): input_image = gr.Image(type="filepath", label="Upload Shelf Image") with gr.Accordion("Settings", open=False): use_vlm = gr.Checkbox(value=True, label="Enable VLM Fallback (Qwen2.5-VL)") clip_threshold = gr.Slider(0.5, 0.9, value=0.65, step=0.05, label="CLIP Match Threshold") run_btn = gr.Button("Analyze Shelf", variant="primary")
gr.Markdown("### Catalogue (20 products)") gr.Markdown(catalogue_info)
with gr.Column(scale=2): output_image = gr.Image(label="Annotated Result") summary_md = gr.Markdown(label="Summary")
with gr.Row(): result_json = gr.Code(label="Detection Result (JSON)", language="json") compliance_json = gr.Code(label="Compliance Report (JSON)", language="json")
run_btn.click( fn=analyze_shelf, inputs=[input_image, use_vlm, clip_threshold], outputs=[output_image, summary_md, result_json, compliance_json], )
gr.Markdown( "---\n" "Built with Grounding DINO, CLIP, Qwen2.5-VL | " "[GitHub](https://github.com/rixav77/ShelfEye)" )
if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162[ { "sku_id": "parle_g_250g", "product_name": "Parle-G Gold Biscuits", "brand": "Parle", "category": "biscuits", "weight": "250g", "image_path": "catalogue/images/parle_g_250g.jpg" }, { "sku_id": "parle_monaco_200g", "product_name": "Parle Monaco Classic Biscuits", "brand": "Parle", "category": "biscuits", "weight": "200g", "image_path": "catalogue/images/parle_monaco_200g.jpg" }, { "sku_id": "parle_hide_seek_100g", "product_name": "Parle Hide & Seek Chocolate Chip Cookies", "brand": "Parle", "category": "biscuits", "weight": "100g", "image_path": "catalogue/images/parle_hide_seek_100g.jpg" }, { "sku_id": "britannia_good_day_butter_150g", "product_name": "Britannia Good Day Butter Cookies", "brand": "Britannia", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/britannia_good_day_butter_150g.jpg" }, { "sku_id": "britannia_good_day_cashew_150g", "product_name": "Britannia Good Day Cashew Cookies", "brand": "Britannia", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/britannia_good_day_cashew_150g.jpg" }, { "sku_id": "britannia_bourbon_150g", "product_name": "Britannia Bourbon Chocolate Cream Biscuits", "brand": "Britannia", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/britannia_bourbon_150g.jpg" }, { "sku_id": "britannia_marie_gold_250g", "product_name": "Britannia Marie Gold Biscuits", "brand": "Britannia", "category": "biscuits", "weight": "250g", "image_path": "catalogue/images/britannia_marie_gold_250g.jpg" }, { "sku_id": "britannia_5050_150g", "product_name": "Britannia 50-50 Maska Chaska", "brand": "Britannia", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/britannia_5050_150g.jpg" }, { "sku_id": "oreo_vanilla_120g", "product_name": "Oreo Vanilla Creme Biscuits", "brand": "Cadbury Oreo", "category": "biscuits", "weight": "120g", "image_path": "catalogue/images/oreo_vanilla_120g.jpg" }, { "sku_id": "oreo_chocolate_120g", "product_name": "Oreo Chocolate Creme Biscuits", "brand": "Cadbury Oreo", "category": "biscuits", "weight": "120g", "image_path": "catalogue/images/oreo_chocolate_120g.jpg" }, { "sku_id": "sunfeast_dark_fantasy_150g", "product_name": "Sunfeast Dark Fantasy Choco Fills", "brand": "Sunfeast", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/sunfeast_dark_fantasy_150g.jpg" }, { "sku_id": "sunfeast_marie_light_200g", "product_name": "Sunfeast Marie Light Original", "brand": "Sunfeast", "category": "biscuits", "weight": "200g", "image_path": "catalogue/images/sunfeast_marie_light_200g.jpg" }, { "sku_id": "mcvities_digestive_250g", "product_name": "McVitie's Digestive Biscuits", "brand": "McVitie's", "category": "biscuits", "weight": "250g", "image_path": "catalogue/images/mcvities_digestive_250g.jpg" }, { "sku_id": "parle_krackjack_200g", "product_name": "Parle Krackjack Sweet & Salty Biscuits", "brand": "Parle", "category": "biscuits", "weight": "200g", "image_path": "catalogue/images/parle_krackjack_200g.jpg" }, { "sku_id": "britannia_jimjam_150g", "product_name": "Britannia Jim Jam Cream Biscuits", "brand": "Britannia", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/britannia_jimjam_150g.jpg" }, { "sku_id": "britannia_milk_bikis_200g", "product_name": "Britannia Milk Bikis Biscuits", "brand": "Britannia", "category": "biscuits", "weight": "200g", "image_path": "catalogue/images/britannia_milk_bikis_200g.jpg" }, { "sku_id": "sunfeast_mom_magic_200g", "product_name": "Sunfeast Mom's Magic Butter Biscuits", "brand": "Sunfeast", "category": "biscuits", "weight": "200g", "image_path": "catalogue/images/sunfeast_mom_magic_200g.jpg" }, { "sku_id": "priyagold_butter_bite_200g", "product_name": "Priyagold Butter Bite Biscuits", "brand": "Priyagold", "category": "biscuits", "weight": "200g", "image_path": "catalogue/images/priyagold_butter_bite_200g.jpg" }, { "sku_id": "britannia_tiger_glucose_250g", "product_name": "Britannia Tiger Glucose Biscuits", "brand": "Britannia", "category": "biscuits", "weight": "250g", "image_path": "catalogue/images/britannia_tiger_glucose_250g.jpg" }, { "sku_id": "unibic_choco_chip_150g", "product_name": "Unibic Choco Chip Cookies", "brand": "Unibic", "category": "biscuits", "weight": "150g", "image_path": "catalogue/images/unibic_choco_chip_150g.jpg" }]1234567891011{ "name": "Biscuit Shelf Standard Layout", "source_image": "shelf_03.jpg", "rows": { "1": ["oreo_chocolate_120g"], "2": ["britannia_milk_bikis_200g", "oreo_chocolate_120g", "britannia_good_day_butter_150g", "sunfeast_mom_magic_200g"], "3": ["britannia_good_day_butter_150g"], "4": ["parle_g_250g", "unibic_choco_chip_150g", "sunfeast_marie_light_200g"], "5": ["parle_krackjack_200g"] }}123456789torchtorchvisiontransformersaccelerategradioopencv-python-headlessPillownumpyqwen-vl-utils123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Compare detected shelf state against expected planogram."""
import jsonfrom pathlib import Path
def check_compliance( pipeline_result: dict, planogram_path: str = "catalogue/planogram.json",) -> dict: """Compare pipeline result against planogram and flag violations.
Returns a compliance report with: - compliant: list of products in expected position - out_of_stock: expected products not found on shelf - wrong_position: expected products found but in wrong row - unexpected: detected products not in planogram - score: compliance percentage """ with open(planogram_path) as f: planogram = json.load(f)
expected_rows = planogram["rows"]
# Build set of all expected SKUs and their expected rows expected = {} for row_str, skus in expected_rows.items(): row = int(row_str) for sku in skus: if sku not in expected: expected[sku] = [] expected[sku].append(row)
# Build detected SKU -> rows mapping detected = {} for p in pipeline_result["products"]: if p["matched"] and p["sku_id"]: sku = p["sku_id"] if sku not in detected: detected[sku] = [] detected[sku].append(p["row"])
compliant = [] out_of_stock = [] wrong_position = [] unexpected = []
# Check each expected SKU for sku, expected_row_list in expected.items(): if sku not in detected: out_of_stock.append({ "sku_id": sku, "expected_rows": expected_row_list, "violation": "out_of_stock", }) else: detected_rows = detected[sku] # Check if at least one detection is in an expected row in_correct_row = any(r in expected_row_list for r in detected_rows) if in_correct_row: compliant.append({ "sku_id": sku, "expected_rows": expected_row_list, "detected_rows": detected_rows, }) else: wrong_position.append({ "sku_id": sku, "expected_rows": expected_row_list, "detected_rows": detected_rows, "violation": "wrong_position", })
# Check for products on shelf but not in planogram expected_skus = set(expected.keys()) for sku, rows in detected.items(): if sku not in expected_skus: unexpected.append({ "sku_id": sku, "detected_rows": rows, "violation": "not_in_planogram", })
# Also flag unmatched detections unmatched = [ {"bbox": p["bbox"], "row": p["row"], "column": p["column"], "violation": "unrecognized"} for p in pipeline_result["products"] if not p["matched"] ]
total_expected = len(expected) compliant_count = len(compliant) score = (compliant_count / total_expected * 100) if total_expected > 0 else 0
report = { "planogram": planogram["name"], "image": pipeline_result["image"], "compliance_score": round(score, 1), "total_expected": total_expected, "summary": { "compliant": compliant_count, "out_of_stock": len(out_of_stock), "wrong_position": len(wrong_position), "unexpected": len(unexpected), "unrecognized": len(unmatched), }, "compliant": compliant, "violations": { "out_of_stock": out_of_stock, "wrong_position": wrong_position, "unexpected": unexpected, "unrecognized": unmatched, }, }
print(f"[compliance] {pipeline_result['image']}: score={score:.1f}% " f"({compliant_count}/{total_expected} compliant, " f"{len(out_of_stock)} OOS, {len(wrong_position)} misplaced, " f"{len(unexpected)} unexpected)")
return report
if __name__ == "__main__": import sys
result_path = sys.argv[1] if len(sys.argv) > 1 else "outputs/result_shelf_03.json" planogram_path = sys.argv[2] if len(sys.argv) > 2 else "catalogue/planogram.json"
with open(result_path) as f: result = json.load(f)
report = check_compliance(result, planogram_path)
out_path = result_path.replace("result_", "compliance_") with open(out_path, "w") as f: json.dump(report, f, indent=2)
print(f"\nCompliance report saved to {out_path}") print(json.dumps(report, indent=2))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Crop detected product regions from shelf images."""
import cv2import numpy as npfrom pathlib import Path
def crop_detections( image_path: str, detections: list[dict], output_dir: str = None, padding: int = 5,) -> list[dict]: """ Crop each detected bounding box from the shelf image.
Args: image_path: path to the shelf image detections: list of dicts with 'bbox' key ([x1, y1, x2, y2]) output_dir: if set, save crops as JPEGs padding: pixels to add around each box (clamped to image bounds)
Returns: Same detections list, each dict augmented with: - 'crop': np.ndarray of the cropped region (BGR) - 'crop_path': str path if output_dir was set """ img = cv2.imread(image_path) h, w = img.shape[:2] image_name = Path(image_path).stem
if output_dir: Path(output_dir).mkdir(parents=True, exist_ok=True)
for i, det in enumerate(detections): x1, y1, x2, y2 = [int(c) for c in det["bbox"]]
x1 = max(0, x1 - padding) y1 = max(0, y1 - padding) x2 = min(w, x2 + padding) y2 = min(h, y2 + padding)
crop = img[y1:y2, x1:x2] det["crop"] = crop
if output_dir: crop_path = str(Path(output_dir) / f"{image_name}_crop_{i:03d}.jpg") cv2.imwrite(crop_path, crop) det["crop_path"] = crop_path
print(f"[cropper] Cropped {len(detections)} regions from {image_path}") return detections
if __name__ == "__main__": import sys from detector import detect_products
path = sys.argv[1] if len(sys.argv) > 1 else "shelf_images/shelf_01.jpg" out_dir = sys.argv[2] if len(sys.argv) > 2 else "outputs/crops"
dets = detect_products(path) dets = crop_detections(path, dets, output_dir=out_dir) print(f"Saved {len(dets)} crops to {out_dir}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""Product detection using Grounding DINO (zero-shot, text-prompted).Detects bounding boxes of products on retail shelf images."""
import torchfrom torchvision.ops import nmsfrom PIL import Imagefrom transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
MODEL_ID = "IDEA-Research/grounding-dino-tiny"
_model = None_processor = None
def load_model(device: str = None): global _model, _processor if _model is not None: return _model, _processor
if device is None: device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"[detector] Loading Grounding DINO ({MODEL_ID}) on {device}...") _processor = AutoProcessor.from_pretrained(MODEL_ID) _model = AutoModelForZeroShotObjectDetection.from_pretrained(MODEL_ID).to(device) _model.eval() print("[detector] Model loaded.") return _model, _processor
def _filter_boxes(detections: list[dict], image_w: int, image_h: int) -> list[dict]: """Remove boxes that are too large (shelf-level) or too small (noise).""" image_area = image_w * image_h filtered = [] for d in detections: x1, y1, x2, y2 = d["bbox"] box_w = x2 - x1 box_h = y2 - y1 box_area = box_w * box_h area_ratio = box_area / image_area
# Skip boxes covering >10% of image (shelf-level detections) if area_ratio > 0.10: continue # Skip tiny boxes <0.5% of image (noise) if area_ratio < 0.005: continue # Skip extreme aspect ratios (>5:1) aspect = max(box_w, box_h) / (min(box_w, box_h) + 1e-6) if aspect > 5: continue
filtered.append(d) return filtered
def _apply_nms(detections: list[dict], iou_threshold: float = 0.5) -> list[dict]: """Non-max suppression to remove overlapping boxes.""" if not detections: return detections
boxes = torch.tensor([d["bbox"] for d in detections]) scores = torch.tensor([d["confidence"] for d in detections]) keep = nms(boxes, scores, iou_threshold) return [detections[i] for i in keep.tolist()]
def detect_products( image_path: str, text_prompt: str = "biscuit packet . product package . snack pack .", box_threshold: float = 0.15, text_threshold: float = 0.15, nms_threshold: float = 0.5, device: str = None,) -> list[dict]: """ Detect products in a shelf image.
Returns list of dicts with keys: bbox, confidence, label bbox is [x1, y1, x2, y2] in pixel coordinates. """ if device is None: device = "cuda" if torch.cuda.is_available() else "cpu"
model, processor = load_model(device) image = Image.open(image_path).convert("RGB") w, h = image.size
inputs = processor(images=image, text=text_prompt, return_tensors="pt").to(device)
with torch.no_grad(): outputs = model(**inputs)
results = processor.post_process_grounded_object_detection( outputs, input_ids=inputs["input_ids"], threshold=box_threshold, text_threshold=text_threshold, target_sizes=[(h, w)], )[0]
detections = [] for box, score, label in zip( results["boxes"].cpu().tolist(), results["scores"].cpu().tolist(), results["labels"], ): detections.append({ "bbox": [round(c, 1) for c in box], "confidence": round(score, 4), "label": label, })
detections = _filter_boxes(detections, w, h) detections = _apply_nms(detections, nms_threshold) detections.sort(key=lambda d: d["confidence"], reverse=True)
print(f"[detector] Found {len(detections)} products in {image_path}") return detections
if __name__ == "__main__": import sys import json
path = sys.argv[1] if len(sys.argv) > 1 else "shelf_images/shelf_01.jpg" dets = detect_products(path) print(json.dumps(dets, indent=2)) print(f"\nTotal: {len(dets)} detections")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Generate CLIP embeddings for catalogue images and detected crop regions."""
import jsonimport pickleimport torchimport numpy as npfrom pathlib import Pathfrom PIL import Imagefrom transformers import CLIPModel, CLIPProcessor
CLIP_MODEL_ID = "openai/clip-vit-base-patch32"CATALOGUE_CACHE = "catalogue/embeddings.pkl"
_model = None_processor = None
def load_clip(device: str = None): global _model, _processor if _model is not None: return _model, _processor
if device is None: device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"[embedder] Loading CLIP ({CLIP_MODEL_ID}) on {device}...") _processor = CLIPProcessor.from_pretrained(CLIP_MODEL_ID) _model = CLIPModel.from_pretrained(CLIP_MODEL_ID).to(device) _model.eval() print("[embedder] CLIP loaded.") return _model, _processor
def embed_images(images: list[Image.Image], device: str = None) -> np.ndarray: """Compute CLIP image embeddings for a list of PIL images.
Returns (N, 512) normalized embedding matrix. """ if device is None: device = "cuda" if torch.cuda.is_available() else "cpu"
model, processor = load_clip(device) inputs = processor(images=images, return_tensors="pt", padding=True).to(device)
with torch.no_grad(): out = model.get_image_features(**inputs) feats = out.pooler_output if hasattr(out, "pooler_output") else out
feats = feats / feats.norm(dim=-1, keepdim=True) return feats.cpu().numpy()
def embed_catalogue( catalogue_path: str = "catalogue/catalogue.json", cache_path: str = CATALOGUE_CACHE, force: bool = False, device: str = None,) -> dict: """Embed all catalogue reference images.
Returns dict with: - 'embeddings': (N, 512) numpy array - 'sku_ids': list of sku_id strings (same order as rows) - 'products': list of product dicts from catalogue.json """ cache = Path(cache_path) if cache.exists() and not force: with open(cache, "rb") as f: data = pickle.load(f) print(f"[embedder] Loaded cached catalogue embeddings ({len(data['sku_ids'])} products)") return data
with open(catalogue_path) as f: products = json.load(f)
images = [] sku_ids = [] valid_products = []
for p in products: img_path = Path(p["image_path"]) if not img_path.exists(): print(f"[embedder] WARNING: missing image for {p['sku_id']}, skipping") continue images.append(Image.open(img_path).convert("RGB")) sku_ids.append(p["sku_id"]) valid_products.append(p)
embeddings = embed_images(images, device=device)
data = { "embeddings": embeddings, "sku_ids": sku_ids, "products": valid_products, }
cache.parent.mkdir(parents=True, exist_ok=True) with open(cache, "wb") as f: pickle.dump(data, f)
print(f"[embedder] Embedded {len(sku_ids)} catalogue products -> {cache}") return data
def embed_crops(detections: list[dict], device: str = None) -> np.ndarray: """Compute CLIP embeddings for cropped detection regions.
Each detection must have a 'crop' key (BGR numpy array from cropper). Returns (N, 512) normalized embedding matrix. """ images = [] for det in detections: bgr = det["crop"] rgb = bgr[:, :, ::-1] images.append(Image.fromarray(rgb))
return embed_images(images, device=device)
if __name__ == "__main__": cat_data = embed_catalogue(force=True) print(f"\nCatalogue: {cat_data['embeddings'].shape}") for sku, emb in zip(cat_data["sku_ids"], cat_data["embeddings"]): print(f" {sku}: norm={np.linalg.norm(emb):.4f}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Match detected crops to catalogue products using CLIP + Qwen2.5-VL fallback."""
import numpy as np
from embedder import embed_catalogue, embed_cropsfrom vlm_fallback import identify as vlm_identify
CLIP_THRESHOLD = 0.65
def match_detections( detections: list[dict], catalogue_path: str = "catalogue/catalogue.json", clip_threshold: float = CLIP_THRESHOLD, use_vlm: bool = True, device: str = None,) -> list[dict]: """ Match each detection to a catalogue product.
Augments each detection dict with: - matched: True/False - product_name: matched product name (or 'unknown') - sku_id: matched SKU (or None) - similarity: cosine similarity score - match_method: 'clip' or 'vlm' """ import torch if device is None: device = "cuda" if torch.cuda.is_available() else "cpu"
cat = embed_catalogue(catalogue_path) cat_embs = cat["embeddings"] products = cat["products"] product_names = [p["product_name"] for p in products]
crop_embs = embed_crops(detections, device=device) sims = crop_embs @ cat_embs.T
vlm_queue = []
for i, det in enumerate(detections): max_idx = int(np.argmax(sims[i])) max_sim = float(sims[i][max_idx])
det["similarity"] = round(max_sim, 4)
if max_sim >= clip_threshold: det["matched"] = True det["product_name"] = products[max_idx]["product_name"] det["sku_id"] = products[max_idx]["sku_id"] det["match_method"] = "clip" else: vlm_queue.append(i)
if vlm_queue and use_vlm: print(f"[matcher] Sending {len(vlm_queue)} low-confidence crops to Qwen2.5-VL...") for i in vlm_queue: det = detections[i] result = vlm_identify(det["crop"], product_names, device=device)
if result in product_names: idx = product_names.index(result) det["matched"] = True det["product_name"] = result det["sku_id"] = products[idx]["sku_id"] det["match_method"] = "vlm" else: det["matched"] = False det["product_name"] = "unknown" det["sku_id"] = None det["match_method"] = "vlm" elif vlm_queue: for i in vlm_queue: det = detections[i] det["matched"] = False det["product_name"] = "unknown" det["sku_id"] = None det["match_method"] = "clip"
matched = sum(1 for d in detections if d.get("matched")) print(f"[matcher] {matched}/{len(detections)} products matched") return detections
if __name__ == "__main__": import sys from detector import detect_products from cropper import crop_detections
path = sys.argv[1] if len(sys.argv) > 1 else "shelf_images/shelf_01.jpg"
dets = detect_products(path) dets = crop_detections(path, dets) dets = match_detections(dets)
print(f"\n{'='*60}") print(f"Results for {path}") print(f"{'='*60}") for d in dets: status = "MATCH" if d["matched"] else "UNKNOWN" print(f" [{status}] {d['product_name']:40s} sim={d['similarity']:.4f} via={d['match_method']}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Full ShelfEye pipeline: detect → crop → embed → match → position → JSON output."""
import jsonfrom datetime import datetimefrom pathlib import Path
from detector import detect_productsfrom cropper import crop_detectionsfrom matcher import match_detectionsfrom position import assign_positionsfrom visualizer import draw_detections
def run_pipeline( image_path: str, output_dir: str = "outputs", use_vlm: bool = True, device: str = None,) -> dict: """Run the full pipeline on a single shelf image.
Returns structured JSON result. """ dets = detect_products(image_path, device=device) dets = crop_detections(image_path, dets) dets = match_detections(dets, use_vlm=use_vlm, device=device) dets = assign_positions(dets)
products = [] for d in dets: products.append({ "sku_id": d.get("sku_id"), "product_name": d.get("product_name", "unknown"), "confidence": d.get("similarity", d.get("confidence", 0)), "bbox": [int(c) for c in d["bbox"]], "row": d["row"], "column": d["column"], "matched": d.get("matched", False), "match_method": d.get("match_method", "none"), })
matched_count = sum(1 for p in products if p["matched"])
result = { "image": Path(image_path).name, "timestamp": datetime.now().isoformat(timespec="seconds"), "total_products": len(products), "matched": matched_count, "unmatched": len(products) - matched_count, "products": products, }
Path(output_dir).mkdir(parents=True, exist_ok=True) out_path = Path(output_dir) / f"result_{Path(image_path).stem}.json" with open(out_path, "w") as f: json.dump(result, f, indent=2)
img_out = str(Path(output_dir) / f"annotated_{Path(image_path).stem}.jpg") draw_detections(image_path, dets, img_out)
print(f"[pipeline] Saved result to {out_path}") return result
if __name__ == "__main__": import sys
images = sys.argv[1:] or ["shelf_images/shelf_01.jpg"]
for img in images: result = run_pipeline(img) print(f"\n{result['image']}: {result['matched']}/{result['total_products']} matched, " f"{result['unmatched']} unknown")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Assign row and column positions to detected products based on bounding box layout."""
import numpy as np
def _cluster_rows(y_centers: list[float], min_gap_ratio: float = 0.4) -> list[int]: """Cluster y-center values into shelf rows using gap-based splitting.
Sorts detections by y-center, then splits into a new row whenever the gap between consecutive detections exceeds min_gap_ratio * median_box_height. """ if not y_centers: return []
indices = np.argsort(y_centers) sorted_y = np.array(y_centers)[indices]
if len(sorted_y) == 1: row_labels = np.array([1]) result = np.empty_like(row_labels) result[indices] = row_labels return result.tolist()
gaps = np.diff(sorted_y) median_gap = np.median(gaps) if len(gaps) > 0 else 1.0 threshold = max(median_gap * 1.5, 20)
row_labels = np.ones(len(sorted_y), dtype=int) current_row = 1 for i in range(1, len(sorted_y)): if gaps[i - 1] > threshold: current_row += 1 row_labels[i] = current_row
result = np.empty_like(row_labels) result[indices] = row_labels return result.tolist()
def assign_positions(detections: list[dict]) -> list[dict]: """Assign row and column positions to each detection.
Rows are numbered top-to-bottom (row 1 = top shelf). Columns are numbered left-to-right within each row. """ if not detections: return detections
y_centers = [] for det in detections: x1, y1, x2, y2 = det["bbox"] y_centers.append((y1 + y2) / 2)
rows = _cluster_rows(y_centers)
for det, row in zip(detections, rows): det["row"] = row
max_row = max(rows) for r in range(1, max_row + 1): row_dets = [(i, det) for i, det in enumerate(detections) if det["row"] == r] row_dets.sort(key=lambda x: x[1]["bbox"][0]) for col, (i, det) in enumerate(row_dets, start=1): detections[i]["column"] = col
row_counts = {} for r in rows: row_counts[r] = row_counts.get(r, 0) + 1
print(f"[position] {len(detections)} detections -> {max_row} rows: {dict(sorted(row_counts.items()))}") return detections
if __name__ == "__main__": import sys import json sys.path.insert(0, "src") from detector import detect_products
path = sys.argv[1] if len(sys.argv) > 1 else "shelf_images/shelf_01.jpg" dets = detect_products(path) dets = assign_positions(dets)
for d in dets: print(f" row={d['row']} col={d['column']} bbox={d['bbox']} conf={d['confidence']:.4f}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""Visualize detection results on shelf images."""
import cv2import numpy as npfrom pathlib import Path
def draw_detections( image_path: str, detections: list[dict], output_path: str = None, show_position: bool = True,) -> np.ndarray: """Draw bounding boxes, labels, and row/column info on image.""" img = cv2.imread(image_path)
for det in detections: x1, y1, x2, y2 = [int(c) for c in det["bbox"]]
matched = det.get("matched", None) if matched is True: color = (0, 200, 0) elif matched is False: color = (0, 0, 200) else: color = (255, 165, 0)
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
# Build label text parts = [] if "product_name" in det: name = det["product_name"] if len(name) > 22: name = name[:20] + ".." parts.append(name)
conf = det.get("similarity", det.get("confidence", 0)) parts.append(f"{conf:.2f}")
if det.get("match_method") == "vlm": parts.append("VLM")
text = " | ".join(parts)
font_scale = 0.4 thickness = 1 (tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness) cv2.rectangle(img, (x1, y1 - th - 6), (x1 + tw + 4, y1), color, -1) cv2.putText(img, text, (x1 + 2, y1 - 4), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), thickness)
# Row/column tag in bottom-right corner if show_position and "row" in det and "column" in det: pos_text = f"R{det['row']}C{det['column']}" (pw, ph), _ = cv2.getTextSize(pos_text, cv2.FONT_HERSHEY_SIMPLEX, 0.35, 1) cv2.rectangle(img, (x2 - pw - 4, y2 - ph - 4), (x2, y2), (50, 50, 50), -1) cv2.putText(img, pos_text, (x2 - pw - 2, y2 - 3), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1)
# Draw summary legend h, w = img.shape[:2] matched_count = sum(1 for d in detections if d.get("matched")) unknown_count = len(detections) - matched_count legend = f"Total: {len(detections)} | Matched: {matched_count} | Unknown: {unknown_count}"
font_scale_lg = 0.55 (lw, lh), _ = cv2.getTextSize(legend, cv2.FONT_HERSHEY_SIMPLEX, font_scale_lg, 1) cv2.rectangle(img, (5, h - lh - 12), (lw + 15, h - 2), (0, 0, 0), -1) cv2.putText(img, legend, (10, h - 8), cv2.FONT_HERSHEY_SIMPLEX, font_scale_lg, (255, 255, 255), 1)
if output_path: Path(output_path).parent.mkdir(parents=True, exist_ok=True) cv2.imwrite(output_path, img) print(f"[visualizer] Saved annotated image to {output_path}")
return img
if __name__ == "__main__": import sys from detector import detect_products from cropper import crop_detections from matcher import match_detections from position import assign_positions
path = sys.argv[1] if len(sys.argv) > 1 else "shelf_images/shelf_01.jpg" out = sys.argv[2] if len(sys.argv) > 2 else None
dets = detect_products(path) dets = crop_detections(path, dets) dets = match_detections(dets) dets = assign_positions(dets)
if out is None: out = f"outputs/annotated_{Path(path).stem}.jpg"
draw_detections(path, dets, out) print(f"Detections: {len(dets)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""VLM fallback using Qwen2.5-VL for low-confidence product identification."""
import numpy as npfrom PIL import Image
QWEN_MODEL_ID = "Qwen/Qwen2.5-VL-3B-Instruct"
_model = None_processor = None
def load_vlm(device: str = "cuda"): global _model, _processor if _model is not None: return _model, _processor
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor import torch
print(f"[vlm] Loading Qwen2.5-VL ({QWEN_MODEL_ID}) on {device}...") _model = Qwen2_5_VLForConditionalGeneration.from_pretrained( QWEN_MODEL_ID, torch_dtype=torch.float16, device_map=device, ) _processor = AutoProcessor.from_pretrained(QWEN_MODEL_ID) _model.eval() print("[vlm] Qwen2.5-VL loaded.") return _model, _processor
def identify(crop_bgr: np.ndarray, product_names: list[str], device: str = "cuda") -> str: """Use Qwen2.5-VL to identify a product crop from a list of known products.
Returns the matched product name or 'unknown'. """ import torch from qwen_vl_utils import process_vision_info
model, processor = load_vlm(device)
rgb = crop_bgr[:, :, ::-1] pil_img = Image.fromarray(rgb)
product_list = "\n".join(f"- {name}" for name in product_names)
messages = [ { "role": "user", "content": [ {"type": "image", "image": pil_img}, {"type": "text", "text": ( "This is a product on a retail shelf. Identify which product it is " "from this list:\n" f"{product_list}\n\n" "If it matches one, reply with ONLY the exact product name from the list. " "If it does not match any, reply with ONLY the word 'unknown'." )}, ], } ]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) image_inputs, video_inputs = process_vision_info(messages) inputs = processor( text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt", ).to(device)
with torch.no_grad(): output_ids = model.generate(**inputs, max_new_tokens=50)
input_len = inputs.input_ids.shape[1] response = processor.batch_decode(output_ids[:, input_len:], skip_special_tokens=True)[0].strip()
for name in product_names: if name.lower() in response.lower(): return name
return response
if __name__ == "__main__": import cv2 import sys
img_path = sys.argv[1] if len(sys.argv) > 1 else "outputs/crops/shelf_03_crop_000.jpg" crop = cv2.imread(img_path)
product_names = [ "Parle-G Gold Biscuits", "Britannia Good Day Butter Cookies", "Oreo Chocolate Creme Biscuits", "Sunfeast Dark Fantasy Choco Fills", ]
result = identify(crop, product_names) print(f"VLM result: {result}").gitattributes+12
app.pyAdded+128
catalogue/catalogue.jsonAdded+162
catalogue/images/britannia_5050_150g.jpgAdded

catalogue/images/britannia_bourbon_150g.jpgAdded

Large File Pointer Details
- SHA256: ce2a41ace04d4b33df7e5cfbb2dcd71b4d6437fbd6999c7b2e13a72f76a06b75
- Pointer size: 131 Bytes
- Size of remote file: 263 kB
catalogue/images/britannia_good_day_butter_150g.jpgAdded

catalogue/images/britannia_good_day_cashew_150g.jpgAdded

Large File Pointer Details
- SHA256: b45e4746fa266c00a5d21d56633bab4dcd1766d0326e3ead51ffded8186b96ab
- Pointer size: 131 Bytes
- Size of remote file: 185 kB
catalogue/images/britannia_jimjam_150g.jpgAdded

catalogue/images/britannia_marie_gold_250g.jpgAdded

catalogue/images/britannia_milk_bikis_200g.jpgAdded

catalogue/images/britannia_tiger_glucose_250g.jpgAdded

catalogue/images/mcvities_digestive_250g.jpgAdded

Large File Pointer Details
- SHA256: d4998ec322accd4e5d83c272f2f41df0f80aeb53d2400748e25c739ef0e6d1f4
- Pointer size: 131 Bytes
- Size of remote file: 103 kB
catalogue/images/oreo_chocolate_120g.jpgAdded

catalogue/images/oreo_vanilla_120g.jpgAdded

Large File Pointer Details
- SHA256: 39ab5e8bde2cc7c649c32f2599ccabc1934b7b427c445fbe8e030c191116789d
- Pointer size: 131 Bytes
- Size of remote file: 113 kB
catalogue/images/parle_g_250g.jpgAdded

Large File Pointer Details
- SHA256: 818decddf86667a7d6cd8daa8e6469065d64a72e60ec05914ef14278b2705c67
- Pointer size: 131 Bytes
- Size of remote file: 123 kB
catalogue/images/parle_hide_seek_100g.jpgAdded

Large File Pointer Details
- SHA256: 0a2453a4ba17efa469d666121b42ca1143b7b983753b647225277af09361acca
- Pointer size: 131 Bytes
- Size of remote file: 360 kB
catalogue/images/parle_krackjack_200g.jpgAdded

Large File Pointer Details
- SHA256: d966c31d1957f81b7ee0ad1794ea778404d47aa7b3316bdf58ed3487ea180d4d
- Pointer size: 131 Bytes
- Size of remote file: 154 kB
catalogue/images/parle_monaco_200g.jpgAdded

catalogue/images/priyagold_butter_bite_200g.jpgAdded

catalogue/images/sunfeast_dark_fantasy_150g.jpgAdded

Large File Pointer Details
- SHA256: 16ccd54cdf7e75e79c8515c2f07fe0d93c5a7070f63887f8315d61362283ddfb
- Pointer size: 131 Bytes
- Size of remote file: 119 kB
catalogue/images/sunfeast_marie_light_200g.jpgAdded

Large File Pointer Details
- SHA256: 25a242e243dd0ba5367666f8df0d792a8b67013854d16f0b4127e5c6d27bd0ff
- Pointer size: 131 Bytes
- Size of remote file: 115 kB
catalogue/images/sunfeast_mom_magic_200g.jpgAdded

catalogue/images/unibic_choco_chip_150g.jpgAdded

Large File Pointer Details
- SHA256: 0897e2bf171acd324f7f1d1445ef8ef2acaea165a4b3043e44427ac0dd8c8cfe
- Pointer size: 131 Bytes
- Size of remote file: 123 kB
catalogue/planogram.jsonAdded+11
requirements.txtAdded+9
shelf_images/shelf_01.jpgAdded

Large File Pointer Details
- SHA256: 81e7c0dfd8fbaedbad5bb544efc0e72033d49e723892b8f43707cae91acae1b2
- Pointer size: 132 Bytes
- Size of remote file: 1.32 MB
shelf_images/shelf_03.jpgAdded

Large File Pointer Details
- SHA256: ae5b9a7400667b5959afe14baa5f3f76b9d1c77c1865b71f7e397dd549620b79
- Pointer size: 131 Bytes
- Size of remote file: 327 kB
src/__init__.pyAdded
src/compliance.pyAdded+140
src/cropper.pyAdded+64
src/detector.pyAdded+131
src/embedder.pyAdded+124
src/matcher.pyAdded+102
src/pipeline.pyAdded+73
src/position.pyAdded+85
src/visualizer.pyAdded+100
src/vlm_fallback.pyAdded+99