Spaces:
Sleeping
feat: pivot CSV → EBP (fin du PDF) + unités préservées ligne par ligne
Browse filesEntrée désormais CSV (le PDF est abandonné) :
- nouvel onglet « 📄 CSV → CSV EBP » : mapping des colonnes (menus remplis depuis
les vrais en-têtes du CSV), analyse des sous-familles sur le libellé, aperçu
éditable, export 1 CSV par famille + 0_familles_articles.csv
- core/csv_import.py : lecture CSV (encodage/séparateur auto), détection des
colonnes, parse prix FR, conversion en articles. Unité prise TELLE QUELLE
ligne par ligne, jamais imposée ni uniformisée.
- csv_writer : _build_article_ebp_row n'impose plus d'unité par défaut
- suppression du code PDF : core/agent.py, core/extractor.py,
core/regex_extractor.py + leurs tests ; PyMuPDF retiré des requirements
- tests : +14 (core.csv_import), suite à 64 verts
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- app.py +2 -2
- app_gradio.py +236 -543
- core/agent.py +0 -307
- core/csv_import.py +87 -0
- core/csv_writer.py +4 -4
- core/extractor.py +0 -184
- core/regex_extractor.py +0 -78
- requirements.txt +0 -1
- tests/test_agent_validation.py +0 -54
- tests/test_csv_import.py +74 -0
- tests/test_new_features.py +0 -210
|
@@ -2,8 +2,8 @@
|
|
| 2 |
Point d'entrée du Space : FastAPI minimal + UI Gradio à onglets servie sur /.
|
| 3 |
|
| 4 |
Une seule page, deux onglets :
|
| 5 |
-
- 🧹 Nettoyeur CSV
|
| 6 |
-
- 📄
|
| 7 |
|
| 8 |
Lancement (Docker) : uvicorn app:app --host 0.0.0.0 --port 7860
|
| 9 |
"""
|
|
|
|
| 2 |
Point d'entrée du Space : FastAPI minimal + UI Gradio à onglets servie sur /.
|
| 3 |
|
| 4 |
Une seule page, deux onglets :
|
| 5 |
+
- 🧹 Nettoyeur CSV (core.cleaner — 100 % local, sans IA)
|
| 6 |
+
- 📄 CSV → CSV EBP (core.subfamily — mapping colonnes + analyse sous-familles + aperçu éditable)
|
| 7 |
|
| 8 |
Lancement (Docker) : uvicorn app:app --host 0.0.0.0 --port 7860
|
| 9 |
"""
|
|
@@ -1,30 +1,29 @@
|
|
| 1 |
"""
|
| 2 |
-
Interface Gradio —
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
-
import csv
|
| 8 |
-
import json
|
| 9 |
import os
|
| 10 |
-
import shutil
|
| 11 |
import tempfile
|
| 12 |
import traceback
|
| 13 |
import zipfile
|
| 14 |
-
from collections import defaultdict
|
| 15 |
from pathlib import Path
|
| 16 |
|
| 17 |
import gradio as gr
|
| 18 |
from dotenv import load_dotenv
|
| 19 |
|
| 20 |
-
from core.
|
|
|
|
|
|
|
|
|
|
| 21 |
from core.csv_writer import (
|
| 22 |
-
|
| 23 |
-
COLS_ARTICLES_EBP, _build_article_ebp_row,
|
| 24 |
)
|
| 25 |
-
from core.cleaner import clean_csv
|
| 26 |
-
from core.extractor import debug_layout
|
| 27 |
-
from core.profil import list_profiles, load_profile, save_profile
|
| 28 |
from core.subfamily import analyse_sous_familles
|
| 29 |
|
| 30 |
load_dotenv()
|
|
@@ -32,209 +31,122 @@ load_dotenv()
|
|
| 32 |
|
| 33 |
# ── Constantes ────────────────────────────────────────────────────────────────
|
| 34 |
|
| 35 |
-
TVA_CHOICES
|
| 36 |
-
|
| 37 |
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
def run_debug_layout(pdf_file, page_from: int, page_to: int) -> str:
|
| 42 |
-
if pdf_file is None:
|
| 43 |
-
return "⚠️ Aucun fichier PDF fourni."
|
| 44 |
-
try:
|
| 45 |
-
pages = debug_layout(pdf_file.name, page_from, page_to)
|
| 46 |
-
if not pages:
|
| 47 |
-
return "Impossible d'analyser (pdfplumber manquant ?)."
|
| 48 |
-
lines = ["Page | Tables | Lignes texte | Prix trouvés"]
|
| 49 |
-
lines.append("-----|--------|-------------|-------------")
|
| 50 |
-
vides = []
|
| 51 |
-
for p in pages:
|
| 52 |
-
marker = " ← vide" if p["prix_trouves"] == 0 and p["lignes_texte"] == 0 else ""
|
| 53 |
-
lines.append(
|
| 54 |
-
f" {p['page']:3d} | {p['tables']:3d} | {p['lignes_texte']:3d} | {p['prix_trouves']:3d}{marker}"
|
| 55 |
-
)
|
| 56 |
-
if p["prix_trouves"] == 0:
|
| 57 |
-
vides.append(str(p["page"]))
|
| 58 |
-
if vides:
|
| 59 |
-
lines.append(f"\n⚠️ Pages sans prix détecté : {', '.join(vides)}")
|
| 60 |
-
return "\n".join(lines)
|
| 61 |
-
except Exception as exc:
|
| 62 |
-
return f"❌ Erreur : {exc}"
|
| 63 |
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
if not fournisseur_code:
|
| 80 |
-
fournisseur_code = fournisseur_nom[:8].upper().replace(" ", "")
|
| 81 |
|
| 82 |
-
taux_tva = 20.0
|
| 83 |
-
for label, val in TVA_CHOICES:
|
| 84 |
-
if label == taux_tva_label:
|
| 85 |
-
taux_tva = val
|
| 86 |
-
break
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
raise ValueError("JSON de l'extracteur regex invalide.")
|
| 101 |
-
|
| 102 |
-
if (profil_nom_save or "").strip():
|
| 103 |
-
profil_data: dict = {
|
| 104 |
-
"fournisseur_nom": fournisseur_nom,
|
| 105 |
-
"fournisseur_code": fournisseur_code,
|
| 106 |
-
"code_famille": code_famille,
|
| 107 |
-
"remise": remise,
|
| 108 |
-
"prix_sont_ttc": prix_sont_ttc,
|
| 109 |
-
"taux_tva_label": taux_tva_label,
|
| 110 |
-
"unite_defaut": unite_defaut,
|
| 111 |
-
}
|
| 112 |
-
if collection_famille_map:
|
| 113 |
-
profil_data["collection_famille_map"] = collection_famille_map
|
| 114 |
-
if regex_config:
|
| 115 |
-
profil_data["regex_config"] = regex_config
|
| 116 |
-
save_profile(profil_nom_save.strip(), profil_data)
|
| 117 |
-
|
| 118 |
-
return {
|
| 119 |
-
"fournisseur_nom": fournisseur_nom,
|
| 120 |
-
"fournisseur_code": fournisseur_code,
|
| 121 |
-
"code_famille": code_famille,
|
| 122 |
-
"remise": remise,
|
| 123 |
-
"prix_sont_ttc": prix_sont_ttc,
|
| 124 |
-
"taux_tva": taux_tva,
|
| 125 |
-
"unite_defaut": unite_defaut,
|
| 126 |
-
"sample_mode": sample_mode,
|
| 127 |
-
"collection_famille_map": collection_famille_map,
|
| 128 |
-
"regex_config": regex_config,
|
| 129 |
-
"analyse_familles": analyse_familles,
|
| 130 |
-
"classif_llm": classif_llm,
|
| 131 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
def _extract_and_analyse(pdf_path, page_from, page_to, params, progress_cb=None):
|
| 135 |
-
"""Extraction + analyse des sous-familles. Retourne (valides, anomalies, rapport, rapport_familles)."""
|
| 136 |
-
valides, anomalies, rapport = extract_articles(
|
| 137 |
-
pdf_path=pdf_path,
|
| 138 |
-
page_from=page_from,
|
| 139 |
-
page_to=page_to,
|
| 140 |
-
password="",
|
| 141 |
-
default_unit=params["unite_defaut"],
|
| 142 |
-
progress_cb=progress_cb,
|
| 143 |
-
sample_mode=params["sample_mode"],
|
| 144 |
-
regex_config=params["regex_config"],
|
| 145 |
-
)
|
| 146 |
-
|
| 147 |
-
rapport_familles = None
|
| 148 |
-
if params["analyse_familles"] and valides:
|
| 149 |
-
client = None
|
| 150 |
-
if params["classif_llm"]:
|
| 151 |
-
import anthropic
|
| 152 |
-
try:
|
| 153 |
-
client = anthropic.Anthropic()
|
| 154 |
-
except Exception:
|
| 155 |
-
client = None
|
| 156 |
-
valides, rapport_familles = analyse_sous_familles(
|
| 157 |
-
valides, use_llm=params["classif_llm"] and client is not None, client=client,
|
| 158 |
-
)
|
| 159 |
-
return valides, anomalies, rapport, rapport_familles
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
def _do_export(valides, anomalies, rapport, rapport_familles, params):
|
| 163 |
-
"""Écrit tous les CSV + rapport + ZIP. Retourne (zip_path, rapport_txt)."""
|
| 164 |
-
out_dir = tempfile.mkdtemp(prefix="ebp_export_")
|
| 165 |
-
|
| 166 |
-
export_ebp(
|
| 167 |
-
articles=valides,
|
| 168 |
-
output_dir=out_dir,
|
| 169 |
-
fournisseur_nom=params["fournisseur_nom"],
|
| 170 |
-
fournisseur_code=params["fournisseur_code"],
|
| 171 |
-
remise=params["remise"],
|
| 172 |
-
unite_defaut=params["unite_defaut"],
|
| 173 |
-
code_famille=params["code_famille"],
|
| 174 |
-
prix_sont_ttc=params["prix_sont_ttc"],
|
| 175 |
-
taux_tva=params["taux_tva"],
|
| 176 |
-
collection_famille_map=params["collection_famille_map"],
|
| 177 |
-
)
|
| 178 |
-
|
| 179 |
-
if params["analyse_familles"] and valides:
|
| 180 |
-
export_articles_par_famille(
|
| 181 |
-
articles=valides,
|
| 182 |
-
output_dir=out_dir,
|
| 183 |
-
fournisseur_code=params["fournisseur_code"],
|
| 184 |
-
remise=params["remise"],
|
| 185 |
-
unite_defaut=params["unite_defaut"],
|
| 186 |
-
taux_tva=params["taux_tva"],
|
| 187 |
-
prix_sont_ttc=params["prix_sont_ttc"],
|
| 188 |
-
)
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
Path(rapport_path).write_text(rapport_txt, encoding="utf-8")
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
|
| 207 |
-
# ── Aperçu éditable
|
| 208 |
|
| 209 |
-
def _articles_to_preview(articles
|
| 210 |
-
"""Premiers n articles → lignes au format colonnes EBP (pour le tableau éditable)."""
|
| 211 |
rows = []
|
| 212 |
for a in articles[:n]:
|
| 213 |
r = _build_article_ebp_row(
|
| 214 |
-
a, params["fournisseur_code"], params["remise"],
|
| 215 |
"TVA20", params["taux_tva"], params["prix_sont_ttc"],
|
| 216 |
)
|
| 217 |
rows.append([r[c] for c in COLS_ARTICLES_EBP])
|
| 218 |
return rows
|
| 219 |
|
| 220 |
|
| 221 |
-
def _apply_preview_edits(articles
|
| 222 |
"""
|
| 223 |
Réinjecte les corrections de l'aperçu (libellé, prix HT, unité, famille)
|
| 224 |
-
|
| 225 |
-
Les colonnes dérivées (PV TTC, Prix d'achat…) sont recalculées à l'export.
|
| 226 |
"""
|
| 227 |
if edited_rows is None:
|
| 228 |
return articles
|
| 229 |
rows = edited_rows.values.tolist() if hasattr(edited_rows, "values") else list(edited_rows)
|
| 230 |
-
|
| 231 |
idx = {c: i for i, c in enumerate(COLS_ARTICLES_EBP)}
|
| 232 |
by_ref: dict[str, dict] = {}
|
| 233 |
for a in articles:
|
| 234 |
-
ref = str(a.get("reference") or
|
| 235 |
if ref and ref not in by_ref:
|
| 236 |
by_ref[ref] = a
|
| 237 |
-
|
| 238 |
for row in rows:
|
| 239 |
if not row or len(row) < len(COLS_ARTICLES_EBP):
|
| 240 |
continue
|
|
@@ -254,139 +166,15 @@ def _apply_preview_edits(articles: list[dict], edited_rows) -> list[dict]:
|
|
| 254 |
return articles
|
| 255 |
|
| 256 |
|
| 257 |
-
|
| 258 |
-
pdf_file, page_from, page_to, fournisseur_nom, fournisseur_code, code_famille,
|
| 259 |
-
remise, prix_sont_ttc, taux_tva_label, unite_defaut, sample_mode, profil_nom_save,
|
| 260 |
-
collection_famille_map_json, regex_config_json, analyse_familles, classif_llm,
|
| 261 |
-
progress=gr.Progress(),
|
| 262 |
-
):
|
| 263 |
-
if pdf_file is None:
|
| 264 |
-
return None, gr.update(), "⚠️ Aucun fichier PDF fourni.", ""
|
| 265 |
-
try:
|
| 266 |
-
params = _build_params(
|
| 267 |
-
fournisseur_nom, fournisseur_code, code_famille, remise, prix_sont_ttc,
|
| 268 |
-
taux_tva_label, unite_defaut, sample_mode, profil_nom_save,
|
| 269 |
-
collection_famille_map_json, regex_config_json, analyse_familles, classif_llm,
|
| 270 |
-
)
|
| 271 |
-
except ValueError as exc:
|
| 272 |
-
return None, gr.update(), f"⚠️ {exc}", ""
|
| 273 |
-
|
| 274 |
-
def _cb(done, total):
|
| 275 |
-
progress(done / max(total, 1), desc=f"Batch {done}/{total}")
|
| 276 |
-
|
| 277 |
-
try:
|
| 278 |
-
progress(0, desc="Extraction + analyse pour aperçu…")
|
| 279 |
-
valides, anomalies, rapport, rapport_familles = _extract_and_analyse(
|
| 280 |
-
pdf_file.name, page_from, page_to, params, _cb,
|
| 281 |
-
)
|
| 282 |
-
if not valides and not anomalies:
|
| 283 |
-
return None, gr.update(visible=False), "⚠️ Aucun article détecté.", ""
|
| 284 |
-
|
| 285 |
-
preview_rows = _articles_to_preview(valides, params, PREVIEW_N)
|
| 286 |
-
state = {
|
| 287 |
-
"valides": valides, "anomalies": anomalies,
|
| 288 |
-
"rapport": rapport, "rapport_familles": rapport_familles,
|
| 289 |
-
"params": params,
|
| 290 |
-
}
|
| 291 |
-
info = (f"Aperçu de {min(PREVIEW_N, len(valides))} réf. sur {len(valides)}. "
|
| 292 |
-
"Corrige le tableau (famille, libellé, prix HT, unité) puis clique « Exporter ».")
|
| 293 |
-
progress(1.0, desc="Aperçu prêt")
|
| 294 |
-
return (state, gr.update(value=preview_rows, visible=True),
|
| 295 |
-
info, _anomalies_preview(anomalies))
|
| 296 |
-
except Exception as exc:
|
| 297 |
-
tb = traceback.format_exc()
|
| 298 |
-
return None, gr.update(visible=False), f"❌ Erreur : {exc}\n\n{tb[-600:]}", ""
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
def run_export_from_preview(state, edited_rows, progress=gr.Progress()):
|
| 302 |
-
if not state:
|
| 303 |
-
return None, "⚠️ Lance d'abord un aperçu avant d'exporter.", ""
|
| 304 |
-
try:
|
| 305 |
-
progress(0.2, desc="Application des corrections…")
|
| 306 |
-
valides = _apply_preview_edits(state["valides"], edited_rows)
|
| 307 |
-
params = state["params"]
|
| 308 |
-
|
| 309 |
-
# Répartition familles recalculée après édition
|
| 310 |
-
rapport_familles = state["rapport_familles"]
|
| 311 |
-
if params["analyse_familles"]:
|
| 312 |
-
repart: dict[str, int] = {}
|
| 313 |
-
for a in valides:
|
| 314 |
-
fam = a.get("code_sous_famille", "DIVERS")
|
| 315 |
-
repart[fam] = repart.get(fam, 0) + 1
|
| 316 |
-
if rapport_familles:
|
| 317 |
-
rapport_familles = dict(rapport_familles)
|
| 318 |
-
rapport_familles["repartition"] = dict(sorted(repart.items(), key=lambda kv: -kv[1]))
|
| 319 |
-
|
| 320 |
-
progress(0.6, desc="Écriture des CSV…")
|
| 321 |
-
zip_path, rapport_txt = _do_export(
|
| 322 |
-
valides, state["anomalies"], state["rapport"], rapport_familles, params,
|
| 323 |
-
)
|
| 324 |
-
progress(1.0, desc="Terminé !")
|
| 325 |
-
return zip_path, rapport_txt, _anomalies_preview(state["anomalies"])
|
| 326 |
-
except Exception as exc:
|
| 327 |
-
tb = traceback.format_exc()
|
| 328 |
-
return None, f"❌ Erreur : {exc}\n\n{tb[-600:]}", ""
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
def run_conversion(
|
| 332 |
-
pdf_file, page_from, page_to, fournisseur_nom, fournisseur_code, code_famille,
|
| 333 |
-
remise, prix_sont_ttc, taux_tva_label, unite_defaut, sample_mode, profil_nom_save,
|
| 334 |
-
collection_famille_map_json, regex_config_json, analyse_familles, classif_llm,
|
| 335 |
-
progress=gr.Progress(),
|
| 336 |
-
):
|
| 337 |
-
"""Conversion directe sans aperçu (un seul clic)."""
|
| 338 |
-
if pdf_file is None:
|
| 339 |
-
return None, "⚠️ Aucun fichier PDF fourni.", "", ""
|
| 340 |
-
try:
|
| 341 |
-
params = _build_params(
|
| 342 |
-
fournisseur_nom, fournisseur_code, code_famille, remise, prix_sont_ttc,
|
| 343 |
-
taux_tva_label, unite_defaut, sample_mode, profil_nom_save,
|
| 344 |
-
collection_famille_map_json, regex_config_json, analyse_familles, classif_llm,
|
| 345 |
-
)
|
| 346 |
-
except ValueError as exc:
|
| 347 |
-
return None, f"⚠️ {exc}", "", ""
|
| 348 |
-
|
| 349 |
-
def _cb(done, total):
|
| 350 |
-
progress(done / max(total, 1), desc=f"Batch {done}/{total}")
|
| 351 |
-
|
| 352 |
-
try:
|
| 353 |
-
progress(0, desc="Extraction en cours…")
|
| 354 |
-
valides, anomalies, rapport, rapport_familles = _extract_and_analyse(
|
| 355 |
-
pdf_file.name, page_from, page_to, params, _cb,
|
| 356 |
-
)
|
| 357 |
-
if not valides and not anomalies:
|
| 358 |
-
return None, "⚠️ Aucun article détecté dans ces pages.", "", ""
|
| 359 |
-
|
| 360 |
-
progress(0.9, desc="Écriture des fichiers CSV…")
|
| 361 |
-
zip_path, rapport_txt = _do_export(
|
| 362 |
-
valides, anomalies, rapport, rapport_familles, params,
|
| 363 |
-
)
|
| 364 |
-
progress(1.0, desc="Terminé !")
|
| 365 |
-
return zip_path, rapport_txt, _anomalies_preview(anomalies), ""
|
| 366 |
-
except Exception as exc:
|
| 367 |
-
tb = traceback.format_exc()
|
| 368 |
-
return None, f"❌ Erreur : {exc}\n\n{tb[-800:]}", "", ""
|
| 369 |
-
|
| 370 |
|
| 371 |
-
def _build_rapport(
|
| 372 |
-
rapport_familles: dict | None = None) -> str:
|
| 373 |
-
mode_extract = rapport.get("mode", "text")
|
| 374 |
lines = [
|
| 375 |
-
"═══ RAPPORT
|
| 376 |
-
f"
|
| 377 |
-
f"
|
| 378 |
-
f"
|
| 379 |
-
f"Articles OK : {rapport['articles_ecrits']}",
|
| 380 |
-
f"Anomalies : {rapport['anomalies']}",
|
| 381 |
-
f"Couverture : {rapport['taux_couverture_pct']} %",
|
| 382 |
-
"",
|
| 383 |
-
"Fichiers produits (à importer dans cet ordre) :",
|
| 384 |
-
" 1. 1_familles_articles.csv",
|
| 385 |
-
" 2. 2_fournisseur.csv",
|
| 386 |
-
" 3. 3_articles.csv",
|
| 387 |
]
|
| 388 |
-
|
| 389 |
-
# ── Bilan analyse des sous-familles ───────────────────────────────────────
|
| 390 |
if rapport_familles:
|
| 391 |
lines += [
|
| 392 |
"",
|
|
@@ -399,143 +187,126 @@ def _build_rapport(rapport: dict, valides, anomalies, sample_mode: bool,
|
|
| 399 |
]
|
| 400 |
for fam, n in rapport_familles["repartition"].items():
|
| 401 |
lines.append(f" • articles_{fam}.csv : {n} article(s)")
|
| 402 |
-
|
| 403 |
-
# Top 10 prix les plus élevés
|
| 404 |
-
avec_prix = [a for a in valides if a.get("prix_conseille", 0) > 0]
|
| 405 |
-
if avec_prix:
|
| 406 |
-
top10 = sorted(avec_prix, key=lambda a: a["prix_conseille"], reverse=True)[:10]
|
| 407 |
-
lines += ["", "── Top 10 prix conseillés ──"]
|
| 408 |
-
for a in top10:
|
| 409 |
-
ref = a.get("reference", "?")
|
| 410 |
-
nom = str(a.get("nom_dessin", ""))[:30]
|
| 411 |
-
prix = f"{a['prix_conseille']:.2f}".replace(".", ",")
|
| 412 |
-
lines.append(f" {prix} € [{ref}] {nom}")
|
| 413 |
-
|
| 414 |
-
# Doublons (même référence, prix différents)
|
| 415 |
-
ref_prix: dict[str, list] = defaultdict(list)
|
| 416 |
-
for a in valides:
|
| 417 |
-
ref = a.get("reference", "")
|
| 418 |
-
if ref:
|
| 419 |
-
ref_prix[ref].append(a.get("prix_conseille", 0))
|
| 420 |
-
doublons = {ref: prix for ref, prix in ref_prix.items() if len(set(prix)) > 1}
|
| 421 |
-
if doublons:
|
| 422 |
-
lines += ["", f"── {len(doublons)} référence(s) en doublon (prix différents) ──"]
|
| 423 |
-
for ref, prix_list in list(doublons.items())[:10]:
|
| 424 |
-
prix_fmt = " / ".join(f"{p:.2f}".replace(".", ",") for p in prix_list)
|
| 425 |
-
lines.append(f" [{ref}] → {prix_fmt}")
|
| 426 |
-
|
| 427 |
-
if anomalies:
|
| 428 |
-
lines += ["", f"⚠️ {len(anomalies)} lignes en anomalie → anomalies.csv (à revoir manuellement)."]
|
| 429 |
return "\n".join(lines)
|
| 430 |
|
| 431 |
|
| 432 |
-
def
|
| 433 |
-
|
| 434 |
-
return
|
| 435 |
-
cols = ["code", "libelle", "prix_brut", "unite", "famille_suggeree", "anomalie_raison"]
|
| 436 |
-
with open(path, "w", newline="", encoding="utf-8-sig") as f:
|
| 437 |
-
w = csv.DictWriter(f, fieldnames=cols, delimiter=";",
|
| 438 |
-
extrasaction="ignore", lineterminator="\r\n")
|
| 439 |
-
w.writeheader()
|
| 440 |
-
w.writerows(anomalies)
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
def _anomalies_preview(anomalies: list[dict]) -> str:
|
| 444 |
-
if not anomalies:
|
| 445 |
-
return "✅ Aucune anomalie détectée."
|
| 446 |
-
lines = [f"⚠️ {len(anomalies)} anomalie(s) — prix non traçables à la source :"]
|
| 447 |
-
for a in anomalies[:10]:
|
| 448 |
-
lines.append(f" [{a.get('code','?')}] {str(a.get('libelle',''))[:40]} — {a.get('anomalie_raison','')}")
|
| 449 |
-
if len(anomalies) > 10:
|
| 450 |
-
lines.append(f" … et {len(anomalies)-10} autres (voir anomalies.csv)")
|
| 451 |
-
return "\n".join(lines)
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
# ── Gestion des profils ───────────────────────────────────────────────────────
|
| 455 |
-
|
| 456 |
-
def on_profil_load(profil_nom: str):
|
| 457 |
-
empty = tuple(gr.update() for _ in range(9))
|
| 458 |
-
if not profil_nom or profil_nom == "(aucun)":
|
| 459 |
-
return empty
|
| 460 |
-
try:
|
| 461 |
-
p = load_profile(profil_nom)
|
| 462 |
-
mapping = p.get("collection_famille_map")
|
| 463 |
-
mapping_str = json.dumps(mapping, ensure_ascii=False) if mapping else ""
|
| 464 |
-
regex = p.get("regex_config")
|
| 465 |
-
regex_str = json.dumps(regex, ensure_ascii=False, indent=2) if regex else ""
|
| 466 |
-
return (
|
| 467 |
-
p.get("fournisseur_nom", ""),
|
| 468 |
-
p.get("fournisseur_code", ""),
|
| 469 |
-
p.get("code_famille", "FFR00001"),
|
| 470 |
-
p.get("remise", 45.0),
|
| 471 |
-
p.get("prix_sont_ttc", False),
|
| 472 |
-
p.get("taux_tva_label", "20 %"),
|
| 473 |
-
p.get("unite_defaut", "ml"),
|
| 474 |
-
mapping_str,
|
| 475 |
-
regex_str,
|
| 476 |
-
)
|
| 477 |
-
except Exception:
|
| 478 |
-
return empty
|
| 479 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
|
|
|
|
|
|
|
|
|
|
| 485 |
|
| 486 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 487 |
|
| 488 |
-
def _format_clean_report(report: dict) -> str:
|
| 489 |
-
lines = [
|
| 490 |
-
"═══ RAPPORT DE NETTOYAGE ═══",
|
| 491 |
-
f"Encodage détecté : {report.get('encodage_detecte')}",
|
| 492 |
-
f"Séparateur détecté : {report.get('separateur_detecte')}",
|
| 493 |
-
f"Lignes : {report.get('lignes_initiales')} → {report.get('lignes_finales')}",
|
| 494 |
-
f"Colonnes : {report.get('colonnes_initiales')} → {report.get('colonnes_finales')}",
|
| 495 |
-
f"Sortie : séparateur '{report.get('separateur_sortie')}' / {report.get('encodage_sortie')}",
|
| 496 |
-
"",
|
| 497 |
-
"Actions :",
|
| 498 |
-
]
|
| 499 |
-
for a in report.get("actions", []):
|
| 500 |
-
lines.append(f" • {a}")
|
| 501 |
-
return "\n".join(lines)
|
| 502 |
|
|
|
|
| 503 |
|
| 504 |
-
def
|
| 505 |
-
|
| 506 |
-
|
| 507 |
if csv_file is None:
|
| 508 |
-
return None, "⚠️ Aucun fichier CSV fourni."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
try:
|
| 510 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
except Exception as exc:
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
return None, "⚠️ Le fichier est vide."
|
| 515 |
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
"decimal_comma": decimal_comma, "ebp_format": ebp_format,
|
| 521 |
-
}
|
| 522 |
try:
|
| 523 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
except Exception as exc:
|
| 525 |
tb = traceback.format_exc()
|
| 526 |
-
return None, f"❌ Erreur : {exc}\n\n{tb[-
|
| 527 |
|
| 528 |
-
base = Path(csv_file.name).stem or "fichier"
|
| 529 |
-
out_dir = tempfile.mkdtemp(prefix="csv_clean_")
|
| 530 |
-
out_path = os.path.join(out_dir, f"{base}_nettoye.csv")
|
| 531 |
-
Path(out_path).write_bytes(cleaned)
|
| 532 |
-
return out_path, _format_clean_report(report)
|
| 533 |
|
| 534 |
-
|
| 535 |
-
#
|
|
|
|
| 536 |
|
| 537 |
with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
| 538 |
-
gr.Markdown("# 🧰 Atelier — Outils CSV
|
| 539 |
|
| 540 |
with gr.Tabs():
|
| 541 |
|
|
@@ -565,119 +336,55 @@ with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
|
| 565 |
clean_report_out = gr.Textbox(label="📊 Rapport de nettoyage",
|
| 566 |
lines=16, interactive=False)
|
| 567 |
|
| 568 |
-
# ══════════ ONGLET 2 :
|
| 569 |
-
with gr.Tab("📄
|
| 570 |
gr.Markdown(
|
| 571 |
-
"
|
| 572 |
-
"
|
| 573 |
-
"Les
|
| 574 |
)
|
| 575 |
-
|
| 576 |
with gr.Row():
|
| 577 |
with gr.Column(scale=2):
|
| 578 |
-
gr.
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
btn_debug = gr.Button("🔍 Analyser la structure du PDF", size="sm")
|
| 586 |
-
debug_output = gr.Textbox(label="Structure par page (tables / lignes / prix)", lines=8,
|
| 587 |
-
interactive=False, visible=False)
|
| 588 |
-
|
| 589 |
-
with gr.Column(scale=2):
|
| 590 |
-
gr.Markdown("### 🏭 Fournisseur")
|
| 591 |
-
with gr.Row():
|
| 592 |
-
profil_dropdown = gr.Dropdown(
|
| 593 |
-
choices=["(aucun)"] + list_profiles(),
|
| 594 |
-
value="(aucun)",
|
| 595 |
-
label="Charger un profil",
|
| 596 |
-
interactive=True,
|
| 597 |
-
)
|
| 598 |
-
btn_refresh = gr.Button("🔄", size="sm")
|
| 599 |
-
|
| 600 |
-
fournisseur_nom = gr.Textbox(label="Nom du fournisseur *", placeholder="Ex : CASAMANCE")
|
| 601 |
-
fournisseur_code = gr.Textbox(label="Code fournisseur", placeholder="Ex : CAS001")
|
| 602 |
-
code_famille = gr.Textbox(label="Code famille EBP par défaut", value="FFR00001")
|
| 603 |
-
collection_famille_map_input = gr.Textbox(
|
| 604 |
-
label="Mapping collection → code famille EBP (JSON optionnel)",
|
| 605 |
-
placeholder='{"CHOREGRAPHIE": "TIS-DEC", "PIUMA": "TIS-VEL"}',
|
| 606 |
-
lines=2,
|
| 607 |
-
)
|
| 608 |
-
profil_save_nom = gr.Textbox(label="Sauvegarder ce profil sous…",
|
| 609 |
-
placeholder="laisser vide pour ne pas sauvegarder")
|
| 610 |
|
| 611 |
with gr.Column(scale=1):
|
| 612 |
-
gr.Markdown("###
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
placeholder='{"pattern_ligne": "...", "group_nom": 1, ...}',
|
| 620 |
-
lines=3,
|
| 621 |
-
)
|
| 622 |
-
|
| 623 |
-
with gr.Row():
|
| 624 |
-
with gr.Column():
|
| 625 |
-
gr.Markdown("### 🗂️ Analyse des sous-familles")
|
| 626 |
-
gr.Markdown(
|
| 627 |
-
"Classe chaque article dans sa famille EBP "
|
| 628 |
-
"(TAPISSERIE · RIDEAU · MOUSSE · SELLERIE) et produit "
|
| 629 |
-
"**1 fichier CSV par famille** au format écran « Articles » EBP."
|
| 630 |
-
)
|
| 631 |
-
analyse_familles_toggle = gr.Checkbox(
|
| 632 |
-
label="Activer l'analyse des sous-familles (export par famille)",
|
| 633 |
-
value=True,
|
| 634 |
-
)
|
| 635 |
-
classif_llm_toggle = gr.Checkbox(
|
| 636 |
-
label="Affiner les cas ambigus avec Claude (sinon règles seules)",
|
| 637 |
-
value=True,
|
| 638 |
-
)
|
| 639 |
|
| 640 |
with gr.Row():
|
| 641 |
-
|
| 642 |
-
btn_convert = gr.Button("▶️ Convertir directement (sans aperçu)", variant="primary", size="lg")
|
| 643 |
|
| 644 |
-
|
| 645 |
-
gr.
|
| 646 |
-
preview_info = gr.Textbox(label="Aperçu", interactive=False, lines=2)
|
| 647 |
-
preview_table = gr.Dataframe(
|
| 648 |
headers=COLS_ARTICLES_EBP,
|
| 649 |
datatype=["str"] * len(COLS_ARTICLES_EBP),
|
| 650 |
col_count=(len(COLS_ARTICLES_EBP), "fixed"),
|
| 651 |
type="pandas",
|
| 652 |
interactive=True,
|
| 653 |
-
# « Code article » (clé d'appariement)
|
| 654 |
-
static_columns=[0],
|
| 655 |
wrap=True,
|
| 656 |
visible=False,
|
| 657 |
label="Échantillon — colonnes éditables, sauf « Code article »",
|
| 658 |
)
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
preview_state = gr.State()
|
| 662 |
|
| 663 |
with gr.Row():
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
anomalies_output = gr.Textbox(label="⚠️ Anomalies (prix non traçables)", lines=6, interactive=False)
|
| 668 |
-
err_output = gr.Textbox(label="Erreur", visible=False)
|
| 669 |
-
|
| 670 |
-
_convert_inputs = [
|
| 671 |
-
pdf_input, page_from, page_to,
|
| 672 |
-
fournisseur_nom, fournisseur_code,
|
| 673 |
-
code_famille, remise_input, prix_ttc_toggle,
|
| 674 |
-
taux_tva, unite_def,
|
| 675 |
-
sample_mode, profil_save_nom,
|
| 676 |
-
collection_famille_map_input, regex_config_input,
|
| 677 |
-
analyse_familles_toggle, classif_llm_toggle,
|
| 678 |
-
]
|
| 679 |
|
| 680 |
-
# ── Événements ──────────────────────────────────────────────────────────
|
| 681 |
btn_clean.click(
|
| 682 |
fn=run_clean,
|
| 683 |
inputs=[clean_input, opt_drop_empty, opt_drop_dup, opt_trim, opt_headers,
|
|
@@ -685,40 +392,26 @@ with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
|
| 685 |
outputs=[clean_file_out, clean_report_out],
|
| 686 |
)
|
| 687 |
|
| 688 |
-
|
| 689 |
-
fn=
|
| 690 |
-
inputs=[
|
| 691 |
-
outputs=[
|
| 692 |
-
).then(fn=lambda: gr.update(visible=True), outputs=[debug_output])
|
| 693 |
-
|
| 694 |
-
btn_preview.click(
|
| 695 |
-
fn=run_preview,
|
| 696 |
-
inputs=_convert_inputs,
|
| 697 |
-
outputs=[preview_state, preview_table, preview_info, anomalies_output],
|
| 698 |
-
)
|
| 699 |
-
|
| 700 |
-
btn_export.click(
|
| 701 |
-
fn=run_export_from_preview,
|
| 702 |
-
inputs=[preview_state, preview_table],
|
| 703 |
-
outputs=[zip_output, rapport_output, anomalies_output],
|
| 704 |
)
|
| 705 |
|
| 706 |
-
|
| 707 |
-
fn=
|
| 708 |
-
inputs=
|
| 709 |
-
|
|
|
|
|
|
|
| 710 |
)
|
| 711 |
|
| 712 |
-
|
| 713 |
-
fn=
|
| 714 |
-
inputs=[
|
| 715 |
-
outputs=[
|
| 716 |
-
remise_input, prix_ttc_toggle, taux_tva, unite_def,
|
| 717 |
-
collection_famille_map_input, regex_config_input],
|
| 718 |
)
|
| 719 |
|
| 720 |
-
btn_refresh.click(fn=refresh_profiles, outputs=[profil_dropdown])
|
| 721 |
-
|
| 722 |
|
| 723 |
if __name__ == "__main__":
|
| 724 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
"""
|
| 2 |
+
Interface Gradio — Atelier EBP, page unique à deux onglets :
|
| 3 |
+
- 🧹 Nettoyeur CSV (core.cleaner — 100 % local, sans IA)
|
| 4 |
+
- 📄 CSV → CSV EBP (mapping colonnes + analyse sous-familles + export par famille)
|
| 5 |
+
|
| 6 |
+
L'entrée est toujours un CSV (le PDF a été abandonné).
|
| 7 |
+
Lancer en local : python app_gradio.py
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
|
|
|
|
|
|
| 11 |
import os
|
|
|
|
| 12 |
import tempfile
|
| 13 |
import traceback
|
| 14 |
import zipfile
|
|
|
|
| 15 |
from pathlib import Path
|
| 16 |
|
| 17 |
import gradio as gr
|
| 18 |
from dotenv import load_dotenv
|
| 19 |
|
| 20 |
+
from core.cleaner import clean_csv
|
| 21 |
+
from core.csv_import import (
|
| 22 |
+
read_csv_df, guess_col, csv_to_articles, GUESS, NONE_COL,
|
| 23 |
+
)
|
| 24 |
from core.csv_writer import (
|
| 25 |
+
export_articles_par_famille, COLS_ARTICLES_EBP, _build_article_ebp_row,
|
|
|
|
| 26 |
)
|
|
|
|
|
|
|
|
|
|
| 27 |
from core.subfamily import analyse_sous_familles
|
| 28 |
|
| 29 |
load_dotenv()
|
|
|
|
| 31 |
|
| 32 |
# ── Constantes ────────────────────────────────────────────────────────────────
|
| 33 |
|
| 34 |
+
TVA_CHOICES = [("20 %", 20.0), ("10 %", 10.0), ("5,5 %", 5.5)]
|
| 35 |
+
PREVIEW_N = 10 # nombre de références montrées dans l'aperçu éditable
|
| 36 |
|
| 37 |
|
| 38 |
+
def _resolve_tva(label: str) -> float:
|
| 39 |
+
for lab, val in TVA_CHOICES:
|
| 40 |
+
if lab == label:
|
| 41 |
+
return val
|
| 42 |
+
return 20.0
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 46 |
+
# ONGLET 1 — Nettoyeur CSV
|
| 47 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 48 |
|
| 49 |
+
def _format_clean_report(report: dict) -> str:
|
| 50 |
+
lines = [
|
| 51 |
+
"═══ RAPPORT DE NETTOYAGE ═══",
|
| 52 |
+
f"Encodage détecté : {report.get('encodage_detecte')}",
|
| 53 |
+
f"Séparateur détecté : {report.get('separateur_detecte')}",
|
| 54 |
+
f"Lignes : {report.get('lignes_initiales')} → {report.get('lignes_finales')}",
|
| 55 |
+
f"Colonnes : {report.get('colonnes_initiales')} → {report.get('colonnes_finales')}",
|
| 56 |
+
f"Sortie : séparateur '{report.get('separateur_sortie')}' / {report.get('encodage_sortie')}",
|
| 57 |
+
"",
|
| 58 |
+
"Actions :",
|
| 59 |
+
]
|
| 60 |
+
for a in report.get("actions", []):
|
| 61 |
+
lines.append(f" • {a}")
|
| 62 |
+
return "\n".join(lines)
|
|
|
|
|
|
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
def run_clean(csv_file, drop_empty, drop_duplicates, trim_whitespace,
|
| 66 |
+
normalize_headers, remove_symbols, keep_digits_only,
|
| 67 |
+
decimal_comma, ebp_format):
|
| 68 |
+
if csv_file is None:
|
| 69 |
+
return None, "⚠️ Aucun fichier CSV fourni."
|
| 70 |
+
try:
|
| 71 |
+
raw = Path(csv_file.name).read_bytes()
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
return None, f"❌ Lecture impossible : {exc}"
|
| 74 |
+
if not raw.strip():
|
| 75 |
+
return None, "⚠️ Le fichier est vide."
|
| 76 |
|
| 77 |
+
options = {
|
| 78 |
+
"drop_empty": drop_empty, "drop_duplicates": drop_duplicates,
|
| 79 |
+
"trim_whitespace": trim_whitespace, "normalize_headers": normalize_headers,
|
| 80 |
+
"remove_symbols": remove_symbols, "keep_digits_only": keep_digits_only,
|
| 81 |
+
"decimal_comma": decimal_comma, "ebp_format": ebp_format,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
}
|
| 83 |
+
try:
|
| 84 |
+
cleaned, report = clean_csv(raw, options)
|
| 85 |
+
except Exception as exc:
|
| 86 |
+
tb = traceback.format_exc()
|
| 87 |
+
return None, f"❌ Erreur : {exc}\n\n{tb[-500:]}"
|
| 88 |
|
| 89 |
+
base = Path(csv_file.name).stem or "fichier"
|
| 90 |
+
out_dir = tempfile.mkdtemp(prefix="csv_clean_")
|
| 91 |
+
out_path = os.path.join(out_dir, f"{base}_nettoye.csv")
|
| 92 |
+
Path(out_path).write_bytes(cleaned)
|
| 93 |
+
return out_path, _format_clean_report(report)
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 97 |
+
# ONGLET 2 — CSV → CSV EBP (mapping + sous-familles)
|
| 98 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 99 |
|
| 100 |
+
def on_csv_uploaded(csv_file):
|
| 101 |
+
"""À l'upload : lit les colonnes réelles et pré-remplit les menus de mapping."""
|
| 102 |
+
empty = gr.update(choices=[], value=None)
|
| 103 |
+
empty_opt = gr.update(choices=[NONE_COL], value=NONE_COL)
|
| 104 |
+
if csv_file is None:
|
| 105 |
+
return empty, empty, empty_opt, empty_opt, ""
|
| 106 |
+
try:
|
| 107 |
+
df = read_csv_df(csv_file.name)
|
| 108 |
+
except Exception as exc:
|
| 109 |
+
return empty, empty, empty_opt, empty_opt, f"❌ Lecture impossible : {exc}"
|
| 110 |
|
| 111 |
+
cols = [str(c) for c in df.columns]
|
| 112 |
+
ref = guess_col(cols, GUESS["reference"])
|
| 113 |
+
lib = guess_col(cols, GUESS["libelle"])
|
| 114 |
+
prix = guess_col(cols, GUESS["prix"])
|
| 115 |
+
unite = guess_col(cols, GUESS["unite"])
|
| 116 |
|
| 117 |
+
req = lambda v: gr.update(choices=cols, value=v or (cols[0] if cols else None))
|
| 118 |
+
opt = lambda v: gr.update(choices=[NONE_COL] + cols, value=v or NONE_COL)
|
| 119 |
+
info = f"{len(df)} ligne(s), {len(cols)} colonne(s) : {', '.join(cols[:8])}{'…' if len(cols) > 8 else ''}"
|
| 120 |
+
return req(ref), req(lib), opt(prix), opt(unite), info
|
| 121 |
|
| 122 |
|
| 123 |
+
# ── Aperçu éditable ───────────────────────────────────────────────────────────
|
| 124 |
|
| 125 |
+
def _articles_to_preview(articles, params, n) -> list[list[str]]:
|
|
|
|
| 126 |
rows = []
|
| 127 |
for a in articles[:n]:
|
| 128 |
r = _build_article_ebp_row(
|
| 129 |
+
a, params["fournisseur_code"], params["remise"],
|
| 130 |
"TVA20", params["taux_tva"], params["prix_sont_ttc"],
|
| 131 |
)
|
| 132 |
rows.append([r[c] for c in COLS_ARTICLES_EBP])
|
| 133 |
return rows
|
| 134 |
|
| 135 |
|
| 136 |
+
def _apply_preview_edits(articles, edited_rows):
|
| 137 |
"""
|
| 138 |
Réinjecte les corrections de l'aperçu (libellé, prix HT, unité, famille)
|
| 139 |
+
par appariement sur le « Code article ». Code article reste verrouillé.
|
|
|
|
| 140 |
"""
|
| 141 |
if edited_rows is None:
|
| 142 |
return articles
|
| 143 |
rows = edited_rows.values.tolist() if hasattr(edited_rows, "values") else list(edited_rows)
|
|
|
|
| 144 |
idx = {c: i for i, c in enumerate(COLS_ARTICLES_EBP)}
|
| 145 |
by_ref: dict[str, dict] = {}
|
| 146 |
for a in articles:
|
| 147 |
+
ref = str(a.get("reference") or "").strip()
|
| 148 |
if ref and ref not in by_ref:
|
| 149 |
by_ref[ref] = a
|
|
|
|
| 150 |
for row in rows:
|
| 151 |
if not row or len(row) < len(COLS_ARTICLES_EBP):
|
| 152 |
continue
|
|
|
|
| 166 |
return articles
|
| 167 |
|
| 168 |
|
| 169 |
+
# ── Export ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
def _build_rapport(valides, rapport_familles, params) -> str:
|
|
|
|
|
|
|
| 172 |
lines = [
|
| 173 |
+
"═══ RAPPORT CSV → EBP ═══",
|
| 174 |
+
f"Articles : {len(valides)}",
|
| 175 |
+
f"Fournisseur : {params['fournisseur_code']}",
|
| 176 |
+
f"Remise : {params['remise']} %",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
]
|
|
|
|
|
|
|
| 178 |
if rapport_familles:
|
| 179 |
lines += [
|
| 180 |
"",
|
|
|
|
| 187 |
]
|
| 188 |
for fam, n in rapport_familles["repartition"].items():
|
| 189 |
lines.append(f" • articles_{fam}.csv : {n} article(s)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
return "\n".join(lines)
|
| 191 |
|
| 192 |
|
| 193 |
+
def _do_csv_export(valides, rapport_familles, params) -> tuple[str, str]:
|
| 194 |
+
out_dir = tempfile.mkdtemp(prefix="ebp_csv_")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
export_articles_par_famille(
|
| 197 |
+
articles=valides,
|
| 198 |
+
output_dir=out_dir,
|
| 199 |
+
fournisseur_code=params["fournisseur_code"],
|
| 200 |
+
remise=params["remise"],
|
| 201 |
+
taux_tva=params["taux_tva"],
|
| 202 |
+
prix_sont_ttc=params["prix_sont_ttc"],
|
| 203 |
+
)
|
| 204 |
|
| 205 |
+
# Fichier familles articles (codes distincts) — format écran EBP « Familles Articles »
|
| 206 |
+
familles = sorted({a.get("code_sous_famille", "DIVERS") for a in valides})
|
| 207 |
+
fam_path = os.path.join(out_dir, "0_familles_articles.csv")
|
| 208 |
+
with open(fam_path, "w", newline="", encoding="utf-8-sig") as f:
|
| 209 |
+
f.write("Code Famille Articles;Famille Articles\r\n")
|
| 210 |
+
for fam in familles:
|
| 211 |
+
f.write(f"{fam};{fam}\r\n")
|
| 212 |
|
| 213 |
+
rapport_txt = _build_rapport(valides, rapport_familles, params)
|
| 214 |
+
rapport_path = os.path.join(out_dir, "rapport.txt")
|
| 215 |
+
Path(rapport_path).write_text(rapport_txt, encoding="utf-8")
|
| 216 |
|
| 217 |
+
zip_path = os.path.join(out_dir, "export_ebp.zip")
|
| 218 |
+
with zipfile.ZipFile(zip_path, "w") as zf:
|
| 219 |
+
for fp in Path(out_dir).glob("*.csv"):
|
| 220 |
+
zf.write(fp, fp.name)
|
| 221 |
+
zf.write(rapport_path, "rapport.txt")
|
| 222 |
+
return zip_path, rapport_txt
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
+
# ── Callbacks principaux ──────────────────────────────────────────────────────
|
| 226 |
|
| 227 |
+
def run_csv_preview(csv_file, ref_col, lib_col, prix_col, unite_col,
|
| 228 |
+
fournisseur_code, remise, taux_tva_label, prix_sont_ttc,
|
| 229 |
+
analyse_familles, classif_llm, progress=gr.Progress()):
|
| 230 |
if csv_file is None:
|
| 231 |
+
return None, gr.update(visible=False), "⚠️ Aucun fichier CSV fourni."
|
| 232 |
+
if not ref_col or not lib_col:
|
| 233 |
+
return None, gr.update(visible=False), "⚠️ Choisis au moins les colonnes Référence et Libellé."
|
| 234 |
+
|
| 235 |
+
fournisseur_code = (fournisseur_code or "").strip().upper() or "FOUR001"
|
| 236 |
+
params = {
|
| 237 |
+
"fournisseur_code": fournisseur_code,
|
| 238 |
+
"remise": float(remise),
|
| 239 |
+
"taux_tva": _resolve_tva(taux_tva_label),
|
| 240 |
+
"prix_sont_ttc": bool(prix_sont_ttc),
|
| 241 |
+
"analyse_familles": bool(analyse_familles),
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
try:
|
| 245 |
+
progress(0.2, desc="Lecture du CSV…")
|
| 246 |
+
df = read_csv_df(csv_file.name)
|
| 247 |
+
articles = csv_to_articles(df, ref_col, lib_col, prix_col, unite_col)
|
| 248 |
+
if not articles:
|
| 249 |
+
return None, gr.update(visible=False), "⚠️ Aucune ligne exploitable dans ce CSV."
|
| 250 |
+
|
| 251 |
+
rapport_familles = None
|
| 252 |
+
if analyse_familles:
|
| 253 |
+
progress(0.5, desc="Analyse des sous-familles…")
|
| 254 |
+
client = None
|
| 255 |
+
if classif_llm:
|
| 256 |
+
import anthropic
|
| 257 |
+
try:
|
| 258 |
+
client = anthropic.Anthropic()
|
| 259 |
+
except Exception:
|
| 260 |
+
client = None
|
| 261 |
+
articles, rapport_familles = analyse_sous_familles(
|
| 262 |
+
articles, use_llm=classif_llm and client is not None, client=client,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
preview_rows = _articles_to_preview(articles, params, PREVIEW_N)
|
| 266 |
+
state = {"valides": articles, "rapport_familles": rapport_familles, "params": params}
|
| 267 |
+
info = (f"Aperçu de {min(PREVIEW_N, len(articles))} réf. sur {len(articles)}. "
|
| 268 |
+
"Corrige le tableau (famille, libellé, prix HT, unité) puis « Exporter ». "
|
| 269 |
+
"L'unité de chaque ligne est laissée telle quelle.")
|
| 270 |
+
progress(1.0, desc="Aperçu prêt")
|
| 271 |
+
return state, gr.update(value=preview_rows, visible=True), info
|
| 272 |
except Exception as exc:
|
| 273 |
+
tb = traceback.format_exc()
|
| 274 |
+
return None, gr.update(visible=False), f"❌ Erreur : {exc}\n\n{tb[-600:]}"
|
|
|
|
| 275 |
|
| 276 |
+
|
| 277 |
+
def run_csv_export(state, edited_rows, progress=gr.Progress()):
|
| 278 |
+
if not state:
|
| 279 |
+
return None, "⚠️ Lance d'abord « Analyser & aperçu »."
|
|
|
|
|
|
|
| 280 |
try:
|
| 281 |
+
progress(0.3, desc="Application des corrections…")
|
| 282 |
+
valides = _apply_preview_edits(state["valides"], edited_rows)
|
| 283 |
+
params = state["params"]
|
| 284 |
+
|
| 285 |
+
rapport_familles = state.get("rapport_familles")
|
| 286 |
+
if params["analyse_familles"]:
|
| 287 |
+
repart: dict[str, int] = {}
|
| 288 |
+
for a in valides:
|
| 289 |
+
fam = a.get("code_sous_famille", "DIVERS")
|
| 290 |
+
repart[fam] = repart.get(fam, 0) + 1
|
| 291 |
+
if rapport_familles:
|
| 292 |
+
rapport_familles = dict(rapport_familles)
|
| 293 |
+
rapport_familles["repartition"] = dict(sorted(repart.items(), key=lambda kv: -kv[1]))
|
| 294 |
+
|
| 295 |
+
progress(0.6, desc="Écriture des CSV par famille…")
|
| 296 |
+
zip_path, rapport_txt = _do_csv_export(valides, rapport_familles, params)
|
| 297 |
+
progress(1.0, desc="Terminé !")
|
| 298 |
+
return zip_path, rapport_txt
|
| 299 |
except Exception as exc:
|
| 300 |
tb = traceback.format_exc()
|
| 301 |
+
return None, f"❌ Erreur : {exc}\n\n{tb[-600:]}"
|
| 302 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 305 |
+
# Interface
|
| 306 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 307 |
|
| 308 |
with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
| 309 |
+
gr.Markdown("# 🧰 Atelier — Outils CSV pour EBP Gestion Commerciale")
|
| 310 |
|
| 311 |
with gr.Tabs():
|
| 312 |
|
|
|
|
| 336 |
clean_report_out = gr.Textbox(label="📊 Rapport de nettoyage",
|
| 337 |
lines=16, interactive=False)
|
| 338 |
|
| 339 |
+
# ══════════ ONGLET 2 : CSV → CSV EBP ══════════
|
| 340 |
+
with gr.Tab("📄 CSV → CSV EBP (sous-familles)"):
|
| 341 |
gr.Markdown(
|
| 342 |
+
"Charge un CSV fournisseur, **mappe ses colonnes**, et obtiens un export EBP "
|
| 343 |
+
"**1 fichier CSV par famille** (TAPISSERIE · RIDEAU · MOUSSE · SELLERIE). "
|
| 344 |
+
"Les unités sont reprises telles quelles, ligne par ligne."
|
| 345 |
)
|
|
|
|
| 346 |
with gr.Row():
|
| 347 |
with gr.Column(scale=2):
|
| 348 |
+
csv_in = gr.File(label="CSV fournisseur", file_types=[".csv", ".tsv", ".txt"])
|
| 349 |
+
map_info = gr.Textbox(label="Colonnes détectées", interactive=False, lines=1)
|
| 350 |
+
gr.Markdown("**Mapping des colonnes** (rempli automatiquement, ajuste si besoin)")
|
| 351 |
+
col_ref = gr.Dropdown(label="Colonne Référence (Code article) *", choices=[])
|
| 352 |
+
col_lib = gr.Dropdown(label="Colonne Libellé (sert à classer la famille) *", choices=[])
|
| 353 |
+
col_prix = gr.Dropdown(label="Colonne Prix HT conseillé", choices=[NONE_COL], value=NONE_COL)
|
| 354 |
+
col_unite = gr.Dropdown(label="Colonne Unité (laissée telle quelle)", choices=[NONE_COL], value=NONE_COL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
with gr.Column(scale=1):
|
| 357 |
+
gr.Markdown("### 🏭 Paramètres EBP")
|
| 358 |
+
csv_fourn_code = gr.Textbox(label="Code fournisseur", placeholder="Ex : CAS001")
|
| 359 |
+
csv_remise = gr.Slider(0, 80, value=45, step=1, label="Remise fournisseur (%)")
|
| 360 |
+
csv_prix_ttc = gr.Checkbox(label="Les prix du CSV sont TTC", value=False)
|
| 361 |
+
csv_taux_tva = gr.Radio([l for l, _ in TVA_CHOICES], value="20 %", label="Taux TVA")
|
| 362 |
+
csv_analyse = gr.Checkbox(label="Analyse des sous-familles (export par famille)", value=True)
|
| 363 |
+
csv_classif = gr.Checkbox(label="Affiner les cas ambigus avec Claude", value=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
|
| 365 |
with gr.Row():
|
| 366 |
+
btn_csv_preview = gr.Button("👁️ Analyser & aperçu (10 réf.)", variant="secondary", size="lg")
|
|
|
|
| 367 |
|
| 368 |
+
csv_preview_info = gr.Textbox(label="Aperçu", interactive=False, lines=2)
|
| 369 |
+
csv_preview_table = gr.Dataframe(
|
|
|
|
|
|
|
| 370 |
headers=COLS_ARTICLES_EBP,
|
| 371 |
datatype=["str"] * len(COLS_ARTICLES_EBP),
|
| 372 |
col_count=(len(COLS_ARTICLES_EBP), "fixed"),
|
| 373 |
type="pandas",
|
| 374 |
interactive=True,
|
| 375 |
+
static_columns=[0], # « Code article » verrouillé (clé d'appariement)
|
|
|
|
| 376 |
wrap=True,
|
| 377 |
visible=False,
|
| 378 |
label="Échantillon — colonnes éditables, sauf « Code article »",
|
| 379 |
)
|
| 380 |
+
btn_csv_export = gr.Button("📦 Exporter par famille", variant="primary", size="lg")
|
| 381 |
+
csv_state = gr.State()
|
|
|
|
| 382 |
|
| 383 |
with gr.Row():
|
| 384 |
+
csv_zip = gr.File(label="📦 Télécharger les CSV EBP (ZIP)")
|
| 385 |
+
csv_report = gr.Textbox(label="📊 Rapport", lines=16, interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
+
# ── Événements ────────────────────────────────────────────────────────────
|
| 388 |
btn_clean.click(
|
| 389 |
fn=run_clean,
|
| 390 |
inputs=[clean_input, opt_drop_empty, opt_drop_dup, opt_trim, opt_headers,
|
|
|
|
| 392 |
outputs=[clean_file_out, clean_report_out],
|
| 393 |
)
|
| 394 |
|
| 395 |
+
csv_in.change(
|
| 396 |
+
fn=on_csv_uploaded,
|
| 397 |
+
inputs=[csv_in],
|
| 398 |
+
outputs=[col_ref, col_lib, col_prix, col_unite, map_info],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
)
|
| 400 |
|
| 401 |
+
btn_csv_preview.click(
|
| 402 |
+
fn=run_csv_preview,
|
| 403 |
+
inputs=[csv_in, col_ref, col_lib, col_prix, col_unite,
|
| 404 |
+
csv_fourn_code, csv_remise, csv_taux_tva, csv_prix_ttc,
|
| 405 |
+
csv_analyse, csv_classif],
|
| 406 |
+
outputs=[csv_state, csv_preview_table, csv_preview_info],
|
| 407 |
)
|
| 408 |
|
| 409 |
+
btn_csv_export.click(
|
| 410 |
+
fn=run_csv_export,
|
| 411 |
+
inputs=[csv_state, csv_preview_table],
|
| 412 |
+
outputs=[csv_zip, csv_report],
|
|
|
|
|
|
|
| 413 |
)
|
| 414 |
|
|
|
|
|
|
|
| 415 |
|
| 416 |
if __name__ == "__main__":
|
| 417 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
@@ -1,307 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Extraction et structuration des articles via Claude.
|
| 3 |
-
Anti-hallucination : le LLM structure uniquement, ne calcule jamais de prix.
|
| 4 |
-
Chaque prix structuré est validé contre les tokens prix du texte source.
|
| 5 |
-
"""
|
| 6 |
-
from __future__ import annotations
|
| 7 |
-
|
| 8 |
-
import base64
|
| 9 |
-
import json
|
| 10 |
-
import re
|
| 11 |
-
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
|
| 12 |
-
from typing import Callable
|
| 13 |
-
|
| 14 |
-
import anthropic
|
| 15 |
-
|
| 16 |
-
from core.extractor import (
|
| 17 |
-
extract_raw_lines, extract_lines_or_tables,
|
| 18 |
-
extract_tables, has_tables, PRICE_RE,
|
| 19 |
-
)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
_SYSTEM_TEXT = """\
|
| 23 |
-
Tu es un extracteur de données de catalogue textile/décoration.
|
| 24 |
-
À partir des lignes brutes fournies, identifie chaque article et retourne UNIQUEMENT un tableau JSON valide.
|
| 25 |
-
Chaque objet a exactement ces champs :
|
| 26 |
-
- "nom_dessin" : string — nom du dessin + coloris complet (ex: "Adagio Bleu nuit"), 80 chars max
|
| 27 |
-
- "reference" : string — référence complète incluant suffixe coloris si présent (ex: "4172-01")
|
| 28 |
-
- "collection" : string — nom de la collection ou gamme (vide si absent)
|
| 29 |
-
- "prix_brut" : string — le prix conseillé HT EXACTEMENT tel qu'il apparaît dans le texte \
|
| 30 |
-
(ex: "70,92" ou "83,25") — JAMAIS un chiffre inventé, calculé ou interpolé
|
| 31 |
-
- "unite" : string — unité de vente telle qu'écrite (ml, M, U, m², etc.)
|
| 32 |
-
|
| 33 |
-
RÈGLES ABSOLUES :
|
| 34 |
-
- Si un dessin a plusieurs coloris, génère UN objet JSON par coloris avec sa référence propre.
|
| 35 |
-
- Si tu ne vois pas de prix dans le texte, mets "prix_brut": "".
|
| 36 |
-
- Ne jamais inventer, estimer, recalculer ou interpoler un prix.
|
| 37 |
-
- Ne pas confondre prix d'achat et prix conseillé : extrais TOUJOURS le prix public conseillé.
|
| 38 |
-
- Ne retourne aucun texte, commentaire ou balise avant ou après le tableau JSON.\
|
| 39 |
-
"""
|
| 40 |
-
|
| 41 |
-
_SYSTEM_VISION = """\
|
| 42 |
-
Tu es un extracteur de données de catalogue textile/décoration.
|
| 43 |
-
À partir des images de pages fournies, identifie chaque article et retourne UNIQUEMENT un tableau JSON valide.
|
| 44 |
-
Chaque objet a exactement ces champs :
|
| 45 |
-
- "nom_dessin" : string — nom du dessin + coloris complet (ex: "Adagio Bleu nuit"), 80 chars max
|
| 46 |
-
- "reference" : string — référence complète incluant suffixe coloris si présent (ex: "4172-01")
|
| 47 |
-
- "collection" : string — nom de la collection ou gamme (vide si absent)
|
| 48 |
-
- "prix_brut" : string — le prix conseillé HT EXACTEMENT tel qu'il est affiché dans l'image \
|
| 49 |
-
(ex: "70,92" ou "83,25") — JAMAIS un chiffre inventé, calculé ou interpolé
|
| 50 |
-
- "unite" : string — unité de vente telle qu'écrite (ml, M, U, m², etc.)
|
| 51 |
-
|
| 52 |
-
RÈGLES ABSOLUES :
|
| 53 |
-
- Si un dessin a plusieurs coloris, génère UN objet JSON par coloris avec sa référence propre.
|
| 54 |
-
- Si le prix n'est pas lisible ou absent, mets "prix_brut": "".
|
| 55 |
-
- Ne jamais inventer, estimer, recalculer ou interpoler un prix.
|
| 56 |
-
- Ne pas confondre prix d'achat et prix conseillé : extrais TOUJOURS le prix public conseillé.
|
| 57 |
-
- Ne retourne aucun texte, commentaire ou balise avant ou après le tableau JSON.\
|
| 58 |
-
"""
|
| 59 |
-
|
| 60 |
-
_BATCH_SIZE = 3
|
| 61 |
-
_BATCH_TIMEOUT = 120
|
| 62 |
-
_DPI = 150
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
# ── Parsing LLM ───────────────────────────────────────────────────────────────
|
| 66 |
-
|
| 67 |
-
def _parse_json_safe(raw: str) -> list[dict]:
|
| 68 |
-
raw = raw.strip()
|
| 69 |
-
if raw.startswith("```"):
|
| 70 |
-
raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
|
| 71 |
-
try:
|
| 72 |
-
return json.loads(raw)
|
| 73 |
-
except json.JSONDecodeError:
|
| 74 |
-
results = []
|
| 75 |
-
for obj in re.findall(r'\{[^{}]*\}', raw):
|
| 76 |
-
try:
|
| 77 |
-
results.append(json.loads(obj))
|
| 78 |
-
except json.JSONDecodeError:
|
| 79 |
-
continue
|
| 80 |
-
return results
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
# ── Validation déterministe des prix ─────────────────────────────────────────
|
| 84 |
-
|
| 85 |
-
def _normalize_price(prix_brut: str) -> str:
|
| 86 |
-
"""Normalise un prix brut pour comparaison : remplace point par virgule."""
|
| 87 |
-
return str(prix_brut or "").strip().replace(".", ",")
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def validate_prices(
|
| 91 |
-
articles: list[dict],
|
| 92 |
-
prix_source_tokens: list[str],
|
| 93 |
-
) -> tuple[list[dict], list[dict]]:
|
| 94 |
-
"""
|
| 95 |
-
Sépare les articles en deux listes : valides et anomalies.
|
| 96 |
-
Un prix est valide s'il correspond exactement à un token prix trouvé dans le texte source.
|
| 97 |
-
Un article sans prix (prix_brut="") est accepté directement (prix vide = OK).
|
| 98 |
-
"""
|
| 99 |
-
valides: list[dict] = []
|
| 100 |
-
anomalies: list[dict] = []
|
| 101 |
-
|
| 102 |
-
source_set = set(prix_source_tokens)
|
| 103 |
-
|
| 104 |
-
for a in articles:
|
| 105 |
-
prix_brut = _normalize_price(a.get("prix_brut", ""))
|
| 106 |
-
if not prix_brut:
|
| 107 |
-
# Prix absent dans la source → accepté avec prix_conseille = 0
|
| 108 |
-
a["prix_conseille"] = 0.0
|
| 109 |
-
a["prix_valide"] = True
|
| 110 |
-
valides.append(a)
|
| 111 |
-
elif prix_brut in source_set:
|
| 112 |
-
a["prix_conseille"] = float(prix_brut.replace(",", "."))
|
| 113 |
-
a["prix_valide"] = True
|
| 114 |
-
valides.append(a)
|
| 115 |
-
else:
|
| 116 |
-
a["prix_conseille"] = 0.0
|
| 117 |
-
a["prix_valide"] = False
|
| 118 |
-
a["anomalie_raison"] = f"prix_brut '{prix_brut}' non trouvé dans le texte source"
|
| 119 |
-
anomalies.append(a)
|
| 120 |
-
|
| 121 |
-
return valides, anomalies
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# ── Multi-coloris ────────────────────────────────────────────────────────────
|
| 125 |
-
|
| 126 |
-
def expand_coloris(articles: list[dict]) -> list[dict]:
|
| 127 |
-
"""
|
| 128 |
-
Si la même référence de base apparaît plusieurs fois avec des noms différents
|
| 129 |
-
(coloris multiples non suffixés), génère des références uniques en -01, -02…
|
| 130 |
-
Ne touche pas aux références déjà suffixées (ex: "4172-01").
|
| 131 |
-
"""
|
| 132 |
-
from collections import defaultdict
|
| 133 |
-
groups: dict[str, list[int]] = defaultdict(list)
|
| 134 |
-
for i, a in enumerate(articles):
|
| 135 |
-
ref = a.get("reference", "")
|
| 136 |
-
if ref:
|
| 137 |
-
groups[ref].append(i)
|
| 138 |
-
|
| 139 |
-
result = list(articles)
|
| 140 |
-
for ref, indices in groups.items():
|
| 141 |
-
if len(indices) <= 1:
|
| 142 |
-
continue
|
| 143 |
-
noms = [articles[i].get("nom_dessin", "") for i in indices]
|
| 144 |
-
if len(set(noms)) <= 1:
|
| 145 |
-
continue # même nom → vraie anomalie doublon, pas multi-coloris
|
| 146 |
-
for j, idx in enumerate(indices, 1):
|
| 147 |
-
a = dict(result[idx])
|
| 148 |
-
a["reference"] = f"{ref}-{j:02d}"
|
| 149 |
-
result[idx] = a
|
| 150 |
-
return result
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# ── Appels Claude ─────────────────────────────────────────────────────────────
|
| 154 |
-
|
| 155 |
-
def _call_claude_text(
|
| 156 |
-
client: anthropic.Anthropic,
|
| 157 |
-
lines: list[str],
|
| 158 |
-
default_unit: str,
|
| 159 |
-
) -> list[dict]:
|
| 160 |
-
text_block = "\n".join(lines)
|
| 161 |
-
message = client.messages.create(
|
| 162 |
-
model="claude-sonnet-4-6",
|
| 163 |
-
max_tokens=16000,
|
| 164 |
-
system=_SYSTEM_TEXT,
|
| 165 |
-
messages=[{
|
| 166 |
-
"role": "user",
|
| 167 |
-
"content": (
|
| 168 |
-
f"Unité par défaut si non précisée : {default_unit}\n\n"
|
| 169 |
-
f"Lignes brutes du catalogue :\n{text_block}"
|
| 170 |
-
),
|
| 171 |
-
}],
|
| 172 |
-
)
|
| 173 |
-
return _parse_json_safe(message.content[0].text)
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
def _normalise_article(a: dict) -> dict:
|
| 177 |
-
"""
|
| 178 |
-
Normalise les clés renvoyées par le LLM vers les clés internes attendues.
|
| 179 |
-
Gère les variations de nommage (libelle/nom_dessin, code/reference, etc.).
|
| 180 |
-
"""
|
| 181 |
-
# Alias tolerants
|
| 182 |
-
if "libelle" in a and "nom_dessin" not in a:
|
| 183 |
-
a["nom_dessin"] = a.pop("libelle")
|
| 184 |
-
if "code" in a and "reference" not in a:
|
| 185 |
-
a["reference"] = a.pop("code")
|
| 186 |
-
if "famille_suggeree" in a and "collection" not in a:
|
| 187 |
-
a["collection"] = a.pop("famille_suggeree")
|
| 188 |
-
return a
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
def _page_to_image_b64(page) -> str:
|
| 192 |
-
import fitz
|
| 193 |
-
mat = fitz.Matrix(_DPI / 72, _DPI / 72)
|
| 194 |
-
pix = page.get_pixmap(matrix=mat, alpha=False)
|
| 195 |
-
return base64.standard_b64encode(pix.tobytes("png")).decode()
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
def _call_claude_vision(
|
| 199 |
-
client: anthropic.Anthropic,
|
| 200 |
-
pages,
|
| 201 |
-
default_unit: str,
|
| 202 |
-
) -> list[dict]:
|
| 203 |
-
content = []
|
| 204 |
-
for page in pages:
|
| 205 |
-
b64 = _page_to_image_b64(page)
|
| 206 |
-
content.append({
|
| 207 |
-
"type": "image",
|
| 208 |
-
"source": {"type": "base64", "media_type": "image/png", "data": b64},
|
| 209 |
-
})
|
| 210 |
-
content.append({
|
| 211 |
-
"type": "text",
|
| 212 |
-
"text": (
|
| 213 |
-
f"Unité par défaut : {default_unit}\n"
|
| 214 |
-
"Extrais tous les produits de ces pages."
|
| 215 |
-
),
|
| 216 |
-
})
|
| 217 |
-
message = client.messages.create(
|
| 218 |
-
model="claude-sonnet-4-6",
|
| 219 |
-
max_tokens=16000,
|
| 220 |
-
system=_SYSTEM_VISION,
|
| 221 |
-
messages=[{"role": "user", "content": content}],
|
| 222 |
-
)
|
| 223 |
-
return _parse_json_safe(message.content[0].text)
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
# ── Point d'entrée principal ──────────────────────────────────────────────────
|
| 227 |
-
|
| 228 |
-
def extract_articles(
|
| 229 |
-
pdf_path: str,
|
| 230 |
-
page_from: int,
|
| 231 |
-
page_to: int,
|
| 232 |
-
password: str,
|
| 233 |
-
default_unit: str,
|
| 234 |
-
progress_cb: Callable | None = None,
|
| 235 |
-
sample_mode: bool = False,
|
| 236 |
-
sample_lines: int = 30,
|
| 237 |
-
regex_config: dict | None = None,
|
| 238 |
-
) -> tuple[list[dict], list[dict], dict]:
|
| 239 |
-
"""
|
| 240 |
-
Extrait et structure les articles d'un PDF.
|
| 241 |
-
|
| 242 |
-
Retourne (articles_valides, anomalies, rapport).
|
| 243 |
-
rapport = {lues, ecrites, anomalies, taux_couverture, mode}
|
| 244 |
-
|
| 245 |
-
Si regex_config est fourni, délègue à extract_with_regex (sans LLM).
|
| 246 |
-
Sinon : extraction texte/tables + LLM Claude.
|
| 247 |
-
"""
|
| 248 |
-
if regex_config:
|
| 249 |
-
from core.regex_extractor import extract_with_regex
|
| 250 |
-
return extract_with_regex(
|
| 251 |
-
pdf_path, page_from, page_to, password, regex_config, default_unit,
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
# ── Extraction texte source (tables en priorité) ──────────────────────────
|
| 255 |
-
lines, prix_source_tokens, extract_mode = extract_lines_or_tables(
|
| 256 |
-
pdf_path, page_from, page_to, password,
|
| 257 |
-
)
|
| 258 |
-
|
| 259 |
-
if sample_mode:
|
| 260 |
-
lines = lines[:sample_lines]
|
| 261 |
-
|
| 262 |
-
n_lues = len(lines)
|
| 263 |
-
|
| 264 |
-
# ── Structuration LLM ─────────────────────────────────────────────────────
|
| 265 |
-
client = anthropic.Anthropic(timeout=_BATCH_TIMEOUT + 10)
|
| 266 |
-
all_structured: list[dict] = []
|
| 267 |
-
|
| 268 |
-
LINE_BATCH = 200
|
| 269 |
-
batches = [lines[i:i + LINE_BATCH] for i in range(0, len(lines), LINE_BATCH)]
|
| 270 |
-
|
| 271 |
-
with ThreadPoolExecutor(max_workers=1) as pool:
|
| 272 |
-
for i, batch in enumerate(batches):
|
| 273 |
-
future = pool.submit(_call_claude_text, client, batch, default_unit)
|
| 274 |
-
try:
|
| 275 |
-
structured = [_normalise_article(a) for a in future.result(timeout=_BATCH_TIMEOUT)]
|
| 276 |
-
all_structured.extend(structured)
|
| 277 |
-
except FutureTimeout:
|
| 278 |
-
future.cancel()
|
| 279 |
-
except anthropic.APIConnectionError as exc:
|
| 280 |
-
raise RuntimeError(
|
| 281 |
-
"Impossible de joindre l'API Anthropic. "
|
| 282 |
-
"Vérifiez ANTHROPIC_API_KEY."
|
| 283 |
-
) from exc
|
| 284 |
-
except anthropic.AuthenticationError as exc:
|
| 285 |
-
raise RuntimeError("Clé API Anthropic invalide ou expirée.") from exc
|
| 286 |
-
except Exception:
|
| 287 |
-
pass
|
| 288 |
-
|
| 289 |
-
if progress_cb:
|
| 290 |
-
progress_cb(i + 1, len(batches))
|
| 291 |
-
|
| 292 |
-
# ── Expansion coloris ─────────────────────────────────────────────────────
|
| 293 |
-
all_structured = expand_coloris(all_structured)
|
| 294 |
-
|
| 295 |
-
# ── Validation déterministe ───────────────────────────────────────────────
|
| 296 |
-
valides, anomalies = validate_prices(all_structured, prix_source_tokens)
|
| 297 |
-
|
| 298 |
-
rapport = {
|
| 299 |
-
"lignes_lues": n_lues,
|
| 300 |
-
"articles_ecrits": len(valides),
|
| 301 |
-
"anomalies": len(anomalies),
|
| 302 |
-
"taux_couverture_pct": round(len(valides) / max(n_lues, 1) * 100, 1),
|
| 303 |
-
"prix_source_tokens": len(prix_source_tokens),
|
| 304 |
-
"mode": extract_mode,
|
| 305 |
-
}
|
| 306 |
-
|
| 307 |
-
return valides, anomalies, rapport
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lecture d'un CSV fournisseur + mapping de ses colonnes vers les champs article.
|
| 3 |
+
|
| 4 |
+
L'entrée est toujours un CSV (structure variable selon le fournisseur) ; on lit
|
| 5 |
+
les colonnes réelles, on devine un mapping par défaut, et on construit des dicts
|
| 6 |
+
article exploitables par core.subfamily / core.csv_writer.
|
| 7 |
+
|
| 8 |
+
Règle d'or : l'unité de chaque ligne est prise TELLE QUELLE, jamais imposée ni
|
| 9 |
+
uniformisée pour l'ensemble du fichier.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import io
|
| 14 |
+
import re
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
from core.cleaner import detect_delimiter, detect_encoding
|
| 20 |
+
|
| 21 |
+
NONE_COL = "(aucune)"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def read_csv_df(path: str) -> pd.DataFrame:
|
| 25 |
+
"""Lit le CSV en str ; encodage + séparateur auto-détectés."""
|
| 26 |
+
raw = Path(path).read_bytes()
|
| 27 |
+
text, _enc = detect_encoding(raw)
|
| 28 |
+
delim = detect_delimiter(text)
|
| 29 |
+
return pd.read_csv(
|
| 30 |
+
io.StringIO(text), sep=delim, dtype=str, keep_default_na=False,
|
| 31 |
+
engine="python", on_bad_lines="skip",
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def guess_col(cols: list[str], keywords: list[str]) -> str | None:
|
| 36 |
+
"""Premier en-tête contenant un des mots-clés (insensible à la casse)."""
|
| 37 |
+
for c in cols:
|
| 38 |
+
cl = str(c).lower()
|
| 39 |
+
if any(k in cl for k in keywords):
|
| 40 |
+
return c
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Mots-clés de détection automatique par champ
|
| 45 |
+
GUESS = {
|
| 46 |
+
"reference": ["référence", "reference", "réf", "ref", "code article", "code"],
|
| 47 |
+
"libelle": ["libellé", "libelle", "désignation", "designation", "nom", "dessin", "article", "produit"],
|
| 48 |
+
"prix": ["prix", "pv", "tarif", "montant", "conseillé"],
|
| 49 |
+
"unite": ["unité", "unite", "unit", "cond", "vente", "ml"],
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def parse_price(val) -> float:
|
| 54 |
+
"""'70,92 €' / '1 234,50' → float. Vide ou non numérique → 0.0."""
|
| 55 |
+
s = str(val or "").strip()
|
| 56 |
+
if not s:
|
| 57 |
+
return 0.0
|
| 58 |
+
s = s.replace(" ", "").replace(" ", "").replace("€", "")
|
| 59 |
+
s = s.replace(",", ".")
|
| 60 |
+
m = re.search(r"-?\d+(?:\.\d+)?", s)
|
| 61 |
+
return float(m.group()) if m else 0.0
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def csv_to_articles(df: pd.DataFrame, ref_col: str, lib_col: str,
|
| 65 |
+
prix_col: str | None, unite_col: str | None) -> list[dict]:
|
| 66 |
+
"""
|
| 67 |
+
Convertit les lignes du DataFrame en dicts article.
|
| 68 |
+
`prix_col`/`unite_col` peuvent valoir None ou NONE_COL (champ absent).
|
| 69 |
+
"""
|
| 70 |
+
articles: list[dict] = []
|
| 71 |
+
for _, row in df.iterrows():
|
| 72 |
+
a = {
|
| 73 |
+
"reference": str(row.get(ref_col, "")).strip(),
|
| 74 |
+
"nom_dessin": str(row.get(lib_col, "")).strip(),
|
| 75 |
+
}
|
| 76 |
+
a["prix_conseille"] = (
|
| 77 |
+
parse_price(row.get(prix_col, ""))
|
| 78 |
+
if prix_col and prix_col != NONE_COL else 0.0
|
| 79 |
+
)
|
| 80 |
+
# Unité telle quelle, ligne par ligne ; jamais imposée.
|
| 81 |
+
a["unite"] = (
|
| 82 |
+
str(row.get(unite_col, "")).strip()
|
| 83 |
+
if unite_col and unite_col != NONE_COL else ""
|
| 84 |
+
)
|
| 85 |
+
if a["reference"] or a["nom_dessin"]:
|
| 86 |
+
articles.append(a)
|
| 87 |
+
return articles
|
|
@@ -236,7 +236,6 @@ def _build_article_ebp_row(
|
|
| 236 |
a: dict,
|
| 237 |
fournisseur_code: str,
|
| 238 |
remise: float,
|
| 239 |
-
unite_defaut: str,
|
| 240 |
code_tva: str,
|
| 241 |
taux_tva: float,
|
| 242 |
prix_sont_ttc: bool,
|
|
@@ -244,7 +243,9 @@ def _build_article_ebp_row(
|
|
| 244 |
"""Construit une ligne au format écran « Articles » EBP."""
|
| 245 |
ref = str(a.get("reference") or a.get("code") or "").strip()
|
| 246 |
libelle = _truncate(a.get("nom_dessin") or a.get("libelle") or "", 80)
|
| 247 |
-
|
|
|
|
|
|
|
| 248 |
remise_art = float(a.get("remise_specifique") or remise)
|
| 249 |
famille = str(a.get("code_sous_famille") or "").strip()
|
| 250 |
|
|
@@ -275,7 +276,6 @@ def export_articles_par_famille(
|
|
| 275 |
output_dir: str,
|
| 276 |
fournisseur_code: str,
|
| 277 |
remise: float = 45.0,
|
| 278 |
-
unite_defaut: str = "ml",
|
| 279 |
code_tva: str = "TVA20",
|
| 280 |
taux_tva: float = 20.0,
|
| 281 |
prix_sont_ttc: bool = False,
|
|
@@ -300,7 +300,7 @@ def export_articles_par_famille(
|
|
| 300 |
for famille in sorted(groupes):
|
| 301 |
rows = [
|
| 302 |
_build_article_ebp_row(
|
| 303 |
-
a, fournisseur_code, remise,
|
| 304 |
code_tva, taux_tva, prix_sont_ttc,
|
| 305 |
)
|
| 306 |
for a in groupes[famille]
|
|
|
|
| 236 |
a: dict,
|
| 237 |
fournisseur_code: str,
|
| 238 |
remise: float,
|
|
|
|
| 239 |
code_tva: str,
|
| 240 |
taux_tva: float,
|
| 241 |
prix_sont_ttc: bool,
|
|
|
|
| 243 |
"""Construit une ligne au format écran « Articles » EBP."""
|
| 244 |
ref = str(a.get("reference") or a.get("code") or "").strip()
|
| 245 |
libelle = _truncate(a.get("nom_dessin") or a.get("libelle") or "", 80)
|
| 246 |
+
# Unité prise telle quelle dans la source, jamais imposée ni uniformisée.
|
| 247 |
+
# Chaque référence garde sa propre unité ; vide si la source n'en donne pas.
|
| 248 |
+
unite_art = str(a.get("unite") or "").strip()
|
| 249 |
remise_art = float(a.get("remise_specifique") or remise)
|
| 250 |
famille = str(a.get("code_sous_famille") or "").strip()
|
| 251 |
|
|
|
|
| 276 |
output_dir: str,
|
| 277 |
fournisseur_code: str,
|
| 278 |
remise: float = 45.0,
|
|
|
|
| 279 |
code_tva: str = "TVA20",
|
| 280 |
taux_tva: float = 20.0,
|
| 281 |
prix_sont_ttc: bool = False,
|
|
|
|
| 300 |
for famille in sorted(groupes):
|
| 301 |
rows = [
|
| 302 |
_build_article_ebp_row(
|
| 303 |
+
a, fournisseur_code, remise,
|
| 304 |
code_tva, taux_tva, prix_sont_ttc,
|
| 305 |
)
|
| 306 |
for a in groupes[famille]
|
|
@@ -1,184 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Extraction PDF : pdfplumber (tables en priorité), fallback PyMuPDF texte ligne à ligne.
|
| 3 |
-
"""
|
| 4 |
-
from __future__ import annotations
|
| 5 |
-
|
| 6 |
-
import re
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
PRICE_RE = re.compile(r"\b\d{1,6}[,\.]\d{2}\b")
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def debug_layout(
|
| 13 |
-
pdf_path: str,
|
| 14 |
-
page_from: int,
|
| 15 |
-
page_to: int,
|
| 16 |
-
password: str = "",
|
| 17 |
-
) -> list[dict]:
|
| 18 |
-
"""
|
| 19 |
-
Retourne des stats par page pour diagnostic de structure.
|
| 20 |
-
Chaque dict : {page, tables, lignes_texte, prix_trouves}.
|
| 21 |
-
"""
|
| 22 |
-
try:
|
| 23 |
-
import pdfplumber
|
| 24 |
-
except ImportError:
|
| 25 |
-
return []
|
| 26 |
-
|
| 27 |
-
results = []
|
| 28 |
-
with pdfplumber.open(pdf_path, password=password or None) as pdf:
|
| 29 |
-
start = max(0, page_from - 1)
|
| 30 |
-
end = min(len(pdf.pages), page_to)
|
| 31 |
-
for i, page in enumerate(pdf.pages[start:end], start=start + 1):
|
| 32 |
-
text = page.extract_text() or ""
|
| 33 |
-
tables = [t for t in (page.extract_tables() or []) if t and len(t) > 1]
|
| 34 |
-
lines = [l for l in text.splitlines() if l.strip()]
|
| 35 |
-
prix = PRICE_RE.findall(text)
|
| 36 |
-
results.append({
|
| 37 |
-
"page": i,
|
| 38 |
-
"tables": len(tables),
|
| 39 |
-
"lignes_texte": len(lines),
|
| 40 |
-
"prix_trouves": len(prix),
|
| 41 |
-
})
|
| 42 |
-
return results
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def extract_lines_or_tables(
|
| 46 |
-
pdf_path: str,
|
| 47 |
-
page_from: int,
|
| 48 |
-
page_to: int,
|
| 49 |
-
password: str = "",
|
| 50 |
-
) -> tuple[list[str], list[str], str]:
|
| 51 |
-
"""
|
| 52 |
-
Si pdfplumber détecte des tables valides (>1 ligne), les convertit en lignes pipe-séparées.
|
| 53 |
-
Sinon retourne le texte ligne à ligne.
|
| 54 |
-
Retourne (lignes, prix_source_tokens, mode) où mode = "tables" | "text".
|
| 55 |
-
"""
|
| 56 |
-
try:
|
| 57 |
-
import pdfplumber
|
| 58 |
-
except ImportError:
|
| 59 |
-
lines, prix = extract_raw_lines(pdf_path, page_from, page_to, password)
|
| 60 |
-
return lines, prix, "text"
|
| 61 |
-
|
| 62 |
-
all_lines: list[str] = []
|
| 63 |
-
full_text_parts: list[str] = []
|
| 64 |
-
found_tables = False
|
| 65 |
-
|
| 66 |
-
with pdfplumber.open(pdf_path, password=password or None) as pdf:
|
| 67 |
-
start = max(0, page_from - 1)
|
| 68 |
-
end = min(len(pdf.pages), page_to)
|
| 69 |
-
for page in pdf.pages[start:end]:
|
| 70 |
-
text = page.extract_text() or ""
|
| 71 |
-
tables = [t for t in (page.extract_tables() or []) if t and len(t) > 1]
|
| 72 |
-
full_text_parts.append(text)
|
| 73 |
-
if tables:
|
| 74 |
-
found_tables = True
|
| 75 |
-
for table in tables:
|
| 76 |
-
for row in table:
|
| 77 |
-
cells = [str(c or "").strip() for c in row]
|
| 78 |
-
line = " | ".join(cells)
|
| 79 |
-
if any(c for c in cells):
|
| 80 |
-
all_lines.append(line)
|
| 81 |
-
else:
|
| 82 |
-
for l in text.splitlines():
|
| 83 |
-
if l.strip():
|
| 84 |
-
all_lines.append(l.strip())
|
| 85 |
-
|
| 86 |
-
full_text = "\n".join(full_text_parts)
|
| 87 |
-
prix_tokens = [p.replace(".", ",") for p in PRICE_RE.findall(full_text)]
|
| 88 |
-
return all_lines, prix_tokens, "tables" if found_tables else "text"
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def extract_pages(
|
| 92 |
-
pdf_path: str,
|
| 93 |
-
page_from: int,
|
| 94 |
-
page_to: int,
|
| 95 |
-
password: str = "",
|
| 96 |
-
) -> list[str]:
|
| 97 |
-
"""
|
| 98 |
-
Retourne une liste de chaînes (une par page) dans la plage 1-based donnée.
|
| 99 |
-
Essaie pdfplumber d'abord, repli sur PyMuPDF si non disponible.
|
| 100 |
-
"""
|
| 101 |
-
try:
|
| 102 |
-
return _extract_pdfplumber(pdf_path, page_from, page_to, password)
|
| 103 |
-
except ImportError:
|
| 104 |
-
return _extract_pymupdf(pdf_path, page_from, page_to, password)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def extract_raw_lines(
|
| 108 |
-
pdf_path: str,
|
| 109 |
-
page_from: int,
|
| 110 |
-
page_to: int,
|
| 111 |
-
password: str = "",
|
| 112 |
-
) -> tuple[list[str], list[str]]:
|
| 113 |
-
"""
|
| 114 |
-
Retourne (lignes_texte, tokens_prix_source).
|
| 115 |
-
tokens_prix_source contient tous les prix trouvés dans le texte brut —
|
| 116 |
-
utilisé ensuite pour valider les prix structurés par le LLM.
|
| 117 |
-
"""
|
| 118 |
-
pages = extract_pages(pdf_path, page_from, page_to, password)
|
| 119 |
-
full_text = "\n".join(pages)
|
| 120 |
-
lines = [l.strip() for l in full_text.splitlines() if l.strip()]
|
| 121 |
-
prix_tokens = PRICE_RE.findall(full_text)
|
| 122 |
-
# Normaliser : remplacer point décimal par virgule pour comparaison uniforme
|
| 123 |
-
prix_tokens_norm = [p.replace(".", ",") for p in prix_tokens]
|
| 124 |
-
return lines, prix_tokens_norm
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
def extract_tables(
|
| 128 |
-
pdf_path: str,
|
| 129 |
-
page_from: int,
|
| 130 |
-
page_to: int,
|
| 131 |
-
password: str = "",
|
| 132 |
-
) -> list[list[list[str | None]]]:
|
| 133 |
-
"""
|
| 134 |
-
Extraction structurée par tableaux (pdfplumber uniquement).
|
| 135 |
-
Retourne une liste de tables ; chaque table est une liste de lignes ;
|
| 136 |
-
chaque ligne est une liste de cellules (str ou None).
|
| 137 |
-
"""
|
| 138 |
-
try:
|
| 139 |
-
import pdfplumber
|
| 140 |
-
except ImportError:
|
| 141 |
-
return []
|
| 142 |
-
|
| 143 |
-
all_tables: list[list[list[str | None]]] = []
|
| 144 |
-
with pdfplumber.open(pdf_path, password=password or None) as pdf:
|
| 145 |
-
start = max(0, page_from - 1)
|
| 146 |
-
end = min(len(pdf.pages), page_to)
|
| 147 |
-
for page in pdf.pages[start:end]:
|
| 148 |
-
for table in (page.extract_tables() or []):
|
| 149 |
-
if table:
|
| 150 |
-
all_tables.append(table)
|
| 151 |
-
return all_tables
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
def has_tables(
|
| 155 |
-
pdf_path: str,
|
| 156 |
-
page_from: int,
|
| 157 |
-
page_to: int,
|
| 158 |
-
password: str = "",
|
| 159 |
-
) -> bool:
|
| 160 |
-
return bool(extract_tables(pdf_path, page_from, page_to, password))
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# ── Backends ─────────────────────────────────────────────────────────────────
|
| 164 |
-
|
| 165 |
-
def _extract_pdfplumber(pdf_path, page_from, page_to, password) -> list[str]:
|
| 166 |
-
import pdfplumber
|
| 167 |
-
texts = []
|
| 168 |
-
with pdfplumber.open(pdf_path, password=password or None) as pdf:
|
| 169 |
-
start = max(0, page_from - 1)
|
| 170 |
-
end = min(len(pdf.pages), page_to)
|
| 171 |
-
for page in pdf.pages[start:end]:
|
| 172 |
-
texts.append(page.extract_text() or "")
|
| 173 |
-
return texts
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
def _extract_pymupdf(pdf_path, page_from, page_to, password) -> list[str]:
|
| 177 |
-
import fitz
|
| 178 |
-
doc = fitz.open(pdf_path)
|
| 179 |
-
if doc.is_encrypted:
|
| 180 |
-
if not doc.authenticate(password):
|
| 181 |
-
raise ValueError("Mot de passe incorrect ou PDF non supporté.")
|
| 182 |
-
start = max(0, page_from - 1)
|
| 183 |
-
end = min(doc.page_count, page_to)
|
| 184 |
-
return [doc[i].get_text() for i in range(start, end)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,78 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Extracteur regex pur — pour catalogues à structure PDF stable d'une année sur l'autre.
|
| 3 |
-
Défini dans le profil fournisseur sous la clé "regex_config".
|
| 4 |
-
Même interface que extract_articles : retourne (valides, anomalies, rapport).
|
| 5 |
-
"""
|
| 6 |
-
from __future__ import annotations
|
| 7 |
-
|
| 8 |
-
import re
|
| 9 |
-
|
| 10 |
-
from core.extractor import extract_raw_lines
|
| 11 |
-
from core.agent import validate_prices
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def extract_with_regex(
|
| 15 |
-
pdf_path: str,
|
| 16 |
-
page_from: int,
|
| 17 |
-
page_to: int,
|
| 18 |
-
password: str,
|
| 19 |
-
regex_config: dict,
|
| 20 |
-
default_unit: str = "ml",
|
| 21 |
-
) -> tuple[list[dict], list[dict], dict]:
|
| 22 |
-
"""
|
| 23 |
-
Extrait les articles via regex pures, sans appel LLM.
|
| 24 |
-
|
| 25 |
-
Clés attendues dans regex_config :
|
| 26 |
-
pattern_ligne : regex qui matche une ligne article complète (obligatoire)
|
| 27 |
-
group_nom : numéro de groupe capturant le nom du dessin (défaut 1)
|
| 28 |
-
group_reference : numéro de groupe capturant la référence (défaut 2)
|
| 29 |
-
group_prix : numéro de groupe capturant le prix brut (défaut 3)
|
| 30 |
-
group_unite : numéro de groupe capturant l'unité (optionnel)
|
| 31 |
-
collection : valeur fixe à mettre dans le champ collection (optionnel)
|
| 32 |
-
pattern_ignore : regex — les lignes qui matchent sont ignorées (optionnel)
|
| 33 |
-
"""
|
| 34 |
-
lines, prix_source_tokens = extract_raw_lines(pdf_path, page_from, page_to, password)
|
| 35 |
-
|
| 36 |
-
pat_ligne = re.compile(regex_config.get("pattern_ligne", "(?!x)x"), re.IGNORECASE)
|
| 37 |
-
pat_ignore_str = regex_config.get("pattern_ignore", "")
|
| 38 |
-
pat_ignore = re.compile(pat_ignore_str, re.IGNORECASE) if pat_ignore_str else None
|
| 39 |
-
|
| 40 |
-
g_nom = regex_config.get("group_nom", 1)
|
| 41 |
-
g_ref = regex_config.get("group_reference", 2)
|
| 42 |
-
g_prix = regex_config.get("group_prix", 3)
|
| 43 |
-
g_unite = regex_config.get("group_unite")
|
| 44 |
-
collection = regex_config.get("collection", "")
|
| 45 |
-
|
| 46 |
-
articles: list[dict] = []
|
| 47 |
-
for line in lines:
|
| 48 |
-
if pat_ignore and pat_ignore.search(line):
|
| 49 |
-
continue
|
| 50 |
-
m = pat_ligne.search(line)
|
| 51 |
-
if not m:
|
| 52 |
-
continue
|
| 53 |
-
try:
|
| 54 |
-
nom = m.group(g_nom).strip() if g_nom else ""
|
| 55 |
-
ref = m.group(g_ref).strip() if g_ref else ""
|
| 56 |
-
prix = m.group(g_prix).strip().replace(".", ",") if g_prix else ""
|
| 57 |
-
unite = m.group(g_unite).strip() if g_unite else default_unit
|
| 58 |
-
except IndexError:
|
| 59 |
-
continue
|
| 60 |
-
articles.append({
|
| 61 |
-
"nom_dessin": nom,
|
| 62 |
-
"reference": ref,
|
| 63 |
-
"collection": collection,
|
| 64 |
-
"prix_brut": prix,
|
| 65 |
-
"unite": unite,
|
| 66 |
-
})
|
| 67 |
-
|
| 68 |
-
valides, anomalies = validate_prices(articles, prix_source_tokens)
|
| 69 |
-
|
| 70 |
-
rapport = {
|
| 71 |
-
"lignes_lues": len(lines),
|
| 72 |
-
"articles_ecrits": len(valides),
|
| 73 |
-
"anomalies": len(anomalies),
|
| 74 |
-
"taux_couverture_pct": round(len(valides) / max(len(lines), 1) * 100, 1),
|
| 75 |
-
"prix_source_tokens": len(prix_source_tokens),
|
| 76 |
-
"mode": "regex",
|
| 77 |
-
}
|
| 78 |
-
return valides, anomalies, rapport
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -2,7 +2,6 @@ fastapi>=0.110.0
|
|
| 2 |
uvicorn[standard]>=0.29.0
|
| 3 |
python-multipart>=0.0.9
|
| 4 |
pandas>=2.0.0
|
| 5 |
-
PyMuPDF>=1.24.0
|
| 6 |
python-dotenv>=1.0.0
|
| 7 |
gradio>=5.6.0
|
| 8 |
anthropic>=0.40.0
|
|
|
|
| 2 |
uvicorn[standard]>=0.29.0
|
| 3 |
python-multipart>=0.0.9
|
| 4 |
pandas>=2.0.0
|
|
|
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
gradio>=5.6.0
|
| 7 |
anthropic>=0.40.0
|
|
@@ -1,54 +0,0 @@
|
|
| 1 |
-
"""Tests Phase 5 — validation anti-hallucination des prix."""
|
| 2 |
-
import pytest
|
| 3 |
-
|
| 4 |
-
from core.agent import validate_prices
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def test_prix_valide_present_dans_source():
|
| 8 |
-
articles = [{"code": "A001", "libelle": "Tissu", "prix_brut": "42,00", "unite": "ML"}]
|
| 9 |
-
tokens = ["42,00", "15,50"]
|
| 10 |
-
valides, anomalies = validate_prices(articles, tokens)
|
| 11 |
-
assert len(valides) == 1
|
| 12 |
-
assert len(anomalies) == 0
|
| 13 |
-
assert valides[0]["prix_conseille"] == pytest.approx(42.0)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def test_prix_absent_de_source_va_en_anomalie():
|
| 17 |
-
articles = [{"code": "A002", "libelle": "Galon", "prix_brut": "99,99", "unite": "M"}]
|
| 18 |
-
tokens = ["42,00", "15,50"] # 99,99 n'est pas dans la source
|
| 19 |
-
valides, anomalies = validate_prices(articles, tokens)
|
| 20 |
-
assert len(valides) == 0
|
| 21 |
-
assert len(anomalies) == 1
|
| 22 |
-
assert "99,99" in anomalies[0]["anomalie_raison"]
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def test_prix_vide_accepte():
|
| 26 |
-
articles = [{"code": "A003", "libelle": "Service", "prix_brut": "", "unite": "H"}]
|
| 27 |
-
tokens = ["42,00"]
|
| 28 |
-
valides, anomalies = validate_prices(articles, tokens)
|
| 29 |
-
assert len(valides) == 1
|
| 30 |
-
assert valides[0]["prix_conseille"] == 0.0
|
| 31 |
-
assert len(anomalies) == 0
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def test_normalisation_point_vers_virgule():
|
| 35 |
-
"""Un prix avec point décimal dans la source doit matcher la valeur structurée avec virgule."""
|
| 36 |
-
articles = [{"code": "A004", "libelle": "Tissu", "prix_brut": "42,00", "unite": "ML"}]
|
| 37 |
-
tokens = ["42.00"] # source avec point (normalisé en virgule par extractor)
|
| 38 |
-
# extractor normalise déjà : "42.00" → "42,00"
|
| 39 |
-
tokens_norm = [t.replace(".", ",") for t in tokens]
|
| 40 |
-
valides, anomalies = validate_prices(articles, tokens_norm)
|
| 41 |
-
assert len(valides) == 1
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def test_mix_valides_et_anomalies():
|
| 45 |
-
articles = [
|
| 46 |
-
{"code": "B001", "libelle": "OK", "prix_brut": "10,00", "unite": "U"},
|
| 47 |
-
{"code": "B002", "libelle": "Inventé", "prix_brut": "777,00", "unite": "U"},
|
| 48 |
-
{"code": "B003", "libelle": "Vide", "prix_brut": "", "unite": "U"},
|
| 49 |
-
]
|
| 50 |
-
tokens = ["10,00", "25,00"]
|
| 51 |
-
valides, anomalies = validate_prices(articles, tokens)
|
| 52 |
-
assert len(valides) == 2 # B001 et B003
|
| 53 |
-
assert len(anomalies) == 1 # B002
|
| 54 |
-
assert anomalies[0]["code"] == "B002"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests de l'ingestion CSV + mapping (core.csv_import)."""
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
from core.csv_import import parse_price, guess_col, csv_to_articles, GUESS, NONE_COL
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# ── parse_price ───────────────────────────────────────────────────────────────
|
| 8 |
+
|
| 9 |
+
def test_parse_price_virgule():
|
| 10 |
+
assert parse_price("70,92") == 70.92
|
| 11 |
+
|
| 12 |
+
def test_parse_price_euro_et_espace():
|
| 13 |
+
assert parse_price("1 234,50 €") == 1234.50
|
| 14 |
+
|
| 15 |
+
def test_parse_price_entier():
|
| 16 |
+
assert parse_price("45") == 45.0
|
| 17 |
+
|
| 18 |
+
def test_parse_price_vide():
|
| 19 |
+
assert parse_price("") == 0.0
|
| 20 |
+
assert parse_price(None) == 0.0
|
| 21 |
+
|
| 22 |
+
def test_parse_price_non_numerique():
|
| 23 |
+
assert parse_price("sur devis") == 0.0
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# ── guess_col ─────────────────────────────────────────────────────────────────
|
| 27 |
+
|
| 28 |
+
def test_guess_col_reference():
|
| 29 |
+
cols = ["Code Article", "Désignation", "Tarif"]
|
| 30 |
+
assert guess_col(cols, GUESS["reference"]) == "Code Article"
|
| 31 |
+
|
| 32 |
+
def test_guess_col_libelle():
|
| 33 |
+
cols = ["Ref", "Désignation", "PU"]
|
| 34 |
+
assert guess_col(cols, GUESS["libelle"]) == "Désignation"
|
| 35 |
+
|
| 36 |
+
def test_guess_col_aucun():
|
| 37 |
+
assert guess_col(["X", "Y"], GUESS["prix"]) is None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ── csv_to_articles : unités variables préservées ────────────────────────────
|
| 41 |
+
|
| 42 |
+
def _df():
|
| 43 |
+
return pd.DataFrame({
|
| 44 |
+
"Ref": ["V1", "R1", "M1", "S1"],
|
| 45 |
+
"Designation":["Velours bleu", "Voilage", "Mousse 35kg", "Simili cuir"],
|
| 46 |
+
"Tarif": ["70,92", "30,00", "12,50 €", "45"],
|
| 47 |
+
"Cond": ["ml", "M", "U", "m²"],
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
def test_csv_to_articles_basic():
|
| 51 |
+
arts = csv_to_articles(_df(), "Ref", "Designation", "Tarif", "Cond")
|
| 52 |
+
assert len(arts) == 4
|
| 53 |
+
assert arts[0]["reference"] == "V1"
|
| 54 |
+
assert arts[0]["nom_dessin"] == "Velours bleu"
|
| 55 |
+
assert arts[0]["prix_conseille"] == 70.92
|
| 56 |
+
|
| 57 |
+
def test_csv_to_articles_unites_telles_quelles():
|
| 58 |
+
arts = csv_to_articles(_df(), "Ref", "Designation", "Tarif", "Cond")
|
| 59 |
+
unites = [a["unite"] for a in arts]
|
| 60 |
+
# chaque ligne garde son unité propre, aucune uniformisation
|
| 61 |
+
assert unites == ["ml", "M", "U", "m²"]
|
| 62 |
+
|
| 63 |
+
def test_csv_to_articles_sans_colonne_unite():
|
| 64 |
+
arts = csv_to_articles(_df(), "Ref", "Designation", "Tarif", NONE_COL)
|
| 65 |
+
assert all(a["unite"] == "" for a in arts) # vide, jamais une valeur imposée
|
| 66 |
+
|
| 67 |
+
def test_csv_to_articles_sans_prix():
|
| 68 |
+
arts = csv_to_articles(_df(), "Ref", "Designation", NONE_COL, "Cond")
|
| 69 |
+
assert all(a["prix_conseille"] == 0.0 for a in arts)
|
| 70 |
+
|
| 71 |
+
def test_csv_to_articles_ignore_lignes_vides():
|
| 72 |
+
df = pd.DataFrame({"Ref": ["A", ""], "Designation": ["x", ""], "Tarif": ["1", ""], "Cond": ["ml", ""]})
|
| 73 |
+
arts = csv_to_articles(df, "Ref", "Designation", "Tarif", "Cond")
|
| 74 |
+
assert len(arts) == 1
|
|
@@ -1,210 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Tests pour les nouvelles fonctionnalités :
|
| 3 |
-
1. expand_coloris (multi-coloris)
|
| 4 |
-
2. collection_famille_map dans export_ebp
|
| 5 |
-
3. extract_with_regex (mode regex)
|
| 6 |
-
"""
|
| 7 |
-
import csv
|
| 8 |
-
import os
|
| 9 |
-
import tempfile
|
| 10 |
-
|
| 11 |
-
import pytest
|
| 12 |
-
|
| 13 |
-
from core.agent import expand_coloris
|
| 14 |
-
from core.csv_writer import export_ebp
|
| 15 |
-
from core.regex_extractor import extract_with_regex
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# ── 1. expand_coloris ────────────────────────────────────────────────────────
|
| 19 |
-
|
| 20 |
-
def test_expand_coloris_same_ref_different_names():
|
| 21 |
-
articles = [
|
| 22 |
-
{"reference": "4172", "nom_dessin": "Adagio Bleu nuit", "prix_conseille": 70.0},
|
| 23 |
-
{"reference": "4172", "nom_dessin": "Adagio Ivoire", "prix_conseille": 70.0},
|
| 24 |
-
{"reference": "4172", "nom_dessin": "Adagio Rouge", "prix_conseille": 72.0},
|
| 25 |
-
]
|
| 26 |
-
result = expand_coloris(articles)
|
| 27 |
-
refs = [a["reference"] for a in result]
|
| 28 |
-
assert refs == ["4172-01", "4172-02", "4172-03"]
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def test_expand_coloris_no_change_when_names_identical():
|
| 32 |
-
articles = [
|
| 33 |
-
{"reference": "9999", "nom_dessin": "Tissu X", "prix_conseille": 50.0},
|
| 34 |
-
{"reference": "9999", "nom_dessin": "Tissu X", "prix_conseille": 50.0},
|
| 35 |
-
]
|
| 36 |
-
result = expand_coloris(articles)
|
| 37 |
-
# Même nom → considéré doublon, référence non modifiée
|
| 38 |
-
refs = [a["reference"] for a in result]
|
| 39 |
-
assert refs == ["9999", "9999"]
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def test_expand_coloris_already_suffixed_not_touched():
|
| 43 |
-
articles = [
|
| 44 |
-
{"reference": "4172-01", "nom_dessin": "Adagio Bleu", "prix_conseille": 70.0},
|
| 45 |
-
{"reference": "4172-02", "nom_dessin": "Adagio Rouge", "prix_conseille": 70.0},
|
| 46 |
-
]
|
| 47 |
-
result = expand_coloris(articles)
|
| 48 |
-
refs = [a["reference"] for a in result]
|
| 49 |
-
assert refs == ["4172-01", "4172-02"]
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
def test_expand_coloris_unique_ref_unchanged():
|
| 53 |
-
articles = [
|
| 54 |
-
{"reference": "A001", "nom_dessin": "Uni", "prix_conseille": 30.0},
|
| 55 |
-
{"reference": "A002", "nom_dessin": "Rayures", "prix_conseille": 35.0},
|
| 56 |
-
]
|
| 57 |
-
result = expand_coloris(articles)
|
| 58 |
-
assert [a["reference"] for a in result] == ["A001", "A002"]
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# ── 2. collection_famille_map ─────────────────────────────────────────────────
|
| 62 |
-
|
| 63 |
-
SAMPLE_ARTICLES = [
|
| 64 |
-
{
|
| 65 |
-
"nom_dessin": "Adagio", "reference": "3953",
|
| 66 |
-
"collection": "CHOREGRAPHIE", "prix_conseille": 70.92, "unite": "ml",
|
| 67 |
-
},
|
| 68 |
-
{
|
| 69 |
-
"nom_dessin": "Ballerine", "reference": "3936",
|
| 70 |
-
"collection": "PIUMA", "prix_conseille": 96.08, "unite": "ml",
|
| 71 |
-
},
|
| 72 |
-
{
|
| 73 |
-
"nom_dessin": "Inconnu", "reference": "0000",
|
| 74 |
-
"collection": "AUTRE", "prix_conseille": 50.0, "unite": "ml",
|
| 75 |
-
},
|
| 76 |
-
]
|
| 77 |
-
|
| 78 |
-
MAPPING = {"CHOREGRAPHIE": "TIS-DEC", "PIUMA": "TIS-VEL"}
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def test_collection_famille_map_applied():
|
| 82 |
-
with tempfile.TemporaryDirectory() as d:
|
| 83 |
-
export_ebp(SAMPLE_ARTICLES, d, "TEST", "TST001",
|
| 84 |
-
remise=45.0, collection_famille_map=MAPPING)
|
| 85 |
-
with open(os.path.join(d, "3_articles.csv"), encoding="utf-8-sig") as f:
|
| 86 |
-
reader = list(csv.DictReader(f, delimiter=";"))
|
| 87 |
-
assert reader[0]["Code famille"] == "TIS-DEC"
|
| 88 |
-
assert reader[1]["Code famille"] == "TIS-VEL"
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def test_collection_famille_map_fallback_to_default():
|
| 92 |
-
with tempfile.TemporaryDirectory() as d:
|
| 93 |
-
export_ebp(SAMPLE_ARTICLES, d, "TEST", "TST001",
|
| 94 |
-
remise=45.0, code_famille="DEF001",
|
| 95 |
-
collection_famille_map=MAPPING)
|
| 96 |
-
with open(os.path.join(d, "3_articles.csv"), encoding="utf-8-sig") as f:
|
| 97 |
-
reader = list(csv.DictReader(f, delimiter=";"))
|
| 98 |
-
# "AUTRE" n'est pas dans le mapping → doit utiliser code_famille par défaut
|
| 99 |
-
assert reader[2]["Code famille"] == "DEF001"
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def test_no_collection_famille_map_uses_default():
|
| 103 |
-
with tempfile.TemporaryDirectory() as d:
|
| 104 |
-
export_ebp(SAMPLE_ARTICLES, d, "TEST", "TST001",
|
| 105 |
-
remise=45.0, code_famille="GEN001")
|
| 106 |
-
with open(os.path.join(d, "3_articles.csv"), encoding="utf-8-sig") as f:
|
| 107 |
-
reader = list(csv.DictReader(f, delimiter=";"))
|
| 108 |
-
for row in reader:
|
| 109 |
-
assert row["Code famille"] == "GEN001"
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
# ── 3. Extracteur regex ───────────────────────────────────────────────────────
|
| 113 |
-
|
| 114 |
-
def _make_temp_pdf_with_text(text: str) -> str:
|
| 115 |
-
"""Crée un PDF minimal via reportlab (si disponible) ou renvoie None."""
|
| 116 |
-
try:
|
| 117 |
-
from reportlab.pdfgen import canvas as rl_canvas
|
| 118 |
-
import tempfile
|
| 119 |
-
f = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
|
| 120 |
-
c = rl_canvas.Canvas(f.name)
|
| 121 |
-
y = 750
|
| 122 |
-
for line in text.splitlines():
|
| 123 |
-
c.drawString(50, y, line)
|
| 124 |
-
y -= 15
|
| 125 |
-
c.save()
|
| 126 |
-
return f.name
|
| 127 |
-
except ImportError:
|
| 128 |
-
return None
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def test_regex_extractor_basic(tmp_path):
|
| 132 |
-
"""Test l'extracteur regex sur du texte synthétique."""
|
| 133 |
-
# Simuler des lignes comme pdfplumber les extrairait
|
| 134 |
-
from unittest.mock import patch
|
| 135 |
-
|
| 136 |
-
fake_lines = [
|
| 137 |
-
"HOULÈS 001 Tissu Velours 42,00 ml",
|
| 138 |
-
"HOULÈS 002 Tissu Satin 56,50 ml",
|
| 139 |
-
"====== Entête à ignorer ======",
|
| 140 |
-
"HOULÈS 003 Tissu Lin 33,00 ml",
|
| 141 |
-
]
|
| 142 |
-
fake_prix = ["42,00", "56,50", "33,00"]
|
| 143 |
-
|
| 144 |
-
regex_config = {
|
| 145 |
-
"pattern_ligne": r"HOULÈS\s+(\d+)\s+(.+?)\s+(\d+,\d{2})\s+ml",
|
| 146 |
-
"group_nom": 2,
|
| 147 |
-
"group_reference": 1,
|
| 148 |
-
"group_prix": 3,
|
| 149 |
-
"pattern_ignore": r"={3,}",
|
| 150 |
-
"collection": "HOULES",
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
with patch("core.regex_extractor.extract_raw_lines", return_value=(fake_lines, fake_prix)):
|
| 154 |
-
valides, anomalies, rapport = extract_with_regex(
|
| 155 |
-
"fake.pdf", 1, 1, "", regex_config, "ml",
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
assert len(valides) == 3
|
| 159 |
-
assert len(anomalies) == 0
|
| 160 |
-
assert rapport["mode"] == "regex"
|
| 161 |
-
refs = [a["reference"] for a in valides]
|
| 162 |
-
assert "001" in refs and "002" in refs and "003" in refs
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
def test_regex_extractor_bad_price_goes_to_anomaly():
|
| 166 |
-
from unittest.mock import patch
|
| 167 |
-
|
| 168 |
-
fake_lines = ["HOULÈS 004 Tissu Coton 99,99 ml"]
|
| 169 |
-
fake_prix = ["42,00"] # 99,99 absent de la source
|
| 170 |
-
|
| 171 |
-
regex_config = {
|
| 172 |
-
"pattern_ligne": r"HOULÈS\s+(\d+)\s+(.+?)\s+(\d+,\d{2})\s+ml",
|
| 173 |
-
"group_nom": 2,
|
| 174 |
-
"group_reference": 1,
|
| 175 |
-
"group_prix": 3,
|
| 176 |
-
}
|
| 177 |
-
|
| 178 |
-
with patch("core.regex_extractor.extract_raw_lines", return_value=(fake_lines, fake_prix)):
|
| 179 |
-
valides, anomalies, rapport = extract_with_regex(
|
| 180 |
-
"fake.pdf", 1, 1, "", regex_config, "ml",
|
| 181 |
-
)
|
| 182 |
-
|
| 183 |
-
assert len(valides) == 0
|
| 184 |
-
assert len(anomalies) == 1
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
def test_regex_extractor_pattern_ignore():
|
| 188 |
-
from unittest.mock import patch
|
| 189 |
-
|
| 190 |
-
fake_lines = [
|
| 191 |
-
"HOULÈS 010 Tissu A 10,00 ml",
|
| 192 |
-
"Page titre — à ignorer",
|
| 193 |
-
"HOULÈS 011 Tissu B 20,00 ml",
|
| 194 |
-
]
|
| 195 |
-
fake_prix = ["10,00", "20,00"]
|
| 196 |
-
|
| 197 |
-
regex_config = {
|
| 198 |
-
"pattern_ligne": r"HOULÈS\s+(\d+)\s+(.+?)\s+(\d+,\d{2})\s+ml",
|
| 199 |
-
"group_nom": 2,
|
| 200 |
-
"group_reference": 1,
|
| 201 |
-
"group_prix": 3,
|
| 202 |
-
"pattern_ignore": r"titre",
|
| 203 |
-
}
|
| 204 |
-
|
| 205 |
-
with patch("core.regex_extractor.extract_raw_lines", return_value=(fake_lines, fake_prix)):
|
| 206 |
-
valides, anomalies, _ = extract_with_regex(
|
| 207 |
-
"fake.pdf", 1, 1, "", regex_config, "ml",
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
-
assert len(valides) == 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|