Stephan86 Claude Opus 4.8 commited on
Commit
be49328
·
2 Parent(s): 4403c66d156937

merge: fusion nettoyeur CSV (HF) + extracteur PDF→CSV EBP en une codebase

Browse files

Réconcilie les deux branches divergentes depuis 8845c50 :
- HF (nettoyeur CSV sans IA) : core/cleaner.py, app.py FastAPI, UI statique
- extracteur (Claude + sous-familles + aperçu éditable) : core/agent, extractor,
csv_writer, subfamily, regex_extractor, app_gradio

Architecture fusionnée :
- app.py (FastAPI nettoyeur) reste l'entrypoint uvicorn → / = nettoyeur CSV
- extracteur Gradio monté sur /extracteur via gr.mount_gradio_app (montage isolé)
- requirements.txt = union des deux stacks (pandas + PyMuPDF + anthropic + gradio)
- lien de découverte vers /extracteur ajouté dans l'UI nettoyeur

Rien n'est perdu : les 3 commits du nettoyeur CSV et le travail extracteur
coexistent. 66 tests verts (cleaner + extracteur).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Files changed (7) hide show
  1. README.md +19 -31
  2. app.py +97 -134
  3. core/cleaner.py +285 -0
  4. docs/index.html +11 -11
  5. requirements.txt +1 -1
  6. static/index.html +154 -255
  7. tests/test_cleaner.py +109 -0
README.md CHANGED
@@ -1,24 +1,28 @@
1
  ---
2
- title: PDF CSV Agent
3
- emoji: 📄
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
7
  pinned: false
8
  ---
9
 
10
- # PDF → CSV Agent
11
 
12
- Extrait les articles d'un catalogue PDF et génère un fichier CSV tarifaire prêt à l'import.
 
13
 
14
- ## Fonctionnement
15
 
16
- 1. Chargez un PDF de catalogue fournisseur
17
- 2. Sélectionnez la plage de pages à analyser
18
- 3. Renseignez votre taux de marge et l'unité par défaut
19
- 4. Cliquez **Extraire → CSV** — l'IA (Claude Sonnet) analyse le texte et produit le CSV
 
 
20
 
21
- Le CSV contient : `Code article`, `Libellé`, `PV HT` (calculé depuis le prix TTC et la marge), `Unité`.
 
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
- python app.py
45
  ```
46
 
47
- L'interface Gradio s'ouvre sur `http://localhost:7860`.
48
 
49
  ## Structure
50
 
51
  ```
52
  core/
53
- extractor.py # extraction texte PDF (PyMuPDF)
54
- agent.py # appel Claude Sonnet → JSON articles
55
- csv_writer.py # calcul PV HT + export CSV (pandas)
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.agent import extract_articles
16
- from core.csv_writer import to_csv
17
 
18
- load_dotenv()
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
- _jobs: dict[str, dict] = {}
30
 
31
- MAX_PDF_MB = 50
 
 
32
 
33
 
34
- def _run_job(job_id: str, pdf_path: str, page_from: int, page_to: int,
35
- default_unit: str, brand: str, password: str):
36
- try:
37
- def _progress(done, total):
38
- _jobs[job_id]["progress"] = f"{done}/{total}"
39
-
40
- articles = extract_articles(
41
- pdf_path, page_from, page_to, password, default_unit, progress_cb=_progress
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,105 +41,97 @@ 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("/extract")
101
- async def extract(
102
- pdf: UploadFile = File(...),
103
- page_from: int = Form(1),
104
- page_to: int = Form(10),
105
- default_unit: str = Form("Pièce"),
106
- brand: str = Form(""),
107
- password: str = Form(""),
 
 
 
108
  ):
109
- if not pdf.filename.lower().endswith(".pdf"):
110
- raise HTTPException(status_code=400, detail="Le fichier doit être un PDF.")
111
- if page_to > 300:
112
- raise HTTPException(status_code=400, detail="Limite : 300 pages maximum.")
113
- if page_from > page_to:
114
- raise HTTPException(status_code=400, detail="Page de début > page de fin.")
115
-
116
- # Sauvegarde du PDF en lisant par chunks pour éviter l'OOM
117
- with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
118
- size = 0
119
- chunk_size = 1024 * 1024 # 1 MB
120
- while True:
121
- chunk = await pdf.read(chunk_size)
122
- if not chunk:
123
- break
124
- size += len(chunk)
125
- if size > MAX_PDF_MB * 1024 * 1024:
126
- os.unlink(tmp.name)
127
- raise HTTPException(
128
- status_code=413,
129
- detail=f"PDF trop volumineux (max {MAX_PDF_MB} MB)."
130
- )
131
- tmp.write(chunk)
132
- pdf_path = tmp.name
133
-
134
- job_id = str(uuid.uuid4())
135
- _jobs[job_id] = {"status": "processing"}
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
- @app.get("/status/{job_id}")
148
- async def status(job_id: str):
149
- job = _jobs.get(job_id)
150
- if not job:
151
- raise HTTPException(status_code=404, detail="Job introuvable.")
152
- if job["status"] == "error":
153
- return JSONResponse({"status": "error", "error": job["error"]})
154
- if job["status"] == "done":
155
- return JSONResponse({"status": "done", "count": job["count"]})
156
- if job.get("progress"):
157
- return JSONResponse({"status": "processing", "progress": job["progress"]})
158
- return JSONResponse({"status": "processing"})
159
-
160
-
161
- @app.get("/download/{job_id}")
162
- async def download(job_id: str):
163
- job = _jobs.get(job_id)
164
- if not job or job["status"] != "done":
165
- raise HTTPException(status_code=404, detail="Résultat non disponible.")
 
 
 
 
 
166
  return FileResponse(
167
- job["result"],
168
- filename="articles.csv",
169
  media_type="text/csv; charset=utf-8",
170
- headers={"X-Article-Count": str(job["count"])},
171
  )
172
 
173
 
174
  app.mount("/static", StaticFiles(directory="static"), name="static")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ remove_symbols: bool = Form(False),
57
+ keep_digits_only: bool = Form(False),
58
+ decimal_comma: bool = Form(False),
59
+ ebp_format: bool = Form(False),
60
  ):
61
+ name = csv_file.filename or "fichier.csv"
62
+ if not name.lower().endswith((".csv", ".txt", ".tsv")):
63
+ raise HTTPException(status_code=400, detail="Le fichier doit être un .csv, .tsv ou .txt.")
64
+
65
+ raw = b""
66
+ chunk_size = 1024 * 1024
67
+ while True:
68
+ chunk = await csv_file.read(chunk_size)
69
+ if not chunk:
70
+ break
71
+ raw += chunk
72
+ if len(raw) > MAX_CSV_MB * 1024 * 1024:
73
+ raise HTTPException(
74
+ status_code=413,
75
+ detail=f"Fichier trop volumineux (max {MAX_CSV_MB} MB).",
76
+ )
77
+
78
+ if not raw.strip():
79
+ raise HTTPException(status_code=400, detail="Le fichier est vide.")
80
+
81
+ options = {
82
+ "drop_empty": drop_empty,
83
+ "drop_duplicates": drop_duplicates,
84
+ "trim_whitespace": trim_whitespace,
85
+ "normalize_headers": normalize_headers,
86
+ "remove_symbols": remove_symbols,
87
+ "keep_digits_only": keep_digits_only,
88
+ "decimal_comma": decimal_comma,
89
+ "ebp_format": ebp_format,
90
+ }
 
 
 
 
 
 
91
 
92
+ try:
93
+ cleaned, report = clean_csv(raw, options)
94
+ except Exception as exc: # noqa: BLE001
95
+ detail = f"{type(exc).__name__}: {exc}\n{traceback.format_exc()[-400:]}"
96
+ raise HTTPException(status_code=422, detail=detail)
97
+
98
+ _purge_old()
99
+ out = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
100
+ out.write(cleaned)
101
+ out.close()
102
+
103
+ download_id = os.path.splitext(os.path.basename(out.name))[0]
104
+ base, ext = os.path.splitext(os.path.basename(name))
105
+ out_name = f"{base}_nettoye{ext or '.csv'}"
106
+ _results[download_id] = (out.name, out_name, time.time())
107
+
108
+ return JSONResponse({"download_id": download_id, "report": report})
109
+
110
+
111
+ @app.get("/download/{download_id}")
112
+ async def download(download_id: str):
113
+ entry = _results.get(download_id)
114
+ if not entry:
115
+ raise HTTPException(status_code=404, detail="Résultat expiré ou introuvable.")
116
+ path, out_name, _ts = entry
117
  return FileResponse(
118
+ path,
119
+ filename=out_name,
120
  media_type="text/csv; charset=utf-8",
 
121
  )
122
 
123
 
124
  app.mount("/static", StaticFiles(directory="static"), name="static")
125
+
126
+
127
+ # ── Extracteur catalogue PDF → CSV EBP (UI Gradio) ───────────────────────────
128
+ # Monté sur /extracteur. Inclut l'analyse des sous-familles et l'aperçu éditable.
129
+ # Isolé dans un try : si une dépendance lourde (PyMuPDF/anthropic/gradio) manque,
130
+ # le nettoyeur CSV reste disponible sur /.
131
+ try:
132
+ import gradio as gr
133
+ from app_gradio import demo as _extracteur_demo
134
+
135
+ app = gr.mount_gradio_app(app, _extracteur_demo, path="/extracteur")
136
+ except Exception as exc: # noqa: BLE001
137
+ print(f"[extracteur] UI Gradio non montée : {type(exc).__name__}: {exc}")
core/cleaner.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Tout sauf lettres (accents compris), chiffres, espaces et séparateurs , . -
86
+ _SYMBOL_RE = re.compile(r"[^\w\s.,\-]", re.UNICODE)
87
+
88
+
89
+ def _remove_symbols(value: str) -> str:
90
+ """Retire les symboles (€, %, #, *, ®, etc.) en gardant lettres, chiffres,
91
+ espaces et séparateurs décimaux. Ex. : "12,50 €" → "12,50", "Réf#12" → "Réf12"."""
92
+ new = _SYMBOL_RE.sub("", value)
93
+ return re.sub(r"\s+", " ", new).strip()
94
+
95
+
96
+ def _strip_to_digits(value: str) -> str:
97
+ """
98
+ Retire lettres, symboles et espaces, ne garde que les chiffres et les
99
+ séparateurs décimaux (, . -). Ex. : "12,50€" → "12,50", "A123" → "123",
100
+ "10 ml" → "10". Les cellules sans aucun chiffre sont laissées intactes.
101
+ """
102
+ if not any(c.isdigit() for c in value):
103
+ return value
104
+ core = re.sub(r"[^\d.,\-]", "", value)
105
+ core = core.strip(".,") # retire d'éventuels séparateurs en bord
106
+ return core if any(c.isdigit() for c in core) else value
107
+
108
+
109
+ def _to_decimal_comma(value: str) -> str:
110
+ """Normalise un nombre vers la virgule décimale française, sans séparateur de milliers."""
111
+ v = value.strip().replace(" ", " ")
112
+ # Retire les espaces utilisés comme séparateur de milliers
113
+ v = v.replace(" ", "")
114
+ if "," in v and "." in v:
115
+ # Le dernier symbole rencontré est le séparateur décimal
116
+ if v.rfind(",") > v.rfind("."):
117
+ v = v.replace(".", "") # points = milliers
118
+ else:
119
+ v = v.replace(",", "") # virgules = milliers
120
+ v = v.replace(".", ",")
121
+ else:
122
+ v = v.replace(".", ",")
123
+ return v
124
+
125
+
126
+ def _dedupe_headers(headers: list[str]) -> list[str]:
127
+ seen: dict[str, int] = {}
128
+ out: list[str] = []
129
+ for h in headers:
130
+ h = (h or "").strip()
131
+ h = re.sub(r"\s+", " ", h)
132
+ if not h:
133
+ h = "colonne"
134
+ if h in seen:
135
+ seen[h] += 1
136
+ out.append(f"{h}_{seen[h]}")
137
+ else:
138
+ seen[h] = 0
139
+ out.append(h)
140
+ return out
141
+
142
+
143
+ # ── Nettoyage principal ─────────────────────────────────────────────────────────
144
+
145
+ def clean_csv(raw: bytes, options: dict) -> tuple[bytes, dict]:
146
+ text, enc_in = detect_encoding(raw)
147
+ delim_in = detect_delimiter(text)
148
+
149
+ df = pd.read_csv(
150
+ io.StringIO(text),
151
+ sep=delim_in,
152
+ dtype=str,
153
+ keep_default_na=False,
154
+ engine="python",
155
+ on_bad_lines="skip",
156
+ )
157
+
158
+ def _sep_label(d: str) -> str:
159
+ return {"\t": "tabulation", SINGLE_COL: "aucun (1 colonne)"}.get(d, d)
160
+
161
+ report: dict = {
162
+ "encodage_detecte": enc_in,
163
+ "separateur_detecte": _sep_label(delim_in),
164
+ "lignes_initiales": int(len(df)),
165
+ "colonnes_initiales": int(df.shape[1]),
166
+ "actions": [],
167
+ }
168
+
169
+ def log(msg: str):
170
+ report["actions"].append(msg)
171
+
172
+ # 1. Espaces superflus
173
+ if options.get("trim_whitespace"):
174
+ df = df.apply(lambda col: col.map(
175
+ lambda x: re.sub(r"\s+", " ", x).strip() if isinstance(x, str) else x))
176
+ log("Espaces superflus supprimés dans toutes les cellules.")
177
+
178
+ # 2. En-têtes normalisés
179
+ if options.get("normalize_headers"):
180
+ new_cols = _dedupe_headers([str(c) for c in df.columns])
181
+ if list(df.columns) != new_cols:
182
+ log(f"En-têtes nettoyés ({df.shape[1]} colonnes).")
183
+ df.columns = new_cols
184
+
185
+ # 3. Lignes / colonnes vides
186
+ if options.get("drop_empty"):
187
+ before_rows = len(df)
188
+ # Une cellule "vide" = chaîne vide après strip
189
+ mask_nonempty_row = df.apply(
190
+ lambda r: any(str(v).strip() for v in r), axis=1)
191
+ df = df[mask_nonempty_row]
192
+ removed_rows = before_rows - len(df)
193
+
194
+ before_cols = df.shape[1]
195
+ nonempty_cols = [c for c in df.columns
196
+ if df[c].map(lambda x: bool(str(x).strip())).any()]
197
+ df = df[nonempty_cols]
198
+ removed_cols = before_cols - df.shape[1]
199
+
200
+ if removed_rows:
201
+ log(f"{removed_rows} ligne(s) vide(s) supprimée(s).")
202
+ if removed_cols:
203
+ log(f"{removed_cols} colonne(s) vide(s) supprimée(s).")
204
+
205
+ # 4. Doublons
206
+ if options.get("drop_duplicates"):
207
+ before = len(df)
208
+ df = df.drop_duplicates()
209
+ removed = before - len(df)
210
+ if removed:
211
+ log(f"{removed} ligne(s) en double supprimée(s).")
212
+
213
+ # 4a. Retirer tous les symboles (€, %, #, *…) en gardant lettres et chiffres
214
+ if options.get("remove_symbols"):
215
+ cleaned_cells = 0
216
+
217
+ def desymbol(x):
218
+ nonlocal cleaned_cells
219
+ if isinstance(x, str):
220
+ new = _remove_symbols(x)
221
+ if new != x:
222
+ cleaned_cells += 1
223
+ return new
224
+ return x
225
+
226
+ df = df.apply(lambda col: col.map(desymbol))
227
+ if cleaned_cells:
228
+ log(f"{cleaned_cells} cellule(s) : symboles retirés.")
229
+
230
+ # 4b. Garder uniquement les chiffres (retire lettres/symboles des montants)
231
+ if options.get("keep_digits_only"):
232
+ stripped = 0
233
+
234
+ def strip_cell(x):
235
+ nonlocal stripped
236
+ if isinstance(x, str):
237
+ new = _strip_to_digits(x)
238
+ if new != x:
239
+ stripped += 1
240
+ return new
241
+ return x
242
+
243
+ df = df.apply(lambda col: col.map(strip_cell))
244
+ if stripped:
245
+ log(f"{stripped} cellule(s) nettoyée(s) : lettres et symboles retirés.")
246
+
247
+ # 5. Décimales en virgule française
248
+ if options.get("decimal_comma"):
249
+ converted = 0
250
+
251
+ def conv(x):
252
+ nonlocal converted
253
+ if isinstance(x, str) and _looks_numeric(x):
254
+ new = _to_decimal_comma(x)
255
+ if new != x:
256
+ converted += 1
257
+ return new
258
+ return x
259
+
260
+ df = df.apply(lambda col: col.map(conv))
261
+ if converted:
262
+ log(f"{converted} valeur(s) numérique(s) converties en virgule décimale.")
263
+
264
+ # ── Écriture ──────────────────────────────────────────────────────────────
265
+ ebp = options.get("ebp_format")
266
+ if ebp or delim_in in ("\t", SINGLE_COL):
267
+ out_sep = ";" # EBP, tabulation ou mono-colonne → séparateur sûr
268
+ else:
269
+ out_sep = delim_in
270
+ out_enc = "utf-8-sig"
271
+ line_terminator = "\r\n" if ebp else "\n"
272
+
273
+ buf = io.StringIO()
274
+ df.to_csv(buf, sep=out_sep, index=False, lineterminator=line_terminator,
275
+ quoting=csv.QUOTE_MINIMAL)
276
+ cleaned = buf.getvalue().encode(out_enc)
277
+
278
+ report["lignes_finales"] = int(len(df))
279
+ report["colonnes_finales"] = int(df.shape[1])
280
+ report["separateur_sortie"] = out_sep
281
+ report["encodage_sortie"] = out_enc
282
+ if not report["actions"]:
283
+ report["actions"].append("Aucune modification — le fichier était déjà propre.")
284
+
285
+ return cleaned, report
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>PDF → CSV Agent</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>PDF → CSV Agent</h1>
60
- <a class="badge" href="https://github.com/boutique-oss/convertionpdfcsv/releases">v1.0.0</a>
61
 
62
  <p>
63
- Outil open-source qui extrait automatiquement les articles d'un catalogue PDF
64
- (code, libellé, prix TTC) et génère un fichier CSV tarifaire prêt à l'import,
65
- avec calcul du prix de vente HT selon votre taux de marge.
66
  </p>
67
 
68
  <p><strong>Fonctionnalités :</strong></p>
69
  <ul>
70
- <li>Extraction de texte page par page via PyMuPDF</li>
71
- <li>Analyse IA (Claude Sonnet) avec sortie JSON stricte</li>
72
- <li>Calcul automatique du PV HT depuis le prix TTC et la marge</li>
73
- <li>Interface Gradio — aucun code requis</li>
74
- <li>CSV encodé UTF-8 BOM, séparateur point-virgule (compatible Excel)</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,4 +1,3 @@
1
- anthropic>=0.40.0
2
  fastapi>=0.110.0
3
  uvicorn[standard]>=0.29.0
4
  python-multipart>=0.0.9
@@ -6,3 +5,4 @@ pandas>=2.0.0
6
  PyMuPDF>=1.24.0
7
  python-dotenv>=1.0.0
8
  gradio>=5.6.0
 
 
 
1
  fastapi>=0.110.0
2
  uvicorn[standard]>=0.29.0
3
  python-multipart>=0.0.9
 
5
  PyMuPDF>=1.24.0
6
  python-dotenv>=1.0.0
7
  gradio>=5.6.0
8
+ anthropic>=0.40.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>PDF → CSV Agent</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,153 @@
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
- /* Form grid */
85
- .form-grid {
86
- display: grid;
87
- grid-template-columns: 1fr 1fr;
88
- gap: 1rem;
89
- margin-bottom: 1.5rem;
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
- input[type="number"]:focus, select:focus { border-color: var(--accent); }
 
 
 
 
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
- padding: .85rem;
138
- background: var(--accent);
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
- /* Progress */
151
- .progress-wrap {
152
- margin-top: 1.25rem;
153
- display: none;
154
- }
155
  .progress-wrap.visible { display: block; }
156
- .progress-bar-bg {
157
- background: var(--border);
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
- /* Result */
173
- .result {
174
- margin-top: 1.25rem;
175
- border-radius: 10px;
176
- padding: 1rem 1.25rem;
177
- display: none;
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: .5rem 1rem;
197
- background: var(--success);
198
- color: #fff;
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
- footer {
210
- margin-top: 2rem;
211
- font-size: .78rem;
212
- color: var(--muted);
213
- text-align: center;
214
- }
 
215
  footer a { color: var(--accent); text-decoration: none; }
216
  </style>
217
  </head>
218
  <body>
219
 
220
  <header>
221
- <h1>PDF → CSV Agent</h1>
222
- <p>Extrait les articles d'un catalogue PDF et génère un fichier CSV tarifaire.</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="pdf" id="pdfInput" accept=".pdf" required />
231
- <div class="icon">📄</div>
232
- <div class="label">Glisse ton PDF ici ou <strong>clique pour choisir</strong></div>
233
  <div class="file-name" id="fileName"></div>
234
  </div>
235
 
236
- <!-- Parameters -->
237
- <div class="form-grid">
238
- <label>
239
- Page de
240
- <div class="range-row">
241
- <input type="range" id="pageFrom" name="page_from" min="1" max="300" value="1" />
242
- <span class="range-val" id="pageFromVal">1</span>
243
- </div>
 
244
  </label>
245
 
246
- <label>
247
- Page à
248
- <div class="range-row">
249
- <input type="range" id="pageTo" name="page_to" min="1" max="300" value="10" />
250
- <span class="range-val" id="pageToVal">10</span>
251
- </div>
252
  </label>
253
 
254
- <label>
255
- Unité par défaut
256
- <select name="default_unit">
257
- <option value="Pièce">Pièce</option>
258
- <option value="ML">ML</option>
259
- <option value="M²">M²</option>
260
- <option value="Rouleau">Rouleau</option>
261
- </select>
262
  </label>
263
 
264
- <label style="grid-column: 1 / -1;">
265
- Nom de la marque <span>(ajouté sur chaque ligne du CSV)</span>
266
- <input type="text" name="brand" placeholder="ex : Camengo, Casamance…" autocomplete="off" />
 
 
 
267
  </label>
268
 
269
- <label style="grid-column: 1 / -1;">
270
- Mot de passe PDF <span>(optionnel — si le fichier est protégé)</span>
271
- <input type="password" name="password" placeholder="Laisser vide si non protégé" autocomplete="off" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  </label>
273
  </div>
274
 
275
- <button type="submit" id="submitBtn">Extraire → CSV</button>
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">Analyse en cours…</div>
281
  </div>
282
 
283
- <!-- Result -->
284
  <div class="result" id="result"></div>
285
 
286
  </form>
@@ -288,25 +225,16 @@
288
 
289
  <footer>
290
  <a href="https://github.com/boutique-oss/convertionpdfcsv" target="_blank">Code source</a>
291
- &nbsp;·&nbsp; Propulsé par Claude Sonnet
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 pdfInput = document.getElementById('pdfInput');
306
  const fileName = document.getElementById('fileName');
307
 
308
- pdfInput.addEventListener('change', () => {
309
- if (pdfInput.files[0]) fileName.textContent = pdfInput.files[0].name;
310
  });
311
  dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
312
  dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
@@ -314,106 +242,77 @@
314
  e.preventDefault();
315
  dropZone.classList.remove('drag-over');
316
  const f = e.dataTransfer.files[0];
317
- if (f && f.name.endsWith('.pdf')) {
318
  const dt = new DataTransfer();
319
  dt.items.add(f);
320
- pdfInput.files = dt.files;
321
  fileName.textContent = f.name;
322
  }
323
  });
324
 
325
- // Form submit
326
- const form = document.getElementById('form');
327
  const submitBtn = document.getElementById('submitBtn');
328
  const progressWrap = document.getElementById('progressWrap');
329
- const progressBar = document.getElementById('progressBar');
330
- const progressLbl = document.getElementById('progressLabel');
331
- const result = document.getElementById('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 = '5%';
340
  progressLbl.textContent = 'Envoi du fichier…';
341
  submitBtn.disabled = true;
342
 
343
  try {
344
  const base = window.location.origin;
345
-
346
- // 0. Ping pour réveiller le Space si endormi
347
- progressLbl.textContent = 'Vérification du serveur…';
348
- try { await fetch(`${base}/ping`); } catch(_) {}
349
-
350
- // 1. Upload → reçoit un job_id immédiatement
351
- progressBar.style.width = '10%';
352
- progressLbl.textContent = 'Envoi du fichier…';
353
- const fd = new FormData(form);
354
- let uploadResp;
355
- try {
356
- uploadResp = await fetch(`${base}/extract`, { method: 'POST', body: fd });
357
- } catch (netErr) {
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 uploadResp.json()).detail; } catch(_) {}
363
- throw new Error(`HTTP ${uploadResp.status} : ${detail}`);
364
  }
365
- const { job_id } = await uploadResp.json();
366
-
367
- progressBar.style.width = '20%';
368
- progressLbl.textContent = 'Analyse IA en cours…';
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
+ <p><a href="/extracteur" style="color:#7aa2f7;">→ Extracteur catalogue PDF → CSV EBP (sous-familles + aperçu éditable)</a></p>
134
  </header>
135
 
136
  <div class="card">
137
  <form id="form">
138
 
 
139
  <div class="drop-zone" id="dropZone">
140
+ <input type="file" name="csv_file" id="csvInput" accept=".csv,.tsv,.txt" required />
141
+ <div class="icon">🧹</div>
142
+ <div class="label">Glisse ton CSV ici ou <strong>clique pour choisir</strong></div>
143
  <div class="file-name" id="fileName"></div>
144
  </div>
145
 
146
+ <div class="options">
147
+ <h3>Opérations de nettoyage</h3>
148
+
149
+ <label class="opt">
150
+ <input type="checkbox" name="drop_empty" checked />
151
+ <span class="opt-text">
152
+ <span class="opt-title">Lignes & colonnes vides</span>
153
+ <span class="opt-desc">Supprime les lignes et colonnes entièrement vides.</span>
154
+ </span>
155
  </label>
156
 
157
+ <label class="opt">
158
+ <input type="checkbox" name="drop_duplicates" checked />
159
+ <span class="opt-text">
160
+ <span class="opt-title">Doublons</span>
161
+ <span class="opt-desc">Supprime les lignes identiques en double.</span>
162
+ </span>
163
  </label>
164
 
165
+ <label class="opt">
166
+ <input type="checkbox" name="trim_whitespace" checked />
167
+ <span class="opt-text">
168
+ <span class="opt-title">Espaces superflus</span>
169
+ <span class="opt-desc">Nettoie les espaces en début/fin et les doubles espaces.</span>
170
+ </span>
 
 
171
  </label>
172
 
173
+ <label class="opt">
174
+ <input type="checkbox" name="normalize_headers" checked />
175
+ <span class="opt-text">
176
+ <span class="opt-title">En-têtes propres</span>
177
+ <span class="opt-desc">Nettoie et dé-duplique les noms de colonnes.</span>
178
+ </span>
179
  </label>
180
 
181
+ <label class="opt">
182
+ <input type="checkbox" name="remove_symbols" />
183
+ <span class="opt-text">
184
+ <span class="opt-title">Retirer les symboles</span>
185
+ <span class="opt-desc">Supprime €, %, #, *, ®… en gardant lettres et chiffres (12,50 € → 12,50, Réf#12 → Réf12).</span>
186
+ </span>
187
+ </label>
188
+
189
+ <label class="opt">
190
+ <input type="checkbox" name="keep_digits_only" />
191
+ <span class="opt-text">
192
+ <span class="opt-title">Garder uniquement les chiffres</span>
193
+ <span class="opt-desc">Retire lettres et symboles des cellules contenant un nombre (12,50€ → 12,50, A123 → 123). N'active que si une colonne de montants contient des lettres.</span>
194
+ </span>
195
+ </label>
196
+
197
+ <label class="opt">
198
+ <input type="checkbox" name="decimal_comma" />
199
+ <span class="opt-text">
200
+ <span class="opt-title">Virgule décimale (FR)</span>
201
+ <span class="opt-desc">Convertit 1234.56 → 1234,56 et retire les séparateurs de milliers.</span>
202
+ </span>
203
+ </label>
204
+
205
+ <label class="opt">
206
+ <input type="checkbox" name="ebp_format" />
207
+ <span class="opt-text">
208
+ <span class="opt-title">Format EBP</span>
209
+ <span class="opt-desc">Sortie séparateur « ; », encodage UTF-8 BOM, fins de ligne Windows.</span>
210
+ </span>
211
  </label>
212
  </div>
213
 
214
+ <button type="submit" id="submitBtn">Nettoyer le CSV</button>
215
 
 
216
  <div class="progress-wrap" id="progressWrap">
217
  <div class="progress-bar-bg"><div class="progress-bar" id="progressBar"></div></div>
218
+ <div class="progress-label" id="progressLabel">Nettoyage en cours…</div>
219
  </div>
220
 
 
221
  <div class="result" id="result"></div>
222
 
223
  </form>
 
225
 
226
  <footer>
227
  <a href="https://github.com/boutique-oss/convertionpdfcsv" target="_blank">Code source</a>
228
+ &nbsp;·&nbsp; Nettoyage 100 % local, sans IA
229
  </footer>
230
 
231
  <script>
 
 
 
 
 
 
 
 
 
232
  const dropZone = document.getElementById('dropZone');
233
+ const csvInput = document.getElementById('csvInput');
234
  const fileName = document.getElementById('fileName');
235
 
236
+ csvInput.addEventListener('change', () => {
237
+ if (csvInput.files[0]) fileName.textContent = csvInput.files[0].name;
238
  });
239
  dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
240
  dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
 
242
  e.preventDefault();
243
  dropZone.classList.remove('drag-over');
244
  const f = e.dataTransfer.files[0];
245
+ if (f) {
246
  const dt = new DataTransfer();
247
  dt.items.add(f);
248
+ csvInput.files = dt.files;
249
  fileName.textContent = f.name;
250
  }
251
  });
252
 
253
+ const form = document.getElementById('form');
 
254
  const submitBtn = document.getElementById('submitBtn');
255
  const progressWrap = document.getElementById('progressWrap');
256
+ const progressBar = document.getElementById('progressBar');
257
+ const progressLbl = document.getElementById('progressLabel');
258
+ const result = document.getElementById('result');
259
 
260
  form.addEventListener('submit', async e => {
261
  e.preventDefault();
262
 
263
+ if (!csvInput.files[0]) {
264
+ result.className = 'result error';
265
+ result.textContent = 'Choisis d\'abord un fichier CSV.';
266
+ return;
267
+ }
268
+
269
  result.className = 'result';
270
  result.innerHTML = '';
271
  progressWrap.classList.add('visible');
272
+ progressBar.style.width = '15%';
273
  progressLbl.textContent = 'Envoi du fichier…';
274
  submitBtn.disabled = true;
275
 
276
  try {
277
  const base = window.location.origin;
278
+ const fd = new FormData();
279
+ fd.append('csv_file', csvInput.files[0]);
280
+ ['drop_empty','drop_duplicates','trim_whitespace','normalize_headers','remove_symbols','keep_digits_only','decimal_comma','ebp_format']
281
+ .forEach(name => {
282
+ const el = form.querySelector(`[name="${name}"]`);
283
+ fd.append(name, el.checked ? 'true' : 'false');
284
+ });
285
+
286
+ progressBar.style.width = '50%';
287
+ progressLbl.textContent = 'Nettoyage en cours…';
288
+
289
+ const resp = await fetch(`${base}/clean`, { method: 'POST', body: fd });
290
+ if (!resp.ok) {
 
 
 
291
  let detail = 'Erreur serveur';
292
+ try { detail = (await resp.json()).detail; } catch (_) {}
293
+ throw new Error(`${detail}`);
294
  }
295
+ const { download_id, report } = await resp.json();
296
+
297
+ progressBar.style.width = '100%';
298
+ progressWrap.classList.remove('visible');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
 
300
+ const dlUrl = `${base}/download/${download_id}`;
301
+ const sep = report.separateur_sortie === '\t' ? 'tab' : report.separateur_sortie;
302
+ const actions = (report.actions || []).map(a => `<li>${a}</li>`).join('');
303
+
304
+ result.className = 'result success';
305
+ result.innerHTML = `
306
+ <div class="result-head">
307
+ <div class="summary"><strong>${report.lignes_finales}</strong> lignes · ${report.colonnes_finales} colonnes</div>
308
+ <a class="download-btn" href="${dlUrl}">Télécharger</a>
309
+ </div>
310
+ <div class="report-meta">
311
+ <span>Entrée&nbsp;: <strong>${report.lignes_initiales}</strong> lignes, sép. «&nbsp;${report.separateur_detecte}&nbsp;», ${report.encodage_detecte}</span>
312
+ <span>Sortie&nbsp;: sép. «&nbsp;${sep}&nbsp;», ${report.encodage_sortie}</span>
313
+ </div>
314
+ <ul class="actions-list">${actions}</ul>
315
+ `;
316
  } catch (err) {
317
  progressWrap.classList.remove('visible');
318
  result.className = 'result error';
tests/test_cleaner.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, remove_symbols=False, keep_digits_only=False,
8
+ decimal_comma=False, ebp_format=False)
9
+ base.update(over)
10
+ return base
11
+
12
+
13
+ def test_detect_encoding_cp1252():
14
+ raw = "Réf;Prix\né;1".encode("cp1252")
15
+ text, enc = detect_encoding(raw)
16
+ assert "Réf" in text
17
+ assert enc in ("cp1252", "latin-1")
18
+
19
+
20
+ def test_detect_delimiter_semicolon():
21
+ assert detect_delimiter("a;b;c\n1;2;3") == ";"
22
+
23
+
24
+ def test_drop_duplicates():
25
+ raw = b"a,b\n1,2\n1,2\n3,4\n"
26
+ out, rep = clean_csv(raw, _opts(drop_duplicates=True))
27
+ assert rep["lignes_finales"] == 2
28
+ assert out.decode("utf-8-sig").count("1,2") == 1
29
+
30
+
31
+ def test_drop_empty_rows_and_cols():
32
+ raw = b"a,b,vide\n1,2,\n,,\n3,4,\n"
33
+ out, rep = clean_csv(raw, _opts(drop_empty=True))
34
+ assert rep["lignes_finales"] == 2
35
+ assert rep["colonnes_finales"] == 2
36
+
37
+
38
+ def test_trim_whitespace():
39
+ raw = b"a,b\n x , y \n"
40
+ out, _ = clean_csv(raw, _opts(trim_whitespace=True))
41
+ assert "x,y" in out.decode("utf-8-sig")
42
+
43
+
44
+ def test_normalize_headers_strips_whitespace():
45
+ raw = b" nom , prix \n1,2\n"
46
+ out, _ = clean_csv(raw, _opts(normalize_headers=True))
47
+ header = out.decode("utf-8-sig").splitlines()[0]
48
+ assert header == "nom,prix"
49
+
50
+
51
+ def test_duplicate_headers_are_unique():
52
+ raw = b"nom,nom\n1,2\n"
53
+ out, _ = clean_csv(raw, _opts(normalize_headers=True))
54
+ cols = out.decode("utf-8-sig").splitlines()[0].split(",")
55
+ assert len(set(cols)) == 2 # pas de doublon d'en-tête
56
+
57
+
58
+ def test_decimal_comma_with_thousands():
59
+ raw = "p\n1.234,50\n99.90\n1 234,56\n".encode("utf-8")
60
+ out, _ = clean_csv(raw, _opts(decimal_comma=True))
61
+ body = out.decode("utf-8-sig").splitlines()[1:]
62
+ assert body == ["1234,50", "99,90", "1234,56"]
63
+
64
+
65
+ def test_decimal_comma_keeps_dates():
66
+ raw = b"d\n01.02.2024\n"
67
+ out, _ = clean_csv(raw, _opts(decimal_comma=True))
68
+ assert "01.02.2024" in out.decode("utf-8-sig")
69
+
70
+
71
+ def test_ebp_format_output():
72
+ raw = b"a,b\n1,2\n"
73
+ out, rep = clean_csv(raw, _opts(ebp_format=True))
74
+ assert rep["separateur_sortie"] == ";"
75
+ assert out.startswith(b"\xef\xbb\xbf") # BOM utf-8-sig
76
+ assert b"\r\n" in out
77
+
78
+
79
+ def test_remove_symbols_keeps_letters_and_digits():
80
+ raw = "ref;prix\nRéf#12;12,50 €\nA*B;99 %\n".encode("utf-8")
81
+ out, _ = clean_csv(raw, _opts(remove_symbols=True))
82
+ body = out.decode("utf-8-sig").splitlines()[1:]
83
+ assert body == ["Réf12;12,50", "AB;99"]
84
+
85
+
86
+ def test_keep_digits_only_strips_letters_symbols():
87
+ raw = "p\n12,50€\nA123\n10 ml\n€99.90\n".encode("utf-8")
88
+ out, _ = clean_csv(raw, _opts(keep_digits_only=True))
89
+ body = out.decode("utf-8-sig").splitlines()[1:]
90
+ assert body == ["12,50", "123", "10", "99.90"]
91
+
92
+
93
+ def test_keep_digits_only_leaves_pure_text():
94
+ raw = "nom\nCHOREGRAPHIE\nVELOURS\n".encode("utf-8")
95
+ out, _ = clean_csv(raw, _opts(keep_digits_only=True))
96
+ body = out.decode("utf-8-sig").splitlines()[1:]
97
+ assert body == ["CHOREGRAPHIE", "VELOURS"]
98
+
99
+
100
+ def test_keep_digits_then_decimal_comma():
101
+ raw = "prix\n12.50€\n".encode("utf-8")
102
+ out, _ = clean_csv(raw, _opts(keep_digits_only=True, decimal_comma=True))
103
+ assert out.decode("utf-8-sig").splitlines()[1] == "12,50"
104
+
105
+
106
+ def test_no_options_reports_clean():
107
+ raw = b"a,b\n1,2\n"
108
+ _out, rep = clean_csv(raw, _opts())
109
+ assert "Aucune modification" in rep["actions"][0]