Spaces:
Sleeping
Sleeping
feat: pivot vers nettoyeur de CSV (sans IA)
Remplace l extracteur PDF -> CSV par un nettoyeur de CSV 100% local (pandas).
- core/cleaner.py : detection auto encodage + separateur (basee sur l en-tete),
suppression doublons / lignes-colonnes vides, trim espaces, en-tetes propres,
virgule decimale FR (preserve les dates), sortie format EBP
- app.py : endpoints POST /clean (rapport JSON) et GET /download/{id}
- static/index.html + docs : nouvelle UI nettoyeur, options en cases a cocher
- supprime core/agent|extractor|regex_extractor|profil|csv_writer, app_gradio,
anciens tests, dependances anthropic/PyMuPDF/python-dotenv
- tests/test_cleaner.py : 11 tests
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@
- .env.example +0 -1
- README.md +19 -31
- app.py +80 -134
- app_gradio.py +0 -385
- core/agent.py +0 -307
- core/cleaner.py +227 -0
- core/csv_writer.py +0 -234
- core/extractor.py +0 -184
- core/profil.py +0 -35
- core/regex_extractor.py +0 -78
- docs/index.html +11 -11
- requirements.txt +0 -3
- static/index.html +137 -255
- tests/test_agent_validation.py +0 -54
- tests/test_cleaner.py +81 -0
- tests/test_csv_writer.py +0 -198
- tests/test_new_features.py +0 -210
.env.example
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
ANTHROPIC_API_KEY=your_api_key_here
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,24 +1,28 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
#
|
| 11 |
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
-
##
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
## Installation
|
| 24 |
|
|
@@ -32,39 +36,23 @@ source .venv/bin/activate
|
|
| 32 |
pip install -r requirements.txt
|
| 33 |
```
|
| 34 |
|
| 35 |
-
Créez un fichier `.env` à partir de `.env.example` et renseignez votre clé API Anthropic :
|
| 36 |
-
|
| 37 |
-
```
|
| 38 |
-
ANTHROPIC_API_KEY=sk-ant-...
|
| 39 |
-
```
|
| 40 |
-
|
| 41 |
## Lancement
|
| 42 |
|
| 43 |
```bash
|
| 44 |
-
|
| 45 |
```
|
| 46 |
|
| 47 |
-
|
| 48 |
|
| 49 |
## Structure
|
| 50 |
|
| 51 |
```
|
| 52 |
core/
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
app.py # interface Gradio
|
| 57 |
-
docs/ # GitHub Pages landing
|
| 58 |
```
|
| 59 |
|
| 60 |
-
## Formule de calcul
|
| 61 |
-
|
| 62 |
-
```
|
| 63 |
-
PV HT = Prix TTC / (1 + marge%)
|
| 64 |
-
```
|
| 65 |
-
|
| 66 |
-
Exemple avec marge 30 % : `100 € TTC → 76,92 € HT`
|
| 67 |
-
|
| 68 |
## Licence
|
| 69 |
|
| 70 |
MIT
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Nettoyeur CSV
|
| 3 |
+
emoji: 🧹
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
+
# Nettoyeur CSV
|
| 11 |
|
| 12 |
+
Charge un fichier CSV, choisis les opérations de nettoyage et récupère un fichier propre.
|
| 13 |
+
100 % automatique, sans IA ni clé API.
|
| 14 |
|
| 15 |
+
## Opérations
|
| 16 |
|
| 17 |
+
- **Lignes & colonnes vides** — supprime les lignes/colonnes entièrement vides
|
| 18 |
+
- **Doublons** — supprime les lignes identiques en double
|
| 19 |
+
- **Espaces superflus** — nettoie les espaces en début/fin et les doubles espaces
|
| 20 |
+
- **En-têtes propres** — nettoie et dé-duplique les noms de colonnes
|
| 21 |
+
- **Virgule décimale (FR)** — convertit `1234.56` → `1234,56` et retire les séparateurs de milliers
|
| 22 |
+
- **Format EBP** — sortie séparateur `;`, encodage UTF-8 BOM, fins de ligne Windows (`\r\n`)
|
| 23 |
|
| 24 |
+
L'encodage (UTF-8, CP1252, Latin-1…) et le séparateur (`;`, `,`, tab, `|`) du fichier
|
| 25 |
+
d'entrée sont détectés automatiquement.
|
| 26 |
|
| 27 |
## Installation
|
| 28 |
|
|
|
|
| 36 |
pip install -r requirements.txt
|
| 37 |
```
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
## Lancement
|
| 40 |
|
| 41 |
```bash
|
| 42 |
+
uvicorn app:app --host 0.0.0.0 --port 7860
|
| 43 |
```
|
| 44 |
|
| 45 |
+
Puis ouvre `http://localhost:7860`.
|
| 46 |
|
| 47 |
## Structure
|
| 48 |
|
| 49 |
```
|
| 50 |
core/
|
| 51 |
+
cleaner.py # détection encodage/séparateur + nettoyage pandas
|
| 52 |
+
app.py # API FastAPI (/clean, /download)
|
| 53 |
+
static/ # interface web
|
|
|
|
|
|
|
| 54 |
```
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
## Licence
|
| 57 |
|
| 58 |
MIT
|
app.py
CHANGED
|
@@ -1,68 +1,39 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
import os
|
| 3 |
-
import shutil
|
| 4 |
import tempfile
|
|
|
|
| 5 |
import traceback
|
| 6 |
-
import uuid
|
| 7 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
|
| 9 |
-
from dotenv import load_dotenv
|
| 10 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 11 |
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
from fastapi.responses import FileResponse, JSONResponse
|
| 13 |
from fastapi.staticfiles import StaticFiles
|
| 14 |
|
| 15 |
-
from core.
|
| 16 |
-
from core.csv_writer import to_csv
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
app = FastAPI(title="PDF → CSV Agent")
|
| 21 |
app.add_middleware(
|
| 22 |
CORSMiddleware,
|
| 23 |
allow_origins=["*"],
|
| 24 |
allow_methods=["*"],
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
-
_executor = ThreadPoolExecutor(max_workers=2)
|
| 28 |
|
| 29 |
-
|
| 30 |
|
| 31 |
-
|
|
|
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
-
def
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
if not articles:
|
| 44 |
-
_jobs[job_id] = {"status": "error", "error": "Aucun article détecté dans ces pages."}
|
| 45 |
-
return
|
| 46 |
-
|
| 47 |
-
out = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
|
| 48 |
-
out.close()
|
| 49 |
-
to_csv(articles, out.name, brand)
|
| 50 |
-
_jobs[job_id] = {
|
| 51 |
-
"status": "done",
|
| 52 |
-
"result": out.name,
|
| 53 |
-
"count": len(articles),
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
except Exception as exc:
|
| 57 |
-
_jobs[job_id] = {
|
| 58 |
-
"status": "error",
|
| 59 |
-
"error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()[-500:]}",
|
| 60 |
-
}
|
| 61 |
-
finally:
|
| 62 |
-
try:
|
| 63 |
-
os.unlink(pdf_path)
|
| 64 |
-
except OSError:
|
| 65 |
-
pass
|
| 66 |
|
| 67 |
|
| 68 |
@app.get("/ping")
|
|
@@ -70,104 +41,79 @@ async def ping():
|
|
| 70 |
return {"ok": True}
|
| 71 |
|
| 72 |
|
| 73 |
-
@app.post("/preview")
|
| 74 |
-
async def preview(
|
| 75 |
-
pdf: UploadFile = File(...),
|
| 76 |
-
page_from: int = Form(1),
|
| 77 |
-
page_to: int = Form(3),
|
| 78 |
-
password: str = Form(""),
|
| 79 |
-
):
|
| 80 |
-
"""Retourne les 300 premiers caractères de chaque page pour diagnostic."""
|
| 81 |
-
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
|
| 82 |
-
shutil.copyfileobj(pdf.file, tmp)
|
| 83 |
-
pdf_path = tmp.name
|
| 84 |
-
try:
|
| 85 |
-
pages = extract_pages(pdf_path, page_from, page_to, password)
|
| 86 |
-
previews = [
|
| 87 |
-
{"page": page_from + i, "chars": len(p), "extract": p[:300]}
|
| 88 |
-
for i, p in enumerate(pages)
|
| 89 |
-
]
|
| 90 |
-
return JSONResponse({"pages": previews})
|
| 91 |
-
finally:
|
| 92 |
-
os.unlink(pdf_path)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
@app.get("/")
|
| 96 |
async def index():
|
| 97 |
return FileResponse("static/index.html")
|
| 98 |
|
| 99 |
|
| 100 |
-
@app.post("/
|
| 101 |
-
async def
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
| 108 |
):
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
loop = asyncio.get_event_loop()
|
| 138 |
-
loop.run_in_executor(
|
| 139 |
-
_executor,
|
| 140 |
-
_run_job,
|
| 141 |
-
job_id, pdf_path, page_from, page_to, default_unit, brand, password,
|
| 142 |
-
)
|
| 143 |
-
|
| 144 |
-
return JSONResponse({"job_id": job_id})
|
| 145 |
-
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
raise HTTPException(status_code=
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
return FileResponse(
|
| 167 |
-
|
| 168 |
-
filename=
|
| 169 |
media_type="text/csv; charset=utf-8",
|
| 170 |
-
headers={"X-Article-Count": str(job["count"])},
|
| 171 |
)
|
| 172 |
|
| 173 |
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import tempfile
|
| 3 |
+
import time
|
| 4 |
import traceback
|
|
|
|
|
|
|
| 5 |
|
|
|
|
| 6 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
from fastapi.responses import FileResponse, JSONResponse
|
| 9 |
from fastapi.staticfiles import StaticFiles
|
| 10 |
|
| 11 |
+
from core.cleaner import clean_csv
|
|
|
|
| 12 |
|
| 13 |
+
app = FastAPI(title="Nettoyeur CSV")
|
|
|
|
|
|
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
| 16 |
allow_origins=["*"],
|
| 17 |
allow_methods=["*"],
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
|
|
|
| 20 |
|
| 21 |
+
MAX_CSV_MB = 50
|
| 22 |
|
| 23 |
+
# Résultats temporaires : {download_id: (chemin, nom_origine, timestamp)}
|
| 24 |
+
_results: dict[str, tuple[str, str, float]] = {}
|
| 25 |
+
_RESULT_TTL = 3600 # 1 h
|
| 26 |
|
| 27 |
|
| 28 |
+
def _purge_old():
|
| 29 |
+
now = time.time()
|
| 30 |
+
for did, (path, _name, ts) in list(_results.items()):
|
| 31 |
+
if now - ts > _RESULT_TTL:
|
| 32 |
+
try:
|
| 33 |
+
os.unlink(path)
|
| 34 |
+
except OSError:
|
| 35 |
+
pass
|
| 36 |
+
_results.pop(did, None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
@app.get("/ping")
|
|
|
|
| 41 |
return {"ok": True}
|
| 42 |
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
@app.get("/")
|
| 45 |
async def index():
|
| 46 |
return FileResponse("static/index.html")
|
| 47 |
|
| 48 |
|
| 49 |
+
@app.post("/clean")
|
| 50 |
+
async def clean(
|
| 51 |
+
csv_file: UploadFile = File(...),
|
| 52 |
+
drop_empty: bool = Form(True),
|
| 53 |
+
drop_duplicates: bool = Form(True),
|
| 54 |
+
trim_whitespace: bool = Form(True),
|
| 55 |
+
normalize_headers: bool = Form(True),
|
| 56 |
+
decimal_comma: bool = Form(False),
|
| 57 |
+
ebp_format: bool = Form(False),
|
| 58 |
):
|
| 59 |
+
name = csv_file.filename or "fichier.csv"
|
| 60 |
+
if not name.lower().endswith((".csv", ".txt", ".tsv")):
|
| 61 |
+
raise HTTPException(status_code=400, detail="Le fichier doit être un .csv, .tsv ou .txt.")
|
| 62 |
+
|
| 63 |
+
raw = b""
|
| 64 |
+
chunk_size = 1024 * 1024
|
| 65 |
+
while True:
|
| 66 |
+
chunk = await csv_file.read(chunk_size)
|
| 67 |
+
if not chunk:
|
| 68 |
+
break
|
| 69 |
+
raw += chunk
|
| 70 |
+
if len(raw) > MAX_CSV_MB * 1024 * 1024:
|
| 71 |
+
raise HTTPException(
|
| 72 |
+
status_code=413,
|
| 73 |
+
detail=f"Fichier trop volumineux (max {MAX_CSV_MB} MB).",
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
if not raw.strip():
|
| 77 |
+
raise HTTPException(status_code=400, detail="Le fichier est vide.")
|
| 78 |
+
|
| 79 |
+
options = {
|
| 80 |
+
"drop_empty": drop_empty,
|
| 81 |
+
"drop_duplicates": drop_duplicates,
|
| 82 |
+
"trim_whitespace": trim_whitespace,
|
| 83 |
+
"normalize_headers": normalize_headers,
|
| 84 |
+
"decimal_comma": decimal_comma,
|
| 85 |
+
"ebp_format": ebp_format,
|
| 86 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
try:
|
| 89 |
+
cleaned, report = clean_csv(raw, options)
|
| 90 |
+
except Exception as exc: # noqa: BLE001
|
| 91 |
+
detail = f"{type(exc).__name__}: {exc}\n{traceback.format_exc()[-400:]}"
|
| 92 |
+
raise HTTPException(status_code=422, detail=detail)
|
| 93 |
+
|
| 94 |
+
_purge_old()
|
| 95 |
+
out = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
|
| 96 |
+
out.write(cleaned)
|
| 97 |
+
out.close()
|
| 98 |
+
|
| 99 |
+
download_id = os.path.splitext(os.path.basename(out.name))[0]
|
| 100 |
+
base, ext = os.path.splitext(os.path.basename(name))
|
| 101 |
+
out_name = f"{base}_nettoye{ext or '.csv'}"
|
| 102 |
+
_results[download_id] = (out.name, out_name, time.time())
|
| 103 |
+
|
| 104 |
+
return JSONResponse({"download_id": download_id, "report": report})
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@app.get("/download/{download_id}")
|
| 108 |
+
async def download(download_id: str):
|
| 109 |
+
entry = _results.get(download_id)
|
| 110 |
+
if not entry:
|
| 111 |
+
raise HTTPException(status_code=404, detail="Résultat expiré ou introuvable.")
|
| 112 |
+
path, out_name, _ts = entry
|
| 113 |
return FileResponse(
|
| 114 |
+
path,
|
| 115 |
+
filename=out_name,
|
| 116 |
media_type="text/csv; charset=utf-8",
|
|
|
|
| 117 |
)
|
| 118 |
|
| 119 |
|
app_gradio.py
DELETED
|
@@ -1,385 +0,0 @@
|
|
| 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
DELETED
|
@@ -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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
core/cleaner.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Nettoyeur de fichiers CSV — 100 % automatique, sans IA ni clé API.
|
| 3 |
+
|
| 4 |
+
Opérations disponibles (toutes optionnelles, activées par drapeau) :
|
| 5 |
+
- drop_empty : supprime les lignes et colonnes entièrement vides
|
| 6 |
+
- drop_duplicates : supprime les lignes en double
|
| 7 |
+
- trim_whitespace : enlève les espaces superflus en début/fin de cellule
|
| 8 |
+
- normalize_headers : nettoie et dé-duplique les en-têtes de colonnes
|
| 9 |
+
- decimal_comma : convertit les nombres "1234.56" / "1 234,56" → "1234,56"
|
| 10 |
+
- ebp_format : sortie au format EBP (séparateur ;, utf-8-sig, \\r\\n)
|
| 11 |
+
|
| 12 |
+
Détection automatique de l'encodage et du séparateur en entrée.
|
| 13 |
+
|
| 14 |
+
`clean_csv(raw: bytes, options: dict) -> (cleaned_bytes: bytes, report: dict)`
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import csv
|
| 19 |
+
import io
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
import pandas as pd
|
| 23 |
+
|
| 24 |
+
# ── Détection ────────────────────────────────────────────────────────────────
|
| 25 |
+
|
| 26 |
+
ENCODINGS = ("utf-8-sig", "utf-8", "cp1252", "latin-1")
|
| 27 |
+
DELIMITERS = (";", ",", "\t", "|")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def detect_encoding(raw: bytes) -> tuple[str, str]:
|
| 31 |
+
"""Renvoie (texte décodé, nom de l'encodage retenu)."""
|
| 32 |
+
for enc in ENCODINGS:
|
| 33 |
+
try:
|
| 34 |
+
return raw.decode(enc), enc
|
| 35 |
+
except (UnicodeDecodeError, LookupError):
|
| 36 |
+
continue
|
| 37 |
+
# Dernier recours : latin-1 décode toujours
|
| 38 |
+
return raw.decode("latin-1", errors="replace"), "latin-1"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Séparateur sentinelle : aucun délimiteur dans l'en-tête → fichier mono-colonne.
|
| 42 |
+
# On choisit un caractère absent du texte pour que pandas ne découpe rien.
|
| 43 |
+
SINGLE_COL = "\x00"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def detect_delimiter(text: str) -> str:
|
| 47 |
+
"""
|
| 48 |
+
Devine le séparateur de colonnes en se basant d'abord sur la ligne d'en-tête,
|
| 49 |
+
pour éviter de découper à tort un fichier mono-colonne dont les valeurs
|
| 50 |
+
contiennent des virgules (ex. « 1.234,50 »).
|
| 51 |
+
"""
|
| 52 |
+
lines = [l for l in text.splitlines() if l.strip()][:20]
|
| 53 |
+
if not lines:
|
| 54 |
+
return ","
|
| 55 |
+
header = lines[0]
|
| 56 |
+
present = [d for d in DELIMITERS if d in header]
|
| 57 |
+
if not present:
|
| 58 |
+
return SINGLE_COL
|
| 59 |
+
# Parmi les délimiteurs présents dans l'en-tête, on garde celui dont le
|
| 60 |
+
# nombre d'occurrences est le plus constant ligne à ligne.
|
| 61 |
+
def score(d: str) -> tuple[int, int]:
|
| 62 |
+
hc = header.count(d)
|
| 63 |
+
consistent = sum(1 for l in lines if l.count(d) == hc)
|
| 64 |
+
return (consistent, hc)
|
| 65 |
+
|
| 66 |
+
return max(present, key=score)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ── Helpers de normalisation ───────────────────────────────────────────────────
|
| 70 |
+
|
| 71 |
+
# Nombre : partie entiere simple OU groupee par milliers (espace/point/virgule),
|
| 72 |
+
# suivie d'une partie decimale optionnelle. Exclut les dates type 01.02.2024.
|
| 73 |
+
_NUM_RE = re.compile(
|
| 74 |
+
r"^\s*[-+]?"
|
| 75 |
+
r"(?:\d{1,3}(?:[ .,]\d{3})+|\d+)"
|
| 76 |
+
r"(?:[.,]\d+)?"
|
| 77 |
+
r"\s*$"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _looks_numeric(value: str) -> bool:
|
| 82 |
+
return bool(_NUM_RE.match(value)) and any(c.isdigit() for c in value)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _to_decimal_comma(value: str) -> str:
|
| 86 |
+
"""Normalise un nombre vers la virgule décimale française, sans séparateur de milliers."""
|
| 87 |
+
v = value.strip().replace(" ", " ")
|
| 88 |
+
# Retire les espaces utilisés comme séparateur de milliers
|
| 89 |
+
v = v.replace(" ", "")
|
| 90 |
+
if "," in v and "." in v:
|
| 91 |
+
# Le dernier symbole rencontré est le séparateur décimal
|
| 92 |
+
if v.rfind(",") > v.rfind("."):
|
| 93 |
+
v = v.replace(".", "") # points = milliers
|
| 94 |
+
else:
|
| 95 |
+
v = v.replace(",", "") # virgules = milliers
|
| 96 |
+
v = v.replace(".", ",")
|
| 97 |
+
else:
|
| 98 |
+
v = v.replace(".", ",")
|
| 99 |
+
return v
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _dedupe_headers(headers: list[str]) -> list[str]:
|
| 103 |
+
seen: dict[str, int] = {}
|
| 104 |
+
out: list[str] = []
|
| 105 |
+
for h in headers:
|
| 106 |
+
h = (h or "").strip()
|
| 107 |
+
h = re.sub(r"\s+", " ", h)
|
| 108 |
+
if not h:
|
| 109 |
+
h = "colonne"
|
| 110 |
+
if h in seen:
|
| 111 |
+
seen[h] += 1
|
| 112 |
+
out.append(f"{h}_{seen[h]}")
|
| 113 |
+
else:
|
| 114 |
+
seen[h] = 0
|
| 115 |
+
out.append(h)
|
| 116 |
+
return out
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# ── Nettoyage principal ─────────────────────────────────────────────────────────
|
| 120 |
+
|
| 121 |
+
def clean_csv(raw: bytes, options: dict) -> tuple[bytes, dict]:
|
| 122 |
+
text, enc_in = detect_encoding(raw)
|
| 123 |
+
delim_in = detect_delimiter(text)
|
| 124 |
+
|
| 125 |
+
df = pd.read_csv(
|
| 126 |
+
io.StringIO(text),
|
| 127 |
+
sep=delim_in,
|
| 128 |
+
dtype=str,
|
| 129 |
+
keep_default_na=False,
|
| 130 |
+
engine="python",
|
| 131 |
+
on_bad_lines="skip",
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def _sep_label(d: str) -> str:
|
| 135 |
+
return {"\t": "tabulation", SINGLE_COL: "aucun (1 colonne)"}.get(d, d)
|
| 136 |
+
|
| 137 |
+
report: dict = {
|
| 138 |
+
"encodage_detecte": enc_in,
|
| 139 |
+
"separateur_detecte": _sep_label(delim_in),
|
| 140 |
+
"lignes_initiales": int(len(df)),
|
| 141 |
+
"colonnes_initiales": int(df.shape[1]),
|
| 142 |
+
"actions": [],
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
def log(msg: str):
|
| 146 |
+
report["actions"].append(msg)
|
| 147 |
+
|
| 148 |
+
# 1. Espaces superflus
|
| 149 |
+
if options.get("trim_whitespace"):
|
| 150 |
+
df = df.apply(lambda col: col.map(
|
| 151 |
+
lambda x: re.sub(r"\s+", " ", x).strip() if isinstance(x, str) else x))
|
| 152 |
+
log("Espaces superflus supprimés dans toutes les cellules.")
|
| 153 |
+
|
| 154 |
+
# 2. En-têtes normalisés
|
| 155 |
+
if options.get("normalize_headers"):
|
| 156 |
+
new_cols = _dedupe_headers([str(c) for c in df.columns])
|
| 157 |
+
if list(df.columns) != new_cols:
|
| 158 |
+
log(f"En-têtes nettoyés ({df.shape[1]} colonnes).")
|
| 159 |
+
df.columns = new_cols
|
| 160 |
+
|
| 161 |
+
# 3. Lignes / colonnes vides
|
| 162 |
+
if options.get("drop_empty"):
|
| 163 |
+
before_rows = len(df)
|
| 164 |
+
# Une cellule "vide" = chaîne vide après strip
|
| 165 |
+
mask_nonempty_row = df.apply(
|
| 166 |
+
lambda r: any(str(v).strip() for v in r), axis=1)
|
| 167 |
+
df = df[mask_nonempty_row]
|
| 168 |
+
removed_rows = before_rows - len(df)
|
| 169 |
+
|
| 170 |
+
before_cols = df.shape[1]
|
| 171 |
+
nonempty_cols = [c for c in df.columns
|
| 172 |
+
if df[c].map(lambda x: bool(str(x).strip())).any()]
|
| 173 |
+
df = df[nonempty_cols]
|
| 174 |
+
removed_cols = before_cols - df.shape[1]
|
| 175 |
+
|
| 176 |
+
if removed_rows:
|
| 177 |
+
log(f"{removed_rows} ligne(s) vide(s) supprimée(s).")
|
| 178 |
+
if removed_cols:
|
| 179 |
+
log(f"{removed_cols} colonne(s) vide(s) supprimée(s).")
|
| 180 |
+
|
| 181 |
+
# 4. Doublons
|
| 182 |
+
if options.get("drop_duplicates"):
|
| 183 |
+
before = len(df)
|
| 184 |
+
df = df.drop_duplicates()
|
| 185 |
+
removed = before - len(df)
|
| 186 |
+
if removed:
|
| 187 |
+
log(f"{removed} ligne(s) en double supprimée(s).")
|
| 188 |
+
|
| 189 |
+
# 5. Décimales en virgule française
|
| 190 |
+
if options.get("decimal_comma"):
|
| 191 |
+
converted = 0
|
| 192 |
+
|
| 193 |
+
def conv(x):
|
| 194 |
+
nonlocal converted
|
| 195 |
+
if isinstance(x, str) and _looks_numeric(x):
|
| 196 |
+
new = _to_decimal_comma(x)
|
| 197 |
+
if new != x:
|
| 198 |
+
converted += 1
|
| 199 |
+
return new
|
| 200 |
+
return x
|
| 201 |
+
|
| 202 |
+
df = df.apply(lambda col: col.map(conv))
|
| 203 |
+
if converted:
|
| 204 |
+
log(f"{converted} valeur(s) numérique(s) converties en virgule décimale.")
|
| 205 |
+
|
| 206 |
+
# ── Écriture ──────────────────────────────────────────────────────────────
|
| 207 |
+
ebp = options.get("ebp_format")
|
| 208 |
+
if ebp or delim_in in ("\t", SINGLE_COL):
|
| 209 |
+
out_sep = ";" # EBP, tabulation ou mono-colonne → séparateur sûr
|
| 210 |
+
else:
|
| 211 |
+
out_sep = delim_in
|
| 212 |
+
out_enc = "utf-8-sig"
|
| 213 |
+
line_terminator = "\r\n" if ebp else "\n"
|
| 214 |
+
|
| 215 |
+
buf = io.StringIO()
|
| 216 |
+
df.to_csv(buf, sep=out_sep, index=False, lineterminator=line_terminator,
|
| 217 |
+
quoting=csv.QUOTE_MINIMAL)
|
| 218 |
+
cleaned = buf.getvalue().encode(out_enc)
|
| 219 |
+
|
| 220 |
+
report["lignes_finales"] = int(len(df))
|
| 221 |
+
report["colonnes_finales"] = int(df.shape[1])
|
| 222 |
+
report["separateur_sortie"] = out_sep
|
| 223 |
+
report["encodage_sortie"] = out_enc
|
| 224 |
+
if not report["actions"]:
|
| 225 |
+
report["actions"].append("Aucune modification — le fichier était déjà propre.")
|
| 226 |
+
|
| 227 |
+
return cleaned, report
|
core/csv_writer.py
DELETED
|
@@ -1,234 +0,0 @@
|
|
| 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
DELETED
|
@@ -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)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
core/profil.py
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 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
DELETED
|
@@ -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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8" />
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
-
<title>
|
| 7 |
<style>
|
| 8 |
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 9 |
body {
|
|
@@ -56,22 +56,22 @@
|
|
| 56 |
</head>
|
| 57 |
<body>
|
| 58 |
<div class="card">
|
| 59 |
-
<h1>
|
| 60 |
-
<a class="badge" href="https://github.com/boutique-oss/convertionpdfcsv/releases">
|
| 61 |
|
| 62 |
<p>
|
| 63 |
-
Outil open-source qui
|
| 64 |
-
|
| 65 |
-
|
| 66 |
</p>
|
| 67 |
|
| 68 |
<p><strong>Fonctionnalités :</strong></p>
|
| 69 |
<ul>
|
| 70 |
-
<li>
|
| 71 |
-
<li>
|
| 72 |
-
<li>
|
| 73 |
-
<li>
|
| 74 |
-
<li>
|
| 75 |
</ul>
|
| 76 |
|
| 77 |
<div class="actions">
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8" />
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<title>Nettoyeur CSV</title>
|
| 7 |
<style>
|
| 8 |
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 9 |
body {
|
|
|
|
| 56 |
</head>
|
| 57 |
<body>
|
| 58 |
<div class="card">
|
| 59 |
+
<h1>Nettoyeur CSV</h1>
|
| 60 |
+
<a class="badge" href="https://github.com/boutique-oss/convertionpdfcsv/releases">v2.0.0</a>
|
| 61 |
|
| 62 |
<p>
|
| 63 |
+
Outil open-source qui nettoie automatiquement vos fichiers CSV : doublons,
|
| 64 |
+
lignes et colonnes vides, espaces superflus, en-têtes brouillons, encodage
|
| 65 |
+
et séparateurs détectés à la volée. 100 % local, sans IA ni clé API.
|
| 66 |
</p>
|
| 67 |
|
| 68 |
<p><strong>Fonctionnalités :</strong></p>
|
| 69 |
<ul>
|
| 70 |
+
<li>Détection auto de l'encodage (UTF-8, CP1252, Latin-1…) et du séparateur</li>
|
| 71 |
+
<li>Suppression des doublons et des lignes/colonnes vides</li>
|
| 72 |
+
<li>Nettoyage des espaces superflus et des en-têtes de colonnes</li>
|
| 73 |
+
<li>Conversion des nombres en virgule décimale française</li>
|
| 74 |
+
<li>Export au format EBP (séparateur « ; », UTF-8 BOM, fins de ligne Windows)</li>
|
| 75 |
</ul>
|
| 76 |
|
| 77 |
<div class="actions">
|
requirements.txt
CHANGED
|
@@ -1,7 +1,4 @@
|
|
| 1 |
-
anthropic>=0.40.0
|
| 2 |
fastapi>=0.110.0
|
| 3 |
uvicorn[standard]>=0.29.0
|
| 4 |
python-multipart>=0.0.9
|
| 5 |
pandas>=2.0.0
|
| 6 |
-
PyMuPDF>=1.24.0
|
| 7 |
-
python-dotenv>=1.0.0
|
|
|
|
|
|
|
| 1 |
fastapi>=0.110.0
|
| 2 |
uvicorn[standard]>=0.29.0
|
| 3 |
python-multipart>=0.0.9
|
| 4 |
pandas>=2.0.0
|
|
|
|
|
|
static/index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8" />
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
-
<title>
|
| 7 |
<style>
|
| 8 |
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 9 |
|
|
@@ -30,10 +30,7 @@
|
|
| 30 |
padding: 2rem 1rem 4rem;
|
| 31 |
}
|
| 32 |
|
| 33 |
-
header {
|
| 34 |
-
text-align: center;
|
| 35 |
-
margin-bottom: 2.5rem;
|
| 36 |
-
}
|
| 37 |
header h1 {
|
| 38 |
font-size: 2.2rem;
|
| 39 |
font-weight: 700;
|
|
@@ -53,7 +50,6 @@
|
|
| 53 |
max-width: 680px;
|
| 54 |
}
|
| 55 |
|
| 56 |
-
/* Drop zone */
|
| 57 |
.drop-zone {
|
| 58 |
border: 2px dashed var(--border);
|
| 59 |
border-radius: 12px;
|
|
@@ -75,212 +71,136 @@
|
|
| 75 |
.drop-zone .label { font-size: .95rem; color: var(--muted); }
|
| 76 |
.drop-zone .label strong { color: var(--accent); }
|
| 77 |
.drop-zone .file-name {
|
| 78 |
-
margin-top: .75rem;
|
| 79 |
-
font-size: .85rem;
|
| 80 |
-
color: var(--success);
|
| 81 |
-
font-weight: 600;
|
| 82 |
}
|
| 83 |
|
| 84 |
-
|
| 85 |
-
.
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
margin-bottom:
|
| 90 |
-
}
|
| 91 |
-
@media (max-width: 480px) { .form-grid { grid-template-columns: 1fr; } }
|
| 92 |
-
|
| 93 |
-
label {
|
| 94 |
-
display: flex;
|
| 95 |
-
flex-direction: column;
|
| 96 |
-
gap: .4rem;
|
| 97 |
-
font-size: .85rem;
|
| 98 |
-
color: var(--muted);
|
| 99 |
-
font-weight: 500;
|
| 100 |
-
}
|
| 101 |
-
label span { color: var(--text); font-size: .8rem; }
|
| 102 |
-
|
| 103 |
-
input[type="number"], select {
|
| 104 |
-
background: var(--bg);
|
| 105 |
-
border: 1px solid var(--border);
|
| 106 |
-
border-radius: 8px;
|
| 107 |
-
color: var(--text);
|
| 108 |
-
padding: .6rem .8rem;
|
| 109 |
-
font-size: .95rem;
|
| 110 |
-
outline: none;
|
| 111 |
-
transition: border-color .2s;
|
| 112 |
-
width: 100%;
|
| 113 |
}
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
/* Range slider */
|
| 117 |
-
.range-row {
|
| 118 |
-
display: flex;
|
| 119 |
-
align-items: center;
|
| 120 |
-
gap: .75rem;
|
| 121 |
-
}
|
| 122 |
-
input[type="range"] {
|
| 123 |
-
flex: 1;
|
| 124 |
-
accent-color: var(--accent);
|
| 125 |
-
}
|
| 126 |
-
.range-val {
|
| 127 |
-
min-width: 2.5rem;
|
| 128 |
-
text-align: right;
|
| 129 |
-
font-size: .9rem;
|
| 130 |
-
color: var(--accent);
|
| 131 |
-
font-weight: 600;
|
| 132 |
-
}
|
| 133 |
-
|
| 134 |
-
/* Button */
|
| 135 |
button[type="submit"] {
|
| 136 |
-
width: 100%;
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
color: #fff;
|
| 140 |
-
border: none;
|
| 141 |
-
border-radius: 10px;
|
| 142 |
-
font-size: 1rem;
|
| 143 |
-
font-weight: 600;
|
| 144 |
-
cursor: pointer;
|
| 145 |
-
transition: background .2s, opacity .2s;
|
| 146 |
}
|
| 147 |
button[type="submit"]:hover:not(:disabled) { background: var(--accent-hover); }
|
| 148 |
button[type="submit"]:disabled { opacity: .5; cursor: not-allowed; }
|
| 149 |
|
| 150 |
-
|
| 151 |
-
.progress-wrap {
|
| 152 |
-
margin-top: 1.25rem;
|
| 153 |
-
display: none;
|
| 154 |
-
}
|
| 155 |
.progress-wrap.visible { display: block; }
|
| 156 |
-
.progress-bar-bg {
|
| 157 |
-
|
| 158 |
-
border-radius: 999px;
|
| 159 |
-
height: 6px;
|
| 160 |
-
overflow: hidden;
|
| 161 |
-
margin-bottom: .5rem;
|
| 162 |
-
}
|
| 163 |
-
.progress-bar {
|
| 164 |
-
height: 100%;
|
| 165 |
-
background: linear-gradient(90deg, var(--accent), #a78bfa);
|
| 166 |
-
border-radius: 999px;
|
| 167 |
-
width: 0%;
|
| 168 |
-
transition: width .4s ease;
|
| 169 |
-
}
|
| 170 |
.progress-label { font-size: .83rem; color: var(--muted); text-align: center; }
|
| 171 |
|
| 172 |
-
|
| 173 |
-
.result {
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
}
|
| 179 |
-
.result.success {
|
| 180 |
-
display: flex;
|
| 181 |
-
align-items: center;
|
| 182 |
-
justify-content: space-between;
|
| 183 |
-
background: rgba(16,185,129,.1);
|
| 184 |
-
border: 1px solid rgba(16,185,129,.3);
|
| 185 |
-
}
|
| 186 |
-
.result.error {
|
| 187 |
-
display: block;
|
| 188 |
-
background: rgba(239,68,68,.1);
|
| 189 |
-
border: 1px solid rgba(239,68,68,.3);
|
| 190 |
-
color: var(--error);
|
| 191 |
-
font-size: .88rem;
|
| 192 |
-
}
|
| 193 |
-
.result-text { font-size: .9rem; color: var(--success); }
|
| 194 |
-
.result-text strong { font-size: 1.05rem; }
|
| 195 |
.download-btn {
|
| 196 |
-
padding: .
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
border: none;
|
| 200 |
-
border-radius: 8px;
|
| 201 |
-
font-size: .85rem;
|
| 202 |
-
font-weight: 600;
|
| 203 |
-
cursor: pointer;
|
| 204 |
-
text-decoration: none;
|
| 205 |
-
transition: opacity .2s;
|
| 206 |
}
|
| 207 |
.download-btn:hover { opacity: .85; }
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
| 215 |
footer a { color: var(--accent); text-decoration: none; }
|
| 216 |
</style>
|
| 217 |
</head>
|
| 218 |
<body>
|
| 219 |
|
| 220 |
<header>
|
| 221 |
-
<h1>
|
| 222 |
-
<p>
|
| 223 |
</header>
|
| 224 |
|
| 225 |
<div class="card">
|
| 226 |
<form id="form">
|
| 227 |
|
| 228 |
-
<!-- Upload zone -->
|
| 229 |
<div class="drop-zone" id="dropZone">
|
| 230 |
-
<input type="file" name="
|
| 231 |
-
<div class="icon">
|
| 232 |
-
<div class="label">Glisse ton
|
| 233 |
<div class="file-name" id="fileName"></div>
|
| 234 |
</div>
|
| 235 |
|
| 236 |
-
<
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
<
|
| 241 |
-
|
| 242 |
-
<span class="
|
| 243 |
-
|
|
|
|
| 244 |
</label>
|
| 245 |
|
| 246 |
-
<label>
|
| 247 |
-
|
| 248 |
-
<
|
| 249 |
-
<
|
| 250 |
-
<span class="
|
| 251 |
-
</
|
| 252 |
</label>
|
| 253 |
|
| 254 |
-
<label>
|
| 255 |
-
|
| 256 |
-
<
|
| 257 |
-
<
|
| 258 |
-
<
|
| 259 |
-
|
| 260 |
-
<option value="Rouleau">Rouleau</option>
|
| 261 |
-
</select>
|
| 262 |
</label>
|
| 263 |
|
| 264 |
-
<label
|
| 265 |
-
|
| 266 |
-
<
|
|
|
|
|
|
|
|
|
|
| 267 |
</label>
|
| 268 |
|
| 269 |
-
<label
|
| 270 |
-
|
| 271 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
</label>
|
| 273 |
</div>
|
| 274 |
|
| 275 |
-
<button type="submit" id="submitBtn">
|
| 276 |
|
| 277 |
-
<!-- Progress -->
|
| 278 |
<div class="progress-wrap" id="progressWrap">
|
| 279 |
<div class="progress-bar-bg"><div class="progress-bar" id="progressBar"></div></div>
|
| 280 |
-
<div class="progress-label" id="progressLabel">
|
| 281 |
</div>
|
| 282 |
|
| 283 |
-
<!-- Result -->
|
| 284 |
<div class="result" id="result"></div>
|
| 285 |
|
| 286 |
</form>
|
|
@@ -288,25 +208,16 @@
|
|
| 288 |
|
| 289 |
<footer>
|
| 290 |
<a href="https://github.com/boutique-oss/convertionpdfcsv" target="_blank">Code source</a>
|
| 291 |
-
·
|
| 292 |
</footer>
|
| 293 |
|
| 294 |
<script>
|
| 295 |
-
// Sliders
|
| 296 |
-
const pageFrom = document.getElementById('pageFrom');
|
| 297 |
-
const pageTo = document.getElementById('pageTo');
|
| 298 |
-
const pfv = document.getElementById('pageFromVal');
|
| 299 |
-
const ptv = document.getElementById('pageToVal');
|
| 300 |
-
pageFrom.addEventListener('input', () => pfv.textContent = pageFrom.value);
|
| 301 |
-
pageTo.addEventListener('input', () => ptv.textContent = pageTo.value);
|
| 302 |
-
|
| 303 |
-
// Drop zone
|
| 304 |
const dropZone = document.getElementById('dropZone');
|
| 305 |
-
const
|
| 306 |
const fileName = document.getElementById('fileName');
|
| 307 |
|
| 308 |
-
|
| 309 |
-
if (
|
| 310 |
});
|
| 311 |
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
|
| 312 |
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
|
|
@@ -314,106 +225,77 @@
|
|
| 314 |
e.preventDefault();
|
| 315 |
dropZone.classList.remove('drag-over');
|
| 316 |
const f = e.dataTransfer.files[0];
|
| 317 |
-
if (f
|
| 318 |
const dt = new DataTransfer();
|
| 319 |
dt.items.add(f);
|
| 320 |
-
|
| 321 |
fileName.textContent = f.name;
|
| 322 |
}
|
| 323 |
});
|
| 324 |
|
| 325 |
-
|
| 326 |
-
const form = document.getElementById('form');
|
| 327 |
const submitBtn = document.getElementById('submitBtn');
|
| 328 |
const progressWrap = document.getElementById('progressWrap');
|
| 329 |
-
const progressBar
|
| 330 |
-
const progressLbl
|
| 331 |
-
const result
|
| 332 |
|
| 333 |
form.addEventListener('submit', async e => {
|
| 334 |
e.preventDefault();
|
| 335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
result.className = 'result';
|
| 337 |
result.innerHTML = '';
|
| 338 |
progressWrap.classList.add('visible');
|
| 339 |
-
progressBar.style.width = '
|
| 340 |
progressLbl.textContent = 'Envoi du fichier…';
|
| 341 |
submitBtn.disabled = true;
|
| 342 |
|
| 343 |
try {
|
| 344 |
const base = window.location.origin;
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
throw new Error(`Erreur réseau lors de l'envoi : ${netErr.message}`);
|
| 359 |
-
}
|
| 360 |
-
if (!uploadResp.ok) {
|
| 361 |
let detail = 'Erreur serveur';
|
| 362 |
-
try { detail = (await
|
| 363 |
-
throw new Error(`
|
| 364 |
}
|
| 365 |
-
const {
|
| 366 |
-
|
| 367 |
-
progressBar.style.width = '
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
// 2. Polling toutes les 3s jusqu'à done/error
|
| 371 |
-
let pct = 20;
|
| 372 |
-
const ticker = setInterval(() => {
|
| 373 |
-
if (pct < 90) { pct += 2; progressBar.style.width = pct + '%'; }
|
| 374 |
-
}, 1500);
|
| 375 |
-
|
| 376 |
-
await new Promise((resolve, reject) => {
|
| 377 |
-
const started = Date.now();
|
| 378 |
-
const poll = setInterval(async () => {
|
| 379 |
-
if (Date.now() - started > 600_000) {
|
| 380 |
-
clearInterval(poll); clearInterval(ticker);
|
| 381 |
-
reject(new Error('Délai dépassé (10 min). Essaie avec moins de pages.'));
|
| 382 |
-
return;
|
| 383 |
-
}
|
| 384 |
-
try {
|
| 385 |
-
const s = await fetch(`${base}/status/${job_id}`);
|
| 386 |
-
const data = await s.json();
|
| 387 |
-
if (data.status === 'done') {
|
| 388 |
-
clearInterval(poll); clearInterval(ticker);
|
| 389 |
-
resolve(data);
|
| 390 |
-
} else if (data.status === 'error') {
|
| 391 |
-
clearInterval(poll); clearInterval(ticker);
|
| 392 |
-
reject(new Error(data.error));
|
| 393 |
-
} else if (data.progress) {
|
| 394 |
-
const [done, total] = data.progress.split('/').map(Number);
|
| 395 |
-
const pct = 20 + Math.round((done / total) * 75);
|
| 396 |
-
progressBar.style.width = pct + '%';
|
| 397 |
-
progressLbl.textContent = `Batch ${done}/${total} traité…`;
|
| 398 |
-
}
|
| 399 |
-
} catch (e) { /* réseau temporaire, on réessaie */ }
|
| 400 |
-
}, 3000);
|
| 401 |
-
}).then(async (data) => {
|
| 402 |
-
progressBar.style.width = '100%';
|
| 403 |
-
progressWrap.classList.remove('visible');
|
| 404 |
-
|
| 405 |
-
// 3. Téléchargement du CSV
|
| 406 |
-
const dlResp = await fetch(`${base}/download/${job_id}`);
|
| 407 |
-
const blob = await dlResp.blob();
|
| 408 |
-
const url = URL.createObjectURL(blob);
|
| 409 |
-
|
| 410 |
-
result.className = 'result success';
|
| 411 |
-
result.innerHTML = `
|
| 412 |
-
<div class="result-text"><strong>${data.count}</strong> articles extraits</div>
|
| 413 |
-
<a class="download-btn" href="${url}" download="articles.csv">Télécharger CSV</a>
|
| 414 |
-
`;
|
| 415 |
-
});
|
| 416 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
} catch (err) {
|
| 418 |
progressWrap.classList.remove('visible');
|
| 419 |
result.className = 'result error';
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8" />
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<title>Nettoyeur CSV</title>
|
| 7 |
<style>
|
| 8 |
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 9 |
|
|
|
|
| 30 |
padding: 2rem 1rem 4rem;
|
| 31 |
}
|
| 32 |
|
| 33 |
+
header { text-align: center; margin-bottom: 2.5rem; }
|
|
|
|
|
|
|
|
|
|
| 34 |
header h1 {
|
| 35 |
font-size: 2.2rem;
|
| 36 |
font-weight: 700;
|
|
|
|
| 50 |
max-width: 680px;
|
| 51 |
}
|
| 52 |
|
|
|
|
| 53 |
.drop-zone {
|
| 54 |
border: 2px dashed var(--border);
|
| 55 |
border-radius: 12px;
|
|
|
|
| 71 |
.drop-zone .label { font-size: .95rem; color: var(--muted); }
|
| 72 |
.drop-zone .label strong { color: var(--accent); }
|
| 73 |
.drop-zone .file-name {
|
| 74 |
+
margin-top: .75rem; font-size: .85rem; color: var(--success); font-weight: 600;
|
|
|
|
|
|
|
|
|
|
| 75 |
}
|
| 76 |
|
| 77 |
+
.options { margin-bottom: 1.5rem; }
|
| 78 |
+
.options h3 { font-size: .85rem; color: var(--muted); font-weight: 600; margin-bottom: .75rem; text-transform: uppercase; letter-spacing: .04em; }
|
| 79 |
+
.opt {
|
| 80 |
+
display: flex; align-items: flex-start; gap: .65rem;
|
| 81 |
+
padding: .7rem .85rem; border: 1px solid var(--border); border-radius: 10px;
|
| 82 |
+
margin-bottom: .6rem; cursor: pointer; transition: border-color .2s, background .2s;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
}
|
| 84 |
+
.opt:hover { border-color: var(--accent); background: rgba(99,102,241,.04); }
|
| 85 |
+
.opt input { margin-top: .2rem; width: 1.05rem; height: 1.05rem; accent-color: var(--accent); cursor: pointer; }
|
| 86 |
+
.opt .opt-text { display: flex; flex-direction: column; gap: .15rem; }
|
| 87 |
+
.opt .opt-title { font-size: .92rem; color: var(--text); font-weight: 500; }
|
| 88 |
+
.opt .opt-desc { font-size: .78rem; color: var(--muted); }
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
button[type="submit"] {
|
| 91 |
+
width: 100%; padding: .85rem; background: var(--accent); color: #fff;
|
| 92 |
+
border: none; border-radius: 10px; font-size: 1rem; font-weight: 600;
|
| 93 |
+
cursor: pointer; transition: background .2s, opacity .2s;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
}
|
| 95 |
button[type="submit"]:hover:not(:disabled) { background: var(--accent-hover); }
|
| 96 |
button[type="submit"]:disabled { opacity: .5; cursor: not-allowed; }
|
| 97 |
|
| 98 |
+
.progress-wrap { margin-top: 1.25rem; display: none; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
.progress-wrap.visible { display: block; }
|
| 100 |
+
.progress-bar-bg { background: var(--border); border-radius: 999px; height: 6px; overflow: hidden; margin-bottom: .5rem; }
|
| 101 |
+
.progress-bar { height: 100%; background: linear-gradient(90deg, var(--accent), #a78bfa); border-radius: 999px; width: 0%; transition: width .4s ease; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
.progress-label { font-size: .83rem; color: var(--muted); text-align: center; }
|
| 103 |
|
| 104 |
+
.result { margin-top: 1.25rem; border-radius: 10px; padding: 1rem 1.25rem; display: none; }
|
| 105 |
+
.result.success { display: block; background: rgba(16,185,129,.08); border: 1px solid rgba(16,185,129,.3); }
|
| 106 |
+
.result.error { display: block; background: rgba(239,68,68,.1); border: 1px solid rgba(239,68,68,.3); color: var(--error); font-size: .88rem; white-space: pre-wrap; }
|
| 107 |
+
|
| 108 |
+
.result-head { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: .9rem; }
|
| 109 |
+
.result-head .summary { font-size: .9rem; color: var(--success); }
|
| 110 |
+
.result-head .summary strong { font-size: 1.05rem; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
.download-btn {
|
| 112 |
+
padding: .55rem 1.1rem; background: var(--success); color: #fff; border: none;
|
| 113 |
+
border-radius: 8px; font-size: .85rem; font-weight: 600; cursor: pointer;
|
| 114 |
+
text-decoration: none; transition: opacity .2s; white-space: nowrap;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
}
|
| 116 |
.download-btn:hover { opacity: .85; }
|
| 117 |
|
| 118 |
+
.report-meta { display: flex; flex-wrap: wrap; gap: .4rem .9rem; font-size: .78rem; color: var(--muted); margin-bottom: .8rem; }
|
| 119 |
+
.report-meta span strong { color: var(--text); }
|
| 120 |
+
.actions-list { list-style: none; font-size: .85rem; color: var(--text); }
|
| 121 |
+
.actions-list li { padding: .25rem 0 .25rem 1.2rem; position: relative; }
|
| 122 |
+
.actions-list li::before { content: "✓"; position: absolute; left: 0; color: var(--success); }
|
| 123 |
+
|
| 124 |
+
footer { margin-top: 2rem; font-size: .78rem; color: var(--muted); text-align: center; }
|
| 125 |
footer a { color: var(--accent); text-decoration: none; }
|
| 126 |
</style>
|
| 127 |
</head>
|
| 128 |
<body>
|
| 129 |
|
| 130 |
<header>
|
| 131 |
+
<h1>Nettoyeur CSV</h1>
|
| 132 |
+
<p>Charge un CSV, choisis le nettoyage, récupère un fichier propre.</p>
|
| 133 |
</header>
|
| 134 |
|
| 135 |
<div class="card">
|
| 136 |
<form id="form">
|
| 137 |
|
|
|
|
| 138 |
<div class="drop-zone" id="dropZone">
|
| 139 |
+
<input type="file" name="csv_file" id="csvInput" accept=".csv,.tsv,.txt" required />
|
| 140 |
+
<div class="icon">🧹</div>
|
| 141 |
+
<div class="label">Glisse ton CSV ici ou <strong>clique pour choisir</strong></div>
|
| 142 |
<div class="file-name" id="fileName"></div>
|
| 143 |
</div>
|
| 144 |
|
| 145 |
+
<div class="options">
|
| 146 |
+
<h3>Opérations de nettoyage</h3>
|
| 147 |
+
|
| 148 |
+
<label class="opt">
|
| 149 |
+
<input type="checkbox" name="drop_empty" checked />
|
| 150 |
+
<span class="opt-text">
|
| 151 |
+
<span class="opt-title">Lignes & colonnes vides</span>
|
| 152 |
+
<span class="opt-desc">Supprime les lignes et colonnes entièrement vides.</span>
|
| 153 |
+
</span>
|
| 154 |
</label>
|
| 155 |
|
| 156 |
+
<label class="opt">
|
| 157 |
+
<input type="checkbox" name="drop_duplicates" checked />
|
| 158 |
+
<span class="opt-text">
|
| 159 |
+
<span class="opt-title">Doublons</span>
|
| 160 |
+
<span class="opt-desc">Supprime les lignes identiques en double.</span>
|
| 161 |
+
</span>
|
| 162 |
</label>
|
| 163 |
|
| 164 |
+
<label class="opt">
|
| 165 |
+
<input type="checkbox" name="trim_whitespace" checked />
|
| 166 |
+
<span class="opt-text">
|
| 167 |
+
<span class="opt-title">Espaces superflus</span>
|
| 168 |
+
<span class="opt-desc">Nettoie les espaces en début/fin et les doubles espaces.</span>
|
| 169 |
+
</span>
|
|
|
|
|
|
|
| 170 |
</label>
|
| 171 |
|
| 172 |
+
<label class="opt">
|
| 173 |
+
<input type="checkbox" name="normalize_headers" checked />
|
| 174 |
+
<span class="opt-text">
|
| 175 |
+
<span class="opt-title">En-têtes propres</span>
|
| 176 |
+
<span class="opt-desc">Nettoie et dé-duplique les noms de colonnes.</span>
|
| 177 |
+
</span>
|
| 178 |
</label>
|
| 179 |
|
| 180 |
+
<label class="opt">
|
| 181 |
+
<input type="checkbox" name="decimal_comma" />
|
| 182 |
+
<span class="opt-text">
|
| 183 |
+
<span class="opt-title">Virgule décimale (FR)</span>
|
| 184 |
+
<span class="opt-desc">Convertit 1234.56 → 1234,56 et retire les séparateurs de milliers.</span>
|
| 185 |
+
</span>
|
| 186 |
+
</label>
|
| 187 |
+
|
| 188 |
+
<label class="opt">
|
| 189 |
+
<input type="checkbox" name="ebp_format" />
|
| 190 |
+
<span class="opt-text">
|
| 191 |
+
<span class="opt-title">Format EBP</span>
|
| 192 |
+
<span class="opt-desc">Sortie séparateur « ; », encodage UTF-8 BOM, fins de ligne Windows.</span>
|
| 193 |
+
</span>
|
| 194 |
</label>
|
| 195 |
</div>
|
| 196 |
|
| 197 |
+
<button type="submit" id="submitBtn">Nettoyer le CSV</button>
|
| 198 |
|
|
|
|
| 199 |
<div class="progress-wrap" id="progressWrap">
|
| 200 |
<div class="progress-bar-bg"><div class="progress-bar" id="progressBar"></div></div>
|
| 201 |
+
<div class="progress-label" id="progressLabel">Nettoyage en cours…</div>
|
| 202 |
</div>
|
| 203 |
|
|
|
|
| 204 |
<div class="result" id="result"></div>
|
| 205 |
|
| 206 |
</form>
|
|
|
|
| 208 |
|
| 209 |
<footer>
|
| 210 |
<a href="https://github.com/boutique-oss/convertionpdfcsv" target="_blank">Code source</a>
|
| 211 |
+
· Nettoyage 100 % local, sans IA
|
| 212 |
</footer>
|
| 213 |
|
| 214 |
<script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
const dropZone = document.getElementById('dropZone');
|
| 216 |
+
const csvInput = document.getElementById('csvInput');
|
| 217 |
const fileName = document.getElementById('fileName');
|
| 218 |
|
| 219 |
+
csvInput.addEventListener('change', () => {
|
| 220 |
+
if (csvInput.files[0]) fileName.textContent = csvInput.files[0].name;
|
| 221 |
});
|
| 222 |
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
|
| 223 |
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
|
|
|
|
| 225 |
e.preventDefault();
|
| 226 |
dropZone.classList.remove('drag-over');
|
| 227 |
const f = e.dataTransfer.files[0];
|
| 228 |
+
if (f) {
|
| 229 |
const dt = new DataTransfer();
|
| 230 |
dt.items.add(f);
|
| 231 |
+
csvInput.files = dt.files;
|
| 232 |
fileName.textContent = f.name;
|
| 233 |
}
|
| 234 |
});
|
| 235 |
|
| 236 |
+
const form = document.getElementById('form');
|
|
|
|
| 237 |
const submitBtn = document.getElementById('submitBtn');
|
| 238 |
const progressWrap = document.getElementById('progressWrap');
|
| 239 |
+
const progressBar = document.getElementById('progressBar');
|
| 240 |
+
const progressLbl = document.getElementById('progressLabel');
|
| 241 |
+
const result = document.getElementById('result');
|
| 242 |
|
| 243 |
form.addEventListener('submit', async e => {
|
| 244 |
e.preventDefault();
|
| 245 |
|
| 246 |
+
if (!csvInput.files[0]) {
|
| 247 |
+
result.className = 'result error';
|
| 248 |
+
result.textContent = 'Choisis d\'abord un fichier CSV.';
|
| 249 |
+
return;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
result.className = 'result';
|
| 253 |
result.innerHTML = '';
|
| 254 |
progressWrap.classList.add('visible');
|
| 255 |
+
progressBar.style.width = '15%';
|
| 256 |
progressLbl.textContent = 'Envoi du fichier…';
|
| 257 |
submitBtn.disabled = true;
|
| 258 |
|
| 259 |
try {
|
| 260 |
const base = window.location.origin;
|
| 261 |
+
const fd = new FormData();
|
| 262 |
+
fd.append('csv_file', csvInput.files[0]);
|
| 263 |
+
['drop_empty','drop_duplicates','trim_whitespace','normalize_headers','decimal_comma','ebp_format']
|
| 264 |
+
.forEach(name => {
|
| 265 |
+
const el = form.querySelector(`[name="${name}"]`);
|
| 266 |
+
fd.append(name, el.checked ? 'true' : 'false');
|
| 267 |
+
});
|
| 268 |
+
|
| 269 |
+
progressBar.style.width = '50%';
|
| 270 |
+
progressLbl.textContent = 'Nettoyage en cours…';
|
| 271 |
+
|
| 272 |
+
const resp = await fetch(`${base}/clean`, { method: 'POST', body: fd });
|
| 273 |
+
if (!resp.ok) {
|
|
|
|
|
|
|
|
|
|
| 274 |
let detail = 'Erreur serveur';
|
| 275 |
+
try { detail = (await resp.json()).detail; } catch (_) {}
|
| 276 |
+
throw new Error(`${detail}`);
|
| 277 |
}
|
| 278 |
+
const { download_id, report } = await resp.json();
|
| 279 |
+
|
| 280 |
+
progressBar.style.width = '100%';
|
| 281 |
+
progressWrap.classList.remove('visible');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
+
const dlUrl = `${base}/download/${download_id}`;
|
| 284 |
+
const sep = report.separateur_sortie === '\t' ? 'tab' : report.separateur_sortie;
|
| 285 |
+
const actions = (report.actions || []).map(a => `<li>${a}</li>`).join('');
|
| 286 |
+
|
| 287 |
+
result.className = 'result success';
|
| 288 |
+
result.innerHTML = `
|
| 289 |
+
<div class="result-head">
|
| 290 |
+
<div class="summary"><strong>${report.lignes_finales}</strong> lignes · ${report.colonnes_finales} colonnes</div>
|
| 291 |
+
<a class="download-btn" href="${dlUrl}">Télécharger</a>
|
| 292 |
+
</div>
|
| 293 |
+
<div class="report-meta">
|
| 294 |
+
<span>Entrée : <strong>${report.lignes_initiales}</strong> lignes, sép. « ${report.separateur_detecte} », ${report.encodage_detecte}</span>
|
| 295 |
+
<span>Sortie : sép. « ${sep} », ${report.encodage_sortie}</span>
|
| 296 |
+
</div>
|
| 297 |
+
<ul class="actions-list">${actions}</ul>
|
| 298 |
+
`;
|
| 299 |
} catch (err) {
|
| 300 |
progressWrap.classList.remove('visible');
|
| 301 |
result.className = 'result error';
|
tests/test_agent_validation.py
DELETED
|
@@ -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"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_cleaner.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests du nettoyeur CSV (core.cleaner)."""
|
| 2 |
+
from core.cleaner import clean_csv, detect_delimiter, detect_encoding
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _opts(**over):
|
| 6 |
+
base = dict(drop_empty=False, drop_duplicates=False, trim_whitespace=False,
|
| 7 |
+
normalize_headers=False, decimal_comma=False, ebp_format=False)
|
| 8 |
+
base.update(over)
|
| 9 |
+
return base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_detect_encoding_cp1252():
|
| 13 |
+
raw = "Réf;Prix\né;1".encode("cp1252")
|
| 14 |
+
text, enc = detect_encoding(raw)
|
| 15 |
+
assert "Réf" in text
|
| 16 |
+
assert enc in ("cp1252", "latin-1")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_detect_delimiter_semicolon():
|
| 20 |
+
assert detect_delimiter("a;b;c\n1;2;3") == ";"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_drop_duplicates():
|
| 24 |
+
raw = b"a,b\n1,2\n1,2\n3,4\n"
|
| 25 |
+
out, rep = clean_csv(raw, _opts(drop_duplicates=True))
|
| 26 |
+
assert rep["lignes_finales"] == 2
|
| 27 |
+
assert out.decode("utf-8-sig").count("1,2") == 1
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_drop_empty_rows_and_cols():
|
| 31 |
+
raw = b"a,b,vide\n1,2,\n,,\n3,4,\n"
|
| 32 |
+
out, rep = clean_csv(raw, _opts(drop_empty=True))
|
| 33 |
+
assert rep["lignes_finales"] == 2
|
| 34 |
+
assert rep["colonnes_finales"] == 2
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_trim_whitespace():
|
| 38 |
+
raw = b"a,b\n x , y \n"
|
| 39 |
+
out, _ = clean_csv(raw, _opts(trim_whitespace=True))
|
| 40 |
+
assert "x,y" in out.decode("utf-8-sig")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_normalize_headers_strips_whitespace():
|
| 44 |
+
raw = b" nom , prix \n1,2\n"
|
| 45 |
+
out, _ = clean_csv(raw, _opts(normalize_headers=True))
|
| 46 |
+
header = out.decode("utf-8-sig").splitlines()[0]
|
| 47 |
+
assert header == "nom,prix"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_duplicate_headers_are_unique():
|
| 51 |
+
raw = b"nom,nom\n1,2\n"
|
| 52 |
+
out, _ = clean_csv(raw, _opts(normalize_headers=True))
|
| 53 |
+
cols = out.decode("utf-8-sig").splitlines()[0].split(",")
|
| 54 |
+
assert len(set(cols)) == 2 # pas de doublon d'en-tête
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_decimal_comma_with_thousands():
|
| 58 |
+
raw = "p\n1.234,50\n99.90\n1 234,56\n".encode("utf-8")
|
| 59 |
+
out, _ = clean_csv(raw, _opts(decimal_comma=True))
|
| 60 |
+
body = out.decode("utf-8-sig").splitlines()[1:]
|
| 61 |
+
assert body == ["1234,50", "99,90", "1234,56"]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_decimal_comma_keeps_dates():
|
| 65 |
+
raw = b"d\n01.02.2024\n"
|
| 66 |
+
out, _ = clean_csv(raw, _opts(decimal_comma=True))
|
| 67 |
+
assert "01.02.2024" in out.decode("utf-8-sig")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_ebp_format_output():
|
| 71 |
+
raw = b"a,b\n1,2\n"
|
| 72 |
+
out, rep = clean_csv(raw, _opts(ebp_format=True))
|
| 73 |
+
assert rep["separateur_sortie"] == ";"
|
| 74 |
+
assert out.startswith(b"\xef\xbb\xbf") # BOM utf-8-sig
|
| 75 |
+
assert b"\r\n" in out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_no_options_reports_clean():
|
| 79 |
+
raw = b"a,b\n1,2\n"
|
| 80 |
+
_out, rep = clean_csv(raw, _opts())
|
| 81 |
+
assert "Aucune modification" in rep["actions"][0]
|
tests/test_csv_writer.py
DELETED
|
@@ -1,198 +0,0 @@
|
|
| 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
DELETED
|
@@ -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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|