Ajout du serveur Facing AI : engine, router, module kb, lancement serveur
This commit is contained in:
1 parent
1d21c57acb
commit
f5841fa933
21 files changed
+2489
No files matched your search
+22
@@ -235,3 +235,25 @@ __marimo__/
|
|||||||
|
|
||||||
# Streamlit
|
# Streamlit
|
||||||
.streamlit/secrets.toml
|
.streamlit/secrets.toml
|
||||||
|
|
||||||
|
# --- Facing AI : donnees locales, non versionnees ---
|
||||||
|
.idea/
|
||||||
|
logs/
|
||||||
|
data_facing/
|
||||||
|
data_sauvegarde_avant_nettoyage/
|
||||||
|
data_session/
|
||||||
|
crops_eval/
|
||||||
|
kb_base30/
|
||||||
|
kb_base30_sauvegarde/
|
||||||
|
kb_client_01/
|
||||||
|
kb_data_tests/
|
||||||
|
kb_facing/
|
||||||
|
kb_ft/
|
||||||
|
kb_ft_session/
|
||||||
|
kb_session/
|
||||||
|
kb_test/
|
||||||
|
diag.txt
|
||||||
|
diag_*.csv
|
||||||
|
eval_*.txt
|
||||||
|
kb/embedder_ancien.py
|
||||||
|
kb/embedder_ancien.py
|
||||||
@@ -456,3 +456,6 @@ async def health():
|
|||||||
async def list_classes():
|
async def list_classes():
|
||||||
"""Return all class names the classifier knows about."""
|
"""Return all class names the classifier knows about."""
|
||||||
return {"classes": CLASSIFIER.class_names}
|
return {"classes": CLASSIFIER.class_names}
|
||||||
|
|
||||||
|
from facing_router import router as facing_router
|
||||||
|
app.include_router(facing_router)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from PIL import Image
|
||||||
|
from kb.embedder import Embedder
|
||||||
|
from kb.store import KnowledgeBase
|
||||||
|
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--data_dir", required=True) # ex : crops_dataset/train
|
||||||
|
ap.add_argument("--kb_dir", default="kb_data")
|
||||||
|
ap.add_argument("--backbone", default="efficientnet",
|
||||||
|
choices=["efficientnet", "dinov2_small", "dinov2_base"])
|
||||||
|
ap.add_argument("--weights", default=None)
|
||||||
|
ap.add_argument("--max_per_class", type=int, default=100)
|
||||||
|
ap.add_argument("--exclude", nargs="*", default=[]) # classes à cacher (simulation)
|
||||||
|
ap.add_argument("--ocr", action="store_true") # mémorise aussi le texte lu sur les emballages
|
||||||
|
ap.add_argument("--ocr_per_class", type=int, default=5) # nombre d'images lues par produit
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
if args.ocr:
|
||||||
|
from kb.text_utils import full_text, read_text, tokens
|
||||||
|
|
||||||
|
emb = Embedder(args.backbone, weights=args.weights)
|
||||||
|
kb = KnowledgeBase(args.kb_dir, dim=emb.dim, backbone=emb.name)
|
||||||
|
if kb.index.ntotal > 0:
|
||||||
|
raise SystemExit(f"La base '{args.kb_dir}' existe déjà : supprime ce dossier d'abord.")
|
||||||
|
|
||||||
|
for cls in sorted(os.listdir(args.data_dir)):
|
||||||
|
folder = os.path.join(args.data_dir, cls)
|
||||||
|
if not os.path.isdir(folder) or cls.startswith("_") or cls in args.exclude:
|
||||||
|
continue
|
||||||
|
files = [f for f in sorted(os.listdir(folder))
|
||||||
|
if f.lower().endswith((".jpg", ".jpeg", ".png"))][:args.max_per_class]
|
||||||
|
if not files:
|
||||||
|
continue
|
||||||
|
imgs = [Image.open(os.path.join(folder, f)).convert("RGB") for f in files]
|
||||||
|
kb.add_product(cls, {"name": cls, "status": "confirmed"}, emb.encode(imgs))
|
||||||
|
msg = f"{cls}: {len(imgs)} vecteurs"
|
||||||
|
if args.ocr:
|
||||||
|
# on lit the biggest images (texte plus lisible)
|
||||||
|
pick = sorted(range(len(imgs)), key=lambda k: -imgs[k].width * imgs[k].height)[:args.ocr_per_class]
|
||||||
|
kb.add_text(cls, [tokens(full_text(read_text(imgs[k]))) for k in pick])
|
||||||
|
sig = kb.signatures()[0][cls]
|
||||||
|
msg += f" | texte retenu : {', '.join(sorted(sig)[:8])}"
|
||||||
|
print(msg)
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
from kb.embedder import Embedder
|
||||||
|
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--data_dir", required=True) # crops_dataset (contient train/ et val/)
|
||||||
|
ap.add_argument("--backbone", default="efficientnet")
|
||||||
|
ap.add_argument("--weights", default=None)
|
||||||
|
ap.add_argument("--max_per_class", type=int, default=40)
|
||||||
|
args = ap.parse_args()
|
||||||
|
emb = Embedder(args.backbone, weights=args.weights)
|
||||||
|
|
||||||
|
|
||||||
|
def load(split):
|
||||||
|
root = os.path.join(args.data_dir, split)
|
||||||
|
vecs, labels = [], []
|
||||||
|
for c in sorted(os.listdir(root)):
|
||||||
|
folder = os.path.join(root, c)
|
||||||
|
if not os.path.isdir(folder) or c.startswith("_"):
|
||||||
|
continue
|
||||||
|
files = [f for f in sorted(os.listdir(folder))
|
||||||
|
if f.lower().endswith((".jpg", ".jpeg", ".png"))][:args.max_per_class]
|
||||||
|
if not files:
|
||||||
|
continue
|
||||||
|
v = emb.encode([Image.open(os.path.join(folder, f)).convert("RGB") for f in files])
|
||||||
|
vecs.append(v)
|
||||||
|
labels += [c] * len(v)
|
||||||
|
print(f" {split}/{c}: {len(v)}")
|
||||||
|
return np.vstack(vecs), np.array(labels)
|
||||||
|
|
||||||
|
|
||||||
|
print("Encodage du train...")
|
||||||
|
Xtr, ytr = load("train")
|
||||||
|
print("Encodage du val...")
|
||||||
|
Xva, yva = load("val")
|
||||||
|
S = Xva @ Xtr.T
|
||||||
|
|
||||||
|
pos, unk, correct = [], [], 0
|
||||||
|
for i in range(len(Xva)):
|
||||||
|
same = ytr == yva[i]
|
||||||
|
pos.append(S[i][same].max() if same.any() else -1) # produit connu
|
||||||
|
unk.append(S[i][~same].max()) # si sa classe était inconnue
|
||||||
|
correct += ytr[S[i].argmax()] == yva[i]
|
||||||
|
pos, unk = np.array(pos), np.array(unk)
|
||||||
|
|
||||||
|
print(f"\nAccuracy top-1 (1-NN) : {correct / len(Xva):.3f}")
|
||||||
|
print(f"Produit connu : médiane {np.median(pos):.2f}, p10 {np.percentile(pos, 10):.2f}")
|
||||||
|
print(f"Produit inconnu : médiane {np.median(unk):.2f}, p90 {np.percentile(unk, 90):.2f}")
|
||||||
|
best_t, best_s = 0, 0
|
||||||
|
for t in np.linspace(0.3, 0.95, 66):
|
||||||
|
s = ((pos >= t).mean() + (unk < t).mean()) / 2
|
||||||
|
if s > best_s:
|
||||||
|
best_t, best_s = t, s
|
||||||
|
print(f"Seuil connu/inconnu suggéré : {best_t:.2f} (exactitude équilibrée {best_s:.3f})")
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""Diagnostic du jeu crops_eval : quelles classes sont confondues, quelles images sont suspectes.
|
||||||
|
Sorties : diag_per_class.csv, diag_confusions.csv, diag_suspects.csv, diag_suspects.jpg"""
|
||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import os
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--data_dir", default="crops_eval")
|
||||||
|
ap.add_argument("--backbone", default="dinov2_small")
|
||||||
|
ap.add_argument("--max_per_class", type=int, default=60)
|
||||||
|
ap.add_argument("--dup_thr", type=float, default=0.93) # deux images de classes différentes aussi proches = suspect
|
||||||
|
ap.add_argument("--montage", type=int, default=12) # nombre de paires dans l'image de contrôle
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
from kb.embedder import Embedder
|
||||||
|
emb = Embedder(args.backbone)
|
||||||
|
|
||||||
|
|
||||||
|
def load(split):
|
||||||
|
root = os.path.join(args.data_dir, split)
|
||||||
|
paths, labels = [], []
|
||||||
|
for c in sorted(os.listdir(root)):
|
||||||
|
folder = os.path.join(root, c)
|
||||||
|
if not os.path.isdir(folder) or c.startswith("_"):
|
||||||
|
continue
|
||||||
|
files = [f for f in sorted(os.listdir(folder)) if f.lower().endswith((".jpg", ".jpeg", ".png"))]
|
||||||
|
for f in files[:args.max_per_class]:
|
||||||
|
paths.append(os.path.join(folder, f))
|
||||||
|
labels.append(c)
|
||||||
|
vecs = emb.encode([Image.open(p).convert("RGB") for p in paths])
|
||||||
|
return paths, np.array(labels), vecs
|
||||||
|
|
||||||
|
|
||||||
|
ptr, ytr, Xtr = load("train")
|
||||||
|
pva, yva, Xva = load("val")
|
||||||
|
|
||||||
|
# 1) val -> plus proche voisin du train
|
||||||
|
S = Xva @ Xtr.T
|
||||||
|
nn = S.argmax(axis=1)
|
||||||
|
pred = ytr[nn]
|
||||||
|
ok = pred == yva
|
||||||
|
print(f"Top-1 global : {ok.mean():.3f} ({len(yva)} images val)")
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for c in sorted(set(yva)):
|
||||||
|
m = yva == c
|
||||||
|
wrong = Counter(pred[m & ~ok])
|
||||||
|
top = ", ".join(f"{k} x{v}" for k, v in wrong.most_common(3))
|
||||||
|
rows.append((c, int(m.sum()), float(ok[m].mean()), top))
|
||||||
|
rows.sort(key=lambda r: r[2])
|
||||||
|
with open("diag_per_class.csv", "w", newline="", encoding="utf-8-sig") as f:
|
||||||
|
w = csv.writer(f, delimiter=";")
|
||||||
|
w.writerow(["classe", "nb_val", "top1", "souvent_confondu_avec"])
|
||||||
|
w.writerows(rows)
|
||||||
|
print("\nClasses les moins bien reconnues (top-1, confondue surtout avec) :")
|
||||||
|
for c, n, acc, top in rows[:15]:
|
||||||
|
print(f" {c:26s} {acc:5.2f} (n={n:3d}) -> {top}")
|
||||||
|
|
||||||
|
conf = Counter(zip(yva[~ok], pred[~ok]))
|
||||||
|
with open("diag_confusions.csv", "w", newline="", encoding="utf-8-sig") as f:
|
||||||
|
w = csv.writer(f, delimiter=";")
|
||||||
|
w.writerow(["vraie_classe", "predite", "nb"])
|
||||||
|
for (a, b), n in conf.most_common():
|
||||||
|
w.writerow([a, b, n])
|
||||||
|
print("\nConfusions les plus fréquentes (vraie -> prédite) :")
|
||||||
|
for (a, b), n in conf.most_common(15):
|
||||||
|
print(f" {a:26s} -> {b:26s} x{n}")
|
||||||
|
|
||||||
|
# 2) images quasi identiques mais de classes différentes (étiquette douteuse ou classes à fusionner)
|
||||||
|
T = Xtr @ Xtr.T
|
||||||
|
diff = ytr[:, None] != ytr[None, :]
|
||||||
|
T = np.where(diff, T, -1.0)
|
||||||
|
best_j = T.argmax(axis=1)
|
||||||
|
best = T[np.arange(len(T)), best_j]
|
||||||
|
order = [i for i in np.argsort(-best) if best[i] >= args.dup_thr]
|
||||||
|
seen, suspects = set(), []
|
||||||
|
for i in order:
|
||||||
|
j = int(best_j[i])
|
||||||
|
key = tuple(sorted((i, j)))
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
suspects.append((float(best[i]), i, j))
|
||||||
|
with open("diag_suspects.csv", "w", newline="", encoding="utf-8-sig") as f:
|
||||||
|
w = csv.writer(f, delimiter=";")
|
||||||
|
w.writerow(["similarite", "classe_a", "image_a", "classe_b", "image_b"])
|
||||||
|
for s, i, j in suspects:
|
||||||
|
w.writerow([f"{s:.3f}", ytr[i], ptr[i], ytr[j], ptr[j]])
|
||||||
|
pairs = Counter(tuple(sorted((ytr[i], ytr[j]))) for _, i, j in suspects)
|
||||||
|
print(f"\nPaires d'images de classes différentes avec similarité >= {args.dup_thr} : {len(suspects)}")
|
||||||
|
for (a, b), n in pairs.most_common(12):
|
||||||
|
print(f" {a:26s} <-> {b:26s} x{n}")
|
||||||
|
|
||||||
|
# 3) image de contrôle : côte à côte, pour juger à l'oeil
|
||||||
|
if suspects:
|
||||||
|
k = min(args.montage, len(suspects))
|
||||||
|
cell = 200
|
||||||
|
sheet = Image.new("RGB", (2 * cell + 20, k * (cell + 24)), "white")
|
||||||
|
d = ImageDraw.Draw(sheet)
|
||||||
|
for r, (s, i, j) in enumerate(suspects[:k]):
|
||||||
|
y = r * (cell + 24)
|
||||||
|
d.text((4, y + 2), f"{ytr[i]} vs {ytr[j]} sim={s:.2f}", fill="black")
|
||||||
|
for c, p in enumerate((ptr[i], ptr[j])):
|
||||||
|
im = Image.open(p).convert("RGB")
|
||||||
|
im.thumbnail((cell, cell))
|
||||||
|
sheet.paste(im, (c * (cell + 20), y + 20))
|
||||||
|
sheet.save("diag_suspects.jpg", quality=90)
|
||||||
|
print("\nImage de contrôle : diag_suspects.jpg")
|
||||||
|
print("Fichiers : diag_per_class.csv, diag_confusions.csv, diag_suspects.csv")
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import collections
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
log_path, gt_path = sys.argv[1], sys.argv[2]
|
||||||
|
|
||||||
|
pred, times = {}, []
|
||||||
|
with open(log_path, encoding="utf-8") as f:
|
||||||
|
for r in csv.DictReader(f):
|
||||||
|
pred[r["photo"]] = {k.lower().strip(): int(v) for k, v in json.loads(r["counts"]).items()}
|
||||||
|
times.append(float(r["analysis_s"]))
|
||||||
|
|
||||||
|
truth = collections.defaultdict(dict)
|
||||||
|
with open(gt_path, encoding="utf-8-sig") as f:
|
||||||
|
for r in csv.DictReader(f):
|
||||||
|
truth[r["photo"]][r["product"].lower().strip()] = int(r["facings_reels"])
|
||||||
|
|
||||||
|
pairs = exact = 0
|
||||||
|
abs_err = tp = pred_total = true_total = 0
|
||||||
|
per_product = collections.defaultdict(lambda: [0, 0, 0]) # vrais, prédits, erreur absolue
|
||||||
|
missing = []
|
||||||
|
|
||||||
|
for photo, t in truth.items():
|
||||||
|
if photo not in pred:
|
||||||
|
missing.append(photo)
|
||||||
|
continue
|
||||||
|
p = pred[photo]
|
||||||
|
for prod in set(t) | set(p):
|
||||||
|
tv, pv = t.get(prod, 0), p.get(prod, 0)
|
||||||
|
pairs += 1
|
||||||
|
exact += tv == pv
|
||||||
|
abs_err += abs(tv - pv)
|
||||||
|
tp += min(tv, pv)
|
||||||
|
pred_total += pv
|
||||||
|
true_total += tv
|
||||||
|
per_product[prod][0] += tv
|
||||||
|
per_product[prod][1] += pv
|
||||||
|
per_product[prod][2] += abs(tv - pv)
|
||||||
|
|
||||||
|
print(f"Photos non analysées : {missing}" if missing else "Toutes les photos de la vérité terrain ont été analysées.")
|
||||||
|
print(f"\nCouples (photo, produit) évalués : {pairs}")
|
||||||
|
print(f"Comptage exact : {exact / pairs:.1%}")
|
||||||
|
print(f"Erreur absolue moyenne : {abs_err / pairs:.2f} facing(s)")
|
||||||
|
print(f"Précision des facings : {tp / max(pred_total, 1):.1%}")
|
||||||
|
print(f"Rappel des facings : {tp / max(true_total, 1):.1%}")
|
||||||
|
print(f"Temps d'analyse moyen : {sum(times) / len(times):.2f} s par photo")
|
||||||
|
|
||||||
|
print("\nPar produit (vrais / prédits / erreur absolue) :")
|
||||||
|
for prod, (tv, pv, e) in sorted(per_product.items(), key=lambda x: -x[1][2]):
|
||||||
|
print(f" {prod:30s} {tv:4d} {pv:4d} {e:4d}")
|
||||||
@@ -0,0 +1,502 @@
|
|||||||
|
"""Pipeline de shelf_app.py (analyze) sans interface Tkinter.
|
||||||
|
analyze() détecte, reconnaît et regroupe ; state() renvoie l'état JSON décrit dans le contrat (brique 1)."""
|
||||||
|
import base64
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from collections import Counter
|
||||||
|
from datetime import datetime
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
from ultralytics import YOLO
|
||||||
|
|
||||||
|
from kb.auto_enroll import cluster_embeddings, enroll_named, find_product
|
||||||
|
from kb.decision import decide, fuse, source
|
||||||
|
from kb.embedder import Embedder
|
||||||
|
from kb.store import KnowledgeBase
|
||||||
|
from kb.text_utils import full_text, guess_name, read_text, tokens
|
||||||
|
|
||||||
|
MIN_SIZE = 40
|
||||||
|
|
||||||
|
|
||||||
|
class FacingError(Exception):
|
||||||
|
"""Erreur métier : le serveur la renvoie au mobile avec ce code HTTP et ce message."""
|
||||||
|
def __init__(self, code, msg):
|
||||||
|
super().__init__(msg)
|
||||||
|
self.code, self.msg = code, msg
|
||||||
|
|
||||||
|
|
||||||
|
# (sim_thr : accepté automatiquement, min_sim : en dessous = aucune proposition, cluster_thr)
|
||||||
|
DEFAULT_THR = {"efficientnet": (0.70, 0.55, 0.75),
|
||||||
|
"dinov2_small": (0.70, 0.50, 0.70),
|
||||||
|
"dinov2_base": (0.70, 0.50, 0.70)}
|
||||||
|
# mêmes valeurs par défaut que les arguments de shelf_app.py
|
||||||
|
DEFAULTS = dict(det_conf=0.30, sim_thr=None, min_sim=None, cluster_thr=None, min_group=1,
|
||||||
|
margin=0.05, text_w=0.15, min_letters=6, sim_certain=0.90, strict_vis=0.78,
|
||||||
|
ocr_cluster_thr=0.88, ocr=True, strict=True, prop_thr=0.85)
|
||||||
|
|
||||||
|
|
||||||
|
class FacingEngine:
|
||||||
|
def __init__(self, detector="detector/best.pt", backbone="efficientnet", weights=None,
|
||||||
|
kb_dir="kb_data", data_dir="data", **opts):
|
||||||
|
self.args = SimpleNamespace(**{**DEFAULTS, **opts})
|
||||||
|
self.data_dir = data_dir
|
||||||
|
self.det = YOLO(detector)
|
||||||
|
self.emb = Embedder(backbone, weights=weights)
|
||||||
|
self.kb = KnowledgeBase(kb_dir, dim=self.emb.dim, backbone=self.emb.name)
|
||||||
|
d_sim, d_min, d_clu = DEFAULT_THR.get(backbone, (0.70, 0.55, 0.75))
|
||||||
|
a = self.args
|
||||||
|
self.sim_thr = a.sim_thr or d_sim
|
||||||
|
self.min_sim = min(a.min_sim or d_min, self.sim_thr)
|
||||||
|
self.cluster_thr = a.cluster_thr or d_clu
|
||||||
|
if a.ocr:
|
||||||
|
try:
|
||||||
|
import easyocr # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
print("easyocr n'est pas installé : lecture du texte désactivée.")
|
||||||
|
a.ocr = False
|
||||||
|
|
||||||
|
# ---------- décision pour une boîte (identique à App.judge) ----------
|
||||||
|
def judge(self, vis_i, lines, sigs, df):
|
||||||
|
a = self.args
|
||||||
|
scores, tsc, inf = fuse(vis_i, lines, sigs, df, a.text_w, a.min_letters)
|
||||||
|
srcs = {k: source(k, tsc, inf, sigs) for k in scores}
|
||||||
|
veto = {k for k, v in srcs.items() if v == "douteux"}
|
||||||
|
confirmed = {k for k, v in srcs.items() if v == "texte"} if a.strict else None
|
||||||
|
status, top = decide(scores, self.sim_thr, a.margin, veto, confirmed, vis_i, a.strict_vis)
|
||||||
|
return status, top, srcs
|
||||||
|
|
||||||
|
def nearest_anchor(self, vecs, i, anchors):
|
||||||
|
"""(produit, similarité) du produit confirmé auquel la vignette i ressemble nettement, sinon None."""
|
||||||
|
best = {sku: float((vecs[sorted(idx - {i})] @ vecs[i]).max())
|
||||||
|
for sku, idx in anchors.items() if idx - {i}}
|
||||||
|
ranked = sorted(best.items(), key=lambda x: -x[1])
|
||||||
|
if not ranked or ranked[0][1] < self.args.prop_thr:
|
||||||
|
return None
|
||||||
|
if len(ranked) > 1 and ranked[0][1] - ranked[1][1] < 0.03:
|
||||||
|
return None
|
||||||
|
return ranked[0]
|
||||||
|
|
||||||
|
# ---------- analyse d'une photo de rayon (identique à App.analyze, étapes 1 à 4) ----------
|
||||||
|
def analyze(self, img, progress=lambda p: None, sid=None):
|
||||||
|
a = self.args
|
||||||
|
t0 = time.time()
|
||||||
|
h, w = img.shape[:2]
|
||||||
|
progress(5)
|
||||||
|
res = self.det.predict(img, conf=a.det_conf, iou=0.45, verbose=False)[0]
|
||||||
|
boxes, crops = [], []
|
||||||
|
for x1, y1, x2, y2 in res.boxes.xyxy.cpu().numpy().astype(int):
|
||||||
|
x1, y1, x2, y2 = max(int(x1), 0), max(int(y1), 0), min(int(x2), w), min(int(y2), h)
|
||||||
|
if x2 - x1 < 5 or y2 - y1 < 5:
|
||||||
|
continue
|
||||||
|
boxes.append((x1, y1, x2, y2))
|
||||||
|
crops.append(Image.fromarray(cv2.cvtColor(img[y1:y2, x1:x2], cv2.COLOR_BGR2RGB)))
|
||||||
|
n = len(crops)
|
||||||
|
s = SimpleNamespace(id=sid, w=w, h=h, boxes=boxes, crops=crops, vecs=None, big=set(),
|
||||||
|
lines_of={}, assign=[None] * n, sims=[0.0] * n, group_of={}, groups=[],
|
||||||
|
suggest={}, picks={}, guess={}, thumbs={}, new_now={}, notproduct=set(),
|
||||||
|
enrolled=set(), anchors={}, ignored=set(), phase="done", created=time.time(),
|
||||||
|
analysis_s=0.0, t_ready=time.time())
|
||||||
|
if n == 0:
|
||||||
|
return s
|
||||||
|
|
||||||
|
area = lambda m: crops[m].width * crops[m].height
|
||||||
|
s.big = big = {i for i in range(n) if crops[i].width >= MIN_SIZE and crops[i].height >= MIN_SIZE}
|
||||||
|
progress(20)
|
||||||
|
|
||||||
|
# 1) reconnaissance visuelle
|
||||||
|
vecs = self.emb.encode(crops)
|
||||||
|
s.vecs = vecs
|
||||||
|
cands = self.kb.search(vecs, k=60)
|
||||||
|
vis = [dict(c) for c in cands]
|
||||||
|
sigs, df = self.kb.signatures()
|
||||||
|
progress(40)
|
||||||
|
|
||||||
|
# 2) lecture du texte (sauf si la ressemblance visuelle est déjà très nette)
|
||||||
|
lines_of = s.lines_of
|
||||||
|
if a.ocr:
|
||||||
|
need = []
|
||||||
|
for i in sorted(big):
|
||||||
|
v1 = cands[i][0][1] if cands[i] else 0.0
|
||||||
|
v2 = cands[i][1][1] if len(cands[i]) > 1 else 0.0
|
||||||
|
if not (v1 >= a.sim_certain and v1 - v2 >= 2 * a.margin):
|
||||||
|
need.append(i)
|
||||||
|
if need:
|
||||||
|
clusters = cluster_embeddings(vecs[need], a.ocr_cluster_thr)
|
||||||
|
for k, cl in enumerate(clusters):
|
||||||
|
progress(40 + int(40 * (k + 1) / len(clusters)))
|
||||||
|
members = [need[j] for j in cl]
|
||||||
|
lines = read_text(crops[max(members, key=area)])
|
||||||
|
for m in members:
|
||||||
|
lines_of[m] = lines
|
||||||
|
|
||||||
|
# 3) décision : reconnus / en attente
|
||||||
|
assign, sims, pend = s.assign, s.sims, {}
|
||||||
|
for i in range(n):
|
||||||
|
status, top, srcs = self.judge(vis[i], lines_of.get(i), sigs, df)
|
||||||
|
if top:
|
||||||
|
sims[i] = float(top[0][1])
|
||||||
|
if status == "known":
|
||||||
|
assign[i] = top[0][0]
|
||||||
|
else:
|
||||||
|
pend[i] = [(k, float(sc), srcs[k]) for k, sc in top if sc >= self.min_sim]
|
||||||
|
|
||||||
|
# 3b) propagation depuis les exemplaires déjà confirmés de la même photo
|
||||||
|
anchors = s.anchors
|
||||||
|
for i, sku in enumerate(assign):
|
||||||
|
if sku:
|
||||||
|
anchors.setdefault(sku, set()).add(i)
|
||||||
|
for _ in range(3):
|
||||||
|
moved = False
|
||||||
|
for i in list(pend):
|
||||||
|
m = self.nearest_anchor(vecs, i, anchors)
|
||||||
|
if m:
|
||||||
|
assign[i], sims[i] = m[0], float(m[1])
|
||||||
|
anchors[m[0]].add(i)
|
||||||
|
pend.pop(i)
|
||||||
|
moved = True
|
||||||
|
if not moved:
|
||||||
|
break
|
||||||
|
progress(85)
|
||||||
|
|
||||||
|
# 4) ce qui n'est pas sûr est regroupé par produit, pour être nommé ou confirmé
|
||||||
|
pending = sorted(pend)
|
||||||
|
groups = []
|
||||||
|
if pending:
|
||||||
|
for idx in cluster_embeddings(vecs[pending], self.cluster_thr):
|
||||||
|
groups.append([pending[j] for j in idx])
|
||||||
|
groups.sort(key=len, reverse=True)
|
||||||
|
groups = [g for g in groups if len(g) >= a.min_group]
|
||||||
|
s.groups = groups
|
||||||
|
s.group_of = {i: g for g, idx in enumerate(groups) for i in idx}
|
||||||
|
|
||||||
|
for g, idx in enumerate(groups):
|
||||||
|
acc = {}
|
||||||
|
for i in idx:
|
||||||
|
for k, sc, src in pend.get(i, []):
|
||||||
|
t = acc.setdefault(k, ([], []))
|
||||||
|
t[0].append(sc)
|
||||||
|
t[1].append(src)
|
||||||
|
ranked = sorted(((k, sum(t[0]) / len(t[0]), t[1]) for k, t in acc.items()),
|
||||||
|
key=lambda x: -x[1])[:2]
|
||||||
|
opts = []
|
||||||
|
for k, sc, srcs in ranked:
|
||||||
|
src = "texte" if "texte" in srcs else ("douteux" if all(x == "douteux" for x in srcs) else "visuel")
|
||||||
|
opts.append((k, sc, src))
|
||||||
|
if opts:
|
||||||
|
s.suggest[g] = opts
|
||||||
|
# présélection seulement si elle est sûre (même règle que le web)
|
||||||
|
if opts[0][2] != "douteux" and (opts[0][2] == "texte" or not a.strict) and (
|
||||||
|
len(opts) == 1 or opts[0][1] - opts[1][1] >= a.margin
|
||||||
|
or (opts[0][2] == "texte" and opts[1][2] != "texte")):
|
||||||
|
s.picks[g] = 0
|
||||||
|
if a.ocr:
|
||||||
|
order = sorted([i for i in idx if i in big], key=area, reverse=True)
|
||||||
|
if order:
|
||||||
|
lines = lines_of.get(order[0]) or read_text(crops[order[0]])
|
||||||
|
s.guess[g] = guess_name(lines)
|
||||||
|
s.thumbs[g] = [self._thumb(crops[i]) for i in sorted(idx, key=area, reverse=True)[:2]]
|
||||||
|
|
||||||
|
s.analysis_s = round(time.time() - t0, 2)
|
||||||
|
s.t_ready = time.time()
|
||||||
|
progress(100)
|
||||||
|
if groups:
|
||||||
|
s.phase = "review" # le panneau « N groupe(s) à identifier »
|
||||||
|
else:
|
||||||
|
self._enter_resolve(s) # comme le web : pas de panneau, on passe à la suite
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
# ================= actions (les fenêtres du web) =================
|
||||||
|
def area(self, s, i):
|
||||||
|
c = s.crops[i]
|
||||||
|
return c.width * c.height
|
||||||
|
|
||||||
|
def read(self, pil):
|
||||||
|
return read_text(pil)
|
||||||
|
|
||||||
|
def tokens_of(self, lines):
|
||||||
|
return tokens(full_text(lines))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _need_phase(s, phase):
|
||||||
|
if s.phase != phase:
|
||||||
|
raise FacingError(409, "Cette étape n'est pas disponible maintenant.")
|
||||||
|
|
||||||
|
def _ids(self, s, ids):
|
||||||
|
"""Boîtes encore INCONNUES, sans doublon."""
|
||||||
|
out = sorted(set(int(i) for i in ids))
|
||||||
|
un = set(self.unresolved(s))
|
||||||
|
for i in out:
|
||||||
|
if i not in un:
|
||||||
|
raise FacingError(400, f"Le produit {i} est déjà identifié ou n'existe pas.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
def enroll_selection(self, s, idx, name, sku=None):
|
||||||
|
"""Enregistre les produits idx sous ce nom (produit existant ou nouveau). Retourne (sku, est_nouveau)."""
|
||||||
|
idx = list(idx)
|
||||||
|
refs = [i for i in idx if i in s.big] or idx
|
||||||
|
existing = sku or find_product(self.kb, name)
|
||||||
|
new_sku = enroll_named(self.kb, self.emb, name, [s.crops[i] for i in refs],
|
||||||
|
s.vecs[refs], self.data_dir, sku=existing)
|
||||||
|
if self.args.ocr:
|
||||||
|
# le produit apprend aussi les mots lus sur son emballage
|
||||||
|
best3 = sorted(refs, key=lambda i: self.area(s, i), reverse=True)[:3]
|
||||||
|
self.kb.add_text(new_sku, [self.tokens_of(s.lines_of.get(m) or self.read(s.crops[m]))
|
||||||
|
for m in best3])
|
||||||
|
for i in idx:
|
||||||
|
s.assign[i] = new_sku
|
||||||
|
s.enrolled.update(idx)
|
||||||
|
s.anchors.setdefault(new_sku, set()).update(idx)
|
||||||
|
is_new = existing is None
|
||||||
|
if is_new:
|
||||||
|
s.new_now[new_sku] = len(s.new_now) # indice de couleur du produit nouveau
|
||||||
|
return new_sku, is_new
|
||||||
|
|
||||||
|
def reclassify_unresolved(self, s):
|
||||||
|
"""Après un nouveau nom, les autres inconnus qui lui ressemblent sont reconnus seuls
|
||||||
|
(mêmes règles que l'analyse). Retourne le nombre de produits reconnus."""
|
||||||
|
un = self.unresolved(s)
|
||||||
|
if not un:
|
||||||
|
return 0
|
||||||
|
sigs, df = self.kb.signatures()
|
||||||
|
found = 0
|
||||||
|
for i, c in zip(un, self.kb.search(s.vecs[un], k=60)):
|
||||||
|
status, top, srcs = self.judge(dict(c), s.lines_of.get(i), sigs, df)
|
||||||
|
sku = top[0][0] if status == "known" else None
|
||||||
|
if sku is None:
|
||||||
|
m = self.nearest_anchor(s.vecs, i, s.anchors)
|
||||||
|
sku = m[0] if m else None
|
||||||
|
if sku:
|
||||||
|
s.assign[i] = sku
|
||||||
|
s.sims[i] = float(top[0][1]) if top else 0.0
|
||||||
|
found += 1
|
||||||
|
return found
|
||||||
|
|
||||||
|
def _enter_resolve(self, s):
|
||||||
|
"""Fin du panneau (ou pas de panneau) : on tente de reconnaître les inconnus, puis on passe
|
||||||
|
à la sélection. S'il n'en reste aucun, le web va directement au rapport."""
|
||||||
|
s.phase = "resolve"
|
||||||
|
self.reclassify_unresolved(s)
|
||||||
|
if not self.unresolved(s):
|
||||||
|
self.finalize(s)
|
||||||
|
|
||||||
|
def finalize(self, s):
|
||||||
|
"""Compteurs cumulés + journal CSV (Terminer / rapport). Sans effet si déjà fait."""
|
||||||
|
if s.phase == "done":
|
||||||
|
return
|
||||||
|
counts = Counter(x for x in s.assign if x)
|
||||||
|
self.kb.bump(counts)
|
||||||
|
s.phase = "done"
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
os.makedirs("logs", exist_ok=True)
|
||||||
|
path = os.path.join("logs", f"{os.path.basename(self.kb.path)}_analyses.csv")
|
||||||
|
new = not os.path.exists(path)
|
||||||
|
row = {"photo": f"mobile_{s.id}", "analysis_s": s.analysis_s,
|
||||||
|
"user_s": round(time.time() - s.t_ready, 2), "n_detected": len(s.boxes),
|
||||||
|
"n_new_groups": len(s.groups), "n_enrolled": len(s.new_now),
|
||||||
|
"n_ignored": len(s.ignored), "n_unknown_left": len(self.unresolved(s)),
|
||||||
|
"counts": json.dumps({P[k].get("name", k): c for k, c in counts.items()}, ensure_ascii=False)}
|
||||||
|
with open(path, "a", newline="", encoding="utf-8") as f:
|
||||||
|
w = csv.DictWriter(f, fieldnames=list(row.keys()))
|
||||||
|
if new:
|
||||||
|
w.writeheader()
|
||||||
|
w.writerow(row)
|
||||||
|
|
||||||
|
# ---- panneau « N groupe(s) à identifier » ----
|
||||||
|
def apply_review(self, s, choices):
|
||||||
|
"""choices : [{group, kind: existing|new|later, sku?, name?}]. Groupe absent = laissé pour plus tard."""
|
||||||
|
self._need_phase(s, "review")
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
by_group = {}
|
||||||
|
for c in choices:
|
||||||
|
g = int(c["group"])
|
||||||
|
if not 0 <= g < len(s.groups):
|
||||||
|
raise FacingError(400, f"Groupe {g + 1} inconnu.")
|
||||||
|
kind = c.get("kind")
|
||||||
|
if kind == "existing":
|
||||||
|
if c.get("sku") not in P:
|
||||||
|
raise FacingError(400, f"Groupe {g + 1} : produit inconnu.")
|
||||||
|
elif kind == "new":
|
||||||
|
if not (c.get("name") or "").strip():
|
||||||
|
raise FacingError(400, f"Groupe {g + 1} : tapez un nom ou choisissez une autre option.")
|
||||||
|
elif kind != "later":
|
||||||
|
raise FacingError(400, f"Groupe {g + 1} : choix invalide.")
|
||||||
|
by_group[g] = c
|
||||||
|
for g, idx in enumerate(s.groups):
|
||||||
|
c = by_group.get(g)
|
||||||
|
if c and c["kind"] == "existing":
|
||||||
|
self.enroll_selection(s, idx, P[c["sku"]]["name"], sku=c["sku"])
|
||||||
|
elif c and c["kind"] == "new":
|
||||||
|
self.enroll_selection(s, idx, c["name"].strip())
|
||||||
|
else:
|
||||||
|
s.ignored.add(g) # laissé pour plus tard : reste INCONNU
|
||||||
|
self._enter_resolve(s)
|
||||||
|
|
||||||
|
# ---- barre de sélection des inconnus ----
|
||||||
|
def select_similar(self, s, ids):
|
||||||
|
self._need_phase(s, "resolve")
|
||||||
|
sel = self._ids(s, ids)
|
||||||
|
if not sel:
|
||||||
|
raise FacingError(400, "Sélectionnez d'abord au moins un produit.")
|
||||||
|
out = set(sel)
|
||||||
|
un = [i for i in self.unresolved(s) if i not in out]
|
||||||
|
if un:
|
||||||
|
sim = s.vecs[un] @ s.vecs[sel].T
|
||||||
|
for j, i in enumerate(un):
|
||||||
|
if sim[j].max() >= self.cluster_thr:
|
||||||
|
out.add(i)
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
def suggest_for(self, s, ids):
|
||||||
|
"""Propositions pour la sélection : (liste [(sku, score, origine)], nom proposé)."""
|
||||||
|
self._need_phase(s, "resolve")
|
||||||
|
sel = self._ids(s, ids)
|
||||||
|
if not sel:
|
||||||
|
raise FacingError(400, "Sélectionnez d'abord au moins un produit.")
|
||||||
|
sigs, df = self.kb.signatures()
|
||||||
|
acc = {}
|
||||||
|
for r in self.kb.search(s.vecs[sel], k=60):
|
||||||
|
for k, v in r:
|
||||||
|
acc.setdefault(k, []).append(v)
|
||||||
|
vis = {k: sum(v) / len(v) for k, v in acc.items()}
|
||||||
|
lines, guess = None, ""
|
||||||
|
if self.args.ocr:
|
||||||
|
rep = max(sel, key=lambda i: self.area(s, i))
|
||||||
|
lines = s.lines_of.get(rep) or (self.read(s.crops[rep]) if rep in s.big else None)
|
||||||
|
if lines:
|
||||||
|
guess = guess_name(lines)
|
||||||
|
a = self.args
|
||||||
|
scores, tsc, inf = fuse(vis, lines, sigs, df, a.text_w, a.min_letters)
|
||||||
|
ranked = sorted(scores.items(), key=lambda x: -x[1])[:2]
|
||||||
|
opts = [(k, float(sc), source(k, tsc, inf, sigs)) for k, sc in ranked if sc >= self.min_sim]
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
default = P[opts[0][0]]["name"] if opts and opts[0][2] != "douteux" else guess
|
||||||
|
return opts, default
|
||||||
|
|
||||||
|
def name_selection(self, s, ids, name, sku=None):
|
||||||
|
"""Nommer la sélection. Retourne le nombre d'autres produits reconnus automatiquement."""
|
||||||
|
self._need_phase(s, "resolve")
|
||||||
|
sel = self._ids(s, ids)
|
||||||
|
if not sel:
|
||||||
|
raise FacingError(400, "Cliquez d'abord sur les produits à nommer.")
|
||||||
|
name = (name or "").strip()
|
||||||
|
if not name:
|
||||||
|
raise FacingError(400, "Tapez un nom.")
|
||||||
|
if sku is not None and sku not in self.kb.meta["products"]:
|
||||||
|
raise FacingError(400, "Produit inconnu.")
|
||||||
|
self.enroll_selection(s, sel, name, sku=sku)
|
||||||
|
return self.reclassify_unresolved(s)
|
||||||
|
|
||||||
|
def not_product(self, s, ids):
|
||||||
|
self._need_phase(s, "resolve")
|
||||||
|
sel = self._ids(s, ids)
|
||||||
|
if not sel:
|
||||||
|
raise FacingError(400, "Sélectionnez d'abord ce qui n'est pas un produit.")
|
||||||
|
folder = os.path.join(self.data_dir, "_rejected_")
|
||||||
|
os.makedirs(folder, exist_ok=True)
|
||||||
|
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
for i in sel:
|
||||||
|
s.crops[i].save(os.path.join(folder, f"{stamp}_{i}.jpg"), quality=92)
|
||||||
|
s.notproduct.update(sel)
|
||||||
|
|
||||||
|
def reset_box(self, s, i):
|
||||||
|
"""Clic droit du web : remet un produit identifié en INCONNU (sauf s'il vient d'être enregistré)."""
|
||||||
|
self._need_phase(s, "resolve")
|
||||||
|
i = int(i)
|
||||||
|
if not (0 <= i < len(s.boxes)) or not (s.assign[i] is not None or i in s.notproduct):
|
||||||
|
raise FacingError(400, "Ce produit n'est pas identifié.")
|
||||||
|
if i in s.enrolled:
|
||||||
|
raise FacingError(409, "Ce produit vient d'être enregistré dans la base pendant cette analyse. "
|
||||||
|
"Pour ne pas y laisser de mauvaises images, il ne peut pas être remis en "
|
||||||
|
"INCONNU ici. S'il porte un mauvais nom, corrigez-le ensuite "
|
||||||
|
"(renommer ou fusionner le produit).")
|
||||||
|
s.assign[i] = None
|
||||||
|
s.notproduct.discard(i)
|
||||||
|
|
||||||
|
def finish(self, s):
|
||||||
|
self._need_phase(s, "resolve")
|
||||||
|
self.finalize(s)
|
||||||
|
|
||||||
|
# ---- « Ajouter un produit à partir de photos » ----
|
||||||
|
def main_crop(self, pil):
|
||||||
|
bgr = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR)
|
||||||
|
res = self.det.predict(bgr, conf=self.args.det_conf, iou=0.45, verbose=False)[0]
|
||||||
|
boxes = res.boxes.xyxy.cpu().numpy().astype(int)
|
||||||
|
if len(boxes) == 0:
|
||||||
|
return pil
|
||||||
|
x1, y1, x2, y2 = max(boxes, key=lambda b: (b[2] - b[0]) * (b[3] - b[1]))
|
||||||
|
return pil.crop((max(x1, 0), max(y1, 0), x2, y2))
|
||||||
|
|
||||||
|
def add_product(self, name, images, force=False):
|
||||||
|
name = (name or "").strip()
|
||||||
|
if not name:
|
||||||
|
raise FacingError(400, "Tapez le nom du produit.")
|
||||||
|
if not images:
|
||||||
|
raise FacingError(400, "Ajoutez au moins une photo.")
|
||||||
|
crops = [self.main_crop(im) for im in images]
|
||||||
|
vecs = self.emb.encode(crops)
|
||||||
|
top = [r[0] for r in self.kb.search(vecs, k=3) if r]
|
||||||
|
best = max(((sim, sku) for sku, sim in top), default=None)
|
||||||
|
if best and best[0] >= self.sim_thr and not force:
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
return {"ok": False, "duplicate": {"sku": best[1], "name": P[best[1]].get("name", best[1]),
|
||||||
|
"sim": round(float(best[0]), 3)}}
|
||||||
|
sku = enroll_named(self.kb, self.emb, name, crops, vecs, self.data_dir)
|
||||||
|
if self.args.ocr:
|
||||||
|
self.kb.add_text(sku, [self.tokens_of(self.read(c)) for c in crops])
|
||||||
|
return {"ok": True, "sku": sku, "name": name, "photos": len(crops),
|
||||||
|
"folder": os.path.join(self.data_dir, sku)}
|
||||||
|
|
||||||
|
# ================= état =================
|
||||||
|
@staticmethod
|
||||||
|
def _thumb(pil):
|
||||||
|
im = pil.copy()
|
||||||
|
im.thumbnail((90, 120))
|
||||||
|
buf = io.BytesIO()
|
||||||
|
im.convert("RGB").save(buf, "JPEG", quality=80)
|
||||||
|
return base64.b64encode(buf.getvalue()).decode()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def unresolved(s):
|
||||||
|
return [i for i in range(len(s.boxes)) if s.assign[i] is None and i not in s.notproduct]
|
||||||
|
|
||||||
|
def state(self, s):
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
name = lambda sku: P[sku].get("name", sku) if sku in P else sku
|
||||||
|
boxes = []
|
||||||
|
for i, (x1, y1, x2, y2) in enumerate(s.boxes):
|
||||||
|
sku = s.assign[i]
|
||||||
|
if sku:
|
||||||
|
status = "known"
|
||||||
|
elif i in s.notproduct:
|
||||||
|
status = "notproduct"
|
||||||
|
elif s.phase == "review" and i in s.group_of:
|
||||||
|
status = "pending"
|
||||||
|
else:
|
||||||
|
status = "unknown"
|
||||||
|
boxes.append({"id": i, "bbox": [x1, y1, x2, y2], "status": status,
|
||||||
|
"sku": sku, "name": name(sku) if sku else None,
|
||||||
|
"new_idx": s.new_now.get(sku, -1) if sku else -1,
|
||||||
|
"sim": round(float(s.sims[i]), 3),
|
||||||
|
"group": s.group_of.get(i) if s.phase == "review" else None,
|
||||||
|
"enrolled": i in s.enrolled})
|
||||||
|
groups = []
|
||||||
|
if s.phase == "review":
|
||||||
|
for g, idx in enumerate(s.groups):
|
||||||
|
groups.append({
|
||||||
|
"id": g, "box_ids": list(idx), "thumbs": s.thumbs.get(g, []),
|
||||||
|
"suggest": [{"sku": k, "name": name(k), "score": round(float(sc), 3), "source": src}
|
||||||
|
for k, sc, src in s.suggest.get(g, [])],
|
||||||
|
"pick": s.picks.get(g), "guess": s.guess.get(g, "")})
|
||||||
|
counts = Counter(x for x in s.assign if x)
|
||||||
|
return {"session_id": s.id, "phase": s.phase, "image": {"w": s.w, "h": s.h},
|
||||||
|
"boxes": boxes, "groups": groups,
|
||||||
|
"counts": [{"sku": k, "name": name(k), "count": c, "new": k in s.new_now,
|
||||||
|
"cumul": int(P[k].get("total_facings", 0)),
|
||||||
|
"photos": int(P[k].get("photos_seen", 0))} for k, c in counts.most_common()],
|
||||||
|
"unknown_left": len(self.unresolved(s)), "analysis_s": s.analysis_s}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
"""Routes Facing AI « comme le web » (toutes les fenêtres de shelf_app.py), à brancher sur un serveur FastAPI existant.
|
||||||
|
Dans api_server.py :
|
||||||
|
from facing_router import router as facing_router
|
||||||
|
app.include_router(facing_router)
|
||||||
|
Les modèles ne sont chargés qu'à la première utilisation : si la base est absente, seules les routes /facing/...
|
||||||
|
répondent par une erreur claire, l'ancien serveur (/health, /jobs) n'est pas touché."""
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from PIL import Image
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from facing_engine import FacingEngine, FacingError
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# mêmes valeurs que dans votre commande habituelle de shelf_app.py (variables d'environnement)
|
||||||
|
KB_DIR = os.getenv("FACING_KB", "kb_data")
|
||||||
|
LOCK = threading.Lock() # un seul traitement à la fois (modèles, base partagée)
|
||||||
|
POOL = ThreadPoolExecutor(max_workers=1)
|
||||||
|
JOBS, SESSIONS = {}, {}
|
||||||
|
TTL, MAX_SESSIONS = 3600, 20
|
||||||
|
|
||||||
|
_engine = None
|
||||||
|
_engine_lock = threading.Lock()
|
||||||
|
_preload = {"started": False, "error": None}
|
||||||
|
|
||||||
|
|
||||||
|
def eng():
|
||||||
|
"""Moteur Facing, chargé à la première utilisation. Lève FacingError(503) avec un message clair."""
|
||||||
|
global _engine
|
||||||
|
if _engine is not None:
|
||||||
|
return _engine
|
||||||
|
with _engine_lock:
|
||||||
|
if _engine is None:
|
||||||
|
if not os.path.exists(os.path.join(KB_DIR, "index.faiss")) and os.getenv("FACING_ALLOW_EMPTY") != "1":
|
||||||
|
# sans ce contrôle, KnowledgeBase crée en silence une base VIDE et tout devient « inconnu »
|
||||||
|
raise FacingError(503, f"Base introuvable : {os.path.abspath(KB_DIR)} (pas de index.faiss). "
|
||||||
|
"Vérifiez FACING_KB (comme --kb_dir de shelf_app.py).")
|
||||||
|
try:
|
||||||
|
e = FacingEngine(
|
||||||
|
detector=os.getenv("FACING_DETECTOR", "detector/best.pt"),
|
||||||
|
backbone=os.getenv("FACING_BACKBONE", "efficientnet"),
|
||||||
|
weights=os.getenv("FACING_WEIGHTS") or None,
|
||||||
|
kb_dir=KB_DIR,
|
||||||
|
data_dir=os.getenv("FACING_DATA", "data"),
|
||||||
|
)
|
||||||
|
except SystemExit as ex: # KnowledgeBase s'arrête ainsi si l'encodeur ne correspond pas à la base
|
||||||
|
raise FacingError(503, str(ex))
|
||||||
|
except Exception as ex:
|
||||||
|
raise FacingError(503, f"Chargement impossible : {type(ex).__name__}: {ex}")
|
||||||
|
print(f"[KB] dossier={os.path.abspath(KB_DIR)} backbone={e.emb.name} "
|
||||||
|
f"vecteurs={e.kb.index.ntotal} produits={len(e.kb.meta['products'])}")
|
||||||
|
_engine = e
|
||||||
|
return _engine
|
||||||
|
|
||||||
|
|
||||||
|
def _start_preload():
|
||||||
|
"""Charge les modèles en arrière-plan dès la première demande de santé (la page s'ouvre sans attendre)."""
|
||||||
|
if _preload["started"]:
|
||||||
|
return
|
||||||
|
_preload["started"] = True
|
||||||
|
|
||||||
|
def go():
|
||||||
|
try:
|
||||||
|
eng()
|
||||||
|
except FacingError as e:
|
||||||
|
_preload["error"] = e.msg
|
||||||
|
threading.Thread(target=go, daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- corps des requêtes ----------
|
||||||
|
class AnalyzeRequest(BaseModel):
|
||||||
|
image: str # JPEG en base64 (avec ou sans préfixe data:)
|
||||||
|
|
||||||
|
|
||||||
|
class BoxIds(BaseModel):
|
||||||
|
box_ids: List[int]
|
||||||
|
|
||||||
|
|
||||||
|
class NameReq(BaseModel):
|
||||||
|
box_ids: List[int]
|
||||||
|
name: str
|
||||||
|
sku: Optional[str] = None # produit existant choisi dans la liste, sinon nom libre
|
||||||
|
|
||||||
|
|
||||||
|
class ResetReq(BaseModel):
|
||||||
|
box_id: int
|
||||||
|
|
||||||
|
|
||||||
|
class ReviewChoice(BaseModel):
|
||||||
|
group: int
|
||||||
|
kind: str # existing | new | later
|
||||||
|
sku: Optional[str] = None
|
||||||
|
name: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ReviewReq(BaseModel):
|
||||||
|
choices: List[ReviewChoice] = [] # groupe absent = laissé pour plus tard
|
||||||
|
|
||||||
|
|
||||||
|
class ProductReq(BaseModel):
|
||||||
|
name: str
|
||||||
|
images: List[str] # photos du produit, en base64
|
||||||
|
force: bool = False # continuer malgré un doublon possible
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- outils ----------
|
||||||
|
def _decode_bytes(b64):
|
||||||
|
if b64.startswith("data:") and "," in b64:
|
||||||
|
b64 = b64.split(",", 1)[1]
|
||||||
|
return base64.b64decode(b64)
|
||||||
|
|
||||||
|
|
||||||
|
def _decode(b64):
|
||||||
|
img = cv2.imdecode(np.frombuffer(_decode_bytes(b64), np.uint8), cv2.IMREAD_COLOR)
|
||||||
|
if img is None:
|
||||||
|
raise ValueError("image illisible")
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def _dump(m):
|
||||||
|
return m.model_dump() if hasattr(m, "model_dump") else m.dict()
|
||||||
|
|
||||||
|
|
||||||
|
def _purge():
|
||||||
|
now = time.time()
|
||||||
|
for k in [k for k, j in JOBS.items() if now - j["created"] > TTL]:
|
||||||
|
JOBS.pop(k, None)
|
||||||
|
for k in [k for k, s in SESSIONS.items() if now - s.created > TTL]:
|
||||||
|
SESSIONS.pop(k, None)
|
||||||
|
while len(SESSIONS) > MAX_SESSIONS:
|
||||||
|
SESSIONS.pop(min(SESSIONS, key=lambda k: SESSIONS[k].created), None)
|
||||||
|
|
||||||
|
|
||||||
|
def _act(sid, fn):
|
||||||
|
"""Exécute une action sur une session, sous verrou ; les erreurs métier deviennent des erreurs HTTP."""
|
||||||
|
with LOCK:
|
||||||
|
s = SESSIONS.get(sid)
|
||||||
|
if s is None:
|
||||||
|
raise HTTPException(404, "Session expirée : relancez l'analyse.")
|
||||||
|
try:
|
||||||
|
return fn(s, eng())
|
||||||
|
except FacingError as e:
|
||||||
|
raise HTTPException(e.code, e.msg)
|
||||||
|
|
||||||
|
|
||||||
|
def _run(job_id, img):
|
||||||
|
job = JOBS[job_id]
|
||||||
|
try:
|
||||||
|
with LOCK:
|
||||||
|
e = eng() # au premier appel : chargement des modèles (progression à 0 %)
|
||||||
|
sid = uuid.uuid4().hex[:8]
|
||||||
|
s = e.analyze(img, lambda p: job.update(progress=p), sid=sid)
|
||||||
|
SESSIONS[sid] = s
|
||||||
|
job["results"] = e.state(s)
|
||||||
|
job.update(status="done", progress=100)
|
||||||
|
except FacingError as ex:
|
||||||
|
job.update(status="failed", error=ex.msg)
|
||||||
|
except Exception as ex: # le mobile affiche le message
|
||||||
|
job.update(status="failed", error=f"{type(ex).__name__}: {ex}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- analyse ----------
|
||||||
|
@router.get("/facing/health")
|
||||||
|
def health():
|
||||||
|
_start_preload()
|
||||||
|
if _preload["error"]:
|
||||||
|
return JSONResponse(status_code=503, content={"status": "error", "detail": _preload["error"]})
|
||||||
|
out = {"status": "ok", "loaded": _engine is not None, "kb_dir": os.path.abspath(KB_DIR),
|
||||||
|
"active_jobs": sum(1 for j in JOBS.values() if j["status"] == "processing")}
|
||||||
|
if _engine is not None:
|
||||||
|
P = _engine.kb.meta["products"]
|
||||||
|
out.update(backbone=_engine.emb.name, ocr=_engine.args.ocr,
|
||||||
|
products=sum(1 for p in P.values() if p.get("status") != "merged"),
|
||||||
|
vectors=int(_engine.kb.index.ntotal))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/analyze")
|
||||||
|
def analyze(req: AnalyzeRequest):
|
||||||
|
try:
|
||||||
|
img = _decode(req.image)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(400, "image illisible")
|
||||||
|
_purge()
|
||||||
|
job_id = uuid.uuid4().hex
|
||||||
|
JOBS[job_id] = {"status": "processing", "progress": 0, "results": None, "error": None,
|
||||||
|
"created": time.time()}
|
||||||
|
POOL.submit(_run, job_id, img)
|
||||||
|
return {"job_id": job_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/facing/jobs/{job_id}")
|
||||||
|
def job(job_id: str):
|
||||||
|
j = JOBS.get(job_id)
|
||||||
|
if not j:
|
||||||
|
raise HTTPException(404, "job inconnu")
|
||||||
|
return {"status": j["status"], "progress": j["progress"], "results": j["results"], "error": j["error"]}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- produits ----------
|
||||||
|
@router.get("/facing/products")
|
||||||
|
def products():
|
||||||
|
try:
|
||||||
|
P = eng().kb.meta["products"]
|
||||||
|
except FacingError as e:
|
||||||
|
raise HTTPException(e.code, e.msg)
|
||||||
|
items = [{"sku": k, "name": p.get("name", k)} for k, p in P.items() if p.get("status") != "merged"]
|
||||||
|
return {"products": sorted(items, key=lambda x: x["name"].lower())}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/products")
|
||||||
|
def add_product(req: ProductReq):
|
||||||
|
"""« Ajouter un produit à partir de photos » : {ok:true,...} ou {ok:false, duplicate:{name,sim}}."""
|
||||||
|
try:
|
||||||
|
images = [Image.open(io.BytesIO(_decode_bytes(b))).convert("RGB") for b in req.images]
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(400, "photo illisible")
|
||||||
|
with LOCK:
|
||||||
|
try:
|
||||||
|
return eng().add_product(req.name, images, req.force)
|
||||||
|
except FacingError as e:
|
||||||
|
raise HTTPException(e.code, e.msg)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- panneau « N groupe(s) à identifier » ----------
|
||||||
|
@router.post("/facing/{sid}/review")
|
||||||
|
def review(sid: str, req: ReviewReq):
|
||||||
|
def go(s, e):
|
||||||
|
e.apply_review(s, [_dump(c) for c in req.choices])
|
||||||
|
return e.state(s)
|
||||||
|
return _act(sid, go)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- barre de sélection des inconnus ----------
|
||||||
|
@router.post("/facing/{sid}/similar")
|
||||||
|
def similar(sid: str, req: BoxIds):
|
||||||
|
return _act(sid, lambda s, e: {"box_ids": e.select_similar(s, req.box_ids)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/{sid}/suggest")
|
||||||
|
def suggest(sid: str, req: BoxIds):
|
||||||
|
def go(s, e):
|
||||||
|
opts, default = e.suggest_for(s, req.box_ids)
|
||||||
|
P = e.kb.meta["products"]
|
||||||
|
return {"options": [{"sku": k, "name": P[k].get("name", k), "score": round(sc, 3), "source": src}
|
||||||
|
for k, sc, src in opts],
|
||||||
|
"default_name": default}
|
||||||
|
return _act(sid, go)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/{sid}/name")
|
||||||
|
def name(sid: str, req: NameReq):
|
||||||
|
def go(s, e):
|
||||||
|
auto = e.name_selection(s, req.box_ids, req.name, req.sku)
|
||||||
|
st = e.state(s)
|
||||||
|
st["auto_found"] = auto # « N autre(s) produit(s) reconnu(s) automatiquement »
|
||||||
|
return st
|
||||||
|
return _act(sid, go)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/{sid}/not_product")
|
||||||
|
def not_product(sid: str, req: BoxIds):
|
||||||
|
def go(s, e):
|
||||||
|
e.not_product(s, req.box_ids)
|
||||||
|
return e.state(s)
|
||||||
|
return _act(sid, go)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/{sid}/reset")
|
||||||
|
def reset(sid: str, req: ResetReq):
|
||||||
|
def go(s, e):
|
||||||
|
e.reset_box(s, req.box_id)
|
||||||
|
return e.state(s)
|
||||||
|
return _act(sid, go)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/facing/{sid}/finish")
|
||||||
|
def finish(sid: str):
|
||||||
|
def go(s, e):
|
||||||
|
e.finish(s)
|
||||||
|
return e.state(s)
|
||||||
|
return _act(sid, go)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/facing/{sid}")
|
||||||
|
def get_state(sid: str):
|
||||||
|
return _act(sid, lambda s, e: e.state(s))
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from facing_router import router
|
||||||
|
app = FastAPI(title="Facing AI")
|
||||||
|
app.include_router(router)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Inspecte un fichier de poids .pt sans rien modifier : type, clés, formes, métadonnées.
|
||||||
|
Usage : python inspect_weights.py runs\\classify\\best.pt"""
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import torch
|
||||||
|
|
||||||
|
path = sys.argv[1]
|
||||||
|
try:
|
||||||
|
ck = torch.load(path, map_location="cpu", weights_only=True)
|
||||||
|
print("Chargement sécurisé (weights_only=True) : OK")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"weights_only=True a échoué ({type(e).__name__}) -> rechargement classique (fichier à toi)")
|
||||||
|
ck = torch.load(path, map_location="cpu", weights_only=False)
|
||||||
|
|
||||||
|
print("Type :", type(ck).__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def is_state(d):
|
||||||
|
return isinstance(d, dict) and d and all(isinstance(v, torch.Tensor) for v in d.values())
|
||||||
|
|
||||||
|
|
||||||
|
def describe_state(d, indent=" "):
|
||||||
|
n_params = sum(v.numel() for v in d.values())
|
||||||
|
keys = list(d.keys())
|
||||||
|
print(f"{indent}{len(keys)} tenseurs, {n_params / 1e6:.2f} M paramètres")
|
||||||
|
for k in keys[:4]:
|
||||||
|
print(f"{indent} début : {k} {tuple(d[k].shape)}")
|
||||||
|
for k in keys[-4:]:
|
||||||
|
print(f"{indent} fin : {k} {tuple(d[k].shape)}")
|
||||||
|
heads = [k for k in keys if "classifier" in k or k.startswith("fc") or ".head" in k]
|
||||||
|
print(f"{indent}clés de tête (classifier/fc/head) : {heads[:6]}")
|
||||||
|
|
||||||
|
|
||||||
|
if is_state(ck):
|
||||||
|
print("C'est directement un state_dict :")
|
||||||
|
describe_state(ck)
|
||||||
|
elif isinstance(ck, dict):
|
||||||
|
print("Clés de premier niveau :", list(ck.keys()))
|
||||||
|
for k, v in ck.items():
|
||||||
|
if is_state(v):
|
||||||
|
print(f" [{k}] = state_dict :")
|
||||||
|
describe_state(v)
|
||||||
|
elif isinstance(v, (int, float, str, bool)) or v is None:
|
||||||
|
print(f" [{k}] = {v!r}")
|
||||||
|
elif isinstance(v, (list, tuple)):
|
||||||
|
print(f" [{k}] = liste de {len(v)} éléments : {list(v)[:8]}")
|
||||||
|
elif isinstance(v, dict):
|
||||||
|
print(f" [{k}] = dict de {len(v)} entrées : {list(v.items())[:6]}")
|
||||||
|
else:
|
||||||
|
print(f" [{k}] = {type(v).__name__}")
|
||||||
|
else:
|
||||||
|
print("Objet inattendu :", ck if isinstance(ck, (str, int, float)) else type(ck))
|
||||||
Whitespace-only changes.
@@ -0,0 +1,59 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from torchvision import transforms as T
|
||||||
|
|
||||||
|
AUG = T.Compose([T.RandomRotation(10), T.ColorJitter(0.3, 0.3, 0.3)])
|
||||||
|
|
||||||
|
|
||||||
|
def cluster_embeddings(vecs, thr=0.85):
|
||||||
|
"""Regroupe les recadrages d'un même produit : un vecteur rejoint le groupe
|
||||||
|
au centroïde le plus proche si la similarité est >= thr."""
|
||||||
|
clusters, centroids = [], []
|
||||||
|
for i, v in enumerate(vecs):
|
||||||
|
if centroids:
|
||||||
|
sims = np.array(centroids) @ v
|
||||||
|
j = int(sims.argmax())
|
||||||
|
if sims[j] >= thr:
|
||||||
|
clusters[j].append(i)
|
||||||
|
c = vecs[clusters[j]].mean(axis=0)
|
||||||
|
centroids[j] = c / np.linalg.norm(c)
|
||||||
|
continue
|
||||||
|
clusters.append([i])
|
||||||
|
centroids.append(v.copy())
|
||||||
|
return clusters
|
||||||
|
|
||||||
|
|
||||||
|
def slugify(name):
|
||||||
|
s = unicodedata.normalize("NFKD", name.lower()).encode("ascii", "ignore").decode()
|
||||||
|
return re.sub(r"[^a-z0-9]+", "_", s).strip("_") or "produit"
|
||||||
|
|
||||||
|
def find_product(kb, name):
|
||||||
|
"""Retourne le produit déjà présent dans la base dont le nom correspond, sinon None."""
|
||||||
|
target = slugify(name)
|
||||||
|
for sku, p in kb.meta["products"].items():
|
||||||
|
if p.get("status") != "merged" and slugify(p.get("name", sku)) == target:
|
||||||
|
return sku
|
||||||
|
return None
|
||||||
|
|
||||||
|
def enroll_named(kb, embedder, name, crops, vecs, data_dir="data", sku=None):
|
||||||
|
"""Enregistre des recadrages sous un produit : images dans data_dir/<sku>/ et vecteurs dans la base.
|
||||||
|
Si le produit existe déjà, on lui ajoute seulement des références."""
|
||||||
|
sku = sku or find_product(kb, name) or slugify(name)
|
||||||
|
folder = os.path.join(data_dir, sku)
|
||||||
|
os.makedirs(folder, exist_ok=True)
|
||||||
|
start = len(os.listdir(folder))
|
||||||
|
for n, c in enumerate(crops):
|
||||||
|
c.save(os.path.join(folder, f"{sku}_{start + n:03d}.jpg"), quality=92)
|
||||||
|
extra = [AUG(c) for c in crops for _ in range(2)]
|
||||||
|
all_vecs = np.vstack([vecs, embedder.encode(extra)])
|
||||||
|
if sku in kb.meta["products"]:
|
||||||
|
info = {}
|
||||||
|
else:
|
||||||
|
info = {"name": name, "status": "confirmed",
|
||||||
|
"created": datetime.now().isoformat(timespec="seconds")}
|
||||||
|
kb.add_product(sku, info, all_vecs)
|
||||||
|
return sku
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from kb.text_utils import full_text, letters_count, strong_words, text_scores, tokens
|
||||||
|
|
||||||
|
|
||||||
|
def fuse(vis, lines, sigs, df, text_w=0.15, min_letters=6):
|
||||||
|
"""Combine la ressemblance visuelle et la lecture du texte.
|
||||||
|
vis : {produit: similarité visuelle}. Retourne (scores, scores_texte, texte_utilisable).
|
||||||
|
Le texte est utilisable s'il contient assez de lettres OU un mot net dans les plus grandes
|
||||||
|
lignes (une marque courte comme Milka, Tang ou Ramy suffit)."""
|
||||||
|
informative = bool(lines) and (letters_count(lines) >= min_letters or len(strong_words(lines)) > 0)
|
||||||
|
tsc = text_scores(tokens(full_text(lines)), sigs, df, len(sigs)) if informative else {}
|
||||||
|
scores = {}
|
||||||
|
for sku, v in vis.items():
|
||||||
|
s = v
|
||||||
|
if informative and sigs.get(sku):
|
||||||
|
s += text_w * (2.0 * tsc.get(sku, 0.0) - 1.0) # texte lu = bonus, texte contredit = malus
|
||||||
|
scores[sku] = s
|
||||||
|
return scores, tsc, informative
|
||||||
|
|
||||||
|
|
||||||
|
def decide(scores, sim_thr, margin, veto=(), confirmed=None, vis=None, certain=0.90):
|
||||||
|
"""'known' si le meilleur produit est assez sûr, nettement devant le suivant et non contredit
|
||||||
|
par le texte lu (veto) ; sinon 'pending' : le groupe sera proposé à la confirmation.
|
||||||
|
Mode strict (confirmed n'est pas None) : il faut en plus une preuve, c'est-à-dire que le texte lu
|
||||||
|
confirme le produit, ou que sa ressemblance visuelle brute (vis) atteint 'certain'."""
|
||||||
|
ranked = sorted(scores.items(), key=lambda x: -x[1])
|
||||||
|
if not ranked:
|
||||||
|
return "pending", []
|
||||||
|
gap = ranked[0][1] - ranked[1][1] if len(ranked) > 1 else 1.0
|
||||||
|
ok = ranked[0][1] >= sim_thr and gap >= margin and ranked[0][0] not in veto
|
||||||
|
if ok and confirmed is not None:
|
||||||
|
strong_visual = vis is not None and vis.get(ranked[0][0], 0.0) >= certain
|
||||||
|
if ranked[0][0] not in confirmed and not strong_visual:
|
||||||
|
ok = False
|
||||||
|
return ("known" if ok else "pending"), ranked[:2]
|
||||||
|
|
||||||
|
|
||||||
|
def source(sku, tsc, informative, sigs):
|
||||||
|
"""Origine de la proposition : 'texte' (nom lu), 'douteux' (texte lu mais différent) ou 'visuel'."""
|
||||||
|
if not informative or not sigs.get(sku):
|
||||||
|
return "visuel"
|
||||||
|
t = tsc.get(sku, 0.0)
|
||||||
|
if t >= 0.5:
|
||||||
|
return "texte"
|
||||||
|
if t < 0.2:
|
||||||
|
return "douteux"
|
||||||
|
return "visuel"
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import torchvision
|
||||||
|
from torchvision import transforms as T
|
||||||
|
|
||||||
|
BACKBONES = {
|
||||||
|
"efficientnet": (None, 1280),
|
||||||
|
"dinov2_small": ("dinov2_vits14", 384),
|
||||||
|
"dinov2_base": ("dinov2_vitb14", 768),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Embedder:
|
||||||
|
def __init__(self, backbone="efficientnet", device=None, weights=None):
|
||||||
|
self.name = backbone + ("_ft" if weights else "")
|
||||||
|
hub_name, self.dim = BACKBONES[backbone]
|
||||||
|
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
|
||||||
|
if hub_name:
|
||||||
|
self.model = self._load_dinov2(hub_name)
|
||||||
|
else:
|
||||||
|
w = torchvision.models.EfficientNet_B0_Weights.DEFAULT
|
||||||
|
self.model = torchvision.models.efficientnet_b0(weights=w)
|
||||||
|
self.model.classifier = torch.nn.Identity() # on garde les 1280 caractéristiques
|
||||||
|
if weights:
|
||||||
|
ck = torch.load(weights, map_location="cpu")
|
||||||
|
sd = ck.get("state_dict") or ck.get("model_state") or ck # 2_train_classifier.py enregistre 'model_state'
|
||||||
|
sd = {k: v for k, v in sd.items() if not k.startswith("classifier.")} # on garde le corps du réseau, pas la tête à 36 classes
|
||||||
|
self.model.load_state_dict(sd)
|
||||||
|
self.model = self.model.eval().to(self.device)
|
||||||
|
|
||||||
|
self.tf = T.Compose([
|
||||||
|
T.Resize((224, 224)),
|
||||||
|
T.ToTensor(),
|
||||||
|
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
||||||
|
])
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_dinov2(hub_name):
|
||||||
|
"""DINOv2 via torch.hub (GitHub) ; si GitHub est inaccessible, repli sur Hugging Face."""
|
||||||
|
try:
|
||||||
|
return torch.hub.load("facebookresearch/dinov2:main", hub_name)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Embedder] GitHub inaccessible ({type(e).__name__}) : repli sur Hugging Face")
|
||||||
|
from transformers import AutoModel
|
||||||
|
hf_name = {"dinov2_vits14": "facebook/dinov2-small", "dinov2_vitb14": "facebook/dinov2-base"}[hub_name]
|
||||||
|
|
||||||
|
class HFDino(torch.nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.m = AutoModel.from_pretrained(hf_name)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
return self.m(pixel_values=x).pooler_output # jeton CLS normalisé
|
||||||
|
|
||||||
|
return HFDino()
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def encode(self, pil_images, batch_size=32):
|
||||||
|
out = []
|
||||||
|
for i in range(0, len(pil_images), batch_size):
|
||||||
|
batch = pil_images[i:i + batch_size]
|
||||||
|
x = torch.stack([self.tf(im.convert("RGB")) for im in batch]).to(self.device)
|
||||||
|
f = torch.nn.functional.normalize(self.model(x), dim=1)
|
||||||
|
out.append(f.cpu().numpy())
|
||||||
|
return np.vstack(out).astype("float32")
|
||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
import faiss
|
||||||
|
|
||||||
|
from kb.text_utils import name_tokens
|
||||||
|
|
||||||
|
|
||||||
|
class KnowledgeBase:
|
||||||
|
def __init__(self, path="kb_data", dim=1280, backbone="efficientnet"):
|
||||||
|
self.path = path
|
||||||
|
os.makedirs(path, exist_ok=True)
|
||||||
|
self.index_file = os.path.join(path, "index.faiss")
|
||||||
|
self.meta_file = os.path.join(path, "meta.json")
|
||||||
|
if os.path.exists(self.index_file):
|
||||||
|
self.index = faiss.read_index(self.index_file)
|
||||||
|
with open(self.meta_file, encoding="utf-8") as f:
|
||||||
|
self.meta = json.load(f)
|
||||||
|
if self.meta.get("backbone") != backbone:
|
||||||
|
raise SystemExit(
|
||||||
|
f"La base a été créée avec '{self.meta.get('backbone')}', pas '{backbone}'. "
|
||||||
|
f"Supprime le dossier '{path}' ou utilise le même encodeur.")
|
||||||
|
else:
|
||||||
|
self.index = faiss.IndexFlatIP(dim) # similarité cosinus (vecteurs normalisés)
|
||||||
|
self.meta = {"backbone": backbone}
|
||||||
|
self.meta.setdefault("products", {})
|
||||||
|
self.meta.setdefault("vectors", []) # vectors[i] = produit du vecteur i
|
||||||
|
self.meta.setdefault("aliases", {}) # fusion : ancien produit -> produit cible
|
||||||
|
|
||||||
|
def resolve(self, sku):
|
||||||
|
while sku in self.meta["aliases"]:
|
||||||
|
sku = self.meta["aliases"][sku]
|
||||||
|
return sku
|
||||||
|
|
||||||
|
def add_product(self, sku, info, embeddings):
|
||||||
|
self.meta["products"].setdefault(sku, {}).update(info)
|
||||||
|
self.index.add(embeddings)
|
||||||
|
self.meta["vectors"] += [sku] * len(embeddings)
|
||||||
|
self.save()
|
||||||
|
|
||||||
|
def add_text(self, sku, token_lists):
|
||||||
|
"""Mémorise les mots lus sur les images de référence (une liste de mots par image)."""
|
||||||
|
t = self.meta["products"][sku].setdefault("text", {"n": 0, "tok": {}})
|
||||||
|
for toks in token_lists:
|
||||||
|
t["n"] += 1
|
||||||
|
for w in set(toks):
|
||||||
|
if len(w) >= 3:
|
||||||
|
t["tok"][w] = t["tok"].get(w, 0) + 1
|
||||||
|
self.save()
|
||||||
|
|
||||||
|
def signatures(self, min_frac=0.3):
|
||||||
|
"""Signature texte de chaque produit : mots de son nom + mots lus sur ses emballages.
|
||||||
|
Retourne ({produit: {mot: fréquence}}, {mot: nombre de produits qui le portent})."""
|
||||||
|
sigs = {}
|
||||||
|
for sku, p in self.meta["products"].items():
|
||||||
|
if p.get("status") == "merged":
|
||||||
|
continue
|
||||||
|
sig = {w: 1.0 for w in name_tokens(p.get("name", sku))}
|
||||||
|
t = p.get("text")
|
||||||
|
if t and t.get("n"):
|
||||||
|
for w, c in t["tok"].items():
|
||||||
|
f = c / t["n"]
|
||||||
|
if f >= min_frac:
|
||||||
|
sig[w] = max(sig.get(w, 0.0), f)
|
||||||
|
sigs[sku] = sig
|
||||||
|
df = {}
|
||||||
|
for sig in sigs.values():
|
||||||
|
for w in sig:
|
||||||
|
df[w] = df.get(w, 0) + 1
|
||||||
|
return sigs, df
|
||||||
|
|
||||||
|
def bump(self, counts):
|
||||||
|
"""Compteurs cumulés. counts = {produit: facings dans cette photo}"""
|
||||||
|
for sku, n in counts.items():
|
||||||
|
p = self.meta["products"][sku]
|
||||||
|
p["total_facings"] = p.get("total_facings", 0) + n
|
||||||
|
p["photos_seen"] = p.get("photos_seen", 0) + 1
|
||||||
|
self.save()
|
||||||
|
|
||||||
|
def search(self, embeddings, k=60, top_m=3):
|
||||||
|
"""Par vecteur : liste [(produit, score)] triée. Le score est la moyenne des top_m meilleures
|
||||||
|
références du produit (les références absentes comptent comme la plus faible des k voisines) :
|
||||||
|
une seule image de référence atypique ne suffit plus à faire accepter un produit."""
|
||||||
|
if self.index.ntotal == 0:
|
||||||
|
return [[] for _ in embeddings]
|
||||||
|
k = min(k, self.index.ntotal)
|
||||||
|
sims, ids = self.index.search(embeddings, k)
|
||||||
|
results = []
|
||||||
|
for s_row, i_row in zip(sims, ids):
|
||||||
|
floor = float(s_row[-1])
|
||||||
|
per = {}
|
||||||
|
for sc, i in zip(s_row, i_row):
|
||||||
|
per.setdefault(self.resolve(self.meta["vectors"][i]), []).append(float(sc))
|
||||||
|
best = {}
|
||||||
|
for sku, v in per.items():
|
||||||
|
v = sorted(v, reverse=True)[:top_m]
|
||||||
|
v += [floor] * (top_m - len(v))
|
||||||
|
best[sku] = sum(v) / top_m
|
||||||
|
results.append(sorted(best.items(), key=lambda x: -x[1]))
|
||||||
|
return results
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
faiss.write_index(self.index, self.index_file)
|
||||||
|
with open(self.meta_file, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(self.meta, f, ensure_ascii=False, indent=2)
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import math
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
_reader = None
|
||||||
|
|
||||||
|
|
||||||
|
def norm(text):
|
||||||
|
s = unicodedata.normalize("NFKD", text.lower())
|
||||||
|
return "".join(c for c in s if not unicodedata.combining(c))
|
||||||
|
|
||||||
|
|
||||||
|
def tokens(text):
|
||||||
|
return re.findall(r"[a-z0-9]+", norm(text))
|
||||||
|
|
||||||
|
|
||||||
|
def name_tokens(name):
|
||||||
|
"""Mots d'un nom de produit (ex. 'Aroma Gold' -> ['aroma', 'gold'])."""
|
||||||
|
return [t for t in tokens(name) if len(t) >= 3]
|
||||||
|
|
||||||
|
|
||||||
|
def fuzzy_in(word, toks):
|
||||||
|
"""Le mot est-il lu dans le texte (avec tolérance aux petites erreurs de lecture) ?"""
|
||||||
|
for t in toks:
|
||||||
|
if t == word:
|
||||||
|
return True
|
||||||
|
if len(word) >= 4 and len(t) >= 4 and abs(len(t) - len(word)) <= 2 \
|
||||||
|
and SequenceMatcher(None, word, t).ratio() >= 0.75:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def text_scores(toks, sigs, df, n_products):
|
||||||
|
"""Score texte (0 à 1) de chaque produit : part de sa signature retrouvée dans le texte lu.
|
||||||
|
Un mot rare (porté par peu de produits) pèse plus qu'un mot courant."""
|
||||||
|
out = {}
|
||||||
|
for sku, sig in sigs.items():
|
||||||
|
num = den = 0.0
|
||||||
|
for w, f in sig.items():
|
||||||
|
idf = math.log((n_products + 1) / (df.get(w, 1) + 0.5))
|
||||||
|
den += idf * f
|
||||||
|
if fuzzy_in(w, toks):
|
||||||
|
num += idf * f
|
||||||
|
out[sku] = num / den if den > 0 else 0.0
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def read_text(pil_image, min_conf=0.35):
|
||||||
|
"""Lit le texte d'un recadrage. Retourne [(texte, confiance, hauteur)], le plus grand texte d'abord."""
|
||||||
|
global _reader
|
||||||
|
if _reader is None:
|
||||||
|
import easyocr
|
||||||
|
_reader = easyocr.Reader(["fr", "en"], gpu=False, verbose=False)
|
||||||
|
im = pil_image.convert("RGB")
|
||||||
|
if max(im.size) < 300:
|
||||||
|
im = im.resize((im.width * 2, im.height * 2))
|
||||||
|
out = []
|
||||||
|
for box, txt, conf in _reader.readtext(np.array(im)):
|
||||||
|
if conf >= min_conf and txt.strip():
|
||||||
|
ys = [p[1] for p in box]
|
||||||
|
out.append((txt.strip(), float(conf), float(max(ys) - min(ys))))
|
||||||
|
out.sort(key=lambda line: -line[2])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def full_text(lines):
|
||||||
|
return " ".join(t for t, _, _ in lines)
|
||||||
|
|
||||||
|
|
||||||
|
def letters_count(lines):
|
||||||
|
return sum(len(t) for t in tokens(full_text(lines)) if t.isalpha())
|
||||||
|
|
||||||
|
|
||||||
|
def strong_words(lines, n_lines=3, min_conf=0.5, min_len=4):
|
||||||
|
"""Mots lisibles des plus grandes lignes de texte (là où se trouve en général la marque)."""
|
||||||
|
words = set()
|
||||||
|
for txt, conf, _ in lines[:n_lines]:
|
||||||
|
if conf >= min_conf:
|
||||||
|
words.update(t for t in tokens(txt) if t.isalpha() and len(t) >= min_len)
|
||||||
|
return words
|
||||||
|
|
||||||
|
|
||||||
|
def guess_name(lines, n=2):
|
||||||
|
"""Propose un nom de produit à partir des lignes de texte les plus grandes."""
|
||||||
|
picks = [t for t, c, _ in lines if c >= 0.5 and sum(ch.isalpha() for ch in t) >= 3][:n]
|
||||||
|
return " ".join(p.title() if p.isupper() else p for p in picks)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
@'
|
||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
echo Dossier du serveur : %CD%
|
||||||
|
|
||||||
|
set FACING_KB=kb_facing
|
||||||
|
set FACING_DATA=data_facing
|
||||||
|
set FACING_BACKBONE=efficientnet
|
||||||
|
set FACING_DETECTOR=detector\best.pt
|
||||||
|
rem set FACING_WEIGHTS=C:\chemin\vers\vos\poids.pt
|
||||||
|
|
||||||
|
if not exist data_facing mkdir data_facing
|
||||||
|
|
||||||
|
rem Python de l'environnement conda product-detection (sinon python du PATH)
|
||||||
|
set PYEXE=%USERPROFILE%\miniconda3\envs\product-detection\python.exe
|
||||||
|
if not exist "%PYEXE%" set PYEXE=python
|
||||||
|
|
||||||
|
"%PYEXE%" -m uvicorn api_server:app --host 0.0.0.0 --port 2000
|
||||||
|
pause
|
||||||
|
'@ | Set-Content lancer_serveur.bat -Encoding ascii
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""Un seul serveur sur le port 2000 :
|
||||||
|
- ancien serveur (api_server.py) : /health, /classes, /jobs
|
||||||
|
- serveur Facing « comme le web » (facing_server.py) : /facing/...
|
||||||
|
|
||||||
|
Lancement (depuis C:\\Projects\\product-detection, avec FACING_KB, FACING_DATA, FACING_BACKBONE définies) :
|
||||||
|
python -m uvicorn main_2000:app --host 0.0.0.0 --port 2000
|
||||||
|
"""
|
||||||
|
from api_server import app # l'ancien serveur : ses routes gardent la priorité
|
||||||
|
import facing_server # le nouveau serveur : charge sa base au démarrage
|
||||||
|
|
||||||
|
# Les routes du nouveau serveur commencent déjà par /facing : aucun chevauchement avec l'ancien.
|
||||||
|
app.mount("/", facing_server.app)
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""Copie data/<produit>/*.jpg vers crops_eval/train et crops_eval/val (data n'est pas modifié).
|
||||||
|
Les derniers 20 % de chaque produit (ordre des noms) vont en val : des images de séries différentes,
|
||||||
|
pour ne pas mesurer sur des quasi-doublons des images d'entraînement."""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--src", default="data")
|
||||||
|
ap.add_argument("--dst", default="crops_eval")
|
||||||
|
ap.add_argument("--val_frac", type=float, default=0.2)
|
||||||
|
ap.add_argument("--min_images", type=int, default=5) # en dessous : tout en train
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
if os.path.exists(args.dst):
|
||||||
|
raise SystemExit(f"'{args.dst}' existe déjà : supprime ce dossier ou choisis --dst.")
|
||||||
|
|
||||||
|
n_train = n_val = n_cls = 0
|
||||||
|
for cls in sorted(os.listdir(args.src)):
|
||||||
|
folder = os.path.join(args.src, cls)
|
||||||
|
if not os.path.isdir(folder) or cls.startswith((".", "_")):
|
||||||
|
continue
|
||||||
|
files = [f for f in sorted(os.listdir(folder)) if f.lower().endswith((".jpg", ".jpeg", ".png"))]
|
||||||
|
if not files:
|
||||||
|
continue
|
||||||
|
n_val_c = int(len(files) * args.val_frac) if len(files) >= args.min_images else 0
|
||||||
|
train, val = files[:len(files) - n_val_c], files[len(files) - n_val_c:]
|
||||||
|
for split, group in (("train", train), ("val", val)):
|
||||||
|
if not group:
|
||||||
|
continue
|
||||||
|
out = os.path.join(args.dst, split, cls)
|
||||||
|
os.makedirs(out, exist_ok=True)
|
||||||
|
for f in group:
|
||||||
|
shutil.copy2(os.path.join(folder, f), os.path.join(out, f))
|
||||||
|
n_cls += 1
|
||||||
|
n_train += len(train)
|
||||||
|
n_val += len(val)
|
||||||
|
print(f"{cls:28s} train={len(train):4d} val={len(val):3d}")
|
||||||
|
print(f"\n{n_cls} produits | {n_train} images train | {n_val} images val -> {args.dst}")
|
||||||
+849
@@ -0,0 +1,849 @@
|
|||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from collections import Counter
|
||||||
|
from datetime import datetime
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import filedialog, messagebox, simpledialog, ttk
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image, ImageTk
|
||||||
|
from ultralytics import YOLO
|
||||||
|
|
||||||
|
from kb.auto_enroll import cluster_embeddings, enroll_named, find_product
|
||||||
|
from kb.decision import decide, fuse, source
|
||||||
|
from kb.embedder import Embedder
|
||||||
|
from kb.store import KnowledgeBase
|
||||||
|
|
||||||
|
PALETTE = [(255, 128, 0), (255, 0, 255), (0, 255, 255), (255, 255, 0),
|
||||||
|
(128, 0, 255), (0, 128, 255), (255, 0, 128), (128, 255, 0)] # BGR
|
||||||
|
KNOWN, UNKNOWN, GRAY = (0, 200, 0), (0, 0, 255), (150, 150, 150)
|
||||||
|
MIN_SIZE = 40
|
||||||
|
# (sim_thr : accepté automatiquement, min_sim : en dessous = aucune proposition, cluster_thr)
|
||||||
|
DEFAULT_THR = {"efficientnet": (0.70, 0.55, 0.75),
|
||||||
|
"dinov2_small": (0.70, 0.50, 0.70),
|
||||||
|
"dinov2_base": (0.70, 0.50, 0.70)}
|
||||||
|
|
||||||
|
|
||||||
|
def to_hex(bgr):
|
||||||
|
return "#%02x%02x%02x" % bgr[::-1]
|
||||||
|
|
||||||
|
|
||||||
|
class App:
|
||||||
|
def __init__(self, root, args):
|
||||||
|
self.root, self.args = root, args
|
||||||
|
root.title("Reconnaissance de produits en rayon")
|
||||||
|
self.det = YOLO(args.detector)
|
||||||
|
self.emb = Embedder(args.backbone, weights=args.weights)
|
||||||
|
self.kb = KnowledgeBase(args.kb_dir, dim=self.emb.dim, backbone=self.emb.name)
|
||||||
|
print(f"[KB] dossier={os.path.abspath(args.kb_dir)} backbone={self.emb.name} weights={args.weights} " # DEBUG temporaire
|
||||||
|
f"vecteurs={self.kb.index.ntotal} produits={len(self.kb.meta['products'])}")
|
||||||
|
print("[KB] produits :", [p.get("name", k) for k, p in self.kb.meta["products"].items()])
|
||||||
|
d_sim, d_min, d_clu = DEFAULT_THR.get(args.backbone, (0.70, 0.55, 0.75))
|
||||||
|
self.sim_thr = args.sim_thr or d_sim
|
||||||
|
self.min_sim = min(args.min_sim or d_min, self.sim_thr)
|
||||||
|
self.cluster_thr = args.cluster_thr or d_clu
|
||||||
|
self.scale, self.drag, self.rect = 1.0, None, None
|
||||||
|
|
||||||
|
top = tk.Frame(root)
|
||||||
|
top.pack(fill="x")
|
||||||
|
tk.Button(top, text="Analyser une photo de rayon", command=self.open_photo).pack(side="left", padx=6, pady=6)
|
||||||
|
tk.Button(top, text="Ajouter un produit à partir de photos",
|
||||||
|
command=self.add_from_photos).pack(side="left", padx=6, pady=6)
|
||||||
|
self.status = tk.Label(top, text="Prêt" + (" (lecture du texte activée)" if args.ocr else ""))
|
||||||
|
self.status.pack(side="left", padx=10)
|
||||||
|
|
||||||
|
# barre d'outils de sélection des produits inconnus (affichée seulement quand il en reste)
|
||||||
|
self.tools = tk.Frame(root, bg="#fff3cd")
|
||||||
|
self.tools_label = tk.Label(self.tools, bg="#fff3cd", font=("Segoe UI", 10, "bold"), anchor="w")
|
||||||
|
self.tools_label.pack(fill="x", padx=8, pady=(6, 2))
|
||||||
|
row = tk.Frame(self.tools, bg="#fff3cd")
|
||||||
|
row.pack(fill="x", padx=8, pady=(0, 6))
|
||||||
|
for text, cmd in [("Nommer la sélection", self.name_selection),
|
||||||
|
("Sélectionner les semblables", self.select_similar),
|
||||||
|
("Tout sélectionner", self.select_all),
|
||||||
|
("Désélectionner", self.clear_selection),
|
||||||
|
("Pas un produit", self.not_product),
|
||||||
|
("Terminer", self.finish)]:
|
||||||
|
tk.Button(row, text=text, command=cmd).pack(side="left", padx=3)
|
||||||
|
|
||||||
|
self.canvas = tk.Canvas(root, highlightthickness=0, bd=0, width=10, height=10)
|
||||||
|
self.canvas.pack()
|
||||||
|
self.canvas.bind("<ButtonPress-1>", self.on_press)
|
||||||
|
self.canvas.bind("<B1-Motion>", self.on_drag)
|
||||||
|
self.canvas.bind("<ButtonRelease-1>", self.on_release)
|
||||||
|
self.canvas.bind("<Button-3>", self.on_right_click)
|
||||||
|
self.report = tk.Text(root, height=10, width=100)
|
||||||
|
self.report.pack(fill="x")
|
||||||
|
|
||||||
|
def set_status(self, text):
|
||||||
|
self.status.config(text=text)
|
||||||
|
self.root.update_idletasks()
|
||||||
|
|
||||||
|
# ---------- analyse d'une photo de rayon ----------
|
||||||
|
def open_photo(self):
|
||||||
|
path = filedialog.askopenfilename(filetypes=[("Images", "*.jpg *.jpeg *.png *.webp")])
|
||||||
|
if path:
|
||||||
|
self.set_status("Analyse en cours...")
|
||||||
|
self.analyze(path)
|
||||||
|
self.set_status("Terminé")
|
||||||
|
|
||||||
|
def analyze(self, path):
|
||||||
|
t0 = time.time()
|
||||||
|
img = cv2.imread(path)
|
||||||
|
if img is None:
|
||||||
|
messagebox.showerror("Erreur", "Image illisible (format non supporté).")
|
||||||
|
return
|
||||||
|
h, w = img.shape[:2]
|
||||||
|
res = self.det.predict(img, conf=self.args.det_conf, iou=0.45, verbose=False)[0]
|
||||||
|
boxes, crops = [], []
|
||||||
|
for x1, y1, x2, y2 in res.boxes.xyxy.cpu().numpy().astype(int):
|
||||||
|
x1, y1, x2, y2 = max(x1, 0), max(y1, 0), min(x2, w), min(y2, h)
|
||||||
|
if x2 - x1 < 5 or y2 - y1 < 5:
|
||||||
|
continue
|
||||||
|
boxes.append((x1, y1, x2, y2))
|
||||||
|
crops.append(Image.fromarray(cv2.cvtColor(img[y1:y2, x1:x2], cv2.COLOR_BGR2RGB)))
|
||||||
|
if not crops:
|
||||||
|
messagebox.showinfo("Résultat", "Aucun produit détecté.")
|
||||||
|
return
|
||||||
|
n = len(crops)
|
||||||
|
area = lambda m: crops[m].width * crops[m].height
|
||||||
|
big = {i for i in range(n) if crops[i].width >= MIN_SIZE and crops[i].height >= MIN_SIZE}
|
||||||
|
|
||||||
|
# 1) reconnaissance visuelle : tous les produits candidats avec leur similarité
|
||||||
|
vecs = self.emb.encode(crops)
|
||||||
|
cands = self.kb.search(vecs, k=60)
|
||||||
|
vis = [dict(c) for c in cands]
|
||||||
|
sigs, df = self.kb.signatures()
|
||||||
|
|
||||||
|
# 2) lecture du texte (sauf si la ressemblance visuelle est déjà très nette)
|
||||||
|
lines_of = {}
|
||||||
|
if self.args.ocr:
|
||||||
|
need = []
|
||||||
|
for i in sorted(big):
|
||||||
|
v1 = cands[i][0][1] if cands[i] else 0.0
|
||||||
|
v2 = cands[i][1][1] if len(cands[i]) > 1 else 0.0
|
||||||
|
if not (v1 >= self.args.sim_certain and v1 - v2 >= 2 * self.args.margin):
|
||||||
|
need.append(i)
|
||||||
|
if need:
|
||||||
|
clusters = cluster_embeddings(vecs[need], self.args.ocr_cluster_thr)
|
||||||
|
for k, cl in enumerate(clusters):
|
||||||
|
self.set_status(f"Lecture du texte {k + 1}/{len(clusters)}...")
|
||||||
|
members = [need[j] for j in cl]
|
||||||
|
lines = self.read(crops[max(members, key=area)])
|
||||||
|
for m in members:
|
||||||
|
lines_of[m] = lines
|
||||||
|
|
||||||
|
# 3) décision : ressemblance visuelle + texte lu, écart minimum, et (mode strict) une preuve
|
||||||
|
assign, sims, pend, soft = [None] * n, [0.0] * n, {}, {}
|
||||||
|
for i in range(n):
|
||||||
|
status, top, srcs, soft_sku = self.judge(vis[i], lines_of.get(i), sigs, df)
|
||||||
|
if top:
|
||||||
|
sims[i] = top[0][1]
|
||||||
|
if status == "known":
|
||||||
|
assign[i] = top[0][0]
|
||||||
|
else:
|
||||||
|
pend[i] = [(k, s, srcs[k]) for k, s in top if s >= self.min_sim]
|
||||||
|
if soft_sku:
|
||||||
|
soft[i] = soft_sku
|
||||||
|
|
||||||
|
# 3b) propagation : un produit sans preuve propre prend le nom d'un exemplaire déjà confirmé
|
||||||
|
# de la même photo auquel il ressemble nettement (même emballage, même éclairage)
|
||||||
|
anchors = {}
|
||||||
|
for i, a in enumerate(assign):
|
||||||
|
if a:
|
||||||
|
anchors.setdefault(a, set()).add(i)
|
||||||
|
for _ in range(3):
|
||||||
|
moved = False
|
||||||
|
for i in list(pend):
|
||||||
|
m = self.nearest_anchor(vecs, i, anchors)
|
||||||
|
if m:
|
||||||
|
assign[i], sims[i] = m
|
||||||
|
anchors[m[0]].add(i)
|
||||||
|
pend.pop(i)
|
||||||
|
moved = True
|
||||||
|
if not moved:
|
||||||
|
break
|
||||||
|
|
||||||
|
print("[PROP] ancres :", {k: len(v) for k, v in anchors.items()}, # DEBUG temporaire
|
||||||
|
"| reconnus :", sum(a is not None for a in assign), "| restent à confirmer :", len(pend))
|
||||||
|
|
||||||
|
# 4) ce qui n'est pas sûr est regroupé par produit, pour être nommé ou confirmé
|
||||||
|
pending = sorted(pend)
|
||||||
|
groups = []
|
||||||
|
if pending:
|
||||||
|
for idx in cluster_embeddings(vecs[pending], self.cluster_thr):
|
||||||
|
groups.append([pending[j] for j in idx])
|
||||||
|
groups.sort(key=len, reverse=True)
|
||||||
|
groups = [g for g in groups if len(g) >= self.args.min_group]
|
||||||
|
|
||||||
|
suggest, picks, guess = {}, {}, {}
|
||||||
|
for g, idx in enumerate(groups):
|
||||||
|
acc = {}
|
||||||
|
for i in idx:
|
||||||
|
for k, s, src in pend.get(i, []):
|
||||||
|
a = acc.setdefault(k, ([], []))
|
||||||
|
a[0].append(s)
|
||||||
|
a[1].append(src)
|
||||||
|
ranked = sorted(((k, sum(a[0]) / len(a[0]), a[1]) for k, a in acc.items()),
|
||||||
|
key=lambda x: -x[1])[:2]
|
||||||
|
opts = []
|
||||||
|
for k, s, srcs in ranked:
|
||||||
|
src = "texte" if "texte" in srcs else ("douteux" if all(x == "douteux" for x in srcs) else "visuel")
|
||||||
|
opts.append((k, s, src))
|
||||||
|
if opts:
|
||||||
|
suggest[g] = opts
|
||||||
|
# proposition présélectionnée seulement si elle est sûre ; en mode strict, une ressemblance
|
||||||
|
# purement visuelle ne suffit pas : c'est à l'utilisateur de trancher
|
||||||
|
if opts[0][2] != "douteux" and (opts[0][2] == "texte" or not self.args.strict) and (
|
||||||
|
len(opts) == 1 or opts[0][1] - opts[1][1] >= self.args.margin
|
||||||
|
or (opts[0][2] == "texte" and opts[1][2] != "texte")):
|
||||||
|
picks[g] = 0
|
||||||
|
if self.args.ocr:
|
||||||
|
order = sorted([i for i in idx if i in big], key=area, reverse=True)
|
||||||
|
if order:
|
||||||
|
lines = lines_of.get(order[0]) or self.read(crops[order[0]])
|
||||||
|
guess[g] = self.guess(lines)
|
||||||
|
t1 = time.time() # fin de la détection, de la reconnaissance et de la lecture du texte
|
||||||
|
|
||||||
|
self.s = dict(img=img, boxes=boxes, crops=crops, vecs=vecs, big=big, lines_of=lines_of,
|
||||||
|
assign=assign, suggest=suggest, sims=sims, phase="review",
|
||||||
|
group_of={i: g for g, idx in enumerate(groups) for i in idx},
|
||||||
|
new_now={}, ignored=set(), notproduct=set(), selected=set(), enrolled=set(),
|
||||||
|
anchors=anchors)
|
||||||
|
|
||||||
|
# 5) un seul panneau pour tous les groupes à identifier
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
choices = {}
|
||||||
|
if groups:
|
||||||
|
self.render()
|
||||||
|
choices = self.review_groups(groups, suggest, picks, guess)
|
||||||
|
|
||||||
|
for g, idx in enumerate(groups):
|
||||||
|
choice = choices.get(g)
|
||||||
|
if choice:
|
||||||
|
kind, val = choice
|
||||||
|
if kind == "existing":
|
||||||
|
self.enroll_selection(idx, P[val]["name"], sku=val)
|
||||||
|
else:
|
||||||
|
self.enroll_selection(idx, val)
|
||||||
|
else:
|
||||||
|
self.s["ignored"].add(g) # laissé pour plus tard : reste INCONNU
|
||||||
|
|
||||||
|
# 6) les produits encore INCONNUS se résolvent à la souris, jusqu'à ce qu'il n'en reste plus
|
||||||
|
self.s["phase"] = "resolve"
|
||||||
|
self.reclassify_unresolved()
|
||||||
|
self.resolve_unknowns()
|
||||||
|
|
||||||
|
assign = self.s["assign"]
|
||||||
|
self.render()
|
||||||
|
counts = Counter(a for a in assign if a)
|
||||||
|
self.kb.bump(counts) # le compteur cumulé augmente
|
||||||
|
self.show_report(counts)
|
||||||
|
|
||||||
|
self.log({
|
||||||
|
"photo": os.path.basename(path),
|
||||||
|
"analysis_s": round(t1 - t0, 2), # détection + reconnaissance + lecture du texte
|
||||||
|
"user_s": round(time.time() - t1, 2), # temps passé dans le panneau et la sélection
|
||||||
|
"n_detected": len(boxes),
|
||||||
|
"n_new_groups": len(groups),
|
||||||
|
"n_enrolled": len(self.s["new_now"]),
|
||||||
|
"n_ignored": len(self.s["ignored"]),
|
||||||
|
"n_unknown_left": len(self.unresolved()),
|
||||||
|
"counts": json.dumps({P[s]["name"]: c for s, c in counts.items()}, ensure_ascii=False),
|
||||||
|
})
|
||||||
|
|
||||||
|
# ---------- décision pour une boîte ----------
|
||||||
|
def nearest_anchor(self, vecs, i, anchors):
|
||||||
|
"""(produit, similarité) du produit confirmé auquel la vignette i ressemble nettement, sinon None.
|
||||||
|
Il faut une ressemblance >= prop_thr avec un exemplaire confirmé, et un écart d'au moins 0.03
|
||||||
|
avec le meilleur exemplaire d'un autre produit."""
|
||||||
|
best = {sku: float((vecs[sorted(idx - {i})] @ vecs[i]).max())
|
||||||
|
for sku, idx in anchors.items() if idx - {i}}
|
||||||
|
ranked = sorted(best.items(), key=lambda x: -x[1])
|
||||||
|
if not ranked or ranked[0][1] < self.args.prop_thr:
|
||||||
|
return None
|
||||||
|
if len(ranked) > 1 and ranked[0][1] - ranked[1][1] < 0.03:
|
||||||
|
return None
|
||||||
|
return ranked[0]
|
||||||
|
|
||||||
|
def judge(self, vis_i, lines, sigs, df):
|
||||||
|
"""Retourne (statut, [(produit, score)], origines, produit_sans_preuve).
|
||||||
|
Mode strict : un produit n'est accepté seul que si le texte lu le confirme ou si sa ressemblance
|
||||||
|
visuelle est très forte. Sinon il est « sans preuve » : proposé à la confirmation, ou accepté
|
||||||
|
par propagation s'il ressemble nettement à un exemplaire déjà confirmé de la même photo."""
|
||||||
|
scores, tsc, inf = fuse(vis_i, lines, sigs, df, self.args.text_w, self.args.min_letters)
|
||||||
|
srcs = {k: source(k, tsc, inf, sigs) for k in scores}
|
||||||
|
veto = {k for k, v in srcs.items() if v == "douteux"}
|
||||||
|
confirmed = {k for k, v in srcs.items() if v == "texte"} if self.args.strict else None
|
||||||
|
status, top = decide(scores, self.sim_thr, self.args.margin, veto, confirmed, vis_i, self.args.strict_vis)
|
||||||
|
soft = None
|
||||||
|
if status != "known" and self.args.strict:
|
||||||
|
st2, top2 = decide(scores, self.sim_thr, self.args.margin, veto)
|
||||||
|
if st2 == "known":
|
||||||
|
soft = top2[0][0]
|
||||||
|
if top: # DEBUG temporaire : à retirer
|
||||||
|
k = top[0][0]
|
||||||
|
print(f"{k:20s} fusion={top[0][1]:.2f} visuel={vis_i.get(k, 0):.2f} src={srcs.get(k)} statut={status}")
|
||||||
|
return status, top, srcs, soft
|
||||||
|
|
||||||
|
# ---------- enregistrement d'un groupe de produits sous un nom ----------
|
||||||
|
def area(self, i):
|
||||||
|
c = self.s["crops"][i]
|
||||||
|
return c.width * c.height
|
||||||
|
|
||||||
|
def enroll_selection(self, idx, name, sku=None):
|
||||||
|
"""Enregistre les produits idx sous ce nom (produit existant ou nouveau).
|
||||||
|
Retourne (sku, est_nouveau)."""
|
||||||
|
s = self.s
|
||||||
|
idx = list(idx)
|
||||||
|
refs = [i for i in idx if i in s["big"]] or idx
|
||||||
|
existing = sku or find_product(self.kb, name)
|
||||||
|
new_sku = enroll_named(self.kb, self.emb, name, [s["crops"][i] for i in refs],
|
||||||
|
s["vecs"][refs], self.args.data_dir, sku=existing)
|
||||||
|
if self.args.ocr:
|
||||||
|
# le produit apprend aussi les mots lus sur son emballage
|
||||||
|
best3 = sorted(refs, key=self.area, reverse=True)[:3]
|
||||||
|
self.kb.add_text(new_sku, [self.tokens_of(s["lines_of"].get(m) or self.read(s["crops"][m]))
|
||||||
|
for m in best3])
|
||||||
|
for i in idx:
|
||||||
|
s["assign"][i] = new_sku
|
||||||
|
s["enrolled"].update(idx)
|
||||||
|
s["anchors"].setdefault(new_sku, set()).update(idx)
|
||||||
|
is_new = existing is None
|
||||||
|
if is_new:
|
||||||
|
s["new_now"][new_sku] = PALETTE[len(s["new_now"]) % len(PALETTE)]
|
||||||
|
return new_sku, is_new
|
||||||
|
|
||||||
|
# ---------- produits INCONNUS : sélection à la souris ----------
|
||||||
|
def unresolved(self):
|
||||||
|
s = self.s
|
||||||
|
return [i for i in range(len(s["boxes"])) if s["assign"][i] is None and i not in s["notproduct"]]
|
||||||
|
|
||||||
|
def resolve_unknowns(self):
|
||||||
|
s = self.s
|
||||||
|
if not self.unresolved():
|
||||||
|
return
|
||||||
|
s["selected"] = set()
|
||||||
|
self.done = tk.BooleanVar(value=False)
|
||||||
|
self.tools.pack(fill="x", before=self.canvas)
|
||||||
|
self.update_toolbar()
|
||||||
|
self.render()
|
||||||
|
self.root.wait_variable(self.done)
|
||||||
|
self.tools.pack_forget()
|
||||||
|
s["phase"] = "done"
|
||||||
|
s["selected"] = set()
|
||||||
|
|
||||||
|
def update_toolbar(self):
|
||||||
|
s = self.s
|
||||||
|
un = self.unresolved()
|
||||||
|
if un:
|
||||||
|
self.tools_label.config(
|
||||||
|
text=f"{len(un)} produit(s) INCONNU(S) · {len(s['selected'])} sélectionné(s) — "
|
||||||
|
"cliquez sur un produit (cercle) ou tracez un cadre pour en sélectionner plusieurs")
|
||||||
|
else:
|
||||||
|
self.tools_label.config(
|
||||||
|
text="Tous les produits sont identifiés. Vérifiez, puis cliquez sur Terminer "
|
||||||
|
"(clic droit sur un produit pour le remettre en INCONNU)")
|
||||||
|
|
||||||
|
def finish(self):
|
||||||
|
un = self.unresolved()
|
||||||
|
if un and not messagebox.askyesno(
|
||||||
|
"Il reste des produits inconnus",
|
||||||
|
f"Il reste {len(un)} produit(s) INCONNU(S).\nLes laisser non identifiés (et non comptés) ?"):
|
||||||
|
return
|
||||||
|
self.done.set(True)
|
||||||
|
|
||||||
|
def refresh_after_change(self, message=None):
|
||||||
|
self.render()
|
||||||
|
self.update_toolbar()
|
||||||
|
if message:
|
||||||
|
self.set_status(message)
|
||||||
|
|
||||||
|
def select_all(self):
|
||||||
|
self.s["selected"] = set(self.unresolved())
|
||||||
|
self.draw_overlay()
|
||||||
|
self.update_toolbar()
|
||||||
|
|
||||||
|
def clear_selection(self):
|
||||||
|
self.s["selected"] = set()
|
||||||
|
self.draw_overlay()
|
||||||
|
self.update_toolbar()
|
||||||
|
|
||||||
|
def select_similar(self):
|
||||||
|
s = self.s
|
||||||
|
if not s["selected"]:
|
||||||
|
messagebox.showinfo("Sélection", "Sélectionnez d'abord au moins un produit.")
|
||||||
|
return
|
||||||
|
un = [i for i in self.unresolved() if i not in s["selected"]]
|
||||||
|
if un:
|
||||||
|
sim = s["vecs"][un] @ s["vecs"][sorted(s["selected"])].T
|
||||||
|
for j, i in enumerate(un):
|
||||||
|
if sim[j].max() >= self.cluster_thr:
|
||||||
|
s["selected"].add(i)
|
||||||
|
self.draw_overlay()
|
||||||
|
self.update_toolbar()
|
||||||
|
|
||||||
|
def not_product(self):
|
||||||
|
s = self.s
|
||||||
|
sel = sorted(s["selected"])
|
||||||
|
if not sel:
|
||||||
|
messagebox.showinfo("Sélection", "Sélectionnez d'abord ce qui n'est pas un produit.")
|
||||||
|
return
|
||||||
|
folder = os.path.join(self.args.data_dir, "_rejected_")
|
||||||
|
os.makedirs(folder, exist_ok=True)
|
||||||
|
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
for i in sel:
|
||||||
|
s["crops"][i].save(os.path.join(folder, f"{stamp}_{i}.jpg"), quality=92)
|
||||||
|
s["notproduct"].update(sel)
|
||||||
|
s["selected"] = set()
|
||||||
|
self.refresh_after_change()
|
||||||
|
|
||||||
|
def name_selection(self):
|
||||||
|
s = self.s
|
||||||
|
sel = sorted(s["selected"])
|
||||||
|
if not sel:
|
||||||
|
messagebox.showinfo("Sélection", "Cliquez d'abord sur les produits à nommer (cercle) "
|
||||||
|
"ou tracez un cadre autour d'eux.")
|
||||||
|
return
|
||||||
|
options, default = self.suggest_for(sel)
|
||||||
|
name = self.ask_selection_name(sel, options, default)
|
||||||
|
if not name:
|
||||||
|
return
|
||||||
|
self.enroll_selection(sel, name)
|
||||||
|
s["selected"] = set()
|
||||||
|
auto = self.reclassify_unresolved()
|
||||||
|
self.refresh_after_change(f"{auto} autre(s) produit(s) reconnu(s) automatiquement" if auto else None)
|
||||||
|
|
||||||
|
def suggest_for(self, sel):
|
||||||
|
"""Propositions pour la sélection : (liste [(produit, score, origine)], nom proposé)."""
|
||||||
|
s = self.s
|
||||||
|
sigs, df = self.kb.signatures()
|
||||||
|
acc = {}
|
||||||
|
for r in self.kb.search(s["vecs"][sel], k=60):
|
||||||
|
for k, v in r:
|
||||||
|
acc.setdefault(k, []).append(v)
|
||||||
|
vis = {k: sum(v) / len(v) for k, v in acc.items()}
|
||||||
|
lines, guess = None, ""
|
||||||
|
if self.args.ocr:
|
||||||
|
rep = max(sel, key=self.area)
|
||||||
|
lines = s["lines_of"].get(rep) or (self.read(s["crops"][rep]) if rep in s["big"] else None)
|
||||||
|
if lines:
|
||||||
|
guess = self.guess(lines)
|
||||||
|
scores, tsc, inf = fuse(vis, lines, sigs, df, self.args.text_w, self.args.min_letters)
|
||||||
|
ranked = sorted(scores.items(), key=lambda x: -x[1])[:2]
|
||||||
|
opts = [(k, sc, source(k, tsc, inf, sigs)) for k, sc in ranked if sc >= self.min_sim]
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
default = P[opts[0][0]]["name"] if opts and opts[0][2] != "douteux" else guess
|
||||||
|
return opts, default
|
||||||
|
|
||||||
|
def reclassify_unresolved(self):
|
||||||
|
"""Après un nouveau nom, les autres produits inconnus qui lui ressemblent sont reconnus seuls
|
||||||
|
(mêmes règles que l'analyse : preuve par le texte, ou ressemblance nette avec un exemplaire confirmé)."""
|
||||||
|
s = self.s
|
||||||
|
un = self.unresolved()
|
||||||
|
if not un:
|
||||||
|
return 0
|
||||||
|
sigs, df = self.kb.signatures()
|
||||||
|
found = 0
|
||||||
|
for i, c in zip(un, self.kb.search(s["vecs"][un], k=60)):
|
||||||
|
status, top, srcs, soft = self.judge(dict(c), s["lines_of"].get(i), sigs, df)
|
||||||
|
sku = top[0][0] if status == "known" else None
|
||||||
|
if sku is None:
|
||||||
|
m = self.nearest_anchor(s["vecs"], i, s["anchors"])
|
||||||
|
sku = m[0] if m else None
|
||||||
|
if sku:
|
||||||
|
s["assign"][i] = sku
|
||||||
|
s["sims"][i] = top[0][1] if top else 0.0
|
||||||
|
found += 1
|
||||||
|
return found
|
||||||
|
|
||||||
|
# ---------- clics sur l'image ----------
|
||||||
|
def on_press(self, event):
|
||||||
|
if getattr(self, "s", None) and self.s.get("phase") == "resolve":
|
||||||
|
self.drag = (event.x, event.y)
|
||||||
|
|
||||||
|
def on_drag(self, event):
|
||||||
|
if not self.drag:
|
||||||
|
return
|
||||||
|
if self.rect:
|
||||||
|
self.canvas.delete(self.rect)
|
||||||
|
self.rect = self.canvas.create_rectangle(self.drag[0], self.drag[1], event.x, event.y,
|
||||||
|
outline="#00aaff", dash=(4, 2), width=2)
|
||||||
|
|
||||||
|
def on_release(self, event):
|
||||||
|
if not self.drag:
|
||||||
|
return
|
||||||
|
if self.rect:
|
||||||
|
self.canvas.delete(self.rect)
|
||||||
|
self.rect = None
|
||||||
|
x0, y0 = self.drag
|
||||||
|
self.drag = None
|
||||||
|
s, sc = self.s, self.scale
|
||||||
|
if abs(event.x - x0) < 6 and abs(event.y - y0) < 6: # simple clic : bascule le produit cliqué
|
||||||
|
x, y = event.x / sc, event.y / sc
|
||||||
|
hits = [i for i in self.unresolved()
|
||||||
|
if s["boxes"][i][0] <= x <= s["boxes"][i][2] and s["boxes"][i][1] <= y <= s["boxes"][i][3]]
|
||||||
|
if hits:
|
||||||
|
i = min(hits, key=lambda k: (s["boxes"][k][2] - s["boxes"][k][0]) *
|
||||||
|
(s["boxes"][k][3] - s["boxes"][k][1]))
|
||||||
|
s["selected"] ^= {i}
|
||||||
|
else: # cadre : sélectionne tout ce qu'il contient
|
||||||
|
lx, hx = sorted((x0, event.x))
|
||||||
|
ly, hy = sorted((y0, event.y))
|
||||||
|
for i in self.unresolved():
|
||||||
|
x1, y1, x2, y2 = [v * sc for v in s["boxes"][i]]
|
||||||
|
if lx <= (x1 + x2) / 2 <= hx and ly <= (y1 + y2) / 2 <= hy:
|
||||||
|
s["selected"].add(i)
|
||||||
|
self.draw_overlay()
|
||||||
|
self.update_toolbar()
|
||||||
|
|
||||||
|
def on_right_click(self, event):
|
||||||
|
"""Clic droit sur un produit déjà identifié : le remet en INCONNU pour le renommer."""
|
||||||
|
s = getattr(self, "s", None)
|
||||||
|
if not s or s.get("phase") != "resolve":
|
||||||
|
return
|
||||||
|
x, y = event.x / self.scale, event.y / self.scale
|
||||||
|
hits = [i for i in range(len(s["boxes"]))
|
||||||
|
if s["boxes"][i][0] <= x <= s["boxes"][i][2] and s["boxes"][i][1] <= y <= s["boxes"][i][3]
|
||||||
|
and (s["assign"][i] is not None or i in s["notproduct"])]
|
||||||
|
if not hits:
|
||||||
|
return
|
||||||
|
i = min(hits, key=lambda k: (s["boxes"][k][2] - s["boxes"][k][0]) * (s["boxes"][k][3] - s["boxes"][k][1]))
|
||||||
|
if i in s["enrolled"]:
|
||||||
|
messagebox.showinfo(
|
||||||
|
"Produit déjà enregistré",
|
||||||
|
"Ce produit vient d'être enregistré dans la base pendant cette analyse. Pour ne pas y laisser "
|
||||||
|
"de mauvaises images, il ne peut pas être remis en INCONNU ici.\n\nS'il porte un mauvais nom, "
|
||||||
|
"corrigez-le ensuite (renommer ou fusionner le produit).")
|
||||||
|
return
|
||||||
|
s["assign"][i] = None
|
||||||
|
s["notproduct"].discard(i)
|
||||||
|
self.render()
|
||||||
|
self.update_toolbar()
|
||||||
|
|
||||||
|
def draw_overlay(self):
|
||||||
|
"""Cercle de sélection sur chaque produit inconnu : vide = non sélectionné, noir avec coche = sélectionné."""
|
||||||
|
s, sc = self.s, self.scale
|
||||||
|
self.canvas.delete("ov")
|
||||||
|
for i in self.unresolved():
|
||||||
|
x1, y1, x2, y2 = [v * sc for v in s["boxes"][i]]
|
||||||
|
r = max(7, min(13, (x2 - x1) / 4))
|
||||||
|
cx, cy = x2 - r - 3, y1 + r + 3
|
||||||
|
if i in s["selected"]:
|
||||||
|
self.canvas.create_rectangle(x1, y1, x2, y2, outline="#ffd400", width=3, tags="ov")
|
||||||
|
self.canvas.create_oval(cx - r, cy - r, cx + r, cy + r, fill="black", outline="white",
|
||||||
|
width=1, tags="ov")
|
||||||
|
self.canvas.create_line(cx - r * 0.5, cy, cx - r * 0.1, cy + r * 0.4, cx + r * 0.55, cy - r * 0.4,
|
||||||
|
fill="white", width=2, tags="ov")
|
||||||
|
else:
|
||||||
|
self.canvas.create_oval(cx - r, cy - r, cx + r, cy + r, fill="white", outline="#222222",
|
||||||
|
width=2, tags="ov")
|
||||||
|
|
||||||
|
# ---------- fenêtre pour nommer la sélection ----------
|
||||||
|
def ask_selection_name(self, sel, options, default):
|
||||||
|
s, P = self.s, self.kb.meta["products"]
|
||||||
|
dlg = tk.Toplevel(self.root)
|
||||||
|
dlg.title("Nommer les produits sélectionnés")
|
||||||
|
dlg.transient(self.root)
|
||||||
|
dlg.grab_set()
|
||||||
|
tk.Label(dlg, text=f"{len(sel)} produit(s) sélectionné(s)",
|
||||||
|
font=("Segoe UI", 12, "bold")).pack(padx=12, pady=(12, 4))
|
||||||
|
row = tk.Frame(dlg, highlightbackground="#ffd400", highlightthickness=3)
|
||||||
|
row.pack(padx=12, pady=6)
|
||||||
|
refs = []
|
||||||
|
for i in sorted(sel, key=self.area, reverse=True)[:5]:
|
||||||
|
im = s["crops"][i].copy()
|
||||||
|
im.thumbnail((100, 130))
|
||||||
|
ph = ImageTk.PhotoImage(im)
|
||||||
|
refs.append(ph)
|
||||||
|
tk.Label(row, image=ph).pack(side="left", padx=3, pady=3)
|
||||||
|
dlg.refs = refs
|
||||||
|
if options:
|
||||||
|
labels = {"texte": "nom lu", "douteux": "texte différent", "visuel": "ressemblance visuelle"}
|
||||||
|
txt = "Propositions : " + " | ".join(
|
||||||
|
f"{P[k]['name']} ({sc:.2f}, {labels[src]})" for k, sc, src in options)
|
||||||
|
tk.Label(dlg, text=txt, fg="#b35900", wraplength=520, justify="left").pack(padx=12, anchor="w")
|
||||||
|
tk.Label(dlg, text="Produit déjà connu (choisir dans la liste) ou nouveau produit (taper le nom) :"
|
||||||
|
).pack(anchor="w", padx=12, pady=(8, 0))
|
||||||
|
names = sorted({p.get("name", k) for k, p in P.items() if p.get("status") != "merged"},
|
||||||
|
key=str.lower)
|
||||||
|
var = tk.StringVar(value=default)
|
||||||
|
box = ttk.Combobox(dlg, textvariable=var, values=names, width=52)
|
||||||
|
box.pack(padx=12, pady=4)
|
||||||
|
box.focus_set()
|
||||||
|
result = {"name": None}
|
||||||
|
|
||||||
|
def ok(*_):
|
||||||
|
if var.get().strip():
|
||||||
|
result["name"] = var.get().strip()
|
||||||
|
dlg.destroy()
|
||||||
|
|
||||||
|
btns = tk.Frame(dlg)
|
||||||
|
btns.pack(pady=10)
|
||||||
|
tk.Button(btns, text="Valider", width=14, command=ok).pack(side="left", padx=6)
|
||||||
|
tk.Button(btns, text="Annuler", width=14, command=dlg.destroy).pack(side="left", padx=6)
|
||||||
|
dlg.bind("<Return>", ok)
|
||||||
|
self.root.wait_window(dlg)
|
||||||
|
return result["name"]
|
||||||
|
|
||||||
|
# ---------- lecture du texte ----------
|
||||||
|
def read(self, pil):
|
||||||
|
from kb.text_utils import read_text
|
||||||
|
return read_text(pil)
|
||||||
|
|
||||||
|
def tokens_of(self, lines):
|
||||||
|
from kb.text_utils import full_text, tokens
|
||||||
|
return tokens(full_text(lines))
|
||||||
|
|
||||||
|
def guess(self, lines):
|
||||||
|
from kb.text_utils import guess_name
|
||||||
|
return guess_name(lines)
|
||||||
|
|
||||||
|
# ---------- journal CSV ----------
|
||||||
|
def log(self, row):
|
||||||
|
os.makedirs("logs", exist_ok=True)
|
||||||
|
path = os.path.join("logs", f"{os.path.basename(self.args.kb_dir)}_analyses.csv")
|
||||||
|
new = not os.path.exists(path)
|
||||||
|
with open(path, "a", newline="", encoding="utf-8") as f:
|
||||||
|
w = csv.DictWriter(f, fieldnames=list(row.keys()))
|
||||||
|
if new:
|
||||||
|
w.writeheader()
|
||||||
|
w.writerow(row)
|
||||||
|
|
||||||
|
# ---------- ajout à partir de photos du produit ----------
|
||||||
|
def main_crop(self, pil):
|
||||||
|
bgr = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR)
|
||||||
|
res = self.det.predict(bgr, conf=self.args.det_conf, iou=0.45, verbose=False)[0]
|
||||||
|
boxes = res.boxes.xyxy.cpu().numpy().astype(int)
|
||||||
|
if len(boxes) == 0:
|
||||||
|
return pil
|
||||||
|
x1, y1, x2, y2 = max(boxes, key=lambda b: (b[2] - b[0]) * (b[3] - b[1]))
|
||||||
|
return pil.crop((max(x1, 0), max(y1, 0), x2, y2))
|
||||||
|
|
||||||
|
def add_from_photos(self):
|
||||||
|
paths = filedialog.askopenfilenames(title="Photos du nouveau produit",
|
||||||
|
filetypes=[("Images", "*.jpg *.jpeg *.png *.webp")])
|
||||||
|
if not paths:
|
||||||
|
return
|
||||||
|
crops = [self.main_crop(Image.open(p).convert("RGB")) for p in paths]
|
||||||
|
vecs = self.emb.encode(crops)
|
||||||
|
top = [r[0] for r in self.kb.search(vecs, k=3) if r]
|
||||||
|
best = max(((sim, sku) for sku, sim in top), default=None)
|
||||||
|
if best and best[0] >= self.sim_thr:
|
||||||
|
name = self.kb.meta["products"][best[1]]["name"]
|
||||||
|
if not messagebox.askyesno("Doublon possible",
|
||||||
|
f"Ces photos ressemblent à « {name} » (similarité {best[0]:.2f}).\n"
|
||||||
|
"Continuer quand même ?"):
|
||||||
|
return
|
||||||
|
name = simpledialog.askstring("Nom du produit", "Nom du produit :", parent=self.root)
|
||||||
|
if not name or not name.strip():
|
||||||
|
return
|
||||||
|
sku = enroll_named(self.kb, self.emb, name.strip(), crops, vecs, self.args.data_dir)
|
||||||
|
if self.args.ocr:
|
||||||
|
self.set_status("Lecture du texte du produit...")
|
||||||
|
self.kb.add_text(sku, [self.tokens_of(self.read(c)) for c in crops])
|
||||||
|
self.set_status("Prêt")
|
||||||
|
messagebox.showinfo("Produit ajouté",
|
||||||
|
f"« {name.strip()} » ajouté ({len(crops)} photo(s)).\n"
|
||||||
|
f"Dossier : {os.path.join(self.args.data_dir, sku)}")
|
||||||
|
|
||||||
|
# ---------- affichage ----------
|
||||||
|
def render(self, current=None):
|
||||||
|
s, P = self.s, self.kb.meta["products"]
|
||||||
|
out = s["img"].copy()
|
||||||
|
for i, (x1, y1, x2, y2) in enumerate(s["boxes"]):
|
||||||
|
sku, g = s["assign"][i], s["group_of"].get(i)
|
||||||
|
thick = 2
|
||||||
|
if sku:
|
||||||
|
color = s["new_now"].get(sku, KNOWN)
|
||||||
|
label = P[sku]["name"] + ("" if sku in s["new_now"] else f" {s['sims'][i]:.2f}")
|
||||||
|
elif i in s["notproduct"]:
|
||||||
|
color, label, thick = GRAY, "", 1
|
||||||
|
elif s["phase"] == "review" and g is not None:
|
||||||
|
color = PALETTE[g % len(PALETTE)]
|
||||||
|
label = "A CONFIRMER" if g in s["suggest"] else "A NOMMER"
|
||||||
|
else:
|
||||||
|
color, label = UNKNOWN, "INCONNU"
|
||||||
|
if current is not None and g == current:
|
||||||
|
thick = 4
|
||||||
|
cv2.rectangle(out, (x1, y1), (x2, y2), color, thick)
|
||||||
|
if label:
|
||||||
|
cv2.putText(out, label, (x1, max(y1 - 5, 15)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
|
||||||
|
pil = Image.fromarray(cv2.cvtColor(out, cv2.COLOR_BGR2RGB))
|
||||||
|
pil.thumbnail((1000, 600))
|
||||||
|
self.scale = pil.width / s["img"].shape[1]
|
||||||
|
self.tk_img = ImageTk.PhotoImage(pil)
|
||||||
|
self.canvas.config(width=pil.width, height=pil.height)
|
||||||
|
self.canvas.delete("all")
|
||||||
|
self.canvas.create_image(0, 0, anchor="nw", image=self.tk_img)
|
||||||
|
if s["phase"] == "resolve":
|
||||||
|
self.draw_overlay()
|
||||||
|
self.root.update()
|
||||||
|
|
||||||
|
def show_report(self, counts):
|
||||||
|
P = self.kb.meta["products"]
|
||||||
|
self.report.delete("1.0", "end")
|
||||||
|
self.report.insert("end", "=== Facings dans cette photo ===\n")
|
||||||
|
for sku, c in counts.most_common():
|
||||||
|
tag = " [NOUVEAU]" if sku in self.s["new_now"] else ""
|
||||||
|
self.report.insert(
|
||||||
|
"end", f"{P[sku]['name']}: {c}{tag} (cumul : {P[sku].get('total_facings', 0)} "
|
||||||
|
f"facings sur {P[sku].get('photos_seen', 0)} photos)\n")
|
||||||
|
left = len(self.unresolved())
|
||||||
|
if left:
|
||||||
|
self.report.insert("end", f"\nProduits restés INCONNUS (non comptés) : {left}\n")
|
||||||
|
|
||||||
|
# ---------- panneau de revue unique ----------
|
||||||
|
def review_groups(self, groups, suggest, picks, guess):
|
||||||
|
"""Un seul panneau pour tous les groupes.
|
||||||
|
Retourne {groupe: ("existing", sku) | ("new", nom) | None (laissé pour plus tard)}."""
|
||||||
|
s, P = self.s, self.kb.meta["products"]
|
||||||
|
dlg = tk.Toplevel(self.root)
|
||||||
|
dlg.title(f"{len(groups)} groupe(s) à identifier")
|
||||||
|
dlg.transient(self.root)
|
||||||
|
dlg.grab_set()
|
||||||
|
dlg.geometry("860x620+40+40")
|
||||||
|
tk.Label(dlg, text="Pour chaque groupe : confirmez le produit ou donnez le nom du nouveau produit. "
|
||||||
|
"Ce que vous laissez restera INCONNU et se traitera ensuite à la souris.",
|
||||||
|
font=("Segoe UI", 10, "bold"), wraplength=800, justify="left").pack(padx=10, pady=8)
|
||||||
|
|
||||||
|
outer = tk.Frame(dlg)
|
||||||
|
outer.pack(fill="both", expand=True, padx=8)
|
||||||
|
cv = tk.Canvas(outer, highlightthickness=0)
|
||||||
|
sb = tk.Scrollbar(outer, orient="vertical", command=cv.yview)
|
||||||
|
inner = tk.Frame(cv)
|
||||||
|
inner.bind("<Configure>", lambda e: cv.configure(scrollregion=cv.bbox("all")))
|
||||||
|
cv.create_window((0, 0), window=inner, anchor="nw")
|
||||||
|
cv.configure(yscrollcommand=sb.set)
|
||||||
|
cv.pack(side="left", fill="both", expand=True)
|
||||||
|
sb.pack(side="right", fill="y")
|
||||||
|
cv.bind_all("<MouseWheel>", lambda e: cv.yview_scroll(int(-e.delta / 120), "units"))
|
||||||
|
|
||||||
|
refs, rows = [], {}
|
||||||
|
for g, idx in enumerate(groups):
|
||||||
|
frame = tk.Frame(inner, highlightbackground=to_hex(PALETTE[g % len(PALETTE)]),
|
||||||
|
highlightthickness=3)
|
||||||
|
frame.pack(fill="x", padx=4, pady=4)
|
||||||
|
thumbs = tk.Frame(frame)
|
||||||
|
thumbs.pack(side="left", padx=4, pady=4)
|
||||||
|
for i in sorted(idx, key=lambda k: -s["crops"][k].width * s["crops"][k].height)[:2]:
|
||||||
|
im = s["crops"][i].copy()
|
||||||
|
im.thumbnail((90, 120))
|
||||||
|
ph = ImageTk.PhotoImage(im)
|
||||||
|
refs.append(ph)
|
||||||
|
tk.Label(thumbs, image=ph).pack(side="left", padx=2)
|
||||||
|
right = tk.Frame(frame)
|
||||||
|
right.pack(side="left", fill="x", expand=True, padx=8)
|
||||||
|
tk.Label(right, text=f"Groupe {g + 1} : {len(idx)} facing(s)",
|
||||||
|
font=("Segoe UI", 10, "bold")).pack(anchor="w")
|
||||||
|
|
||||||
|
if g in picks:
|
||||||
|
start = f"opt{picks[g]}"
|
||||||
|
elif g in suggest:
|
||||||
|
start = "none" # plusieurs produits possibles : à vous de trancher
|
||||||
|
else:
|
||||||
|
start = "new"
|
||||||
|
mode = tk.StringVar(value=start)
|
||||||
|
name = tk.StringVar(value=guess.get(g, ""))
|
||||||
|
for k, (sku_s, sc, src) in enumerate(suggest.get(g, [])):
|
||||||
|
pname = P[sku_s]["name"]
|
||||||
|
if src == "texte":
|
||||||
|
txt = f"C'est « {pname} » (nom lu sur l'emballage, score {sc:.2f})"
|
||||||
|
elif src == "douteux":
|
||||||
|
txt = f"C'est quand même « {pname} » (score {sc:.2f}, mais le texte lu ne correspond pas)"
|
||||||
|
else:
|
||||||
|
txt = f"C'est « {pname} » (ressemblance visuelle {sc:.2f})"
|
||||||
|
tk.Radiobutton(right, text=txt, variable=mode, value=f"opt{k}").pack(anchor="w")
|
||||||
|
line = tk.Frame(right)
|
||||||
|
line.pack(anchor="w", fill="x")
|
||||||
|
tk.Radiobutton(line, text="Nouveau produit :", variable=mode, value="new").pack(side="left")
|
||||||
|
tk.Entry(line, textvariable=name, width=32).pack(side="left", padx=4)
|
||||||
|
name.trace_add("write", lambda *_, m=mode: m.set("new"))
|
||||||
|
tk.Radiobutton(right, text="Laisser pour plus tard (reste INCONNU)", variable=mode,
|
||||||
|
value="later").pack(anchor="w")
|
||||||
|
rows[g] = (mode, name)
|
||||||
|
dlg.refs = refs
|
||||||
|
|
||||||
|
result = {}
|
||||||
|
|
||||||
|
def close():
|
||||||
|
cv.unbind_all("<MouseWheel>")
|
||||||
|
dlg.destroy()
|
||||||
|
|
||||||
|
def validate():
|
||||||
|
out = {}
|
||||||
|
for g, (mode, name) in rows.items():
|
||||||
|
m = mode.get()
|
||||||
|
if m.startswith("opt"):
|
||||||
|
out[g] = ("existing", suggest[g][int(m[3:])][0])
|
||||||
|
elif m == "new":
|
||||||
|
if not name.get().strip():
|
||||||
|
messagebox.showwarning("Nom manquant",
|
||||||
|
f"Groupe {g + 1} : tapez un nom ou choisissez une autre option.",
|
||||||
|
parent=dlg)
|
||||||
|
return
|
||||||
|
out[g] = ("new", name.get().strip())
|
||||||
|
elif m == "none":
|
||||||
|
messagebox.showwarning("Choix manquant",
|
||||||
|
f"Groupe {g + 1} : plusieurs produits possibles, choisissez-en un, "
|
||||||
|
"donnez un nom, ou laissez pour plus tard.", parent=dlg)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
out[g] = None
|
||||||
|
result.update(out)
|
||||||
|
close()
|
||||||
|
|
||||||
|
def accept_suggestions():
|
||||||
|
for g, (mode, name) in rows.items():
|
||||||
|
mode.set(f"opt{picks[g]}" if g in picks else "later")
|
||||||
|
validate()
|
||||||
|
|
||||||
|
btns = tk.Frame(dlg)
|
||||||
|
btns.pack(pady=10)
|
||||||
|
tk.Button(btns, text="Valider", width=14, command=validate).pack(side="left", padx=6)
|
||||||
|
tk.Button(btns, text="Accepter les propositions sûres\net laisser le reste pour plus tard",
|
||||||
|
command=accept_suggestions).pack(side="left", padx=6)
|
||||||
|
tk.Button(btns, text="Tout laisser pour plus tard", command=close).pack(side="left", padx=6)
|
||||||
|
dlg.protocol("WM_DELETE_WINDOW", close)
|
||||||
|
self.root.wait_window(dlg)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--detector", default="detector/best.pt")
|
||||||
|
ap.add_argument("--backbone", default="efficientnet",
|
||||||
|
choices=["efficientnet", "dinov2_small", "dinov2_base"])
|
||||||
|
ap.add_argument("--weights", default=None)
|
||||||
|
ap.add_argument("--kb_dir", default="kb_data")
|
||||||
|
ap.add_argument("--data_dir", default="data")
|
||||||
|
ap.add_argument("--det_conf", type=float, default=0.30)
|
||||||
|
ap.add_argument("--sim_thr", type=float, default=None) # score minimum pour accepter automatiquement
|
||||||
|
ap.add_argument("--min_sim", type=float, default=None) # en dessous : aucune proposition
|
||||||
|
ap.add_argument("--cluster_thr", type=float, default=None) # regroupement des produits à identifier
|
||||||
|
ap.add_argument("--min_group", type=int, default=1) # facings minimum par groupe proposé
|
||||||
|
ap.add_argument("--margin", type=float, default=0.05) # écart minimum entre les deux meilleurs produits
|
||||||
|
ap.add_argument("--text_w", type=float, default=0.15) # poids du texte lu dans le score
|
||||||
|
ap.add_argument("--min_letters", type=int, default=6) # lettres minimum pour juger sur le texte
|
||||||
|
ap.add_argument("--sim_certain", type=float, default=0.90) # au-dessus, pas de lecture du texte
|
||||||
|
ap.add_argument("--strict_vis", type=float, default=0.78) # mode strict : visuel suffisant si le texte ne contredit pas
|
||||||
|
ap.add_argument("--ocr_cluster_thr", type=float, default=0.88)
|
||||||
|
ap.add_argument("--no_ocr", action="store_true") # désactive la lecture du texte
|
||||||
|
ap.add_argument("--lenient", action="store_true") # désactive le mode strict (moins de questions)
|
||||||
|
ap.add_argument("--prop_thr", type=float, default=0.85) # ressemblance exigée pour la propagation
|
||||||
|
args = ap.parse_args()
|
||||||
|
args.ocr = not args.no_ocr
|
||||||
|
args.strict = not args.lenient
|
||||||
|
if args.ocr:
|
||||||
|
try:
|
||||||
|
import easyocr # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
print("easyocr n'est pas installé : lecture du texte désactivée (pip install easyocr).")
|
||||||
|
args.ocr = False
|
||||||
|
root = tk.Tk()
|
||||||
|
App(root, args)
|
||||||
|
root.mainloop()
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""Parcours complet avec votre photo (propositions sûres seulement, rien de nouveau n'est créé) :
|
||||||
|
python test_facing_flow.py photo.jpg [http://127.0.0.1:2001]
|
||||||
|
ATTENTION : « finish » augmente les compteurs cumulés de la base -> utilisez une copie (kb_session)."""
|
||||||
|
import base64
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
path = sys.argv[1]
|
||||||
|
base = (sys.argv[2] if len(sys.argv) > 2 else "http://127.0.0.1:2001").rstrip("/") + "/facing"
|
||||||
|
|
||||||
|
|
||||||
|
def show(st):
|
||||||
|
print(f" phase={st['phase']} | inconnus restants={st['unknown_left']} | comptage="
|
||||||
|
f"{[(c['name'], c['count']) for c in st['counts']]}")
|
||||||
|
|
||||||
|
|
||||||
|
b64 = base64.b64encode(open(path, "rb").read()).decode()
|
||||||
|
job = requests.post(f"{base}/analyze", json={"image": b64}, timeout=60).json()["job_id"]
|
||||||
|
while True:
|
||||||
|
j = requests.get(f"{base}/jobs/{job}", timeout=10).json()
|
||||||
|
print(f"analyse {j['status']} {j['progress']} %")
|
||||||
|
if j["status"] != "processing":
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
if j["status"] != "done":
|
||||||
|
sys.exit(f"ECHEC : {j['error']}")
|
||||||
|
st = j["results"]
|
||||||
|
sid = st["session_id"]
|
||||||
|
show(st)
|
||||||
|
|
||||||
|
if st["phase"] == "review":
|
||||||
|
choices = []
|
||||||
|
for g in st["groups"]:
|
||||||
|
if g["pick"] is not None and g["pick"] >= 0:
|
||||||
|
sug = g["suggest"][g["pick"]]
|
||||||
|
print(f" groupe {g['id'] + 1} ({len(g['box_ids'])} facings) -> {sug['name']} ({sug['source']})")
|
||||||
|
choices.append({"group": g["id"], "kind": "existing", "sku": sug["sku"]})
|
||||||
|
else:
|
||||||
|
print(f" groupe {g['id'] + 1} ({len(g['box_ids'])} facings) -> plus tard")
|
||||||
|
choices.append({"group": g["id"], "kind": "later"})
|
||||||
|
r = requests.post(f"{base}/{sid}/review", json={"choices": choices}, timeout=60)
|
||||||
|
print("revue :", r.status_code)
|
||||||
|
st = r.json()
|
||||||
|
show(st)
|
||||||
|
|
||||||
|
if st["phase"] == "resolve":
|
||||||
|
print(f"{st['unknown_left']} produit(s) restent INCONNUS (à traiter sur le téléphone) -> terminer")
|
||||||
|
r = requests.post(f"{base}/{sid}/finish", timeout=60)
|
||||||
|
st = r.json()
|
||||||
|
show(st)
|
||||||
|
|
||||||
|
print("\n=== Facings dans cette photo ===")
|
||||||
|
for c in st["counts"]:
|
||||||
|
print(f"{c['name']}: {c['count']}{' [NOUVEAU]' if c['new'] else ''} (cumul : {c['cumul']} facings sur {c['photos']} photos)")
|
||||||
|
if st["unknown_left"]:
|
||||||
|
print(f"\nProduits restés INCONNUS (non comptés) : {st['unknown_left']}")
|
||||||
Reference in new issue
Block a user