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
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)
|
||||
Reference in new issue
Block a user