300 lines
10 KiB
Python
300 lines
10 KiB
Python
"""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))
|