Stephan86 Claude Sonnet 4.6 commited on
Commit
8845c50
·
1 Parent(s): d465d27

feat: détection tables, multi-coloris, mapping collection, rapport amélioré, mode regex

Browse files

- extractor: debug_layout() stats par page + extract_lines_or_tables() préfère les tables pdfplumber
- agent: prompt coloris (1 objet/coloris), expand_coloris(), support regex_config sans LLM
- csv_writer: collection_famille_map optionnel {collection: code_famille_ebp}
- regex_extractor: extracteur pur regex défini en JSON dans le profil fournisseur
- app_gradio: bouton analyse structure, champs mapping et regex, rapport top-10 prix + doublons
- tests: 10 nouveaux tests (37 au total, tous au vert)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

app_gradio.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Interface Gradio — Conversion catalogue PDF → CSV EBP Gestion Commerciale.
3
+ Lancer : python app_gradio.py
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.agent import extract_articles
21
+ from core.csv_writer import export_ebp
22
+ from core.extractor import debug_layout
23
+ from core.profil import list_profiles, load_profile, save_profile
24
+
25
+ load_dotenv()
26
+
27
+
28
+ # ── Constantes ────────────────────────────────────────────────────────────────
29
+
30
+ TVA_CHOICES = [("20 %", 20.0), ("10 %", 10.0), ("5,5 %", 5.5)]
31
+ UNITE_CHOICES = ["ml", "M", "U", "M2", "H", "KG", "L", "RL", "PCE", "Pièce"]
32
+
33
+
34
+ # ── Fonction principale ───────────────────────────────────────────────────────
35
+
36
+ def run_debug_layout(pdf_file, page_from: int, page_to: int) -> str:
37
+ if pdf_file is None:
38
+ return "⚠️ Aucun fichier PDF fourni."
39
+ try:
40
+ pages = debug_layout(pdf_file.name, page_from, page_to)
41
+ if not pages:
42
+ return "Impossible d'analyser (pdfplumber manquant ?)."
43
+ lines = ["Page | Tables | Lignes texte | Prix trouvés"]
44
+ lines.append("-----|--------|-------------|-------------")
45
+ vides = []
46
+ for p in pages:
47
+ marker = " ← vide" if p["prix_trouves"] == 0 and p["lignes_texte"] == 0 else ""
48
+ lines.append(
49
+ f" {p['page']:3d} | {p['tables']:3d} | {p['lignes_texte']:3d} | {p['prix_trouves']:3d}{marker}"
50
+ )
51
+ if p["prix_trouves"] == 0:
52
+ vides.append(str(p["page"]))
53
+ if vides:
54
+ lines.append(f"\n⚠️ Pages sans prix détecté : {', '.join(vides)}")
55
+ return "\n".join(lines)
56
+ except Exception as exc:
57
+ return f"❌ Erreur : {exc}"
58
+
59
+
60
+ def run_conversion(
61
+ pdf_file,
62
+ page_from: int,
63
+ page_to: int,
64
+ fournisseur_nom: str,
65
+ fournisseur_code: str,
66
+ code_famille: str,
67
+ remise: float,
68
+ prix_sont_ttc: bool,
69
+ taux_tva_label: str,
70
+ unite_defaut: str,
71
+ sample_mode: bool,
72
+ profil_nom_save: str,
73
+ collection_famille_map_json: str,
74
+ regex_config_json: str,
75
+ progress=gr.Progress(),
76
+ ):
77
+ if pdf_file is None:
78
+ return None, "⚠️ Aucun fichier PDF fourni.", "", ""
79
+
80
+ fournisseur_nom = fournisseur_nom.strip()
81
+ fournisseur_code = fournisseur_code.strip().upper()
82
+
83
+ if not fournisseur_nom:
84
+ return None, "⚠️ Le nom du fournisseur est obligatoire.", "", ""
85
+ if not fournisseur_code:
86
+ fournisseur_code = fournisseur_nom[:8].upper().replace(" ", "")
87
+
88
+ # Résolution taux TVA
89
+ taux_tva = 20.0
90
+ for label, val in TVA_CHOICES:
91
+ if label == taux_tva_label:
92
+ taux_tva = val
93
+ break
94
+
95
+ # Parse JSON optionnels
96
+ collection_famille_map: dict | None = None
97
+ if collection_famille_map_json.strip():
98
+ try:
99
+ collection_famille_map = json.loads(collection_famille_map_json)
100
+ except json.JSONDecodeError:
101
+ return None, "⚠️ JSON du mapping collection invalide.", "", ""
102
+
103
+ regex_config: dict | None = None
104
+ if regex_config_json.strip():
105
+ try:
106
+ regex_config = json.loads(regex_config_json)
107
+ except json.JSONDecodeError:
108
+ return None, "⚠️ JSON de l'extracteur regex invalide.", "", ""
109
+
110
+ # Sauvegarde du profil si demandée
111
+ if profil_nom_save.strip():
112
+ profil_data: dict = {
113
+ "fournisseur_nom": fournisseur_nom,
114
+ "fournisseur_code": fournisseur_code,
115
+ "code_famille": code_famille,
116
+ "remise": remise,
117
+ "prix_sont_ttc": prix_sont_ttc,
118
+ "taux_tva_label": taux_tva_label,
119
+ "unite_defaut": unite_defaut,
120
+ }
121
+ if collection_famille_map:
122
+ profil_data["collection_famille_map"] = collection_famille_map
123
+ if regex_config:
124
+ profil_data["regex_config"] = regex_config
125
+ save_profile(profil_nom_save.strip(), profil_data)
126
+
127
+ def _progress_cb(done, total):
128
+ progress(done / max(total, 1), desc=f"Batch {done}/{total}")
129
+
130
+ try:
131
+ progress(0, desc="Extraction en cours…")
132
+ valides, anomalies, rapport = extract_articles(
133
+ pdf_path=pdf_file.name,
134
+ page_from=page_from,
135
+ page_to=page_to,
136
+ password="",
137
+ default_unit=unite_defaut,
138
+ progress_cb=_progress_cb,
139
+ sample_mode=sample_mode,
140
+ regex_config=regex_config,
141
+ )
142
+
143
+ if not valides and not anomalies:
144
+ return None, "⚠️ Aucun article détecté dans ces pages.", "", ""
145
+
146
+ # Export CSV
147
+ progress(0.9, desc="Écriture des fichiers CSV…")
148
+ out_dir = tempfile.mkdtemp(prefix="ebp_export_")
149
+ export_ebp(
150
+ articles=valides,
151
+ output_dir=out_dir,
152
+ fournisseur_nom=fournisseur_nom,
153
+ fournisseur_code=fournisseur_code,
154
+ remise=remise,
155
+ unite_defaut=unite_defaut,
156
+ code_famille=code_famille,
157
+ prix_sont_ttc=prix_sont_ttc,
158
+ taux_tva=taux_tva,
159
+ collection_famille_map=collection_famille_map,
160
+ )
161
+
162
+ # Rapport d'audit
163
+ rapport_txt = _build_rapport(rapport, valides, anomalies, sample_mode)
164
+ rapport_path = os.path.join(out_dir, "rapport_conversion.txt")
165
+ Path(rapport_path).write_text(rapport_txt, encoding="utf-8")
166
+
167
+ # Anomalies CSV
168
+ if anomalies:
169
+ anomalies_path = os.path.join(out_dir, "anomalies.csv")
170
+ _write_anomalies(anomalies, anomalies_path)
171
+
172
+ # ZIP de sortie
173
+ zip_path = os.path.join(out_dir, "export_ebp.zip")
174
+ with zipfile.ZipFile(zip_path, "w") as zf:
175
+ for f in Path(out_dir).glob("*.csv"):
176
+ zf.write(f, f.name)
177
+ zf.write(rapport_path, "rapport_conversion.txt")
178
+
179
+ progress(1.0, desc="Terminé !")
180
+ return zip_path, rapport_txt, _anomalies_preview(anomalies), ""
181
+
182
+ except Exception as exc:
183
+ tb = traceback.format_exc()
184
+ return None, f"❌ Erreur : {exc}\n\n{tb[-800:]}", "", ""
185
+
186
+
187
+ def _build_rapport(rapport: dict, valides, anomalies, sample_mode: bool) -> str:
188
+ mode_extract = rapport.get("mode", "text")
189
+ lines = [
190
+ "═══ RAPPORT DE CONVERSION ═══",
191
+ f"Mode : {'ÉCHANTILLON' if sample_mode else 'COMPLET'} ({mode_extract})",
192
+ f"Lignes lues : {rapport['lignes_lues']}",
193
+ f"Prix source : {rapport['prix_source_tokens']} tokens trouvés dans le texte",
194
+ f"Articles OK : {rapport['articles_ecrits']}",
195
+ f"Anomalies : {rapport['anomalies']}",
196
+ f"Couverture : {rapport['taux_couverture_pct']} %",
197
+ "",
198
+ "Fichiers produits (à importer dans cet ordre) :",
199
+ " 1. 1_familles_articles.csv",
200
+ " 2. 2_fournisseur.csv",
201
+ " 3. 3_articles.csv",
202
+ ]
203
+
204
+ # Top 10 prix les plus élevés
205
+ avec_prix = [a for a in valides if a.get("prix_conseille", 0) > 0]
206
+ if avec_prix:
207
+ top10 = sorted(avec_prix, key=lambda a: a["prix_conseille"], reverse=True)[:10]
208
+ lines += ["", "── Top 10 prix conseillés ──"]
209
+ for a in top10:
210
+ ref = a.get("reference", "?")
211
+ nom = str(a.get("nom_dessin", ""))[:30]
212
+ prix = f"{a['prix_conseille']:.2f}".replace(".", ",")
213
+ lines.append(f" {prix} € [{ref}] {nom}")
214
+
215
+ # Doublons (même référence, prix différents)
216
+ ref_prix: dict[str, list] = defaultdict(list)
217
+ for a in valides:
218
+ ref = a.get("reference", "")
219
+ if ref:
220
+ ref_prix[ref].append(a.get("prix_conseille", 0))
221
+ doublons = {ref: prix for ref, prix in ref_prix.items() if len(set(prix)) > 1}
222
+ if doublons:
223
+ lines += ["", f"── {len(doublons)} référence(s) en doublon (prix différents) ──"]
224
+ for ref, prix_list in list(doublons.items())[:10]:
225
+ prix_fmt = " / ".join(f"{p:.2f}".replace(".", ",") for p in prix_list)
226
+ lines.append(f" [{ref}] → {prix_fmt}")
227
+
228
+ if anomalies:
229
+ lines += ["", f"⚠️ {len(anomalies)} lignes en anomalie → anomalies.csv (à revoir manuellement)."]
230
+ return "\n".join(lines)
231
+
232
+
233
+ def _write_anomalies(anomalies: list[dict], path: str) -> None:
234
+ if not anomalies:
235
+ return
236
+ cols = ["code", "libelle", "prix_brut", "unite", "famille_suggeree", "anomalie_raison"]
237
+ with open(path, "w", newline="", encoding="utf-8-sig") as f:
238
+ w = csv.DictWriter(f, fieldnames=cols, delimiter=";",
239
+ extrasaction="ignore", lineterminator="\r\n")
240
+ w.writeheader()
241
+ w.writerows(anomalies)
242
+
243
+
244
+ def _anomalies_preview(anomalies: list[dict]) -> str:
245
+ if not anomalies:
246
+ return "✅ Aucune anomalie détectée."
247
+ lines = [f"⚠️ {len(anomalies)} anomalie(s) — prix non traçables à la source :"]
248
+ for a in anomalies[:10]:
249
+ lines.append(f" [{a.get('code','?')}] {str(a.get('libelle',''))[:40]} — {a.get('anomalie_raison','')}")
250
+ if len(anomalies) > 10:
251
+ lines.append(f" … et {len(anomalies)-10} autres (voir anomalies.csv)")
252
+ return "\n".join(lines)
253
+
254
+
255
+ # ── Gestion des profils ───────────────────────────────────────────────────────
256
+
257
+ def on_profil_load(profil_nom: str):
258
+ empty = tuple(gr.update() for _ in range(9))
259
+ if not profil_nom or profil_nom == "(aucun)":
260
+ return empty
261
+ try:
262
+ p = load_profile(profil_nom)
263
+ mapping = p.get("collection_famille_map")
264
+ mapping_str = json.dumps(mapping, ensure_ascii=False) if mapping else ""
265
+ regex = p.get("regex_config")
266
+ regex_str = json.dumps(regex, ensure_ascii=False, indent=2) if regex else ""
267
+ return (
268
+ p.get("fournisseur_nom", ""),
269
+ p.get("fournisseur_code", ""),
270
+ p.get("code_famille", "FFR00001"),
271
+ p.get("remise", 45.0),
272
+ p.get("prix_sont_ttc", False),
273
+ p.get("taux_tva_label", "20 %"),
274
+ p.get("unite_defaut", "ml"),
275
+ mapping_str,
276
+ regex_str,
277
+ )
278
+ except Exception:
279
+ return empty
280
+
281
+
282
+ def refresh_profiles():
283
+ choices = ["(aucun)"] + list_profiles()
284
+ return gr.update(choices=choices, value="(aucun)")
285
+
286
+
287
+ # ── Interface Gradio ──────────────────────────────────────────────────────────
288
+
289
+ with gr.Blocks(title="PDF → CSV EBP", theme=gr.themes.Soft()) as demo:
290
+ gr.Markdown("# 📄 Catalogue PDF → CSV EBP Gestion Commerciale")
291
+ gr.Markdown(
292
+ "Convertit un catalogue fournisseur PDF en 3 fichiers CSV prêts à importer dans EBP "
293
+ "(familles → fournisseur → articles). Les prix ne sont jamais inventés : "
294
+ "chaque valeur est tracée au texte source."
295
+ )
296
+
297
+ with gr.Row():
298
+ with gr.Column(scale=2):
299
+ gr.Markdown("### 📁 Fichier & pages")
300
+ pdf_input = gr.File(label="Catalogue PDF", file_types=[".pdf"])
301
+ with gr.Row():
302
+ page_from = gr.Slider(1, 500, value=1, step=1, label="Page début")
303
+ page_to = gr.Slider(1, 500, value=50, step=1, label="Page fin")
304
+ sample_mode = gr.Checkbox(label="Mode échantillon (30 premières lignes)", value=False)
305
+ with gr.Row():
306
+ btn_debug = gr.Button("🔍 Analyser la structure du PDF", size="sm")
307
+ debug_output = gr.Textbox(label="Structure par page (tables / lignes / prix)", lines=8,
308
+ interactive=False, visible=False)
309
+
310
+ with gr.Column(scale=2):
311
+ gr.Markdown("### 🏭 Fournisseur")
312
+ with gr.Row():
313
+ profil_dropdown = gr.Dropdown(
314
+ choices=["(aucun)"] + list_profiles(),
315
+ value="(aucun)",
316
+ label="Charger un profil",
317
+ interactive=True,
318
+ )
319
+ btn_refresh = gr.Button("🔄", size="sm")
320
+
321
+ fournisseur_nom = gr.Textbox(label="Nom du fournisseur *", placeholder="Ex : CASAMANCE")
322
+ fournisseur_code = gr.Textbox(label="Code fournisseur", placeholder="Ex : CAS001")
323
+ code_famille = gr.Textbox(label="Code famille EBP par défaut", value="FFR00001")
324
+ collection_famille_map_input = gr.Textbox(
325
+ label="Mapping collection → code famille EBP (JSON optionnel)",
326
+ placeholder='{"CHOREGRAPHIE": "TIS-DEC", "PIUMA": "TIS-VEL"}',
327
+ lines=2,
328
+ )
329
+ profil_save_nom = gr.Textbox(label="Sauvegarder ce profil sous…",
330
+ placeholder="laisser vide pour ne pas sauvegarder")
331
+
332
+ with gr.Column(scale=1):
333
+ gr.Markdown("### ⚙️ Paramètres")
334
+ remise_input = gr.Slider(0, 80, value=45, step=1, label="Remise fournisseur (%)")
335
+ prix_ttc_toggle = gr.Checkbox(label="Les prix du catalogue sont TTC", value=False)
336
+ taux_tva = gr.Radio([l for l, _ in TVA_CHOICES], value="20 %", label="Taux TVA (si prix TTC)")
337
+ unite_def = gr.Dropdown(UNITE_CHOICES, value="ml", label="Unité par défaut")
338
+ regex_config_input = gr.Textbox(
339
+ label="Extracteur regex (JSON optionnel — prioritaire sur le LLM)",
340
+ placeholder='{"pattern_ligne": "...", "group_nom": 1, ...}',
341
+ lines=3,
342
+ )
343
+
344
+ btn_convert = gr.Button("▶️ Lancer la conversion", variant="primary", size="lg")
345
+
346
+ with gr.Row():
347
+ zip_output = gr.File(label="📦 Télécharger les fichiers CSV (ZIP)")
348
+ rapport_output = gr.Textbox(label="📊 Rapport d'audit", lines=20, interactive=False)
349
+
350
+ anomalies_output = gr.Textbox(label="⚠️ Anomalies (prix non traçables)", lines=6, interactive=False)
351
+ err_output = gr.Textbox(label="Erreur", visible=False)
352
+
353
+ # ── Événements ──────────────────────────────────────────────────────────
354
+ btn_debug.click(
355
+ fn=run_debug_layout,
356
+ inputs=[pdf_input, page_from, page_to],
357
+ outputs=[debug_output],
358
+ ).then(fn=lambda: gr.update(visible=True), outputs=[debug_output])
359
+
360
+ btn_convert.click(
361
+ fn=run_conversion,
362
+ inputs=[
363
+ pdf_input, page_from, page_to,
364
+ fournisseur_nom, fournisseur_code,
365
+ code_famille, remise_input, prix_ttc_toggle,
366
+ taux_tva, unite_def,
367
+ sample_mode, profil_save_nom,
368
+ collection_famille_map_input, regex_config_input,
369
+ ],
370
+ outputs=[zip_output, rapport_output, anomalies_output, err_output],
371
+ )
372
+
373
+ profil_dropdown.change(
374
+ fn=on_profil_load,
375
+ inputs=[profil_dropdown],
376
+ outputs=[fournisseur_nom, fournisseur_code, code_famille,
377
+ remise_input, prix_ttc_toggle, taux_tva, unite_def,
378
+ collection_famille_map_input, regex_config_input],
379
+ )
380
+
381
+ btn_refresh.click(fn=refresh_profiles, outputs=[profil_dropdown])
382
+
383
+
384
+ if __name__ == "__main__":
385
+ demo.launch(server_name="0.0.0.0", server_port=7860)
core/agent.py CHANGED
@@ -1,35 +1,68 @@
 
 
 
 
 
 
 
1
  import base64
2
  import json
3
  import re
4
  from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
 
5
 
6
  import anthropic
7
 
8
- _SYSTEM = """\
9
- Tu es un extracteur de données de catalogue. À partir des images de pages fournies, \
10
- identifie chaque produit, référence, tissu, coloris ou article listé — \
11
- quel que soit le terme utilisé dans le document — \
12
- et retourne UNIQUEMENT un tableau JSON valide.
13
- Chaque objet doit avoir exactement ces quatre champs :
14
- - "code" : string — tout code, référence, SKU ou numéro identifiant le produit (vide si absent)
15
- - "libelle" : string — désignation, nom, coloris ou description du produit
16
- - "prix_ttc" : number — tout prix affiché en euros, TTC ou HT (0 si absent)
17
- - "unite" : string — unité de vente (utilise l'unité par défaut si non précisée)
18
- Ne retourne aucun texte, commentaire ou balise avant ou après le tableau JSON.\
 
 
 
 
 
 
 
 
 
 
 
 
19
  """
20
 
21
- _BATCH_SIZE = 3 # pages par appel Claude Vision (images = plus lourd)
22
- _BATCH_TIMEOUT = 120
23
- _DPI = 150 # résolution de rendu des pages
 
 
 
 
 
 
 
24
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- def _page_to_image_b64(page) -> str:
27
- """Render a PDF page to a base64-encoded PNG."""
28
- import fitz
29
- mat = fitz.Matrix(_DPI / 72, _DPI / 72)
30
- pix = page.get_pixmap(matrix=mat, alpha=False)
31
- return base64.standard_b64encode(pix.tobytes("png")).decode()
32
 
 
33
 
34
  def _parse_json_safe(raw: str) -> list[dict]:
35
  raw = raw.strip()
@@ -47,9 +80,124 @@ def _parse_json_safe(raw: str) -> list[dict]:
47
  return results
48
 
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def _call_claude_vision(
51
  client: anthropic.Anthropic,
52
- pages, # list of fitz.Page objects
53
  default_unit: str,
54
  ) -> list[dict]:
55
  content = []
@@ -61,60 +209,99 @@ def _call_claude_vision(
61
  })
62
  content.append({
63
  "type": "text",
64
- "text": f"Unité par défaut : {default_unit}\nExtrait tous les produits/références de ces pages.",
 
 
 
65
  })
66
-
67
  message = client.messages.create(
68
  model="claude-sonnet-4-6",
69
  max_tokens=16000,
70
- system=_SYSTEM,
71
  messages=[{"role": "user", "content": content}],
72
  )
73
  return _parse_json_safe(message.content[0].text)
74
 
75
 
 
 
76
  def extract_articles(
77
  pdf_path: str,
78
  page_from: int,
79
  page_to: int,
80
  password: str,
81
  default_unit: str,
82
- progress_cb=None,
83
- ) -> list[dict]:
84
- """Render PDF pages as images and extract products via Claude Vision."""
85
- import fitz
86
- doc = fitz.open(pdf_path)
87
- if doc.is_encrypted:
88
- if not doc.authenticate(password):
89
- raise ValueError("Mot de passe PDF incorrect.")
90
 
91
- start = max(0, page_from - 1)
92
- end = min(doc.page_count, page_to)
93
- all_pages = [doc[i] for i in range(start, end)]
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  client = anthropic.Anthropic(timeout=_BATCH_TIMEOUT + 10)
96
- all_articles: list[dict] = []
97
- batches = [all_pages[i:i + _BATCH_SIZE] for i in range(0, len(all_pages), _BATCH_SIZE)]
 
 
98
 
99
  with ThreadPoolExecutor(max_workers=1) as pool:
100
  for i, batch in enumerate(batches):
101
- future = pool.submit(_call_claude_vision, client, batch, default_unit)
102
  try:
103
- articles = future.result(timeout=_BATCH_TIMEOUT)
104
- all_articles.extend(articles)
105
  except FutureTimeout:
106
  future.cancel()
107
  except anthropic.APIConnectionError as exc:
108
  raise RuntimeError(
109
  "Impossible de joindre l'API Anthropic. "
110
- "Vérifie ANTHROPIC_API_KEY dans les secrets HF Spaces."
111
  ) from exc
112
  except anthropic.AuthenticationError as exc:
113
  raise RuntimeError("Clé API Anthropic invalide ou expirée.") from exc
114
  except Exception:
115
- pass # batch ignoré
116
 
117
  if progress_cb:
118
  progress_cb(i + 1, len(batches))
119
 
120
- return all_articles
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
 
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 = []
 
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
core/csv_writer.py CHANGED
@@ -1,18 +1,234 @@
1
- import pandas as pd
 
 
2
 
3
- def to_csv(articles: list[dict], output_path: str, brand: str = "") -> str:
4
- """Write articles to a semicolon-separated CSV compatible with EBP Gestion Commerciale."""
5
- rows = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  for a in articles:
7
- row = {
8
- "Référence": a.get("code", ""),
9
- "Désignation": a.get("libelle", ""),
10
- "Prix TTC": float(a.get("prix_ttc") or 0),
11
- "Unité": a.get("unite", ""),
12
- "Marque": brand,
13
- }
14
- rows.append(row)
15
- columns = ["Référence", "Désignation", "Prix TTC", "Unité", "Marque"]
16
- df = pd.DataFrame(rows, columns=columns)
17
- df.to_csv(output_path, index=False, sep=";", encoding="utf-8-sig")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  return output_path
 
1
+ """
2
+ Écriture des fichiers CSV au format EBP Gestion Commerciale.
3
+ Format de référence : CAMENGO import ebp 2026.csv
4
 
5
+ Colonnes articles :
6
+ Nom de dessin ; Référence ; Collection ; Prix d'achat HT par ml ;
7
+ Prix conseillé HT par ml ; Remise ; Unité ; Fournisseur ;
8
+ Code fournisseur ; Code famille
9
+
10
+ Règles : sep=";", encoding="utf-8-sig", décimales en virgule française,
11
+ pas de symbole €/%, fin de ligne \\r\\n.
12
+ Produit 3 fichiers numérotés dans l'ordre d'import EBP.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import os
18
+ from pathlib import Path
19
+
20
+
21
+ # ── Colonnes EBP (format de référence CAMENGO) ───────────────────────────────
22
+
23
+ COLS_ARTICLES = [
24
+ "Nom de dessin",
25
+ "Référence",
26
+ "Collection",
27
+ "Prix d'achat HT par ml",
28
+ "Prix conseillé HT par ml",
29
+ "Remise",
30
+ "Unité",
31
+ "Fournisseur",
32
+ "Code fournisseur",
33
+ "Code famille",
34
+ ]
35
+
36
+ COLS_FAMILLES = [
37
+ "Code famille", "Libellé", "Code TVA",
38
+ "Coefficient de marge", "Compte comptable vente", "Compte comptable achat",
39
+ ]
40
+
41
+ COLS_FOURNISSEUR = [
42
+ "Code fournisseur", "Nom", "Adresse", "Code postal", "Ville", "Pays",
43
+ "Téléphone", "Email", "Famille fournisseur", "Conditions de règlement",
44
+ ]
45
+
46
+
47
+ # ── Helpers ──────────────────────────────────────────────────────────────────
48
+
49
+ def _fmt_decimal(value) -> str:
50
+ """Float ou string → virgule française, sans symbole monétaire ou %."""
51
+ if value is None or value == "":
52
+ return ""
53
+ try:
54
+ f = float(str(value).replace(",", ".").replace("€", "").replace("%", "").strip())
55
+ return f"{f:.2f}".replace(".", ",")
56
+ except (ValueError, TypeError):
57
+ return ""
58
+
59
+
60
+ def _fmt_remise(value) -> str:
61
+ """Remise : entier ou float, sans symbole %."""
62
+ if value is None or value == "":
63
+ return ""
64
+ try:
65
+ f = float(str(value).replace("%", "").replace(",", ".").strip())
66
+ return str(int(f)) if f == int(f) else f"{f:.2f}".replace(".", ",")
67
+ except (ValueError, TypeError):
68
+ return ""
69
+
70
+
71
+ def _truncate(text: str, max_len: int = 80) -> str:
72
+ text = str(text or "").strip()
73
+ return text[:max_len] if len(text) > max_len else text
74
+
75
+
76
+ def _write_csv(rows: list[dict], columns: list[str], path: str) -> None:
77
+ with open(path, "w", newline="", encoding="utf-8-sig") as f:
78
+ w = csv.DictWriter(f, fieldnames=columns, delimiter=";",
79
+ extrasaction="ignore", lineterminator="\r\n")
80
+ w.writeheader()
81
+ for row in rows:
82
+ w.writerow(row)
83
+
84
+
85
+ # ── Calcul prix ──────────────────────────────────────────────────────────────
86
+
87
+ def prix_achat_from_conseille(prix_conseille_ht: float, remise: float) -> float:
88
+ """Prix achat HT = prix_conseillé_HT × (1 - remise/100). Arrondi 2 décimales."""
89
+ if prix_conseille_ht <= 0:
90
+ return 0.0
91
+ return round(prix_conseille_ht * (1 - remise / 100), 2)
92
+
93
+
94
+ def prix_ht_from_ttc(prix_ttc: float, taux_tva: float = 20.0) -> float:
95
+ """PV HT = prix_TTC / (1 + taux_TVA/100). Utilisé si le catalogue affiche des prix TTC."""
96
+ if prix_ttc <= 0:
97
+ return 0.0
98
+ return round(prix_ttc / (1 + taux_tva / 100), 2)
99
+
100
+
101
+ # ── Export principal ──────────────────────────────────────────────────────────
102
+
103
+ def export_ebp(
104
+ articles: list[dict],
105
+ output_dir: str,
106
+ fournisseur_nom: str,
107
+ fournisseur_code: str,
108
+ remise: float = 45.0,
109
+ unite_defaut: str = "ml",
110
+ code_famille: str = "FFR00001",
111
+ code_tva: str = "TVA20",
112
+ prix_sont_ttc: bool = False,
113
+ taux_tva: float = 20.0,
114
+ collection_famille_map: dict | None = None,
115
+ ) -> dict[str, str]:
116
+ """
117
+ Génère les 3 fichiers EBP dans output_dir.
118
+ Retourne un dict {nom_fichier: chemin_absolu}.
119
+
120
+ Chaque article doit avoir :
121
+ - nom_dessin : str
122
+ - reference : str
123
+ - collection : str (→ Collection, sert aussi à déduire la famille)
124
+ - prix_conseille : float (prix conseillé HT, ou TTC si prix_sont_ttc=True)
125
+ - remise_specifique: float|None (si différente de la remise globale)
126
+ - unite : str|None
127
+
128
+ collection_famille_map : dict optionnel {nom_collection: code_famille_ebp}
129
+ Si fourni, le code famille de chaque article est résolu depuis sa collection.
130
+ Exemple : {"CHOREGRAPHIE": "TIS-DEC", "PIUMA": "TIS-VEL"}
131
+ """
132
+ os.makedirs(output_dir, exist_ok=True)
133
+
134
+ # ── 1. Familles ───────────────────────────────────────────────────────────
135
+ # Les collections deviennent des familles (on les regroupe par code famille)
136
+ # Le code famille est unique par fournisseur (ex: FFR00001)
137
+ familles_rows = [{
138
+ "Code famille": code_famille,
139
+ "Libellé": fournisseur_nom,
140
+ "Code TVA": code_tva,
141
+ "Coefficient de marge": "",
142
+ "Compte comptable vente": "",
143
+ "Compte comptable achat": "",
144
+ }]
145
+ path_familles = os.path.join(output_dir, "1_familles_articles.csv")
146
+ _write_csv(familles_rows, COLS_FAMILLES, path_familles)
147
+
148
+ # ── 2. Fournisseur ────────────────────────────────────────────────────────
149
+ fournisseur_row = [{
150
+ "Code fournisseur": fournisseur_code,
151
+ "Nom": fournisseur_nom,
152
+ "Adresse": "",
153
+ "Code postal": "",
154
+ "Ville": "",
155
+ "Pays": "",
156
+ "Téléphone": "",
157
+ "Email": "",
158
+ "Famille fournisseur": "",
159
+ "Conditions de règlement": "",
160
+ }]
161
+ path_fournisseur = os.path.join(output_dir, "2_fournisseur.csv")
162
+ _write_csv(fournisseur_row, COLS_FOURNISSEUR, path_fournisseur)
163
+
164
+ # ── 3. Articles ───────────────────────────────────────────────────────────
165
+ articles_rows = []
166
  for a in articles:
167
+ nom = _truncate(a.get("nom_dessin") or a.get("libelle") or "", 80)
168
+ ref = str(a.get("reference") or a.get("code") or "").strip()
169
+ collection = _truncate(a.get("collection") or a.get("famille_suggeree") or "", 80)
170
+ unite_art = str(a.get("unite") or unite_defaut).strip()
171
+ remise_art = float(a.get("remise_specifique") or remise)
172
+
173
+ # Prix conseillé HT
174
+ prix_brut_val = float(a.get("prix_conseille") or a.get("prix_ttc") or 0)
175
+ if prix_sont_ttc and prix_brut_val > 0:
176
+ prix_conseille_ht = prix_ht_from_ttc(prix_brut_val, taux_tva)
177
+ else:
178
+ prix_conseille_ht = prix_brut_val
179
+
180
+ # Prix achat HT calculé depuis le conseillé et la remise
181
+ prix_achat_ht = prix_achat_from_conseille(prix_conseille_ht, remise_art)
182
+
183
+ # Code famille : résolu depuis le mapping collection si disponible
184
+ famille_art = code_famille
185
+ if collection_famille_map and collection:
186
+ famille_art = collection_famille_map.get(collection, code_famille)
187
+
188
+ articles_rows.append({
189
+ "Nom de dessin": nom,
190
+ "Référence": ref,
191
+ "Collection": collection,
192
+ "Prix d'achat HT par ml": _fmt_decimal(prix_achat_ht) if prix_achat_ht else "",
193
+ "Prix conseillé HT par ml": _fmt_decimal(prix_conseille_ht) if prix_conseille_ht else "",
194
+ "Remise": _fmt_remise(remise_art),
195
+ "Unité": unite_art,
196
+ "Fournisseur": fournisseur_nom,
197
+ "Code fournisseur": fournisseur_code,
198
+ "Code famille": famille_art,
199
+ })
200
+
201
+ path_articles = os.path.join(output_dir, "3_articles.csv")
202
+ _write_csv(articles_rows, COLS_ARTICLES, path_articles)
203
+
204
+ return {
205
+ "1_familles_articles.csv": path_familles,
206
+ "2_fournisseur.csv": path_fournisseur,
207
+ "3_articles.csv": path_articles,
208
+ }
209
+
210
+
211
+ def _make_famille_code(libelle: str) -> str:
212
+ cleaned = "".join(c for c in libelle.upper() if c.isalpha() or c.isspace())
213
+ words = cleaned.split()
214
+ if not words:
215
+ return "DIV"
216
+ if len(words) == 1:
217
+ return words[0][:6]
218
+ return "".join(w[0] for w in words[:6])
219
+
220
+
221
+ # ── Compatibilité ancienne API (app.py) ───────────────────────────────────────
222
+
223
+ def to_csv(articles: list[dict], output_path: str, brand: str = "") -> str:
224
+ """Ancienne signature conservée pour compatibilité."""
225
+ out_dir = os.path.dirname(output_path) or "."
226
+ files = export_ebp(
227
+ articles,
228
+ output_dir=out_dir,
229
+ fournisseur_nom=brand,
230
+ fournisseur_code=brand[:8].upper().replace(" ", "") or "FOUR001",
231
+ )
232
+ import shutil
233
+ shutil.copy(files["3_articles.csv"], output_path)
234
  return output_path
core/extractor.py CHANGED
@@ -1,4 +1,91 @@
1
- import fitz # PyMuPDF
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
 
4
  def extract_pages(
@@ -7,11 +94,91 @@ def extract_pages(
7
  page_to: int,
8
  password: str = "",
9
  ) -> list[str]:
10
- """Return one string per PDF page for the given 1-based page range."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  doc = fitz.open(pdf_path)
12
  if doc.is_encrypted:
13
  if not doc.authenticate(password):
14
  raise ValueError("Mot de passe incorrect ou PDF non supporté.")
15
  start = max(0, page_from - 1)
16
- end = min(doc.page_count, page_to)
17
  return [doc[i].get_text() for i in range(start, end)]
 
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(
 
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)]
core/profil.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gestion des profils fournisseur (save/load JSON).
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+
11
+ PROFILES_DIR = Path(__file__).parent.parent / "profils"
12
+
13
+
14
+ def list_profiles() -> list[str]:
15
+ PROFILES_DIR.mkdir(exist_ok=True)
16
+ return [p.stem for p in PROFILES_DIR.glob("*.json")]
17
+
18
+
19
+ def save_profile(name: str, data: dict) -> None:
20
+ PROFILES_DIR.mkdir(exist_ok=True)
21
+ path = PROFILES_DIR / f"{_safe(name)}.json"
22
+ with open(path, "w", encoding="utf-8") as f:
23
+ json.dump(data, f, ensure_ascii=False, indent=2)
24
+
25
+
26
+ def load_profile(name: str) -> dict:
27
+ path = PROFILES_DIR / f"{_safe(name)}.json"
28
+ if not path.exists():
29
+ raise FileNotFoundError(f"Profil '{name}' introuvable.")
30
+ with open(path, encoding="utf-8") as f:
31
+ return json.load(f)
32
+
33
+
34
+ def _safe(name: str) -> str:
35
+ return "".join(c if c.isalnum() or c in "-_" else "_" for c in name)
core/regex_extractor.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
tests/test_agent_validation.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
tests/test_csv_writer.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests Phase 5 — csv_writer & calcul prix (format de référence CAMENGO)."""
2
+ import csv
3
+ import os
4
+ import tempfile
5
+
6
+ import pytest
7
+
8
+ from core.csv_writer import (
9
+ _fmt_decimal,
10
+ _fmt_remise,
11
+ export_ebp,
12
+ prix_achat_from_conseille,
13
+ prix_ht_from_ttc,
14
+ )
15
+
16
+
17
+ # ── Calcul prix ───────────────────────────────────────────────────────────────
18
+
19
+ def test_prix_achat_remise_45():
20
+ # 70,92 × (1 - 45%) = 70,92 × 0,55 = 39,006 → arrondi 39,01
21
+ assert prix_achat_from_conseille(70.92, 45.0) == pytest.approx(39.006, abs=0.01)
22
+
23
+
24
+ def test_prix_achat_remise_0():
25
+ assert prix_achat_from_conseille(100.0, 0.0) == pytest.approx(100.0)
26
+
27
+
28
+ def test_prix_achat_zero_conseille():
29
+ assert prix_achat_from_conseille(0.0, 45.0) == 0.0
30
+
31
+
32
+ def test_prix_ht_from_ttc_20():
33
+ assert prix_ht_from_ttc(120.0, 20.0) == pytest.approx(100.0, abs=0.01)
34
+
35
+
36
+ def test_prix_ht_from_ttc_10():
37
+ assert prix_ht_from_ttc(110.0, 10.0) == pytest.approx(100.0, abs=0.01)
38
+
39
+
40
+ # ── Formatage décimal ─────────────────────────────────────────────────────────
41
+
42
+ def test_fmt_decimal_virgule():
43
+ assert _fmt_decimal(70.92) == "70,92"
44
+
45
+
46
+ def test_fmt_decimal_no_euro():
47
+ assert "€" not in _fmt_decimal(100.0)
48
+
49
+
50
+ def test_fmt_decimal_no_percent():
51
+ assert "%" not in _fmt_decimal(100.0)
52
+
53
+
54
+ def test_fmt_decimal_empty():
55
+ assert _fmt_decimal("") == ""
56
+ assert _fmt_decimal(None) == ""
57
+
58
+
59
+ def test_fmt_remise_entier():
60
+ assert _fmt_remise(45.0) == "45"
61
+ assert _fmt_remise(45) == "45"
62
+
63
+
64
+ def test_fmt_remise_no_percent():
65
+ assert "%" not in _fmt_remise(45)
66
+
67
+
68
+ # ── Données de test (format CAMENGO) ─────────────────────────────────────────
69
+
70
+ SAMPLE_ARTICLES = [
71
+ {
72
+ "nom_dessin": "Adagio",
73
+ "reference": "3953",
74
+ "collection": "CHOREGRAPHIE",
75
+ "prix_conseille": 70.92,
76
+ "unite": "ml",
77
+ "prix_valide": True,
78
+ },
79
+ {
80
+ "nom_dessin": "Ballerine",
81
+ "reference": "3936",
82
+ "collection": "CHOREGRAPHIE",
83
+ "prix_conseille": 96.08,
84
+ "unite": "ml",
85
+ "prix_valide": True,
86
+ },
87
+ ]
88
+
89
+
90
+ # ── export_ebp — BOM, séparateur, virgule décimale ────────────────────────────
91
+
92
+ def test_bom_present():
93
+ with tempfile.TemporaryDirectory() as d:
94
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
95
+ with open(files["3_articles.csv"], "rb") as f:
96
+ assert f.read(3) == b"\xef\xbb\xbf", "BOM UTF-8 manquant"
97
+
98
+
99
+ def test_separateur_point_virgule():
100
+ with tempfile.TemporaryDirectory() as d:
101
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
102
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
103
+ first_line = f.readline()
104
+ assert ";" in first_line
105
+
106
+
107
+ def test_colonnes_format_camengo():
108
+ with tempfile.TemporaryDirectory() as d:
109
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
110
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
111
+ header = f.readline().strip()
112
+ cols = header.split(";")
113
+ assert cols[0] == "Nom de dessin"
114
+ assert cols[1] == "Référence"
115
+ assert cols[2] == "Collection"
116
+ assert "Prix d'achat HT par ml" in cols
117
+ assert "Prix conseillé HT par ml" in cols
118
+ assert "Remise" in cols
119
+
120
+
121
+ def test_decimal_virgule_dans_articles():
122
+ with tempfile.TemporaryDirectory() as d:
123
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
124
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
125
+ content = f.read()
126
+ assert "70,92" in content
127
+ assert "." not in content.replace("Nom de dessin", "") # pas de point décimal
128
+
129
+
130
+ def test_pas_de_euro_dans_articles():
131
+ with tempfile.TemporaryDirectory() as d:
132
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
133
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
134
+ content = f.read()
135
+ assert "€" not in content
136
+
137
+
138
+ def test_pas_de_percent_dans_articles():
139
+ with tempfile.TemporaryDirectory() as d:
140
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
141
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
142
+ content = f.read()
143
+ assert "%" not in content
144
+
145
+
146
+ def test_trois_fichiers_produits():
147
+ with tempfile.TemporaryDirectory() as d:
148
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
149
+ assert len(files) == 3
150
+ for name in ["1_familles_articles.csv", "2_fournisseur.csv", "3_articles.csv"]:
151
+ assert os.path.exists(files[name])
152
+
153
+
154
+ def test_remise_ecrite_sans_symbole():
155
+ with tempfile.TemporaryDirectory() as d:
156
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
157
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
158
+ reader = csv.DictReader(f, delimiter=";")
159
+ for row in reader:
160
+ assert row["Remise"] == "45"
161
+ assert "%" not in row["Remise"]
162
+
163
+
164
+ def test_prix_achat_calcule_depuis_conseille():
165
+ # Prix conseillé 70,92 × (1-45%) ≈ 38,51
166
+ with tempfile.TemporaryDirectory() as d:
167
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001", remise=45.0)
168
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
169
+ reader = csv.DictReader(f, delimiter=";")
170
+ row = next(reader)
171
+ prix_achat = float(row["Prix d'achat HT par ml"].replace(",", "."))
172
+ assert prix_achat == pytest.approx(39.006, abs=0.01)
173
+
174
+
175
+ def test_libelle_tronque_80():
176
+ articles = [{
177
+ "nom_dessin": "X" * 100,
178
+ "reference": "T001",
179
+ "collection": "TEST",
180
+ "prix_conseille": 50.0,
181
+ "unite": "ml",
182
+ }]
183
+ with tempfile.TemporaryDirectory() as d:
184
+ files = export_ebp(articles, d, "TEST", "TST001", remise=45.0)
185
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
186
+ reader = csv.DictReader(f, delimiter=";")
187
+ row = next(reader)
188
+ assert len(row["Nom de dessin"]) <= 80
189
+
190
+
191
+ def test_code_famille_dans_articles():
192
+ with tempfile.TemporaryDirectory() as d:
193
+ files = export_ebp(SAMPLE_ARTICLES, d, "CASAMANCE", "CAS001",
194
+ remise=45.0, code_famille="FFR00001")
195
+ with open(files["3_articles.csv"], encoding="utf-8-sig") as f:
196
+ reader = csv.DictReader(f, delimiter=";")
197
+ for row in reader:
198
+ assert row["Code famille"] == "FFR00001"
tests/test_new_features.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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