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